Why can I only view content published to current domain? I'm using the Administration Views modules and Domain Access. When I'm logged in as the Administrator (user 1) I can view any content across all domains at /admin/content no matter what domain I'm on.

When I'm logged in as another role (Role X), who has permission to edit any content on any domain I can only see content published to the current domain. What permission or view setting or other setting do I need to apply to allow Role X to see content published on any domain no matter what domain they're on?

The only way Role X can see everything is if I give them the "Bypass content access control" permission, which I'd rather not.

After researching the api and reading up on how the permissions work (here) it looks as if the Node Access module limits a user (who is not user 1) to only be able to see content of the domain of which they belong, regardless of their editing permissions. You could, however, play around with grants (specifically grant_edit) to try and override the active domain. I would suggest some custom script to allow Role X grant_edit, or bite the bullet and use the "Bypass content access control" permission.

I understand this probably isn't the answer you wanted, however hopefully it helps in some way!


_preprocess_views_view__ specify view name I have a view named "taxonomy_term_custom." The preprocess code below works to do some specific stuff for this view, but I would like to override the hook like this:

function mywebsite_glue_preprocess_views_view__taxonomy_term_custom(&$vars) {
}

Is this possible?

function mywebsite_glue_preprocess_views_view(&$vars) {
  if($vars['view']->name == 'taxonomy_term_custom'){
    dpm($vars);
    // do stuff
  }
}

In Drupal 7 this preprocess function will not automatically get picked up as it did in Drupal 6. There is a workaround posted here if you want the same behaviour as Drupal 6. For the issue.


Drupal ajax call within form I am trying to call ajax call within form. here is my code

<?php

function clicktell_form_alter(&$form, &$form_state, $form_id) {
    //print_r($form);

    if($form_id=='user_register_form') {

        $form['choice_wrapper']['poll_more'] = array(

            '#type' => 'submit',

            '#value' => t('More choices'),

            '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),

            '#weight' => 1,
            "#executes_submit_callback" => FALSE,

            '#ajax' => array(

                'callback' => 'poll_choice_js',

                'wrapper' => 'poll-choices',

                'method' => 'replace',

                'effect' => 'fade',

            ),);

    }
}

function poll_choice_js($form, $form_state) {
    print_r($form_state);
    return $form['choice_wrapper']['choice'];

}

when i click on more choice button it is not calling poll_choice_js function. i checked this in firebug but didn't get any result

Thanks

For the ajax callback  and hook_form_alter() to function you should clear the caches from the performance link.
Also you should change the following

return $form['choice_wrapper']['poll_more'];


Table with sqlsrv driver is not showing headers or pagination I just wanted to practice doing the table "header sorting" and pagination to display a Drupal 6 table using a simple MSSQL query. At the moment, the table headers are not showing and there is no pagination, but the data in the query is being displayed. Can anyone see anything wrong with the code?

/* open database connection */
include "mssqlconnection.inc.php";

/* set up the table headers */
$headers = array(
  '',
  array('image_id' => t('image_id'), 'field' => 'image_id', 'sort'=>'asc'),
  array('geo_post' => t('geo_post'), 'field' => 'geo_post'),
  array('geo_sample' => t('geo_sample'), 'field' => 'geo_sample'),
  array('gps_lat' => t('geo_lat'), 'field' => 'geo_lat'),
  array('gps_long' => t('gps_long'), 'field' => 'gps_long'),
  ''
);

/* Set up and execute the query. */
$sql = sprintf ("SELECT TOP 100 image_id,
  geo_post,
  geo_sample,
  gps_lat,
  gps_long,
  FROM images"
);

/* add the order by clause */
$stmt .= tablesort_sql($headers);

$stmt = sqlsrv_query($conn, $sql);
if ( $stmt === false) {
  echo "Error in query preparation/execution.\n";
  die( print_r( sqlsrv_errors(), true));
}

/* collecting results */

while ($doc = sqlsrv_fetch_object($stmt)) {
  $rows[] = array(
    sprintf($imgPublish . '&nbsp;&nbsp;&nbsp;' . $imgDelete, $doc->nid),
    $doc->image_id,
    $doc->geo_post,
    $doc->geo_sample,
    doc->gps_lat,
    $doc->gps_long
  );
}

$table = theme('table', $headers, $rows);
$table .= theme('pager', array(), 10, 0);

return $table;

/* Close the connection. */
include "closemssqlconnection.inc.php";

theme_pager() only works in combination with pager_query() (Or the PagerDefault extender in Drupal 7). And that function is obviously not going to work with sqlsrv().

For Drupal 7, there is the http://drupal.org/project/sqlsrv project, which is properly integrated into the new database abstraction layer. I suggest you have a look at the following answer to see how you might be able to use that in Drupal 6: MSSql or SQL Server Wrapper for custom module? See also How do you make sortable tables with a pager with data from a custom table? for how to create paginated queries with Drupal 7/the DBTNG project.


aborted prematurely while running update #7204 I get this message but nothing is logged (that I can see)

The update process was aborted prematurely while running update #7204 in wysiwyg.module. All errors have been logged. You may need to check the watchdog database table manually.

I did more digging and found it is because the wysiwyg module was disabled. I enabled it and the update worked.


Overwrite add/edit form What I would like to do is to have a ?.tpl.php file in which I can write my own HTML content. A minimal example would be:

      <?php drupal_render($input_label); ?>

      <?php drupal_render($input_text); ?>

As far as I know, path templates are built-in Drupal 7, so just do this:

page--node--add--blog.tpl.php (for blog)
page--node--add--story.tpl.php (for story)
etc.
etc.

Clear cache!


Invalidate block cache programmatically I have a block that is cached per page. However, I need a way to invalidate it's cache in code per page or node. (Or, if no way, all cache per block id).

The SystemMenuBlock of core is invalidated when its menu changes because this method:

public function getCacheTags() {
  // Even when the menu block renders to the empty string for a user, we want
  // the cache tag for this menu to be set: whenever the menu is changed, this
  // menu block must also be re-rendered for that user, because maybe a menu
  // link that is accessible for that user has been added.
  $cache_tags = parent::getCacheTags();
  $cache_tags[] = 'config:system.menu.' . $this->getDerivativeId();
  return $cache_tags;
}

I think you can solve your problem in the same way.


Table prefixes with db_select() in SimpleTest tests How can I do database queries using functions like db_select() and db_query() in my DrupalWebTestCase sub-class? When I try to run them, I get an error:

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'simpletest421143 WHERE (nid = '1')' at line 2`

I think it's because the tables aren't properly prefixed, yet I see the prefix in the error string. So it seems that it's trying to prefix, but not doing it properly.

How can I use these functions in my testing class?

Executing queries inside SimpleTest tests is not different from executing them in a module. The path.test file contains the following code, and it is executed without errors.

$forum_vid = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE module = 'forum'")->fetchField();
$tid = db_insert('taxonomy_term_data')
  ->fields(array(
    'name' => $this->randomName(),
    'vid' => $forum_vid,
  ))
  ->execute();


Strategy for upgrading large Drupal 6 site to D7 We are running a middle sized Drupal 6 site (about 10k nodes plus comments, 200k user accounts), which is using many additional modules like OG, Views, CCK, Messaging, Notifications, CKEditor, Syntaxhighlighter, Pathauto, Token, Captcha, User Relationships, Fivestart, XML Sitemap. In addition, there are about 10 custom modules, most of them rather simple.

We now wonder how to upgrade to D7? We evaluated the following strategies, which don't seem to work:

Start from scratch with a blank D7 installation, configure it, set up all modules as we need them and migrate the existing content. The problem is about migrating existing content. When we set up the site, we need to create things like node types, roles, taxonomies, but when we migrate the content, the IDs of those entities might differ. It seems to be a very error prone approach.
Use official upgrade procedure. If we are not mistaken, the idea of the official upgrade procedure is disable all third party modules, replace core with D7, run update procedure, upload D7 version of modules, enable them and run their update and hope everything goes well. Problem here is that a lot of the modules we are using are moved to core or work now differently, but we still reference their functions in our theme all over the place. This again is very error prone. Also, the database contains afterwards many unused tables, but it is very hard to tell if we really need them.

What other options do we have? Personally, I would prefer to follow strategy 1, but we can't figure out how to migrate content.

Although both methods are valid, #2 can be painful if you have a lof of custom code in your app. I would consider option #1.  Migration is quite straightforward using migrate module.

There is a little more overhead than doing a straight-up upgrade but the process is very well documented and well integrated with Drush.  With migrate you can even have roll-backs and migration reports out of the box, all scriptable and quite easily automated.

I have done some pretty large migrations myself with this module and it works like a charm once in place.

PS: No worry for your entity id's, migrate uses the same nid when it imports the nodes.


How do I find the Delta of a CCK Multivalue Field I have two unlimited multi-value cck fields in one content type: field_before and field_after . In my custom node template file, I need to match up the deltas of each before and after value so I can display my content like this:

Before 0
After 0
------
Before 1
After 1
------
Before 2
After 2

So how do I get this output in my node.tpl file?

I would suggest putting this in a node-TYPE.tpl.php instead of node.tpl.php unless this is your only content type, but anyway, here is a quick start to accomplishing what you asked for using a simple for loop:

<?php $max = max(count($node->field_before), count($node->field_after)); ?>
<?php for ($i = 0; $i < $max; $i++): ?>

Before <?php print !empty($node->field_before[$i]) ? $node->field_before[$i]['view'] : ''; ?>

After <?php print !empty($node->field_after[$i]) ? $node->field_after[$i]['view'] : ''; ?>

  <?php if ($i != ($max - 1)): ?>

------

  <?php endif; ?>
<?php endfor; ?>

This can obviously be tweaked to add a default value if a field lengths are different, or skip the checking if you know that each "before value" will have a corresponding "answer value".

Also, if using default "unlimited fields", a user could rearrange them via drag and drop and potentially screw up your data.  If this is a concern for you, you may want to look at Multigroup for CCK3.


I want to send the username of the person submitting the form along with form data I wanted to know how to get the username for whoever submits a form so I can pass it to db_insert along with form data.

Sorry, I'm new to Drupal and php. I'm just try to learn.

Yes, it is custom code. Here is the form. I have based it on tutorials I've found so far.

function input_simple_form($form, &$form_submit) {

$form['color'] = array(
    '#title' => t('color:'),
    '#type' => 'textfield',
    '#required' => TRUE,
            '#description' => t('What is your favorite color?'),
    '#prefix' => '
',
    '#suffix' => '

',
    );
$form['TV_Show'] = array(
    '#title' => t('TV_Show:'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('What is favorite TV show?'),
    '#prefix' => '
',
    '#suffix' => '

',
    );

$form['input'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('input_simple_form_submit'),
    );

return $form;
}

Then I send the data to database:

function input_simple_form_submit($form, &$form_state) {

// Display a message upon successful submission.
drupal_set_message(t("Added @color @TV_Show", array('@color' => $form_state['values']['color'], '@Name' => $form_state['values']['TV_Show'])));
$id = db_insert("TestForm")
->fields(array(
    'color' => $form_state['values']['color'],
    'TV_Show' => $form_state['values']['TV_Show'],
    'SubmitBy' => $user->name,
    ))
->execute();
}

I'm not sure how to pass $user to the submit function. Hope that helps.

You don't pass $user to the submit function.

Instead, you add a declaration of the global $user object to the start of the submit function to bring it into scope.  Like this:

function input_simple_form_submit($form, &$form_state) {
  global $user;

  // Display a message upon successful submission.
  drupal_set_message(t("Added @color @TV_Show", array(
    '@color' => $form_state['values']['color'],
    '@Name' => $form_state['values']['TV_Show'],
  )));
  $id = db_insert("TestForm")
    ->fields(array(
      'color' => $form_state['values']['color'],
      'TV_Show' => $form_state['values']['TV_Show'],
      'SubmitBy' => $user->name,
    ))
    ->execute();
}


hook_node_access() returning NODE_ACCESS_DENY is ignored I am trying to block the current user from performing any action (view, update, delete) on a node. The user should only be able to view, update, delete the node being displayed if he is the owner of the node, or the owner of the node is a subuser of his (I am using the Subuser module).

The function below returns the correct value for the various tests I performed, but when the function returns NODE_ACCESS_DENY, the access isn't denied. The user can still see the node.

Is there something I am missing?

function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if (is_object($node)) {
    if ($node->type == 'my_content_type') {
      // Determine the current uid and, if the user doesn't have the right role, deny the access
      if (is_array($account->roles) && in_array('vip', $account->roles)) {
        $current_uid  = $account->uid;
      } elseif ( is_array($account->roles) &&
                !in_array('administrator', $account->roles)) {
        return NODE_ACCESS_DENY;
      } else {
        return NODE_ACCESS_ALLOW;
      }

      // Determine the node owner.
      $node_owner = $node->uid;

      // If the node owner is the same as the current user, allow to view the node
      if ($current_uid == $node_owner) {
        return NODE_ACCESS_ALLOW;
      }

      // If not, check if the node owner is a subuser of the current vip user
      $node_owner_profile = user_load($node_owner);
      if (isset($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'])) {
        if ($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'] == $current_uid) {
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      } else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

There is an error in the code you are showing: A variable is initialized inside a if() statement, but it is used outside that statement. $current_uid is initialized from the following code.

  if (is_array($account->roles) && in_array('vip', $account->roles)) {
    $current_uid  = $account->uid;
  }

It is then used from the following code.

  // If the node owner is the same as the current user, allow to view the node
  if ($current_uid == $node_owner) {
    return NODE_ACCESS_ALLOW;
  }

That code only works if the account object passed to the hook has the vip role, or if the node has been created from the anonymous user (the one whose ID is 0). Differently, $current_uid will be NULL.

Also, the code I show in the second snippet is not doing what the comment says. It is not allowing the current user to view the node if the node was created by that user: It is allowing that user to view, edit, update, and delete the node. The only operation that code is not allowing is creating a node of that content type, since in that case Drupal would pass the content type string in $node and the code is checking $node is an object.

To achieve what the comment is describing, the correct code is the following one.

  if ($current_uid == $node_owner && $op == 'view') {
    return NODE_ACCESS_ALLOW;
  }

I would use the following code, but see the notes after the code.

function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if (is_object($node)) {
    if ($type == 'my_content_type') {
      $current_uid = $account->uid;
      $node_owner = $node->uid;
      if (is_array($account->roles)) {
        if (!in_array('vip', $account->roles) && !in_array('administrator', $account->roles)) {
          return NODE_ACCESS_DENY;
        }
        elseif (in_array('administrator', $account->roles)) {
          return NODE_ACCESS_ALLOW;
        }
      }
      else {
        return NODE_ACCESS_IGNORE;
      }

      if ($current_uid == $node_owner && $op == 'view') {
        return NODE_ACCESS_ALLOW;
      }

      $node_owner_profile = user_load($node_owner);
      if (isset($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'])) {
        if ($node_owner_profile->field_parent[LANGUAGE_NONE][0]['value'] == $current_uid) {
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      } else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

Keep in mind the following notes reported in the documentation for hook_node_access(), especially the second one.

  Note that not all modules will want to influence access on all node types. If your module does not want to actively grant or block access, return NODE_ACCESS_IGNORE or simply return nothing. Blindly returning FALSE will break other node access modules.

  Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.) See Node access rights for a full explanation.

Keep also in mind that for users with the bypass node access permission, none of the hook_node_access() implementations are invoked. If the tests are done with accounts having that permission, that would explain why the user is able to act on the nodes even if the code is not giving the permission.

Instead of checking the roles of the user account, I would rather check if the user has a specific permission. hook_node_access() implementations are allowed to use user_permission().


Node Metatag data migration with the Migrate-Update\Drupal-Upgrade module I ask this for freshmen like myself, and others, who want to make sure they are making the best migrate-update possible:

I have created a local copy of a Drupal 7 site and have also created a brand-new Drupal 8 site. I have no content to migrate-update into the Drupal 8 site besides Nodes, their Metatag data, and a list of Redirects. I've already installed the modules Migrate update, Metatag, and Redirect (via GitHub) in the Drupal 8 site as well.

Is here something special that needs to be configured after the installation and enabling of the module in the Drupal 8 site to which I plan to migrate and upgrade content?

In other words, should I configure something in the D8 site Metatag module settings to insure a stable and correct migration of each node's meta title, description, and keywords from the D7 site?

Both redirect and Metatag have to provide their own migrations (migration templates), it's not something that you can just configure.

All you can do, if you don't know how to do it yourself is open issues for those projects and hope someone will do it. Or find someone you can pay that does it for you.


Block editing disappeared Until last week, when i logged in as administrator, on the page of nodes,
i could edit blocks by clicking "edit this block" link which appeared in upper right corner of blocks.
But now i can't see edit block link, so for every time i want to edit block i go to "/admin/structure/block" which is very bad.

When i check the page source i can see the links like:

Edit block

What would be the problem.
How can i solve this?
Can you please help me.

Do you have the Theme Developer module enabled? I had the same problem (disappearing contextual links menu for blocks) and disabling the Theme Developer module resolved the issue. Likely something to do with the z-order being utilized by Theme Developer.


Pricing changes based on line item fields in the add to cart form I've been using commerce_custom_product to add custom line items options to products I'm selling in the shop. The shop is selling servers and if someone when adding a server to their cart wants a bigger hard drive for instance they select it in the "add to cart" form. I want to alter the price of the line item based on which option they select

e.g.

20gb HDD $40
40 gb HDD $70

The hard drives and other things are not really properties of the product I'm buying. They are options I'm selecting for the product. This is why I looked at commerce_custom_product.

Ultimately this question comes down to How can I set the product price based on choices made in the Add to Cart form. Is commerce_custom_product the way forward with something else bolted in? I'm very happy to code if there is a hook I could use to grab the price from the referenced entity if I was to add price to the entities that get selected in the add to cart form

I think you want to stick with Variations for this.
Otherwise you can use Rules to calculate a price


Fieldsets 'IF ELSE' based on checkboxes? So i have a custom form with 3 fieldsets built from FORM API. each fieldset holds its own "mini" form for users to fill out. what i want is the second 2 fieldsets should not display unless either checkbox 2(fieldset B) is clicked or checkbox 3(fieldset C) is clicked. but fieldset one holds the checkbox field and i have it set up as a #tree

$form['Contract'] = array(
 '#theme' => 'form_panel_table',
 '#tree' => TRUE,
 '#title' => t('General Information'),
 '#collapsible' => TRUE, // Added
 '#collapsed' => FALSE,  // Added
);
$form['Contract']['first'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Products applying for:'),
 '#options' => array("Product B", "Product C"),
 '#required' => TRUE, // Added
 );

//if statement should hide this part of form unless checkbox above is clicked
    /* second fieldset starts here for product B */

    $form['Contract']['product B'] = array(
     '#theme' => 'form_panel_table',
     '#type' => 'fieldset',
     '#tree' => TRUE,
     '#title' => t('product b'),
     '#collapsible' => TRUE,
     '#collapsed' => TRUE
    );
    $form['Contract']['product B']['first'] = array(
     '#type' => 'textfield',
     '#title' => t('Zip/Postal Code'),
     '#size' => 30,
     '#maxlength' => 6,
    );

//one more else if statement for last fieldset should be here?
    /* End of product B. Begin product C */

$form['Contract']['product C'] = array(
 '#type' => 'fieldset',
 '#tree' => TRUE,
 '#theme' => 'form_panel_table',
 '#title' => t('example'),
 '#collapsible' => TRUE,
 '#collapsed' => TRUE
);
$form['Contract']['product C']['first'] = array(
 '#title' => t('example'),
 '#rows' => 39,

using php how would i write the if else statement in my custom form(tried it my way didnt show up on my site) in a druapl way?

Assuming you are looking for a #states based solution, which is new in Drupal 7.

First, note that you cannot use 0 as a key for #options. So rewrite your first field set as follows:

$form['Contract']['first'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Products applying for:'),
 '#options' => array('b' => 'Product B', 'c' => 'Product C'),
 '#required' => TRUE, // Added
 );

Now, we hide/show the other fieldsets depending on the above checkboxes' values.

$form['Contract']['product B'] = array(
  '#theme' => 'form_panel_table',
  '#type' => 'fieldset',
  '#tree' => TRUE, // not necessary if parent element has #tree = TRUE.
  '#title' => t('product b'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE
  '#states' => array(
      'visible' => array(
        ':input[name="first[b]"]' => array('checked' => TRUE),
      ),
    ),
);

Likewise,

$form['Contract']['product C'] = array(
  '#type' => 'fieldset',
  '#tree' => TRUE,
  '#theme' => 'form_panel_table',
  '#title' => t('example'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#states' => array(
    'visible' => array(
      ':input[name="first[c]"]' => array('checked' => TRUE),
    ),
  ),
);

What we are doing exactly is that we ask the Form API to generate necessary jQuery code that it should only show the field set in question only if the input tag (it's a specially jQuery selector that selects input, textarea, select, etc tags at once) with name "first" and its value c/b is checked. These 2 visibility settings are individual so there is no else if concept here.

Also note that #tree has nothing to do with the form's settings. if the code above didn't work, try setting if off. When you have #tree, name attribute of input fields get changed so PHP can build an array of submitted information. There is nothing to do with the visibility settings (except it can make our visibility rule never become true)


A relationship to the latest referencing entity in views I am not quite sure how to do this. I have content type A and another content type B which references content type A using an entity reference field. So A can have multiple nodes of type B referencing it. Not B has a date field.

Now what I want to do is create a view that lists content of type A but sorted based on the date field of the latest node of type B that references it.

I am not really sure what is the best way to achieve that. Any help is highly appreciated.

Make a view that lists nodes of Type B.
Sort this view based on date.
Add relationship based on the reference field which reference content type A.
Now list the fields you want from Content type A.
If you don't need fields from Content type B, hide them.


Drupal 7 Most Popular Tags in a list as a block: How? I have found Tagadelic works very well out of the box and is, to my hours of research and knowledge, the only plug & play feature for a tag cloud available for Drupal 7.

This is the only problem I've run into--I want the functionality of Tagadelic but do not need it in the "cloud" format. I need my tag cloud to be in a list from most popular to least popular and no size variation. For example:

Item x
Item h
Item j
Item o
Item 4

Obviously the most popular item being 'Item x' and the least popular item being 'Item 4' How can Tagadelic be modified to this as I know it will require more than a CSS fix? Or is there a better option than Tagadelic?

You can do this with views:

create a view of terms
add a required relationship to "content using tags"
set use aggregation: yes
add the "term name" field a second time, set one of the to "aggregation type: count"
add "term name" as a sort criteria, set "aggregation type: count"

A sample view is at http://drupalbin.com/19467


Show Field Collection fields together in same field item I have a field collection with two fields - Image and Caption. How do I get the two fields to display in the same field item? Right now the HTML is:

I need the HTML to be more like:

The problem was with how the field collection was set up. Originally, the field collection fields had unlimited values, while the field collection in the content type was limited to one value.

I reversed this so that the fields were limited to one value and the field collection has unlimited values.


How to remove ?= from url? I am getting url example.com/?= and I want this example.com
I have tried .htaccess method but nothing happened.
I have also gone through may link like clean urls but nothing happened
My clean URLs test fail.

Please help.

It will sound silly but it can help you.
Go to /admin/config/search/clean-urls
you will get example.com/?=admin/config/search/clean-urls in your address bar
remove ?= from address bar so that your url become example.com/admin/config/search/clean-urls
press enter
Now you will get a check box
tick that box and save configration.

May this Helps you.


Adding cache manifest I need to add cache manifest file just like below in my static markup:

<html manifest="my.manifest">

Is there any module to add this or custom way?

Look at HTML5 tools it enables you to preprocess the HTML element for manifest insertion.

  HTML5 Tools is a module that allows Drupal sites to be built using
  HTML5 ... smartly.

  One of our goals is to provide as much support for HTML5 markup in a
  set of Tools provided by a module so that you can use this module with
  any HTML5 theme you'd like.


Running cron failed and show white page I am using Drupal 7.

When I am running cron manually as an admin, I get white page.
When I am looking at the dblog report immediately after trying to run cron, I always see the following notice:

TYPE    job_scheduler
DATE    Monday, March 17, 2014 - 00:15
USER    Guest (not verified)
LOCATION    http://www.site.com/admin/reports/status/run-cron
REFERRER
MESSAGE Finished processing scheduled jobs (0 sec s, 0 total, 0 failed).
SEVERITY    notice

It is also strange that the user of this activities is "Guest (not verified)" and not Admin.

Yesterday I made alot of changes and installed some performance module as the boost module, file cache module and advagg module. But I always run cron after installing a module.
After few tests and enabling/disabling modules, it looks like that the problem is the filecache module

Can someone help me solve this issue?

Hard to debug without further details.
If you get white page then check your Webserver logs, especially error log.
You can also try to run drush cron to catch some more details (error messages).


A user-friendly, fast way to delete the same field from several content types at once? I have a Drupal 7.39 site with about 10 content types. All of these content types contains 2 fields which I want to delete (It's a long story why).

Is there a way to delete both of these fields from all content types at once, instead of manually deleting each one of them from each content-type? Thanks,

You can execute this code manually

field_delete_field('your_field_machine_name');


Checkout a specific dev version of module using git I want to checkout a specific dev version of the feeds module using git.  I have a site which is using feeds 7.x-2.x-dev.  On the modules admin page the module version number is reported as 7.x-2.0-alpha8+99-dev.

I have cloned the feeds module repo but can't work out how to checkout that specific version.  I tried using git checkout 7.x-2.0-alpha8+99-dev, but it didn't work.  I guess if I knew the commit number I could check it out, but not sure how to easily work this out other than manually reviewing the commit log and working out what was the 99th commit after alpha8.  I am hoping there might be an easier way.

Would appreciate any suggestions.

This is more a git question than Drupal, but you can use rev-list command to retrieve a list of commit hashes since the 7.x-2.0-alpha8 tag. Using the tail command you can reverse the list to show the first 100 commits (I think the +XX- scheme is an offset from the first commit) then filter that down to the last result (which should be +99-dev commit).

git rev-list 7.x-2.0-alpha8^..HEAD  | tail -r -n 100 | tail -n -1


Replicating an existing table-based form as PDF views output? The Drupal 6 project I'm working on involves a custom content type with a bunch of different elements. I'm needing to replicate an existing form -- see screenshot.

Ultimately, I need to take the data stored in the CCK fields attached to this content type, and rebuild them as a table as per the screenshot. It then needs to be savable as a PDF.

It seems like there are two ways of doing PDF content of the nature I'm wanting:

Views PDF -- cumbersome as heck to configure; requires manually positioning each field.
Print -- I can't figure out how to directly access the CCK field variables through its $print object; consequently, I can't rebuild this as a table.

How would one go about taking a lot of CCK fields, formatting them as a table, then making that PDF-able?

Thanks.

Edit: To clarify, I have each row of, say, the FAC table stored as a row in the content type, through a compound/multifield module called "Flexifield". Data isn't stored as per the table; it's stored as a label ("level"), a decimal number and a boolean (above or below grade?). Another boolean toggles between Imperial and Metric for the entire sheet. The columns are generated by converting the number stored to either Imperial or Metric, depending on which the stored measurement is set as. Consequently, I'll ultimately need a way to tweak and restructure the data using PHP. This is why I can't, for instance, just tell the fields to display as a table.

Just a shot in the dark, but the Slickgrid module may be of help in this situation. Here is an excerpt about it from the module's project page:

... is an implementation of Michael Leibman's jquery slickgrid plugin, a lightening fast JavaScript grid/spreadsheet.
It defines a slickgrid view style, so all data can be output as an editable grid.


How to animate set of titles of a View using JQuery There is a View of latest news title linked to the node page and I need to display them like this Effect.

I've trying to do it by creating a new template file for my views named:

  views-view-list--latest-news--block.tpl.php

and this is the code I was trying to set to work:

<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print $list_type_prefix; ?>

         //this is where it shoul be typed...

  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>
<?php
$setOfTitles = "";
foreach($rows as $id=>$row)
     $setoftitles.="'".$row."'".",";
$setoftitles = rtrim($setoftitles , ','); // to remove the last `,`
print_r ($setoftitles); // and it says I have all of you node titles
?>
<?php print_r($setOfTitles); ?>

but it is not a true answer!! because my alert in js is empty and means I couldn't pass variable form php to js. Where is the problem? and how can I solve it? or is there a better way to do it?

Salam :). You need no new Views display type. Create a view of the latest news called it lnews and display it in a block, suppose it's machine name is block_0. select the titles as the Fields. You have to use PHP code inside that block (enable PHP Filter module). Use this code

<?php
$views = views_get_view("lnews");
$views->set_display('block_0');
$views->execute();

Now to get the titles use this code (to get the accurate code use kpr($views))

$setOfTitles = "";
foreach($views->result as $view)
     $setOfTitles .= $view->node_title."*";
$setOfTitles = rtrim($setOfTitles , "*"); // to remove the last `*`

So far you created a string of all of the titles which they are separated by a * sign. There is one more step left, Send this variable to a .JS file that contains

$(function(){

    $("#typed").typed({
        strings: [HERE IS YOUR STRING],
        typeSpeed: 30,
        backDelay: 500,
        loop: false,
        contentType: "html",
        loopCount: false,
        callback: function(){ foo(); },
        resetCallback: function() { newTyped(); }
    });

    $(".reset").click(function(){
        $("#typed").typed('reset');
    });
});

code, then explode the string to an array and send it to the strings object.

To send $setOfTitles variable from the above block to the JS file here is a few tutorials

How to pass values from php to javascript properly?
How to send variable from .php file to .js file in Drupal 7?
How to pass a PHP variable to javascript in Drupal 7

Now I assume you have successfully sent the variable to .JS file, call it's name var titles. use split() function to convert the string in to an array. Now this code should work:

var array_of_titles= titles.split("*");
$(function(){
    $("#typed").typed({
        strings: [array_of_titles],
        typeSpeed: 30,
        backDelay: 500,
        loop: false,
        contentType: "html",
        loopCount: false,
        callback: function(){ foo(); },
        resetCallback: function() { newTyped(); }
    });

    $(".reset").click(function(){
        $("#typed").typed('reset');
    });
});

This solution wont link the titles to the node page. The

foreach($views->result as $view){
     $setOfTitles .= $view->node_title."*";
     $setOFNIDs .= $view->nid."*";
}

creates list of node IDs. You can also pass the node IDs to the JS file and with some js processing link the titles to the /node/nid.

For example in the JS file instead of creating array of title create array of TITLE

UPDATE:

Sounds you had problem with sending the $setOfTitles variable to the javascript file. Use the following method:

In the PHP code I gave you above add this code

drupal_add_js(array('variableName' => $setOfTitles), 'setting');
drupal_add_js(path_to_theme().'/js/js.js');

Create a file in /js directory of your theme folder and rename it to js.js and in the js.js use this code

(function($, Drupal){
  Drupal.behaviors.backgroundAnimation = {
    attach: function(context, settings) {
      alert(Drupal.settings.variableName);
      alert(Drupal.settings.basePath);
    }
  };
})(jQuery, Drupal);

I tested this solution and it successfully alerted the variableName and basePath. So just insert the rest of the Javascript code I gave you above in the (function($, Drupal) function.


Load a custom block and render with subset of data I am loading a block programmatically in a theme preprocess function, and trying to render that block in twig using without to remove some fields. However, the block is still printed in full.

This is the code I am using.

function my_preprocess_node(&$variables) {
    $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
    $variables['my_block'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($my_block);
}

The template code is the following one.

{{ my_block|without('field_1', 'field_2') }}

I also noticed while debugging, that while the result in twig of my_block is a render array, it does not include the keys I'm expecting (the problem, I assume?).

This is the dump() output.

array(3) {
  '#cache' =>
  array(4) {
    'keys' =>
    array(3) {
      [0] =>
      string(11) "entity_view"
      [1] =>
      string(5) "block"
      [2] =>
      string(17) "my_site_footer"
    }
    'contexts' =>
    array(3) {
      [0] =>
      string(28) "languages:language_interface"
      [1] =>
      string(17) "my_theme_section"
      [2] =>
      string(14) "my_theme_site"
    }
    'tags' =>
    array(2) {
      [0] =>
      string(10) "block_view"
      [1] =>
      string(36) "config:block.block.my_block"
    }
    'max-age' =>
    int(-1)
  }
  '#weight' =>
  int(0)
  '#lazy_builder' =>
  array(2) {
    [0] =>
    string(42) "Drupal\block\BlockViewBuilder::lazyBuilder"
    [1] =>
    array(3) {
      [0] =>
      string(17) "my_site_footer"
      [1] =>
      string(4) "full"
      [2] =>
      NULL
    }
  }
}

One way to do this is with a new view mode for blocks. You can add one at /admin/structure/display-modes/view/add (Manage > Structure > Display Modes > View Modes > Add new view mode). Then, you have two options, 1. go to your custom block type and configure this view mode display to only have the fields you want, or 2. create a template file with a name like block--BLOCK-TYPE--MY-NEW-VIEW-MODE.html.twig, then remove the fields you don't want to print like you were trying to do in the node template. (Replace BLOCK-TYPE with your block type's machine name, and MY-NEW-VIEW-MODE with the machine name of the new view mode you created. Convert all underscores in these machine names to dashes.) After you've done this you can update your preprocess hook's view() call like ->view($my_block, 'MY_NEW_VIEW_MODE')(keep the underscores in the machine name of your view mode here). This will make your preprocess hook look like:

function my_preprocess_node(&$variables) {
  $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
  $variables['my_block'] = \Drupal::entityManager()
    ->getViewBuilder('block')
    ->view($my_block, 'MY_NEW_VIEW_MODE);
}

Lastly, because you add your block to the variables array with the my_block key, update your node's twig template to simply be:

{{ my_block }}


Use print_pdf in the background on node save? As the Print module's creation of a PDF can be quite slow (and use a lot of memory/CPU), is it possible to save a PDF into the public:// files area each time a node is saved?

Has anyone done this? Presumably you could call a save-PDF function on hook_node_presave but I'm not sure what the next step is. Call a print-PDF function with a file path? Where is that print-PDF function and how would you call it?

The function used from that module to output PDF is print_pdf_generate_html(), which gets a filename as last parameter.

To understand what to pass as first argument, see print_pdf_generate_path(), which is the function calling print_pdf_generate_html(). In particular, see the following code.

$print = print_controller($path, $cid, PRINT_PDF_FORMAT);
if ($print === FALSE) {
  return;
}


add class to book navigation block links I use navigation block generated by block module. Tha block is displayes on all pages that belongs to book. I would like to add custom class to all links inside navigation block. I found that the block is generated by code here>

https://api.drupal.org/api/drupal/modules!book!book.module/function/book_block_view/7

But I am unable to figure out how to alter links. Any help appreciated. Thank you.

Give a try to Block class module: Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent <div class="block ..."> element of a block.


Multiple separate forms for searching up different apache solr indexes Mac_Weber in IRC gave me some great info in relation to this earlier, but I have a more indepth question: is it possible to have multiple separate forms for searching up different apache solr indexes? Say for example I had a separate indexes on rock stars, countries, and organic food suppliers. I want a drupal website that has literaly separate pages with a search box to search upon these indexes.

The the Search API is perfect for the job. This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine (including Solr). You can create multiple indexes with their own individual search pages/blocks and have granular control over what fields are searched and the relevancy.


How to add form fields dynamically using webform Using webform 3 module, is there a way to dynamically add more fields or do these fields have to be created in the database first?
Currently that's what I am doing and with javascript toggling the css display attribute to show or hide fields.

You can use Webform Add More module to dynamically add more fields in webform.
The project page says:

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields. This module adds a checkbox
  setting to webform fieldset components to select which should have Add
  more functionality, as well as an advanced setting to override the
  button label per Webform


Add extra button on webform and Ajaxify I'm building a form similar to attached image.

Customer enters values for all 3 text fields and click 'Get Online quote'. This will perform a database query (using AJAX) and display a value just below 'Get Online quote' button.

If he's happy with the quote, can ask to get contacted by clicking the second button, 'Contact me for more details'. Therefore second button act as the form submit button which will redirect to a thank you page.

So far I have coded like below.

// online quote button
function fence_quote_form_alter( &$form, &$form_state,$form_id ){
  if ($form_id == 'webform_client_form_4208') {
    $form['actions']['fence_quote']  = array(
    '#type' => 'submit',
    '#value' => t('Get online estimate'),
    '#submit' => array('fence_quote_custom_submit'),
    '#ajax' => array(
      'callback' => 'fence_quote_form_callback',
      'wrapper' => 'fence_quote-submit-button',
    ),
  );
    $form['#validate'][] = 'fence_quote_custom_validate';
  }
}

function fence_quote_custom_validate($form, &$form_state) {
  // your validation code
}

function fence_quote_custom_submit($form, &$form_state) {
  $query = db_select('fence_900', 'f');
  $query->fields('f', array('total_cost'));
        ->condition('meters', 2, '=');
  $result = $query->execute();
}

function fence_quote_form_callback($form, &$form_state) {

}

I'm unclear on what to put under AJAX callback function. Should I
have the database query in it instead of putting inside custom submit
function?
How can I display the database query value below the 'online quote' button on a new text field? I'm unable to print using $form_state['values']['total']

Db Query in Ajax callback. I would suggest to change type of Ajax-Button from submit to button.
In callback return instead of print. You should also use ->fetchAll() for instance after ->execute()


What causes a search_api based view to stay cached for anonymous users even after the index is updated? I have a search api based view. The index this view is based on indexes new content as soon as it is published. When new contest is published, logged in users can indeed see the latest content at the top of the search results.
However, anonymous users don't see the newly published content until the cache is cleared. How do I avoid having to manually clear the cache? What should I check?

Is it possible you have a "non Drupal" cache for anonymous users? Common such caches include Varnish (server based) or Cloudflare (cloud/cdn based)
Failing that, have you checked the cache settings on the view itself? I believe for search API the correct settings should be Caching: Search API (tag based) (under advanced in the view edit screen). If that doesn't work you could try turning off the views cache temporarily to at least determine if that is the root cause.
Finally check your modules are up to date, including Search API & check the issue queue to see if there are any patches that may solve your issue: https://www.drupal.org/project/issues/search_api?categories

“There are only two hard things in Computer Science: cache invalidation and naming things”


Is it possible to assign attributes to different roles? So let's say I have a student role. And I want assign variables to student such as attendance and grade.

Then i want a teacher role that can assign this attendance and grade to their students.

We can pretend that there is only one teacher and there are many students.

How would this be done? I know that you can edit fields under Config->People in drupal 7, but this causes there to be the same fields for all users.

In a similar way, is it possible to have like a "Student Page' where a student sees his/her own grade but not any one else?

I've been trying to find similar function but it seems to not exist.

Thanks

Yes. There many ways to go about this but the Profile2 module is one that covers the entity field data (variables) per a specified user role.

  Designed to be the successor of the core profile module, which is
  deprecated for Drupal 7. In contrast to the deprecated module this
  module provides a new, fieldable 'profile' entity - leverage the power
  of fields!

Your your student role can be assigned to have to have a student profile which a Teacher can edit, but only a student can view. It has the additional permission View Own Profile... which should restrict students from seeing other profile pages.


Get Thumbnail Image URL for Video in Views I've got a Video field and the Video Thumbnail is uploaded by the user.

I've got a View which is generating JSON (with the views_datasource extension). I want to include the image url to the Video Thumbnail has one of the fields in my JSON. I've set the formatter on this field to be "Video Thumbnail":

However, the value shown in my JSON output is the url to the original video and not to the Thumbnail image.

So, I tried enabling Rewriting on that field in the Views configuration. I used the [field_video-thumbnail] token to try to get the URL of the Thumbnail image...

but what I get in my JSON is the fid of the Image and not the URL of the image.

  "node" : {
    "title" : "Test 6",
    "body" : "
test
\n",
    "field_image" : null,
    "path" : "/blog/test-6",
    "created" : "Monday, November, 2012",
    "field_video" : "38"
  }

How can I get the Image Thumbnail URL?

You are looking for the Image URL Formatter module.


When developing a module's theming functions, should you use "template_preprocess..." or "mymodulename_preprocess..."? I got into a discussion with co-workers today after reviewing some code on a Drupal 6 project.

When creating a module, I tend to define all template preprocessor functions by including the module name

function mymodulename_preprocess_news_item(&$vars){ ... }

If another module/theme needs to override/expand this, I add the function definition with the new module/theme name.  This is how I've come to understand the theme layer to work.

My co-worker's mentioned that I should be using the following instead for custom preprocessor definitions:

function template_preprocess_news_item(&$vars){ ... }

According to the documentation on theme(), template_preprocess gets executed before anything else so I'm leaning towards agreeing with my co-workers since these are custom theme elements and the originating module should process the initial content.

I am curious if there are any best practices/opinions out there on this matter.

Why not look at drupal core for best practice which favors template_process_X.

Also for some processors both template_preprocess and module_preprocess hooks can get called, see template_preprocess_block and system_preprocess_block as an example.


Ubercart review order button redirects to cart page, does not allow checkout I am using Ubercart 3.3, Secure Pages latest dev, and Drupal 7.18.

When I go to the site, login, and add a product to my cart all goes well.  I then go to the cart page which shows correctly and I click checkout.  It then redirects me to the checkout page where I fill in my information and choose paypal as my payment of choice.  When I'm all done I click review order at the bottom of the form and it redirects me back to the cart page instead of the review order page.

To make matters worse, after that happens I can no longer get back to the checkout page, every time I click checkout it just redirects me back to the cart page.

Some things i've checked:

User 0 is in the database
Clearing cache
Truncating the cache tables
Try a different product
Applied patches Secure Pages requires
Adding $conf['https'] = TRUE; at the bottom of my settings.php file

It actually turned out that I had a product in my cart that was no longer on the site, and my theme did not have the proper messages outputting.  I switched the theme back to Bartik and got a message saying there were products in my cart that were no longer available.


how to validate email id is already register or not function lawyer_register_form_submit($form,&$form_state)
{
$mail = $form_state['values']['mail'];
$new_password = user_password();
$edit = array(
  'name' => $form_state['values']['name'],
  'pass' => $new_password,
  'mail' => $mail,
  'init' => $mail,
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE mail = :mail;", array(':mail' =>  $mail))->fetchField())
  {
  $to = $form_state['values']['mail'];
  $subject = 'Lawandmoney New account created';
  $headers = "From: admin@lawandmoney.info\nContent-type: text/html";
  $body = 'A new user account has been created for you at us.lawandmoney.info.
 Your login details are as  follows:
Username: '.$form_state['values']['name'].'
 Password:  '.$new_password.'

 Please login to us.lawandmoney.org and change your password.
';
     user_save(drupal_anonymous_user(), $edit);
     if($form_state['values']['send_message'] == 1)
     {
     mail($to,$subject,$body,$headers);
     drupal_set_message("Sussessful register.Please check your Email for login   deatils.");
     }
     else
     {
     drupal_set_message("mail not send.");
     }
     }
     else
     {
     drupal_set_message("You are already register.");
     }

we created a custom user registration form.now we have to checked if user is already register then its give error like You are already register, data will not inserted into database and mail not send to user.

This can be done with hook_form_alter:

function module_(&$form, &$form_state, $form_id) {
  $user_login_forms = array('user_login', 'user_login_block');
  if (in_array($form_id, $user_login_forms)) {
    $form['#validate'][] = 'my_validate_function';
  }
}

function my_validate_function(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  // Drupal 6:
  if (!db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s';", $name))) {
    // User doesn't exist
  }
  // Drupal 7:
  if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' => $name))->fetchField()) {
    // User doesn't exist
   }
}

It's better to query the DB directly in this case than than using user_load as it hooks into other modules as well.


Show list of taxonomy terms, with node's current terms given a class My goal is simple: to display a list of taxonomy terms (alphabetically), with the terms on the current node being highlighted by a current css class. I've tried using views of taxonomy term, but I can only get either the full list or the terms on the node to display, and I want something of a mashup.

So for the visual thinkers I want an output of this:

< ul >
    < li class="current" >Blue< /li >
    < li >Red< /li >
    < li class="current" >Rouge< /li >
    < li >Yellow< /li >
< /ul >

I feel like I'm about to have a very "duh!" moment, so please, enlighten me. Seems like this should be simple to do in Views, yet I can't seem to get it and will resort to doing it in the template.php file if I can't find an answer. Thanks for any help.

I think I have found a solution that achieves the desired result in good way (in terms of not writing spaghetti php or hardcoding stuff in the theming layer). Instead of providing the full configuration at once, I will try to guide you step by step.

1/ Create a new view (mine is called 'test') that only has a Block display, and displays Taxonomy terms for a specific vocabulary (mine is called 'Target Group'). Use 'HTML list' as the selected Format, make sure the
'Taxonomy term: Name' is added in the list of the displayed fields, also use 'Taxonomy term: Name' as a sorting option in ascending order, select 'Display all items' in the pager settings, and make sure query Distinct settings are DISABLED (we will achieve that via aggregation later on). Save your view. You can see the view results in the preview section of the view manage page, or place the block in the respective node display if you prefer to view it directly in the front end. At this point, you will be able to see a list of all the terms form the specific vocabulary.

2/ Add a new relationship to your view (in the Advanced section). The relationship should be the one labeled 'Taxonomy term: Content with term'. It is highly important (for the rest of the code that will be provided) that you choose this generic relationship option, instead of the more specific one labeled 'Taxonomy term: Content using Target group' (where Target Group is the vocabulary name I used for this example). Provide an identifier for this relationship - I left the default one labeled 'node'. Make sure that 'Require this relationship' is NOT checked - this will create a LEFT JOIN between the terms table and the node term data table. Now go to the fields section and add the field 'Content: Nid' and set it to use the relationship with the aforementioned identifier. Any other field settings do not matter for now - we will adjust them later on. Save your view. At this point you will be able to see plenty of duplicates for all terms, each one with a different nid. Good.

3/ Now go to the contexual filter section and add a new one for 'Content: Nid'. Make sure the 'node' relationship is used. For 'When the filter value is NOT available' choose 'Provide default value' and set 'Type' to 'Content ID from URL'. It is recommended to 'Specify validation criteria' as you see fit. Save your view. The configuration until this step, is actually the one presented in this excellent answer here which has some screenshots too. Up to this point, you will be able to see only the terms with which the current node is tagged. "Duhh, that was the original problem" you'll say, but bear with me as we take it one step further.

You see, when adding a contexual filter, views adds the restriction to the WHERE clause of the generated query (which is good and desired in the majority of cases). The current query generated is the following:

SELECT DISTINCT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, node_taxonomy_index.nid AS node_taxonomy_index_nid
    FROM
    taxonomy_term_data taxonomy_term_data
    LEFT JOIN taxonomy_index taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
    LEFT JOIN node node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
    LEFT JOIN taxonomy_vocabulary taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
    WHERE (( (node_taxonomy_index.nid = '4072' ) )AND(( (taxonomy_vocabulary.machine_name IN  ('topics')) )))
    ORDER BY taxonomy_term_data_name ASC

But what we DO want in our case, is that the nid restriction is applied as an additional restriction to the LEFT JOIN with the node_taxonomy_index in order to filter the join and not the whole result set. Unfortunately, views does not support that out of the box but after some digging I found that it is programmatically supported in views_join handler which can be gracefully managed via hook_views_query_alter. So, moving on.

4/ In order to implement a hook, you will require a custom module. If you are not sure how, then read the respective documentation. Here is the implementation that removes the nid restriction from the where clause and adds it to the LEFT JOIN clause

function my_custom_module_views_query_alter(&$view, &$query) {
  if ($view->name == "test") {
    // try to resolve the nid from the contexual filter condition
    $contexual_nid = null;
    if (!empty($query->where)) {
      foreach ($query->where as $delta => $where_clause) {
        if (isset($where_clause['conditions']) && count($where_clause['conditions'])) {
          $condition = $where_clause['conditions'][0]; // in the current use case, there will be only one condition
          if (isset($condition['field']) && strpos($condition['field'], "nid") !== FALSE) {
            $contexual_nid = array_shift($condition['value']);
            // remove the nid constraint from the where clause
            unset($query->where[$delta]);
          }
        }
      }
    }
    // add the nid constraint to the relationship
    if ($contexual_nid != null && isset($query->table_queue['node_taxonomy_index']) && isset($query->table_queue['node_taxonomy_index']['join'])) {
      $join = $query->table_queue['node_taxonomy_index']['join'];
      $join->extra = array(
        array(
          "field" => "nid",
          "value" => $contexual_nid
        )
      );
      $query->table_queue['node_taxonomy_index']['join'] = $join;
    }
  }
}

So, at this point, you have a list that has tons of duplicates. "Duh, I had achieved that via 'views_field_view' and with less duplicates" you'll think. Well, no. First of all, the list is now sorted alphabetically, and second, getting rid of the duplicates, now that we are dealing with a single result set, is a piece of cake via aggregation. Back to the view administration then.

5/ In the Advanced section, set 'Use aggregation' to Yes. For field 'Content: Nid', click on the 'Aggregation settings' and set 'Aggregation type' to 'Count'. For field 'Taxonomy term: Name' the aggregation type should be the default 'Group results together'. Save your view and say goodbye to the duplicates.

6/ Last step in order to convert the 'Content: Nid' to useful markup. Click on the field which is now labeled '(node) COUNT(Content: Nid) (Nid)' and apply the following settings:

Create a label: unckeck
Exclude from display: check
REWRITE RESULTS: Rewrite the output of this field: checked
REWRITE RESULTS: Text: 'current' (the actual literal 'current'
without the quotes)
NO RESULTS BEHAVIOR: Count the number 0 as empty: checked
NO RESULTS BEHAVIOR: Hide if empty: checked
NO RESULTS BEHAVIOR: Hide rewriting if empty : checked

And finally click on the Settings link for the HMTL list format and for 'Row class' enter token '[nid]'. Save your view. Everything should look as expected.


Internet Explorer 11 Overlay does not close I am experiencing an issue where the overlay wont close when saving a piece of content. This only happens on Internet Explorer 11. I've tested it on Chrome Firefox and IE 10 and it is working fine.

The problem is when I save content, the overlay modal disappears and I'm left with a grayed out page and cant click or do anything. Also when I save a setting everything saves but I cant exit the modal and if I click another admin link the site forces itself to non-overlay mode. Weird stuff! Anyone ever experience this problem? Again its only on Internet Explorer 11.

I thought it might be jQuery related so I checked every version of jQuery that I use with the jQuery update module and it didn't fix it.

I fixed it yay! It was a problem with jquery update. I updated the module to the alpha3 release which adds support for jquery version 1.11 and it works fine now.


Display content between squares with links I want to build a Drupal 7 website with big squares which contain a title and some text. In a desktop layout there will be 3 rows of 3 squares. Each square is a link to one or more underlaying pages. I am thinking of using the views module to make this work.

After clicking on a square, the content of the underlaying page has to be displayed right under the row of this square. So, if a visitor clicks on a square in the first row, content should be displayed between row 1 and row 2. By clicking on a square in the second row, content should be displayed between row 2 and 3. I have no idea how to do this. Any suggestions would be welcome.

Thanks,
Steven

What you want to do can be easily accomplished with JavaScript and CSS. And. since Drupal already ships with jQuery, you could make use of the slideToggle() effect to slide up and down your content.

I'll give you a general idea:

In Drupal, create a page that displays your 3 nodes. For example, you could create a View and show the Title and Body fields of your articles.
In your JavaScript, hide the Body field by default and then add a click event to your Title field, so when users click on it, the following Body field slides down or up.

$('#title-one').click(function() {
    $('#body-one').slideToggle();
});

Of course, this is just a starting point and one way of doing it. Good luck!


How to make metatags output proper images urls I'm tring to create set of open graph tags for better sharing of my page. Unfortunatelly I cannot make Metatags output proper path to images attached to nodes. I have node with field_promoted_image. In metatags configuration I put:
[node:field-promoted-image]
[node:field-promoted-image:file:url]
[node:field-promoted-image:file]

but all I get is field name or file name but without proper path.

if you get the file name with [node:field-promoted-image:file:url] just put the right path bevore the token. yoursite.de/thepathtoimage[node:field-promoted-image:file:url]or maybe you can put the base path token before it


Boost Cache, External CDN? I have been thrown into a Drupal 6 environment, helping a client whose site has been running terribly for some time now. Among other issues, they had a ton of traffic and were serving it all locally, so we aim to implement a CDN.

Our CDN of choice is Incapsula, who operate much like Cloudflare if you're familiar with them. At their most basic, they can cache static content. Should be simple.

What I'm finding is that when Incapsula's caching is enabled, the cache never updates. If you go through the public address to the site, you will see old content. It's not just old images and CSS, entire pages will be missing if they are added after the cache is enabled. If you bypass the proxy, you see the correct content. Manually clearing the cache from within the Incapsula control panel does not resolve the problem, I can only do that by actually disabling the cache. Of course, while it is enabled, the site flies!

Complicating this, they have Boost installed and enabled. I am new to Drupal, newer to Boost, and I am attempting to understand how the caching works but have not made much progress. Are there specific settings within Boost that might affect this? It feels like a header is misconfigured. Any thoughts and advice are appreciated!

If the CDN caches whole pages you can most likely disable boost.
https://drupal.org/project/advagg - Needed for D6 CSS/JS
https://drupal.org/project/imageinfo_cache - Should help with imagecache generation


Commerce order access checks in Views I realize this is quite a specific Drupal commerce question, but perhaps I can get some insights as I am stuck here.

I need to control access to commerce orders on a per-order basis based on an entity reference field. So users will not have access to view commerce orders, except if they are related to them.

My custom access check requires an operation, and entity and a user.

Looking at all the hooks Drupal commerce executes in order to determine access:

commerce_order_access() calls the generic access helper, commerce_entity_access() for view operations, this constructs an access query based on the entity, which relies on Database API invoking hook_query_TAG_alter(). For orders, this is hook_query_commerce_order_access_alter().
commerce order's implementation of this hook, commerce_order_query_commerce_order_access_alter(), calls a generic implementation back in commerce module, commerce_entity_access_query_alter().
commerce_entity_access_query_alter() checks entity type and user access permissions for the entity and builds an OR conditions array that you can alter for Orders using hook_commerce_entity_access_condition_commerce_order_alter().

All these functions however never get a specific entity to operate on and always check 'global' permissions with user_access().
The committed patch Pass entity to Commerce entity access check contexts changes this so the entity is added to the query metadata in commerce_entity_access() and as such can also be used in hook_commerce_entity_access_condition_commerce_order_alter().

So far so good, this works and I can check access to my order in hook_commerce_entity_access_condition_commerce_order_alter().

The real problem

The problem I run into occurs when loading the orders through Views;

Views does not load the entity but just adds it to the select query and then performs the above access checks, starting with commerce_order_query_commerce_order_access_alter() (hook_query_TAG_alter()). This way the entity is not set (commerce_entity_access() is never called) and thus not available for access checking and all there is for me to alter is the query.

The thing I came up with

Actually the only thing I could think of was to load all commerce order entities, run them all through my access check and save the id's of the allowed orders. Then in hook_commerce_entity_access_condition_commerce_order_alter() add all these id's to the query in a condition.
I am however afraid this will be a huge performance drop once there have been made some orders

So is there a way I can fetch entities from a Views select query? Or id's? Or do I need to implement my check elsewhere?

Your thing you came up with is certainly one way of doing it, though you're adding a step. If you can guarantee that your entity reference field will always be on the order, then you could just join your query to the entity reference table and check it against the current user's UID.

Something to the effect of:

INNER JOIN `field_order_user_reference` ON `commerce_order`.order_id = `field_order_user_reference`.entity_id
...
WHERE
`field_order_user_reference`.user_id = ***CURRENT_USER***

Or something to that effect.

The way you have it implemented now, you will start to see performance degradation since you're adding a lot of overhead. Using pure SQL will help tremendously and you shouldn't see any slowdown.

Alternatively, since your order has an entity/user reference field attached to it, you should be able to just add it as a filter and set the filter user as the current one. Maybe not, but if you haven't tried it, it'd be worth a shot.


Services 3: How to retrieve the current logged in user ID I can get a list of all users by going to //endpoint/user/ but how do I return the current user?

My primary goal is to find out if the user is authenticated.

To do this you can use the system resource "connect".  Enable that resource:

to go admin/structure/services/list/serp/resources
expand "system"
check "connect" Hit save

Then, you post (posting nothing) to /system/connect and it returns the current user info and session id.


How to pull node history into a view Is there a way to add a relationship to the node history table in views. If not, is there a module which can do it?

As it turns out the history table is already available under views as part of the content section (field 'Has new Content').

Download Views Field View module and install it.

Next create a new view that shows content revision instead of content. See image below.

Pull in the fields you want to see. See Image below.

Add a views contextual filter. See Image below.

Add the Content: Nid field as the contextual filter. Image below.

Configure the field as below.

Next edit your original view that pulls over the current content. Add a field and select the Content: Nid. Make sure to uncheck the Create Label checkbox. We just want the number. Then check the exclude button.

Now we add the views_field_view to the view via the field section of the view. You should select Global: View.

Now we configure it like the image below.

Save your view and now you should be able to go and see each node along with the historical data.


How to get Search API module to index the full country and state name from Addressfield Module? The Addressfield module stores an abbrivated name for countries and state such as US for United States and FL for Florida. The Search API indexes the these words which are not very useful when doing searches for places like New York, Boston, France, ect.. Should I just discard the Addressfield module and make text fields or is there another way to go about doing this?

you might want to use SOLR search and write a synonym.txt file to translate the state and country codes into names


un-escaped _server variable in settings.php - bad idea right? I recently started working for a new company hosting drupal sites that is using a switch statement within the settings.php for multiple environments. I am accustomed to using multi-site and am exploring the feasibility of having configurations like this.

What concerns me is the lack of any sanitation or escaping of the variable and using it in its raw form. Is this a terrible idea or is it fine if we start sanitizing the 'http_host' variable?

Code:

    switch ($_SERVER['HTTP_HOST']) {

    //Live Settings
    case (preg_match('/^www\.domain\.com$/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : !$_SERVER ['HTTP_HOST']) :
    case (preg_match('/^web001\.domain\.domroot\.com$/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : !$_SERVER['HTTP_HOST']) :
    case (preg_match('/^web002\.domain\.domroot\.com$/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : !$_SERVER['HTTP_HOST']) :
    //Include file that contains sensitive db string
    include_once 'sites/default/settings.live.php';
    break;

    ...

     }

D7 ? No need to do this!

First, talking about what you are doing, if it's for a Drupal 7 site, you do not need to do this in the first place.
Read the sites/example.sites.php for multisite settings.

$_SERVER['HTTP_HOST'] is almost safe.

See this great answer about how much secure $_SERVER variables are.

There is no point of sanitizing it either.

From Drupal.org post Writing Secure code,

  Whether you are writing a PHP snippet or an entire module, it is
  important to keep your code secure. Use check functions on output to
  prevent cross site scripting attacks

  No piece of user-submitted content should ever be placed as-is into
  HTML.

But you are not outputting anything or populating any variable so you do not need to sanitize any output here.


Is there a module for Image Sitemaps? I have been looking to expose the images hosted on my site to Google Images search. I was wondering is there is a Drupal 6 module to do that? I am on Pressflow 6.

I can see such modules available for Drupal 7 (see below). http://drupal.org/project/google_image_sitemap
AND
http://drupal.org/node/451234

The module http://drupal.org/project/google_image_sitemap has a d6 version but it was released after the d7 version :)


ICalendar and Outlook opeing as node For Add to Cal Module Even After Clearing Caches I installed the Add to cal module and enabled it.

Created a View using with fields or Event Date,Location and Title.

Thus when I added Event Date fields to the View and While Configuring i Choosed Formatter to Add to Cal.
The Add to Cal Works fine For Google and Yahoo calendar But When I choose The ICalendar or Outlook Option , corresponding node file gets open eg:- [website name]/node/207/field_date1/addtocal.ics but doesnt downloads the ics file.

I tried Clearing the Cache Varnish Cache as it hosted on the Acquia.com and also the Performance cache but that seems to not work.

I'm a maintainer of the Add To Cal module. It turns out that this is in fact a bug, which we're patching right now.

Until the patch is released, you can fix the issue by downloading and enabling the Entity module on your site. The patch will add this as a dependency to Add To Cal.

Here's the issue on drupal.org: https://www.drupal.org/node/1744684#comment-9056553

EDIT: The 1.x-dev version now includes this bug fix, and it will be included in the beta4 release.


Flags: flagging unflagging rules, how to check if an user has already flagged a node? I'm using Drupal 7 and I created 3 flags for article content type; these flags are global flags: bad, nice and cool. Now, I want create a rule in order to check if an user has already flagged an article.

For example: a user flags article as bad.
Now the user wants to flag the same article as nice.
Theoretically, the user must unflag bad and flag nice.

I want a rule that check if the user has already flagged a node; if yes, the previous flag must unflagged.

In Rules there are Rules Conditions that can execute php code, but flag api, has a $flag-is_flagged function that checks if an user flagged a node only if the flag is non-global flag.

Any idea?

What you're trying to achieve (= allow users to flag nodes by one out of 3 flags), is by design NOT something you can implement by using a global flag. Because global flags cannot be used by individual users. So I suggest you rethink/rework the design of those flags, so that they are NOT defined as global anymore. After you do so, you should be able to implement what you're trying to do, by using the Rules module, and with no need for PHP code. Read on for more details on how to do so.

Have a look at this rule (in Rules export format):

{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "IF" : [
      { "flag_flagged_node" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ]
        }
      }
    ],
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Some details about the above rule:

Rules Event: A node has been flagged, under "Nice".
Rules Condition: The flagged node is flagged with flag "Bad", by the flagging user.
Rules Action: Unflag the flagged node, for flag "Bad", by the flagging user.

You should be able to import the above rule in your own site, provided you first adapt the machine names of both flags (this_is_nice and this_is_bad) to fit your own machine names.

If nice is not sufficient (and it should be cool also ...)

If you want to implement similar logic for the "cool" flag, you can rework the Rules Condition and Rules Action in the sample rule above towards a Rules Component (say you name it "Disallow BAD flag"), and remove them from the rule shown above. Then clone this Rules Component towards a similar one for the "Cool" flag  (say you name it "Disallow COOL flag"), in which you change all "bad" to "cool". And finally invoke both Rules Components via an extra Rules Action (1 for each) in the sample rule above.

Or you can use the Conditional Rules module to consolidate both rules in a single rule. Here is a variation of the above rule (using flags with machine names this_is_nice, this_is_bad and this_is_cool), to illustrate how such rule would look like:

{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "flag_flagged_node" : {
                "flag" : "this_is_bad",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_bad",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          {
            "ELSE IF" : { "flag_flagged_node" : {
                "flag" : "this_is_cool",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_cool",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Easy, no?


How do I use the administrative theme? I'm building a custom Drupal theme and wondering if there is a way to get the modal windows to use the default admin theme. I'm using the Layout builder module with a custom block that uses the Media Library module and it uses jQuery UI classes.

This is also for the modal content like the media modal.

I think Media Library Theme Reset may be what you're looking for. From the module description:

  this module takes on the responsibility of replicating Seven's CSS and
  attaching it, as a library, in the context of the Media Library, when
  accessed via Layout Builder.


Failed to find the Facebook client libraries While trying to configure Drupal for Facebook, I followed the readme and copied their code into my settings.php and placed the facebook-php-sdk file into the stated location under sites/all/libraries but I still get this error:

  Failed to find the Facebook client libraries at sites/all/libraries/facebook-php-sdk/src/facebook.php. Read the README.txt and follow the instructions carefully.

I went to publichtml\sites\all\libraries\facebook-php-sdk-master\src and www\sites\all\libraries\facebook-php-sdk-master\src to check if facebook.php exists to be sure and it's there.

It's looking for the file in sites/all/libraries/facebook-php-sdk/src/facebook.php, while your file exists in publichtml/sites/all/libraries/facebook-php-sdk-master/src/facebook.php and www/sites/all/libraries/facebook-php-sdk-master/src/facebook.php. The difference is between facebook-php-sdk and facebook-php-sdk-master.

Change the folder name from facebook-php-sdk-master to facebook-php-sdk.


Drupal Core Auto Update? Is there a way to update Drupal Core without reuploading files and following the UPDATE.php file?  Something similar to how you can update a Wordpress install with a click of a button?  I wasn't sure if there is a module that will allow this?

--edit--

I've attempted the "drush up" command per @Enxebre's suggestion.

I installed Drush to my shared host and it seems to be running correctly. The site is still not updating though. I checked for updates and its still at 7.22 instead of 7.23.

I also had to run an update on Drush.
Here are my results from the terminal command:

Drush self update:

drush self-update
X-Powered-By: PHP/5.2.17
Content-type: text/html

A newer version of drush, 7.x-5.x-dev (2013-Aug-06), is available.  Would you like to back up your current drush, version 4.3-dev, to /home1/munortap/drush-backups/drush/20130912205746 and replace it with the newer release? (y/n): y

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Drush up:

[~/public_html/misadventureinc]# drush up
X-Powered-By: PHP/5.2.17
Content-type: text/html

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in         /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

If you like you can use the CMS Updater module to enable automatic Drupal core updates. Find the module on drupal.org here: https://www.drupal.org/project/cms_updater

If you need more information about the service behind, lokk here: https://cms-updater.com

Excerpt from project page:

  CMS Updater module helps you to keep your Drupal site secure at all times.
  Right after a new Drupal core release is published, this is recognised by the CMS Updater Service, which in turn will update your Drupal system.

  There is no need for intervention on your part – just check your mailbox from time to time, read your PDF update, and see if the automated updates have been successfully completed (or not).

  The use of this module requires the purchase of a CMS Updater licence key for € 29.99 incl. VAT. This fee covers one year of updates - your subscription will not be automatically extended, although you will be reminded when your subscription is close to expiring. You can buy the licence key directly in your Drupal admin area under /admin/config/system/cms-updater. If you need a hand or more information, visit https://cms-updater.com.

Emphasis on price added for purpose of this answer.


Node creation with parameters I have a form that when submitted and validated, needs to be redirected to a page to create a node (node/add/factura-tmn), but I want to send a parameter to this page. Is it possible?

I currently have the following code:

function add_invoice_file_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/add/factura-tmn';
  drupal_redirect_form($form_state);
}

Why not just use a modified node add form? You can change it to have whatever fields and validation you want.


How to display panes/views/blocks based on time of day and day of week? Building a D7 site, I need to be able to automatically enable/disable Panel panes and/or views (or in the worst case scenario blocks) based on the time of day - different contact info for out-of-office hours and some other stuff. I also need to display drastically different sets of panes and views on the frontpage based on the day of week.

My temporary solution is to set up a number of Panels pages (for changing panes/views) and duplicate themes (for changing blocks) and run cronjobs with Drush's variable-set to change frontpage from one Panel page to another and to change theme to the one with different blocks enabled.

As simple as the above is, it's a terrible long-term solution because all other, unrelated changes made to the site then often require being made more than once and it's really hard to keep track of.

So is there a more straightforward way to configure per-pane, per-view or per-block setting to get enabled/disabled based on time of day / day of week?

Oddly enough, it doesn't look like any of the Date modules integrate with ctools for selection rules.

I think you have two options, that are essentially the same thing.

Panel page variants support PHP code selection rules.
Panels panes support PHP code visibility rules.

So, your page(s) could have variants based on date/time, and each variant could have panes that are only visible based on date/time.

Your PHP selection rules will use time and/or date.  For example, this should set a rule to only select or be visible on Monday.

$now = time();
$day = date("D", $now);
return $day == "Mon";

The date function does default to the current time, but explicitly using a $now parameter can prevent problems when you call date multiple times when you cross midnight.


Search across multiple views I have a page with two view blocks in it, each pulling from different content types. Is there a way to allow the user to search both views at the same time? I want to be able to enter a search term and have both views be filtered by this term.

Edit: Going off of johnbburg's answer, I found a solution using Panels, but would really like to avoid adding Panels to the site. Perhaps I could use javascript to insert the search term into the other field?

You can set the "Filter identifier" for each exposed filter to use the same name. This is available under the "MORE" options in the filter's settings.

These will be used as GET parameters in the request and picked up by both views. This however also means that you can't use ajax with either views as they need to detect the parameter during a page request.


Clear all "pages" cache Is there a way on Drupal 8 to clear all "pages" cache or all "nodes" pages?

I was thinking about a custom drush command but I don't understand how to do this.

If you enable the settings documented in example.settings.local.php then you can easily see the cache tags that are present on a page.

What you will see then is that each rendered node has the node_view cache tag, so you only need to invalidate that.

There's also the 'rendered' cache tag which as added to any render cached item.

I don't quite understand why your cache warmer needs to invalidate the cache first, shouldn't be a problem if it's already warm? Drupal will automatically invalidate something if it is no longer valid.

The internal page cache also has no time limit by default.


Exposed Filter Not working in Views Json Query I am using Views Json Query to fetch JSON data from a URL and display result in a view.

I added certain filter criteria to the view, and created multi valued select option, But it is not working - When selecting each value it displays same results.

Try to use a contextual filter (CF) instead of a Filter criteria - When you pick the CF type - Make sure its one of the options that takes filters the data based on something from the URL (in this case, A JSON file name I guess as I Never worked with VJQ).


problem with hooking node add/edit form I wanted to hook node/add/patient-history form because I wanted to add ajax in that form.

Before adding Ajax I wanted to get field names correctly. So I tried this:

function ajaxify_form_patient_history_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_history_patient_id']['und'][0]['#value'] = "Hello";
  // I also tried
  $form['field_history_patient_id']['#value'] = "Hello";
}

They are not working.

I am not sure if I am taking the field names incorrectly or missing something else.

Hook name seems to be correct because this one works:

  $form['actions']['submit']['#value'] = t('Save History');

I found some similar questions on stackexchange but with no answers.

Any advice/links appreciated very much. Thank you.

I use this in my module to prepopulate the forms with data when hooking on FORM_ALTER:

$form['field_history_patient_id'][LANGUAGE_NONE][0]['value']['#default_value'] = "whatever";

But when defining the form it is enough to do :

$form['field_history_patient_id']['#default_value'] = "whatever";


Compare date field columns to restrict difference in days between the two I have an ad space website, where a person can place an advert, but for a maximum of 30 days.

To do this, I have a date field with a calendar popup and collect an end date on field. So it's one field collecting both dates. I need to validate the input of the end date by comparing it to the first field (start date).
I have the field validation module installed, but I'm not sure how to configure it.

How do I configure it? Or is there a better way to do this?

The field validation module does what you want, the interface description can be confusing.

On your Manage fields screen click the validate action link for your relevant date field.
For your field you want to add a Date range2 validation rule.
Name your rule in Rule name to a memorable description.
For column select value2 to validate your end date.
For Cycle of date select global so you can validate against time relative to the start date.
For Maximum date set it to "+30 day" (or any strtotime() compatible relative string) so that the end date is, at most, 30 days from the start date.
Set your your Custom error message.
Click Save rule.


How to configure the fields in the report created by the Content Audit module? I use the Content Audit module on my site.

Does anyone know how to configure the fields that are present in the resulting report beyond modifying the content_audit_report.views_default.inc file?

Have a look at the article about "Content inventory and content audit with Views". Here is an intro of it:

  Do you know the exact state of the content in your large Drupal site? Thinking of revamping, redesigning or upgrading your site? If you answered 'no!' to the first question or 'yes!' to the second question, it's time for content audit.

  In this blog post, I cover the what, why, who, when, where and how's of content audits. I've conducted a few small content audits, and I'm leading a much bigger one, on Drupal.org.

It's a pretty old article already (from 2011), and still contains Views2 screenprints. But it includes a lot of interesting details that should help to answer your question.

What is also interesting in this article are the recommendations to actually "evaluate your content", via a combination of these options (quote from the same article):

  Option A (Export): export this view to CSV and manage your content audit in spreadsheet software or Google Docs. The Views Bonus Pack module will let you export the view as a CVS file.
  Pro: Less data to store in your database
  Con: Your inventory is almost immediately outdated; will be extra time-consuming to update on a regular basis
  Option B (Flags): 'Flag' content that needs to be updated using the Flag module. You can adjust the flag settings so that only certain roles can use this flag, and then set which content types can be flagged (or set it as global). You can then add the Flag to the content audit view, and/or create a separate view of nodes that have been flagged. However, marking something as "needs work" doesn't provide enough detail, so you'll want to record notes somehow (see Option C). You can create additional flags for each type of action to be taken, e.g. "needs style review" or "redundant", without the casual visitor even knowing, while keeping your content team in the loop.
  Option C: Keep 'audit notes' field on each content type in Drupal site database with the Annotate module or by creating a field on the nodes.
  Option D: Use the Content Audit feature module, which constructs the View, and will soon have configured Annotation (this hasn't been built yet).
  Option E: Create another node type called Audit notes, and once filled in, then nodereference the node it covers. Then, it's easy to build a view of the Audit notes (I'm also wondering whether this could be a custom bit of code to automagically do this, then include in the Content Audit module).

Some more module suggestions to further enhance your content auditing experience (which you may want to use as complements to configuration facilities available in the Content Audit module):

Consider using the Flag module (as in that "Option B" above). And then possibly combine anything that might get flagged with the Rules module to trigger things like:

Unpublish and/or delete this content.
Add it to some type of review (workflow) process, like content accuracy, spell checking, etc.
Notify authors via eMails, like: "Please review this content, and use any of the available flags to indicate what your recommended action for it should be".

Auditors often like charts to visualize what's being audited (a picture is worth more then 1000 words ...). By simply installing (and enabling) the Charts module, and without any additional configuration, you get some Out-of-the-box examples that come with this module (in the format of some charts and/or a Views table display). They contain data about the total number of nodes for each of the available content types. And these data are limited to the nodes for which the user has permission to view them. Visit the Charts demo site for an online preview of of these out-of-the-box examples.


How do I include a class in a link inserted in an entitiy's link area? I want to insert a link to a ctools modal popup with a custom style (class) into the link area at the bottom of an entity (e.g. a node).  I do this using hook_entity_view_alter.  This is how the relevant part of my code looks like:

/**
 * Implements hook_entity_view_alter().
 */
function mymodule_entity_view_alter(&$build) {
  // Set up ctools etc. to use modal omitted for brevity.
  $build['links']['popup']['#links']['mylink']['title'] = 'show popup';
  $build['links']['popup']['#links']['mylink']['href'] = 'mymodule/nojs/modals';
  $build['links']['popup']['#links']['mylink']['html'] = TRUE;
 }

The code shown above inserts the following link in the right place:

show popup

However, this leaves out the class required to give the modal a custom style.  This what I really want to have this link look like:

show popup

Question: How do I get class="ctools-use-modal ctools-modal-mymodule-style" included in this link?

You can add the html attributes using the attributes key which accepts an array of attributes, and add classes using the class key, which also accepts an array of classes.

/**
 * Implements hook_entity_view_alter().
 */
function mymodule_entity_view_alter(&$build) {
  // Set up ctools etc. to use modal omitted for brevity.
  $build['links']['popup']['#links']['mylink'] = array(
    'title' => 'show popup',
    'href' => 'mymodule/nojs/modals',
    'html' => TRUE,
    'attributes' => array(
      'class' => array(
        'ctools-use-modal',
        'ctools-modal-mymodule-style',
      ),
    ),
  );
}

More information about available keys, refer to theme_links() function in Drupal API.


8 How do I display "Showing content between date1 and date2" on the current pager item? I am creating a list of content with a mini pager. I can't seem to find an option to print the date range of all the nodes being displayed in the current pager item. The content type has a date field. I would like to say "Showing content between date1 and date2" on each pager item based on the date field in the content type.

Clarification:
Except the date1 and date2 are the same field. This approach would not print the date range automatically based on a single date field... Let's say I have 100 node items with a NewsDate field. On each page, filter should show the the most recent to the latest date on top of each page. "Showing pages between "date range".

There is an other way for "Showing content between date1 and date2" use the Exposed filters  fields for the "Start date" and "End date" with Is between Operator. According to field created in the content type, From this You can easily filter the content according your filled date and set displayed items in pager.
Hope its helpful to you!