Help with content structure of a typical art gallery website As a way of learning a bit more about how Drupal 7 works, I'm trying to replicate the features of a local art gallery website. I'm having a few problems setting up the content types so I was hoping someone could point me in the right direction. I want to get all the content correctly configured and stored so I can then play around with Views and different ways of presenting that content. Here's what I've come up with having broken down the different types of data:

ARTIST will have one name, a bio and a website
ARTWORK will be associated with one artist only, will have a title, may or may not belong to a SERIES, will also have dimensions, an image, a year of creation, and will have the material used to create the artwork (term reference to a taxonomy vocabulary with terms such as "oil on canvas", "photograph", "mixed media" etc)
SERIES will be associated with one artist only.

So I've set up my content types. Well, the Artist and Artwork ones anyway, but how do I link them? I think I'm supposed to set up Artist as a taxonomy vocabulary, and list the Artist names as terms, and then when creating the content type Artwork have a term reference to it. This is OK but I don't want to have to manually add the term to the vocabulary each time a new content type Artist is created. So I guess what I'm asking is two questions:

Is my approach completely wrong? If so, please guide me in the correct direction!
If it's not wrong, is there some way to automatically generate the terms of the vocabulary Artist based on the Artist name? So when new Artist content is created, the term is automatically added?

This problem is often solved using the Node Reference URL Widget. Here is a video podcast on Node References and another on how to create a gallery.

You should use taxonomy to categorize the different series. Use Views to show the series will take a node reference relationship as an argument as well as the taxonomy id of the series.


How do I use and show a vocabulary with multiple fields? When I create a new vocabulary, I can create it in such a way that there are multiple fields. However, when I then create a content type with a field a term reference to that vocabulary, I only can see the name field from the vocabulary and not the other fields.

This regardless of the method I use, whether be radio buttons, check list, select list, autocomplete, autocomplete deluxe. I want to show those other fields so I can discriminate between two very similar, but with distinct values in the vocabulary.

For example, if it is a vocabulary of names, to add a date of birth which gets at least shown (and preferably is editable when adding a new term using autocomplete deluxe) when I fill in the form when adding an item of that content type.

What you're looking for is Entity Reference.  This will let you create a taxonomy term field on your content type and give you the option to render the entire term using the display of your choice (teaser, full etc).

Setting it up would be very similar to what you've already tried with term reference:

Create an entity reference field in your content type
Target type = taxonomy term
Set target bundle if preferred, then save
Under manage display, set the field format to rendered entity
Set the view mode to your preferred option (you would configure these options under your vocabulary manage display screen)


How to concatenate fields in Views with different separators (Settings)? I have 4 fields : lastname, firstname, middlename, suffix

I selected TABLE Format. In the Settings tab, I put all fields together in the first column so I can have them together in one row, but I want the display to be:

Jones, John David Jr

instead I can get

Jones John David Jr

or

Jones, John, David, Jr

In other words, the separator is applied between every field, and I want it applied only after the first.

I tried the UNFORMATTED LIST but that didn't provide me with any way to concatenate.

Solution 1:

As @rooby suggested here are the steps you can follow

Add the fields Last Name, First Name, Middle Name and Suffix to the view in the same order
For the first 3 fields Last Name, First
Name, Middle Name select the option "Exclude from Display" and save.
In the settings of the field "Suffix" check the option "Rewrite
the output of this field" under the section "Rewrite Results".
In the TextArea that gets displayed enter [field_last_name],
[field_first_name] [field_middle_name] [field_suffix]

For the exact field names you may click on the link "Replacement Patters" below the text area.

This approach works fine if the Suffix field is a required field and all the records for it. If not the complete value is not displayed if the suffix is empty.

Solution 2:

Add the fields Last Name, First Name, Middle Name and Suffix to the view in the same order
Add "Global: Custom text" field to the view at the bottom of all the fields.
For the fields Last Name, First Name, Middle Name and Suffix select the option "Exclude from Display" and save.
In the settings of the custom text field enter [field_last_name],
[field_first_name] [field_middle_name] [field_suffix] under "Text" and save
Look at the replacement patterns for the exact field names in your system

This approach works fine even if there are empty values for any of the fields.


Token path to file URL, filename, etc.? I'm writing a Rule that sends an email when a user uploads a file to a node. How would I output the file's URL and filename in the body of the email?
First, some things to note:

This is an Entityform node
The File Upload field is a mulit-value field
Drupal 7 site

In rules, when I use the replacemement token for the File Upload field...
[entityform:field-file-upload]
...it returns...
property 0, property 1, property 2
There are three files uploaded to this Entityform node, so it appears that Drupal is accurately reporting the correct number of files. But this is all the info I've been able to can extract.
I've tried to change the token in few different way, like these:

[entityform:field-file-upload:file:url]

[entityform:field-file-upload:0:file:url]

[entityform:field-file-upload:url]

[entityform:field-file-upload:0:url]

These all return nothing. What is the corrent token string to return URL, filename, etc.?

Through some trial and error and some further digging, I figured it out. Here's what works:
URL: [entityform:field-file-upload:0:file:url]
Filename: [entityform:field-file-upload:0:file:name]
Upload date: [entityform:field-file-upload:0:file:timestamp:short]
Increment the 0 to return more files from the multi-value array of uploaded files.
Once I had the basic syntax, the Drupal List of Tokens page was particularly useful.


When adding a node, the site images do not show I have some image links that are inside standard  tags, that link to some external sites. Example:

The images display no problem, until I go to add a node of my custom content type "Front Page Announcement". Then, the images do not display - i.e. the path to the image cannot be found.

I URL I get is: http://localhost/bedsastro_new/node/add/front-page-announcement
And the images are in assets/site-images/

When I look at at where the browser is expecting the image to be, it's :
http://localhost/bedsastro_new/node/add/front-page-annoucement/assets/site-images/pic.jpg

How do I ensure that Drupal is looking at right location for the images (i.e. http://localhost/bedsastro_new/assets/site-images/pic.jpg) ?

Thanks!
Daz

It seems that the root of your Drupal site is http://localhost/bedsastro_new/ .

To reference an image with filename pic.jpg (using an img tag) which is located in the site's subfolder named assets/site-images, you should specify /assets/site-images/pic.jpg as the value of the src attribute within the img tag.

With that, Drupal will try to find that image at http://localhost/bedsastro_new/assets/site-images/pic.jpg, which is where your image is actually located, so that should work.


How can I insert a variable into query condition? I am writing a query, and the question is how can I insert an array variable into condition statement. So instead of having (1060,968,1106) I would like to place there an array.

$fields; // array with some predefined ids
$query = $this->connection->select('node', 'node');
$query->innerJoin('node__field_field', 'nfc', "nfc.entity_id=node.nid AND
                (nfc.field_field_target_id IN (1060,968,1106))");

I tried

$query->innerJoin('node__field_field', 'nfc', "nfc.entity_id=node.nid AND
                (nfc.field_field_target_id IN ".$fields." )");

But it doesn't work, could you please help me?

Outside of extreme circumstances, never, ever concatenate variables into an SQL string. You'll leave yourself open to SQL injection.

It feels like you should be using an entity query for this, but for the sake of the exercise, use a placeholder and pass the arguments in:

$args = [
  ':fields[]' => ['id_1', 'id_2', 'id_3'],
];
$query->innerJoin('node__field_field', 'nfc', 'nfc.entity_id=node.nid AND nfc.field_field_target_id IN (:fields[])', $args);


Pre process a template that uses layout display I want to preprocess a user account display. I want to manipulate a field value at display time.
for example, i want to change:
field_prefered_color: redto :
field_prefered_color: red - Cool, that is used 5 times today.
If I don't use layout builder I can easily change that in
function mymodule_preprocess_user(&$variables) {
  $variables['content']['field_prefered_color'][0]['#context'][['value'] .= t(' - Cool, that is used @times times today,['@times' => $times]);
}

But when I use layout builder, where can I find field_prefered_color to manipulate its output?

It appears quite easy to achieve what I want:
I needed to create a conditional field functionality. I know there is a module for that but at this time the module is not stable and not performing well with layout builder.
As indicated by @CG Monroe the last called template is field.html.twig.
If this is a user field the fully loaded user is available in:
$variables['elements']['#object']

So I could access all the user fields I needed to manipulate the field output in the preprocess function
function my_module_preprocess_field(&$variables) {
  $field = $variables['elements']['#object']->field_some_other_field->value;
  // now I can manipulate the output of the field being viewed
  // the manipulation is needed because of the value of "some-other-field"
  $variables['items'][0]['content']['#context']['value'] = ' ***  ****';
  $variables['items'][0]['attributes']->addClass('my-module-field-manipulated');
}


Migrate API - Multiple multi language images in nodes I am using "migrate api" for migrate content from another database (not drupal database).

I need migrate multilingual content with multiple images associated where alt and title are also multilingual.

How must I build this migrate yml for the images?

I have the next config for a unique image file:

'field_image/target_id':
    plugin: migration
    migration: news_image
    source: file
'field_image/alt': 'alt text'

but I don't know how build this config for save multiple values instead one. I searched for examples and in documentation but I didn't find anything similar.

I don't need a manual, only a orientation of how must be the configuration.

Thanks!

In the end, it was easy. Just follow the steps below:

Import files (only files, without alt and title)
Import content. For the field of image must have all the identifiers of the images and the alt and title. It is necessary to use the iterator plugin.

  field_images:
    plugin: iterator
    source: IMAGESVAL
    process:
      target_id:
        plugin: migration
        migration: news_images
        source: fid
      alt: alt
      title: alt


Trouble getting block to display after module enabled I've created a drupal module, it's info file, and a tpl.php for the block all in the same module directory.  When I enable the module, I can see the block listed and assign it to a region.  However when I view the page the block does not display.  If I do a vardump on $content within block_view, the dump displays at the top of the page, and firebug shows that block is wrapped with the right div tags.  I would think if you did a var dump on within the block_view function, it should display in the right region.  This one is probably really simple, but it's got me stumped - any help much appreciated.  Also if I title the block just to see if it shows up anywhere in the page - it's still nowhere to be seen even though admin shows it it in the region, and no filters are set to prevent it being viewed.  I would think that if you gave the block a title -if it's on the page it would at least show a title even if everything else is blank.

module file:

function my_block_block_info() {
   $blocks['my_block'] = array(
      'info' => t('My Block')
   );
   return $blocks;
}

function my_block_block_view() {

if(arg(0) == 'node' && is_numeric(arg(1)))  {
    $id = arg(1);
}
   $query = "SELECT * FROM table WHERE id= :id AND deleted=0";
   $args = array(':id' => $id);
   $result = db_query($query,$args)->fetchAll();
   foreach($result as $item) {
     $stuff[] = array($item->stuff_url,$item->stuff_name);
   }
   $content=
      theme_render_template(drupal_get_path('module','my_module').'/'.'block--         my_block.tpl.php',array("stuff" => $stuffs));
   return $content;
   }

 block--my_block_tpl.php

<div class="wrapper">
 <?php

 foreach($stuffs as $thing) {
 for($i=0; $i < count(thing); $i++) {
       //print out result passed from module
  }
  }
 ?>
 </div>

your hook_block_view() is implemented in a wrong way,

first pass in argument delta as a parameter
you should put the contents of your block inside the $block['content'] variable.
return $block;

heres a very good tutorial
building a custom block


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

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

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

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


How to diagnose an undefined index in a fresh install of Drupal 7? Question:

How do I begin to explore what is causing this error? If this were reporting errors from a contrib module, I would submit a bug report on drupal.org. However, I'm not really sure where I should begin to submit an issue.

Set up:

I installed a Drupal 7 instance installed via Quick Drupal

drush qd -y d7-mysite
cd mysite/drupal
php -S localhost:8080

And immediately installed needed modules via drush en -y field_collection_tabs workbench workbench_moderation

Field Collection 7.x-1.0-beta11,
Field Collection Tabs 7.x-1.0-beta11,
Workbench 7.x-1.2, and
Workbench Moderation 7.x-1.4.

Then the errors:

After a modicum of configuration to get work bench going and adding a writer user, I begin to see these error messages:

  Notice: Undefined index: #contextual_links in
  contextual_pre_render_links() (line 140 of
  /drupal/modules/contextual/contextual.module).

  Warning: Invalid argument supplied for foreach() in contextual_pre_render_links() (line 140 of
  /drupal/modules/contextual/contextual.module).

  Notice: Undefined index: #contextual_links in contextual_pre_render_links() (line 140 of
  /drupal/modules/contextual/contextual.module).

  Warning: Invalid argument supplied for foreach() in contextual_pre_render_links() (line 140 of
  /drupal/modules/contextual/contextual.module).

  Notice: Undefined index: #contextual_links in contextual_pre_render_links() (line 140 of
  /drupal/modules/contextual/contextual.module).

  Warning: Invalid argument supplied for foreach() in contextual_pre_render_links() (line 140 of
  /drupal/modules/contextual/contextual.module).

Location:

This is coming from a function called contextual_pre_render_links($element)

Other Tidbits:

This only happens when the Authenticated User creates new node. Administrator can create a node with out an error message displaying.
I'm trying to implement a work-flow system using Workbench on an inherited site. I'm trying to understand this process so that I can teach others.

In this development copy I've turned off Contextual (drush dis contextual) which of course gets ride of the error message.

I welcome any other answers that might offer a bit of enlightenment to me on this matter. We can live without the Contextual module's functionality but it does add some additional clicks to accomplish certain task.


How can I render more than one field value in the controller? in my case i have a controller that it send for me the title , to the view , but i want to send the tittle and the body of the article both , i have tried to send them from the controller but it doesn't work for me
how can i send them both from the controller (title and body) ?

here is tmy controller

 public function myPage() {
    $data = \Drupal::service('myservice.ran');
    $dataService = $data->getArticles();
    return $this->renderMyPage($dataService);
  }
  function renderMyPage($articleObjects) {
    $articles = [];
    foreach ($articleObjects as $article) {
      $articles[] = [
        '#type' => 'html_tag',
        '#html_tag' => 'h2',
        '#value' => [$article->title->value,$article->body->value],
        '#cache' => [
          'tags' => $article->getCacheTags(),
        ],
      ];
    }
    return $articles;
  }

What I suggest is the this solution, create a custom template, for your page, in controller pass the data to the twig template.
public function myPage() {

    $data = \Drupal::service('myservice.ran');
    $dataService = $data->getArticles();
    $articles = [];
    foreach ($dataService as $article) {
      $articles[] = [
        'title' => $article->title->value,
        'body' => $article->body->value,
      ];
    }
    $build = [
      '#theme' => 'my_template',
      '#data' => [
        'articles' => $articles,
        'whatelse' => "what esle I want"
      ],
      '#cache' => ['max-age' => 0],
    ];
    $output = \Drupal::service('renderer')->renderRoot($build);
    $response = new Response();
    $response->setContent($output);
    return $response;
  }

then all the data will be available on data in your custom twig template. ( you can change its name to whatever you want).
just be sure you clear the cache when you create your custom template.
A helper article


How to extend the basic user object upon installation? I need to build a module to handle Users profiles, and need to extend automatically the basic Drupal user object upon installation.  For Drupal 7 I found a way with:

field_create_field($field);

But this function is not available in Drupal 8, BTW totally noob on Drupal, Learning while working on it.

Fields, like most other things, are configuration (entities) now.

That means you don't have to write code to create them, you can simply create them in the UI, then export them through the Configuration management UI and put the relevant files into your config/install folder. Drupal will automatically import all your configuration from that folder.

Note that a field commonly consists of 4 parts:

The field storage, a file named field.storage.user.yourfieldname.yml (or node, comment,... for other entity types). This defines the field and storage relevant configuration.
The field, a file named field.field.user.user.yourfieldname.yml (user is special because there is only one bundle, for nodes, it would e.g. be node.article). This defines that a field is available on a specific bundle and includes configuration like the label.
One or multiple form displays, for example named core.entity_form_display.user.default.yml. User by default has two form modes, default and register. Node by default has only one. This stores the widget configuration for the field.
One or multiple view displays, for example core.entity_view_display.user.default.yml. This stores the formatter information for a specific view mode.

The first two files can just be copied to your config/install folder. The other two are bit more complicated, because they contain the widget/formatter configuration for all fields of that entity type, bundle and form/view display combination. So in the case of user for example, you do need a bit of code to add the configuration to the existing form/view display. See node_add_body_field() for example code. You can get the exact settings from the exported files.

If you own the bundle, for example, if your module defines a node type with a numer of fields, you can also just add those form/view displays to the configuration folder.


How to use #ajax trigger_as? I'm trying to figure out how to trigger an element with a link in a form using trigger_as.

I tried the following snippet. The button ajax callback works, but the link doesn't. The link does seem to use the right name and value in trigger_as (as seen in the js console), but the post callback doesn't return anything.

$form['add_more'] = array(
  '#type' => 'submit',
  '#value' => t('Add another item'),
  '#attributes' => array('class' => array('add-more-submit')),
  '#submit' => array('field_add_more_submit'),
  '#name' => 'result_fields_add_more',
  '#ajax' => array(
    'callback' => '__update_fields',
    'wrapper' => 'example-wrapper',
    'effect' => 'fade',
  ),
);

$form['add_more_link'] = array(
  '#type' => 'link',
  '#title' => t('add'),
  '#href' => '#',
  '#process' => array('ajax_process_form'),
  '#ajax' => array(
    'callback' => '_update_fields',
    'wrapper' => 'example-wrapper',
    'effect' => 'fade',
    'event' => 'click',
    'trigger_as' => array(
      'name' => 'result_fields_add_more',
      'value' => t('Add another item'),
    ),
  ),
);

I tried to follow this example, but didn't work: http://drupal.org/node/753270#comment-2910362
I also didn't find an ajax link in the rules module, only a button with an ajax callback.
I thought I followed the documentation correctly: http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax_trigger_as

EDIT: One fix is to trigger the submit event through javascript code, but I was really hoping the form api would be able to handle this itself: https://drupal.stackexchange.com/a/34375

No support for links, but for what its worth heres a working snippet that uses a select.

When the select changes it triggers the submit buttons callback.
Note, you still have to define the callback on the select box as ajax.inc assumes all ajax enabled elements have one.

<?php

  $submit_name = 'product-submit-' . $node->nid;
  $form['product_id'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'my-form-wrapper',
      'callback' => 'product_change_callback',
      'trigger_as' => array(
        'name' => $submit_name,
      ),
    ),
  );

  $form['submit'] = array(
    '#name' => $submit_name,
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'product_change_callback',
    ),
  );
?>


Ajax Form to pull two different views I have two different views that need to be toggled on a node page.  I cannot put these two views together so I have created a form that will basically take the values of the form that I create, and send them as arguments to the view and display the view.  I am attempting to do with this ajax.  It works fine but the problem is the second time I run the form it does not refresh or update that view.

function photoflight_albums() {
    photoflight_gallery_themes();
  $output = render(drupal_get_form('photoflight_gallery_form'));
  $output .= "
";
  $output .= views_embed_view('gallery', 'default');
  $output .= "
";

  return $output;

}

//Grabs the node titles
function photoflight_gallery_themes(){
    $type = "photo_theme";
    $theme_list = array();
    $nodes = node_load_multiple(array(), array('type' => $type));
    foreach($nodes as $themes){
        $theme_list[$themes->title] = $themes->title;
    }
    return $theme_list;
}

//Form calls back to the function above to the gallery-ajax-wrapper div output above
    function photoflight_gallery_form($form, &$form_state){
        $form = array();

  $form['themes'] = array(
    '#type' => 'select',
    '#options' => array(photoflight_gallery_themes()),
    '#ajax' => array(
            'callback' => 'photoflight_simplest_callback',
            'wrapper' => 'gallery-ajax-wrapper',
        ),
  );
  //debug($form);
  return $form;
}

//Ajax callback
function photoflight_simplest_callback($form, $form_state) {
    $view = views_get_view('gallery');
    $args = array( 'title' => $form_state['values']['themes']);
    $view->set_exposed_input($args);
    $output = $view->preview('default', $args);
    return array("#markup" => $output);

}

The issue was that it was removing the HTML element so the second call had no HTML to replace.  Changed to either use ajax update or on the call back wrap the return in the div again


How to render a multiple value field of type generic file If I use the textformatter module (included textformatter_contrib) I can display a repeatable field with links as a list.

By selecting 'list' as format for the full view of the field of the content type.
I can't select 'list' for the file field.
The default format for my file field is 'generic file'

That module provides formatters for the following field types:

entityreference
node_reference
user_reference
link
field_collection

(gathered from here).

There's no support for file fields so you'll need to either implement the functionality yourself, or file a feature request to the Textformatter issue queue.


Why does the same form/field appear diffently depending on the browser? I have a custom content entity created with Drupal Console and the corresponding CRUD forms.
In this entity there is a field defined this way:

$fields['startdate'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Membership Start Date'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))

The way this field appears when in edit mode is completely different depending on the browser (see screen captures).

The most 'annoying' being the displayed date format: mm/dd/yyyy with Firefox, yyyy-mm-dd with Safari. The only correct would be dd/mm/yyyy in Chrome.
Because the users of this site are french people that are used to dd/mm/yyyy...
Of course, the settings of my site (language, date and time, etc.) are 'French'.

Any idea how I can fix this and have the same behavior whatever the browser?

The primary confusion around this is that the widgets (the code responsible for field input) for datetime, datetime range, and timestamp fields use HTML5 date/time input elements (except when using the select list version).  One for the date portion, and one for the time portion.

The browser, not Drupal, renders out HTML5 date/time input elements.  So, the actual UI will vary from browser to browser, and OS-to-OS.  In addition, not all browsers support these inputs.

When a browser encounters an input element type it doesn't recognize, it defaults back to plain text entry.  In this case, Drupal provides a polyfill for the date portion based on the jQuery UI component.  There is an issue for the time element, but it currently languishing in the queue.

It looks like from your screenshots, Safari is using the polyfill and the rest are using the browser versions of the inputs.

The "yyyy-mm-dd" format for Safari, is a side effect of the fallback.  The HTML5 input elements require dates in that format, so that is how the widget gets configured and rendered out.  The native elements are using a localized version of the inputs, and handling the conversion behind the scenes so that Drupal gets the right format.


How do you render a View with arguments using a Computed Field? I have a computed field and i want to output a View's - block display with arguments passed into it. Can someone provide me with an example code of how to output a view with arguments?

thanks!

The long way:

$args = array(ARGUMENTS);
$view = views_get_view('VIEWNAME');
print $view->preview('block_1', $args);

The short way:

print views_embed_view('my_view', 'block_1', $arg1, $arg2);

Also keep in mind since this is dynamic data, you will need to uncheck the checkbox on the field settings page or else it will try to store the data thats generated upon saving the node.


How to disable module warning "User warning: The following module is missing from the file system" only visible on update.php? I have a warning when using the update.php. This warning is not visible when using : drush cc all

  User warning: The following module is missing from the file system:
  aaa. For information about how to fix this, see the documentation
  page. in _drupal_trigger_error_with_delayed_logging() (line 1128 of
  C:\www\arlande.nl\includes\bootstrap.inc).

I did run all solutions basis on : https://www.drupal.org/node/2487215

Finally I found out:
There is a record in the system table. If I delete this line using drupal it is oke and the warning is gone.

However when I use  update.php script again the warning is there again and also the record is again available in the system table.

Information in the system table is indicating: The type is a module again but the file reference is not in modules but in profile.

  profiles/aaa/aaa.profile

Big change this is profile of the initial installer but is not there any more and I'm not able to get this anymore.

I scanned all code to see if a hook is used but that 100%  not the case, so the reference should come from somewhere inside the database.

Any suggestion where the update.php file is getting this reference from in the database and/or how to solve this?

Probably you haven't uninstalled the module, so you've to either:

restore the module to its original location and uninstall it,
or manually remove all traces of the module in the database (not recommended) by:

using Module Missing Message Fixer (Drupal 7)
using Drush command:

Drupal 7

drush sql-query "DELETE from system where name = 'old_module1' AND type = 'module';"

Drupal 8

drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='module_name';"

When it's done, clear the site's caches: drush cr.

Or use Devel module by going to: /devel/php and execute:

$query = \Drupal::database()->delete('key_value')
      ->condition('collection', 'system.schema')
      ->condition('name', 'module_name')
      ->execute();

See: How to fix "The following module is missing from the file system..." warning messages.


Error generating images I was experiencing weird GD library issues with Drupal 8, when the site tries to generate thumbnails from image style. I am using Docker PHP.

The error is simply saying Error generating image. I checked the logs, but I didn't find anything helpful.

This is the fix for the issue.

The code taken from duplicated issue in https://stackoverflow.com/questions/36359917/docker-gd-module-for-php-7

Please take this with heaps of grain and salt, and modify the script accordingly.

# Install GD
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng12-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install gd

What is actually happens is your GD library is installed BUT without JPEG library configured. Your Drupal will be chill saying GD installed but there is hidden requirement that JPEG need to be exist too.

The line 179 in GDToolkit.php:

$function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);

Causes the function imagecreateformjpeg fails to be executed.

Hope it helps someone that confused, cant generate thumbnail with limited knowledge of the errors.

:)


How to implement a "switch" in a rule set? I would like to make a rule set that functions as a switch with breaks in PHP.  Example:

Rule 1- User has role A, redirect to 1
Rule 2- User has role B, redirect to 2
Rule 3- User has role C, redirect to 3
Rule 4- no conditions, redirect to 4

In other words:

If a user has role A, redirect to 1.
If a user has roles B and C, redirect to 2.
If a user does not have roles A, B, or C, redirect to 4.

Is there an easy way to do this in Rules?

Declare a variable called "done".

First rule in the set checks for role A, sets done and redirects.
Second rule in the set checks if done is true, and role is B, sets done and
redirects.
Third rule in the set checks if done is true, and role is
C, sets done and redirects.
Fourth rule checks if done is true,
redirects.


Add webform to content type I would like create a webform and add to content type. so when user create node, webform automatially add to node (webform is same for per node of content type).

is this feasible with webform 3?

You can do it by node reference. Add those kind of field to your content type. You can always set default value for automatic add webform to node, but it doesn't add you form automatically to node edit form.

I test it by using node reference and views, but it doesn't display a webform on node edit page (in the same form).

You can try to use hook_from_alter, which means to add programatically fields from reference webform. IMO is the only solution or maybe there are some modules for this, but I didn't look for them.

You need add your submit function to this form too, because you need to filter and save webform fields programatically too. Check WebForm API for this. A lot of work, maybe you should think about better solution without programming and using webform at all?


How to make a view list entities, not translations? I need to list content entities in their original languages, but views module shows all content translations.

I need something like grouping by entity IDs.

I think the proper filter is the following:

"Content: Default translation (= True)"


jquery and an if statement Drupal 7. I have a radio button set. When one of the items is selected I would like it to set the node add title to some string. This is as far as I got, but I get the error: "TypeError: '[object Object]' is not a function (evaluating '$("#edit-field-i-need-help-with-und-printer-ink")')"

(function ($) {
      Drupal.behaviors.cgps_helpdesk_misc = {
        attach: function (context, settings) {
          $("#edit-field-i-need-help-with-und-printer-ink").change(function ($) {
              if ($("#edit-field-i-need-help-with-und-printer-ink").attr("checked")) {
                alert('Handler for .change() called.');
                $('#edit-title').val($('#edit-title').val() + 'bla bla bla');
              }
          });
        }
      };
    }(jQuery));

What MPD is saying is change this line:

$("#edit-field-i-need-help-with-und-printer-ink").change(function ($) {

to this:

$("#edit-field-i-need-help-with-und-printer-ink").change(function () {

You have declared two functions as $ and that may be killing the script.


issue with Clean URLS I've just moved my drupal site from it's development server(just a VM on my home pc) over to it's new home, and all except the URLS are working.

I've setup the new server exactly like the development server, installed mod_rewrite, copied .htaccess, apache2.conf and httpd.conf word for word, yet, regardless of which page/node is displayed, the only thing in the URL is the domain name.
And if I try to navigate to a specific node via the URL, it loads the front page instead of the intended node.

I'm not sure if this is related, but when drupal provides a link to a node, like the Welcome email for first time login, it uses the server's IP address in the URL, instead of the domain name.

Any help with this would be greatly appreciated!

Cheers,

Matt

It sounds like with the 'Forward to' configuration for your domain, it may be iframed instead of the domain pointing directly to your server.  When you type a direct url, the path isn't passed on to your actual site so it only serves the homepage, and when you click on links it only changes the url of the inner frame so the address bar doesn't update.  You can check if the page is actually in an iframe by viewing the source of the page.

For setting up the DNS, you should be creating an 'A' record to point the hostname directly to your IP address.


How to enable/disable Billing Information in Commerce depending on the payment method Till now, I have been using only PayPal checkout on my Commerce site, and I have configured the checkout flow so all of the customer's information is collected over on PayPal's site.

However, I am now trying to add Stripe as an alternate payment method.  I need to collect the customer's billing info on my site when using Stripe, so I need to add Billing information to the checkout pane.

Goal

Show Billing information if the customer selects Stripe as the payment method.  If the customer selects PayPal, do not show Billing information.

I looked through the various commerce events and actions available in the Rules module, but I couldn't find anything that is helpful for this case.

There is no way just through Rules to influence the visibility of a checkout pane. Instead, you'll need to use hook_form_alter() and hook_commerce_checkout_pane_info_alter(). Why both?

You have to use the form alter to remove or disable the billing information checkout pane when you detect PayPal has been selected, which means you also need the payment method selection to be first (and, in the most simplest case, on its own page).

You have to use the checkout pane info alter to set your own validate and submit callbacks for the billing information checkout pane. These should also check the payment method and only invoke the default callbacks if the proper payment method was selected. The reason for this step is that the checkout form validates / submits checkout panes based on where they're configured to appear in the checkout form, not based on whether or not they were actually present on the finally rendered form. You can alter a pane out of the checkout form's array, but its default validate callback will still process it as if it had been there.

To determine what payment method was selected, look in $order->data['payment_method'].


Using Site A to authenticate users of Site B? Is there a module that will pass the authentication request off to a second Drupal site, ideally to an out-of-the-box services endpoint?

There are some similar questions about login integration with other systems, but I couldn't find a Drupal-to-Drupal question.

Have you checked out the Multisite Login module? This allows sharing logins across different domains, and I've had luck with it. They also have a Drupal 7 version available in dev.


How to redirect a user to the current page? How can I redirect user to the current page using Drupal\Core\Link?

I am creating a breadcrumb where I want to redirect user to the current page

Like this you get the actual path:

\Drupal::service('path.current')->getPath()

and then you just use it as:

$current_page_link = new Drupal\Core\Link('So here you are', Drupal\Core\Url::fromUri('base:' . Drupal::service('path.current')->getPath()));


How can I replace all my internal links automatically? I have changed the domain of my website from www.mysite.com to mysite.net. I upload the site to the new domain and all is fine, but I have more than one thousand nodes, and in almost all the nodes I have a link to another node on the site.

The link are absolute so they have this form: www.mysite.com/node/22 and I need to change all nodes to the new domain.

Changing 1,000 links manually is too much. How can I do this automatically??

Why are you using absolute links? If you were using relative links, of the form /node/22, the problem would not arise.

I am assuming you are using Drupal 7. The answer for D6 would be a little more complex.

If the links are in the node body, and if you have direct access to your database, you can update the text by running a query on the field_data_body and field_revision_body tables.

First, back up your database in case this goes wrong.

Then run the following query on your tables:

UPDATE field_data_body SET body_value = REPLACE( body_value, 'a href="http://www.mysite.com/','a href="http://mysite.net/');

Repeat with the field_revision_body table.

This should change all references to the old domain with the new domain.

If you have links in the comments, you might also want to do field_data_comment_body and field_revision_comment_body, scanning for references in the comment_body_value field.

In the event the links are being generated automatically by a text filter, change the REPLACE patterns accordingly.


Field API - which hook to use? I have successfully created a field with my module and managed to show it on user registration form. The next step would be validating my field. There are two hooks for this, and I'm confused as to which one to use. One is hook_field_validate and the other is hook_field_attach_validate. I'm also confused as to how to refer to the field. $instance['user']['field_tckn_no']? (This is what dpm(field_info_instances('user') shows me. Also, one thing that confuses me is that hook_field_validate iterates over the fields but all I have is one field. Is it still the one to use?

Regards,
K.

Well, at last I was able to figure it out. Since the field was part of the form after creating the instance, I thought I could use hook_form_alter, and I was right!


view to list already added referenced nodes to all content types by user I have a content type of DELIVERY, and another content type of BOOK. Now each user has 3 DELIVERY content types that they are the author of. What i do is then edit a users DELIVERY content and add a BOOK to it (i have added a entity reference, referencing BOOK in DELIVERY).

All works fine, what i want to do is create a View, so that when i edit a users DELIVERY it lists the BOOKS i have already assigned to all the other DELIVERY's from that user. is this possible? been playing around with it but cant figure it out.

OK i managed to do it, for anyone curious heres how i did it:

I created a new View
I filtere it to show content of type DELIVERY
i added 2 Relationships
First relationship being the BOOK Reference field and the other being Author relationship
I then added a Contexiual Filter of NID and set it to default value and NID From URL
That was it, and i added the Book ref field to show the books


Running 'composer update' replaces module folders I'm going through the nightmare of trying to update a site to 8.4.4 from 8.3.2. It seems like the best way forward is to delete vendors and composer.lock and let composer replace everything. However, when I do this, it also goes through and replaces all of my module folders as well. A number of them are patched, so replacing them straight out of the gate simply doesn't work.

Is this normal behavior for composer? Is there some way to specify that I only want to replace what's going into the vendor directory?

Is this normal behavior for composer?

Yes

  Is there some way to specify that I only want to replace what's going into the vendor directory?

Sure, remove the reference to the module(s) from composer.json. Obviously at that point you’ll need to manage any updates for them yourself.

A better resolution would be to install Composer patches, and patch the modules automatically as they’re being installed/updated.


Modifying the properties and output of a select list when adding content with the admin Drupal 7 I have a type of content. Depending on the domain (I use Domain Access), I want to show a different content in a field which is a select list with reference to term. By several reasons, I do need to do this programmaticaly, to have full control. Also need to change the property: "required" of the field on-the-fly. What hook should I use, is there some example where I can look at? Thanks.

You need hook_form_FORM_ID_alter() or hook_form_alter() to modify the select list. Something like this should work:

// form_alter hook for "mycontent" content type.
function mymodule_form_mycontent_node_form_alter(&$form, &$form_state, $form_id) {
  switch ($_SERVER['SERVER_NAME']) {
    case 'domain1.example.com':
      // Remove term 2 from select list.
      unset($form['field_myfield']['und']['#options'][2]);
      break;
    case 'domain2.example.com':
      // Make term reference field required.
      $form['field_myfield']['und']['#required'] = TRUE;
      break;
  }
}

Bear in mind that you can't just add new terms to the select list since they will fail validation when the form is submitted. You can only choose which existing terms to include in the list.

What you could also do is create different fields for different groups of terms and unset whole fields depending on the domain so that only the relevant field is displayed.


Is it possible to hook to variable_set() event? I would like to track the system changes event, to make them revertable. When checking variable_set(), I see there is no hook provided for that event. Is there any way for me to do this?

I can alter to hook to settings forms, but there's a lot of settings form to track, if I can hook to variable_set() directly, code becomes much simpler.

I can also track the variable changes with features + strongarm modules, but it's better if Drupal admin can browse the variable history without code touching.

It seems that it's impossible using only Drupal, which means:

variable_set() itself doesn't invoke any hooks, but it uses db_merge(). That function is using the MergeQuery class. Now, it would be nice to hook with hook_query_alter(), but it only works for query classes that implements the QueryAlterableInterface interface. Sadly, this interface is now implemented only by the SelectQuery and the SelectQueryExtender classes, not by the MergeQuery class.

Note that even if you will find a way to create a child class of MergeQuery, that will implement QueryAlterableInterface, and make Drupal use it. hook_query_alter() only works on queries that have tags, and variable_set() doesn't tag its query, so the hook would not be used anyway, unless you are willing to hack core. But if you are, you don't need all that, you could simply hack in a hook call.

If you feel hardcore you can use a more indirect PHP approach: $conf is a global array of configuration variables; you can write a module that will replace it with object acting like an array, as described on Stack Overflow. To make it a good substitute you need to implement ArrayAccess. Pull all values from original $conf into your object. Then, in ArrayAccess::offsetSet() implement your logging logic.


Custom node access control not working with access filter? In some of mine content types I have checkbox field "Content protect". If checked that node should be visible only to registered user. If not checked - visible to everyone:

function hook_node_access($node, $op, $account) {

  // If $node is a string, the node has not yet been created. We don't care
  // about that case.
  if (is_string($node)) {
    return new AccessResultNeutral();
  }
  if ($node->hasField('field_content_protect')) {
    $protected = ($node->field_content_protect->value == 1) ? TRUE : FALSE;
    $userId = $account->id();
    if ($protected && $userId == 0) {
      return new AccessResultForbidden();
    }
  }
  return new AccessResultNeutral();
}

And this works well when I try to access node directly. If it's protected anonymous users can't access it.

Now, I have a view that lists some of those nodes. I want to apply same logic and to exclude protected nodes for anonymous users. So in my view I added filter:

Content access: Access

But it's not working as expected. For authenticated users content is there, but for anonymous users simply whole block content is missing?!? Nodes that don't have this "Content protect" field checked are also not listed?!? Why is that? This filter has no options/settings.

I do have other option, to duplicate view display, check directly the field and display first or second block view depending on user, but this solution with Content access filter looks more elegant.

Lists like views will not be passed through hook_node_access(), as this would create too much overhead. Views does a query on the database to get the results. hook_node_access() is run in PHP, so these won't work (easily/well/efficently) together.

To deal with lists, you will need to create a grant system, using hook_node_access_records() and hook_node_grants(). This system writes to the {node_access} table in the database, and when a list is created, the database query is cross-referenced with that table.

hook_node_access_records() is called when a node is saved. Modules that implement this hook can set up various states by which the node is allowed to be accessed.

hook_node_grants() is then called when the node is viewed/updated/deleted. A set of potential grants is created based on the current environment, and these are compared with the states created in hook_node_access_records(). If there is a match, access is provided.

In your case, hook_node_access_records() should create a state whereby if the node has the field field_content_protect, then a state should be created upon which view access can be either granted or denied in hook_node_grants(). Example:

function MODULE_node_access_records(\Drupal\node\NodeInterface $node) {
  if ($node->hasField('field_content_protect')) {
    $grants = [];

    $grants[] = [
      'realm' => 'MODULE_protect_content',
      // This is set to 1. In hook_node_grants(),
      // A value will be created based on the user's
      // logged in state, and compared to this value.
      'gid' => 1,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
    ];

    return $grants;
  }
}

The above sets up a state, whereby if a grant is created for the realm MODULE_protect_content that has a value of 1, the user should be granted view access. The next thing is to implement hook_node_grants() and create a grant based on the current user's status.

function MODULE_node_grants() {
  $current_user = \Drupal::currentUser();
  $grants = [];

  // This will set a value of 0 (zero) or 1 (one)
  // for the realm MODULE_protect_content. If the
  // value is 1 (authenticated user) the user will
  // be provided view access to the node. Note
  // that an array of values must be passed for
  // realms.
  $status = (int) $current_user->isAuthenticated();
  $grants['MODULE_protect_content'] = [$status];

  return $grants.
}

For the above code, a grant is created based on the logged in status of the current user. If they are logged in, $status will equal 1, which is compared with the state provided in hook_node_access_records() providing access to the user.

You could actually alter the above hook_node_grants() to only return a grant if the user is logged in. I'm not sure which one would be more efficient. I suspect the code below may be:

function MODULE_node_grants() {
  $current_user = \Drupal::currentUser();

  if ($status = (int) $current_user->isAuthenticated()) {
    $grants = [];
    // This will set a value of 1 (one)
    // for the realm MODULE_protect_content, which
    // matches the state created in
    // hook_node_access_records(). Note that
    // an array of values must be passed for
    // realms.
    $grants['MODULE_protect_content'] = [$status];

    return $grants.
  }
}


Views Content: Title as an autocomplete exposed filter? I would like to provide an autocomplete widget for the Content: Title in a view (created by Views), in which this field is an exposed filter. By default, it's a simple textfield.

What's the best solution for this?

You can use the Views autocomplete filter

It will work for node titles and other exposed text fields


Can I use Drupal 7's CSS/JS cache buster/token programmatically? By default Drupal adds a cachebuster to CSS and JS resources:

<style type="text/css" media="all">
@import url("http://example.com/modules/system/system.base.css?o0xoqx");
@import url("http://example.com/modules/system/system.menus.css?o0xoqx");
@import url("http://example.com/modules/system/system.messages.css?o0xoqx");
@import url("http://example.com/modules/system/system.theme.css?o0xoqx");
</style>

Is there a way to use the cache token (o0xoqx) programmatically in the template?

I'd like an easy way to add the same token to some other resources later on (namely: the whole lot of modern favicons), so I could "refresh" them more easily.

You certainly can, it's just a variable:

$current_token = variable_get('css_js_query_string', '0');


Creating a product page with a template file After being a long time observer I finally have a question that I can't find an answer to. I have tried searching, both on here and on Google, but to no avail.

I am using Drupal 8.3.2 with the Drupal Commerce 2 module.

I am trying to theme a product page. I have switched twig debugging and created my own 'commerce-product.html.twig' file to overwrite the default one.

The problem I am having is that I want to be able to insert the different fields in the html using the twig template engine like I have done for custom content types on some of the pages on my site.

{{ fields.field_header.content}}

  {{ fields.body.content}}

For the example above, I created a view and a block, and within the block used the markup above to call the field values within the view.

Now that I have come to the product page I am unsure which is the correct way to proceed.

Should I create a view for a product page, or can I call the product values in a similar fashion to above. For example.

{{ product.field_product_image.content}}

Or do I need to create a view and select the fields I want to display etc. in a similar way to what I have done for my custom content types.

I have tried to search for the answer, but I haven't been able to find much help.

That's landed me here, making my first post.

You should start off with copying the template from the Commerce module /modules/contrib/commerce/modules/product/templates/commerce-product.html.twig:

{#
/**
 * @file
 *
 * Default product template.
 *
 * Available variables:
 * - attributes: HTML attributes for the wrapper.
 * - product: The rendered product fields.
 *   Use 'product' to print them all, or print a subset such as
 *   'product.title'. Use the following code to exclude the
 *   printing of a given field:
 *   @code
 *   {{ product|without('title') }}
 *   @endcode
 * - product_entity: The product entity.
 * - product_url: The product URL.
 *
 * @ingroup themeable
 */
#}

  {{- product|without('variation_attributes') -}}

You can then adjust the display according to your custom fields, so something like:

  {{ product.field_header }}

      {{ product.body }}

  {{- product|without('field_header','body') -}}


Create a view to show nodes tagged with certain terms next to each other in comparison table I have a content type called 'Product Feeds' that contains hundreds of nodes. These product feed nodes have fields attached; product name, product description, product price and also a taxonomy term field for the shop name.

I want a view that shows me all the terms from 'shop name' vocabulary along the top of a table then all the other attributes in rows so I have a comparison of prices, descriptions etc.

Can anyone offer any pointers in how to do this?

The way I would implement this in Views is to create a node (of type 'Products Feeds') for each product the way you suggest.  Then I would add an additional field (field_unique_product_code) and make that field a taxonomy term (term reference) of a vocabulary named 'products'.  That vocabulary would contain unique products codes for all the products your system will process.  The shops need to use the same unique product code (or you need to translate shop-specific SKUs in the incoming products feeds to this unique product before saving the node).  Note that while the product codes may be strings (e.g. sony-kdl-46R473a, each term gets an unique numeric id in the vocabulary (for instance, the term for this particular Sony tv model may have the numeric id '42'.  Take a note of this number, because you're going to need it later.

Now, perform the following steps:

Create and save a new View named 'Comparisons' and make it a view of type 'Products Feeds'. Press 'Save & exit' to save and exit.
Go back and edit the View:

Make the format for the View 'Grid'.
Click on Show: Content, and change the radio button from 'Content' to 'Fields'.
Add the fields you want to display (shop name, price, description), rearrange the sequence and remove the display of labels.

If you look at the auto preview (bottom of page) at this point, you'll see that you have a nice grid display of the shop name, price and description, but for all the products, rather than for a single product.

To narrow down the display for a single product, you need to add a contextual filter.

Expand the Advanced section (to the right in the Views UI), click on 'Add' next to  Contextual Filters, and add the field_unique_product_code as a contextual filter.

Now, look up the numeric ids for your unique product codes. Let's say your database contains a product with product id 42.  Type in '42' in the textfield with label 'Preview with contextual filters', and click 'Update preview'.

Now, the preview should be restricted to a comparison between the shops, restricted to a single product.  Click 'Save' (top right) to save the View.

Now, you can produce comparions of specific products just by including their numeric product ids in the URL.  For instance:

http://example.com/comparison/42

will produce the comparison grid for the product with numeric product id 42.

This should give you the basic functionality you're looking for.  A lot of refinement is possible.  For instance, if you want to use products names in the URL for contextual filtering, you need to create URL aliases for the numeric ids (you do this with Administration » Configuration » Search and metadata » URL aliases).

For more refinement, you can use templates to get a nicer layout of the table grid, and add a left column with labels.

(But if you need help with these refinements, ask separate questions after you've got the basic grid with the contextual filter working.)


drupal form submission I have a very weird problem, my custom forms submition doesn't work unless devel module is active.
any ideas how to solve this problem?

function forexCompare_form_submit($form,&$form_state){

$array = unserialize(variable_get('forexCompare_company1',""));

$array[] = t($_POST['forexCompare_company1']);
variable_set('forexCompare_company1',serialize($array));
//drupal_set_message(print_r($form_state)." k".$_POST['forexCompare_company1']);
}

function forexCompare_form($form,&$form_state){
return array(
            'forexCompare_company1' => array(
                '#type' => 'select',
                '#title' => 'Company #1',
                '#options' => getCompanies()
            ),
            'forexCompare_company2' => array(
                '#type' => 'select',
                '#title' => 'Company #2',
                '#options' => get_stored_comp()
            ),
            'submit' => array(
                '#type' => 'submit',
                '#value' => 'Save',
            ),
            '#submit' => array(
               'forexCompare_form_submit'
            )

);
}

i have notice that when i return the drupal_get_form() on the page callback , but when i pass it as variable in theme function doesnt work

function userOptions_theme(){
global $user;
$user_loaded = user_load($user->uid);
return array(
  'settings_user_transfer'=>array(
      'template' => 'setting',
      'variables' => array('money' => $user_loaded,'form' => drupal_get_form('userOptions_form'))
  )
);
}

There are a few things wrong with your approach, don't use $_POST, the values are there in &$form_state and you will break Drupal form handling using $_POST. If you have devel running use dpm() to explore that array.

In the theme function call drupal_get_form with the right name: forexCompare_form, i.e.
drupal_get_form('forexCompare_form'). Or was the theme function just an example.


Exclude Items from Flat Rate Shipping Calculation I have several product types:
• T-shirts (FlatRate)
• Pins (FlatRate)
• Poker Chips (No Shipping)
• Gift Card (No Shipping)
• Class Registration (No Shipping)

I charge $10 Flat Rate Shipping for all orders under $75.
All orders over $75 are free.
I do not charge shipping for Poker Chips, GiftCards or Class Registration.

I have everything set up and working EXCEPT I don't want to calculate the price of Poker Chips, Gift Cards or Class Registration in the shipping.

So, if the user orders a t-shirt at $20 and a $100 Gift Card, he should still be charged $10 shipping even though his order total is over $75.

I just can't get the flat rate shipping to not calculate the price of the excluded items in the order.

Help!!

This a bit of a complex setup and would be best handled by creating a new inline condition offering the ability to compare the order total of line items of a particular product type to some value. That's really what should be done.

However, this can actually be done with Rules. (Doesn't mean that it should, but it can!)

How would you do this? Well, you'll need a couple of components and a reaction rule. Go ahead and create a free shipping discount with Discounts and then modify the rule that gets created. You'll need to disable the Free shipping action and replace it with something that looks like this: Note that you can't skip the creation of the discount altogether because it's still needed to apply the discount itself (it's down at the bottom in the final rule).

{ "commerce_discount_rule_discount_free_shipping_for_75" : {
    "LABEL" : "Free shipping for $75",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Discount", "Order discount" ],
    "REQUIRES" : [ "rules", "commerce_discount" ],
    "ON" : { "commerce_discount_free_shipping" : [] },
    "DO" : [
      { "component_rules_amount_of_hats_on_order" : {
          "USING" : { "order" : [ "commerce-order" ] },
          "PROVIDE" : { "aount" : { "amount" : "Amount" } }
        }
      },
      { "component_rules_free_shipping_if_order_total_met" : { "order" : [ "commerce-order" ], "amount" : [ "amount" ] } }
    ]
  }
}

This rule has two custom actions on it.

The first one calculates the total amount of the hats on an order (I built this on Kickstart 2.x so change to suit your needs). The title of the rule isn't as important as is that you'll need a component to calculate a new total you'll compare against.
The second action will be the one that actually does the conditional application of free shipping.

Calculating a total on a subset of products

To calculate a total, we need to loop through all of the line items on an order, and then, if the line item's product is of a certain type, add it to a running total. Since Rules out of the box doesn't have if statements, we can emulate that using another custom component inside of the loop which will conditionally the current line_item being inspected add it's value to the running total if our product conditions are met. This could actually be anything, not just product type.

{ "rules_amount_of_hats_on_order" : {
    "LABEL" : "Amount of hats on order",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "order" : { "label" : "Order", "type" : "commerce_order" },
      "amount" : { "label" : "Amount", "type" : "decimal", "parameter" : false }
    },
    "ACTION SET" : [
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0.0" },
          "PROVIDE" : { "variable_added" : { "running_total" : "Running total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_add_total_amount_of_line_item_to_total_if_product_is_of_ty" : {
                "USING" : { "lineitem" : [ "list-item" ], "total" : [ "running-total" ] },
                "PROVIDE" : { "total" : { "total" : "Total" } }
              }
            },
            { "data_set" : { "data" : [ "running-total" ], "value" : [ "total" ] } }
          ]
        }
      },
      { "data_set" : { "data" : [ "amount" ], "value" : [ "running-total" ] } }
    ],
    "PROVIDES VARIABLES" : [ "amount" ]
  }
}

Conditionally add a line item total to a running total

This is where most of the magic happens. This function is simple but could be expanded to do a lot of cool stuff. Currently, all it does is compare the product type to some value, but it could look at taxonomy terms, other fields... you name it! The gist of this rule is that it just does some comparison and then adds the line item value to the running total if it's met. It functions as an if statement. If the conditions are not met, the value doesn't increase.

{ "rules_add_total_amount_of_line_item_to_total_if_product_is_of_ty" : {
    "LABEL" : "Add total amount of line item to total if product is of type",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "lineitem" : { "label" : "Line item", "type" : "commerce_line_item" },
      "total" : { "label" : "Total", "type" : "decimal" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "lineitem" ], "field" : "commerce_product" } },
      { "data_is" : {
          "data" : [ "lineitem:commerce-product:type" ],
          "op" : "IN",
          "value" : { "value" : { "hats" : "hats" } }
        }
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "total" ],
            "op" : "+",
            "input_2" : [ "lineitem:commerce-total:amount-decimal" ]
          },
          "PROVIDE" : { "result" : { "result2" : "Calculation result" } }
        }
      },
      { "data_set" : { "data" : [ "total" ], "value" : [ "result2" ] } }
    ],
    "PROVIDES VARIABLES" : [ "total" ]
  }
}

Conditionally applying the Free shipping

Finally, now that we've gotten the product-subset total amount, we can test against that and then apply our free shipping. Note that this rule will have the comparison of the product total and that's where you'd change the amount to compare against.

{ "rules_free_shipping_if_order_total_met" : {
    "LABEL" : "Free shipping if order total met",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_discount" ],
    "USES VARIABLES" : {
      "order" : { "label" : "Order", "type" : "commerce_order" },
      "amount" : { "label" : "Amount", "type" : "decimal" }
    },
    "IF" : [
      { "data_is" : { "data" : [ "amount" ], "op" : "\u003E", "value" : "74.99" } }
    ],
    "DO" : [
      { "commerce_discount_free_shipping_service" : {
          "entity" : [ "order" ],
          "commerce_discount" : "discount_free_shipping_for_75",
          "shipping_service" : "standard_shipping"
        }
      }
    ]
  }
}


Form API ajax calls reload attached JS using behaviors I have leaflet map attached to my form, this is the container div I used:

$form['general']['map'] = array(
  '#markup' => '

',
);

Everything works fine and map's being loaded. I also added an image upload functionality in bottom of my form like this:

$form['detailed']['img'] = array(
  '#type' => 'managed_file',
  '#upload_location' => 'public://map-images/',
  '#required' => TRUE,
  '#title' => 'Image',
  '#default_value' => $complain['image'],

);

When I click on ajax upload button after selecting the image file, it throws an error and nothings happen:

  Uncaught Error: Map container is already initialized.

Seems like uploading file is forcing leaflet.js to reload map container. My guess is ajax is reloading and rendering the whole form all over again.

How's that possible and what's the easiest fix for this? Thank you.

Edit:
How I added initializing function, look like this attached js is being recalled everytime I click on upload image ajax button:

(function($, Drupal) {

  // Custom functions and variables can go here
  Drupal.behaviors.moduleName = {
    attach:function() {
      map = new L.Map('ngmap', {center: new L.LatLng(37.472, 57.327), zoom: 13});
      googleLayer = new L.Google('HYBRID');
      map.addLayer(googleLayer);
    }
  };
}(jQuery, Drupal));

Drupal calls every declared behaviors when an AJAX call is performed. This is done to apply the declared behaviors to new loaded content via AJAX.

When a behavior is applied to an element a class is used to mark that element as behavior processed, so next behavior call ignore this element. The recommended way to do this is using the jQuery Once, included in Drupal 7. See the behaviors section of this page.

In your case you should use something like this:

(function($) {

  // Custom functions and variables can go here
  Drupal.behaviors.moduleName = {
    attach:function(context, settings) {
      $('#ngmap', context).once('leaflet', function () {
        map = new L.Map('ngmap', {center: new L.LatLng(37.472, 57.327), zoom: 13});
        googleLayer = new L.Google('HYBRID');
        map.addLayer(googleLayer);
      });
    }
  };
}(jQuery));

Once will add a 'leaflet-processed' class to the #ngmap element, so next time the behavior is called the initialized map is ignored.

Imagine you have several maps in the same page, and imagine you can load more by using AJAX calls. The above code, with some modifications, allows you to initialize every new loaded map after the AJAX call.

So, your fix works but is not the right way to do it (in general inline code is discouraged), I recommend you to use the #attached and Once approach.


My javascript is making the drupal admin menu disappear. Not sure how though Ok, so any time I try to view a page on my Drupal 7 site while I am using either
drupal_add_js(drupal_get_path('module', 'floormap') . '/includes/javaScript.js');
or
drupal_add_js('http://code.jquery.com/jquery-1.10.2.js', 'external');

The admin menu is hidden,  As soon as I comment them out, it is back.

First, do I need to include code.jquery.com in Drupal, or is it already there?

Next, I went to my jS file, and made it so that on DOMContentLoaded, it checks the page url, if it isnt the url of my module, nothing is executed...I put in an alert(); and it is only alerting on my pages, but somehow the menu is being hidden still.  Why is it still happening on other pages if my jS is only being executed on my module's URL? It seems like just having this file included breaks everything.

function checkPage() {

    if (window.location.pathname == '/floormap_page'){
        alert(window.location.pathname);
        hideAgentInfo();
    }else if (window.location.pathname == '/floormap_page/setup_floormap') {
        alert(window.location.pathname);
        coordGrabber();
    }
}

function displayAgentInfo(top,left,floormap,uid) {

    var bubble_info = '';
    bubble_info += floormap+','+uid;

    $.ajax({
        type: "POST",
        url: Drupal.settings.basePath + 'floormap_callback',
        data: {'bubble_info':bubble_info},
        success: function(data){
        document.getElementById('agent_info_bubble').innerHTML = data;
        document.getElementById('agent_info_bubble').style.display = "block";
        document.getElementById('agent_info_bubble').style.top = top+'px';
        document.getElementById('agent_info_bubble').style.left = left+'px';
    }
    });

}
function hideAgentInfo() {
    document.getElementById('img').style.height = '550px';
    document.getElementById('img').style.width = 'auto';
    document.getElementById('agent_info_bubble').style.display = "none";
    document.getElementById('agent_info_bubble').innerHTML = '#';

}

document.addEventListener("DOMContentLoaded", checkPage, false);

I've noticed that the admin menu is retieved using $.ajax get, I'm using $.ajax post in my jS, could that be causing issues?  Again though, the post is only happening on the pages with my module's URL....

Another note, when I look at the page's source code, the div for the admin menu isn't there at all, it isn't just not visible.  That is why I'm getting the impression that it's an issue with the GET function.  When I'm watching the log with firebug, it show's the GET when everything is commented out.  When my files are included, firebug doesn't show the GET.

Here is a link to my javaScript file if there is anything else you need from it.
https://gist.github.com/anonymous/9916901

This is what the firebug console gives me if I have ANY drupal_add_js() in my module's inc file:

  ReferenceError: jQuery is not defined

  jQuery.noConflict();

  drupal.js?n3ddny (line 5) ReferenceError: jQuery is not defined

  })(jQuery);

  contex...s?v=1.0 (line 52) ReferenceError: jQuery is not defined

  jQuery(document).ready(function($) {

  scripts.js?n3ddny (line 1) ReferenceError: jQuery is not defined

  jQuery(document).ready(function() {

  scripts.js?n3ddny (line 1) ReferenceError: jQuery is not defined

  })(jQuery);

  admin_...?n3ddny (line 397) ReferenceError: jQuery is not defined

  })(jQuery);

  scripts.js?n3ddny (line 32) ReferenceError: jQuery is not defined

  jQuery(document).ready(function() {

  main.js?n3ddny (line 1) ReferenceError: jQuery is not defined

  ...odules/custom/TLSConnectPackage/TLSApplicationFilter/TLSApplicationFilter.cs...

  app.lo...bal.com (line 58)

If I remove drupal_add_js() the only thing that shows in the console is the GET for the admin menu.

Drupal comes with jQuery so you don't need to add it. You should use https://drupal.org/project/jquery_update when trying to use a newer version of jQuery; doing it the way you are currently can cause unknown side effects.


How to get the unread message count using EntityFieldQuery Using below query I am getting the count of all messages of a user. Now i need to filter them to unread messages only.

global $user;
$query = new EntityFieldQuery();
$count = $query->entityCondition('entity_type', 'message')
 ->propertyCondition('uid', $user->uid)
 ->count()
 ->execute();

If you are using the privatemsg module you can use privatemsg_unread_count().


How do I fetch the product display nodes referencing the given product using "Fetch entity by property"? Let me start off by saying that I am ultimately trying to get the product display from a line item. I would use commerce_rules_extra, which has a feature that is supposed to do this, but I could not get it to work. So I am trying to get the product display node for the product.

My strategy is to create a simple Rules Component that returns all product display nodes that reference a given product.

My component accepts a parameter of type: Commerce Product

My component has a Condition: Data comparison: Product:type - equals - "Product"

My component has an Action:

Fetch entity by property, Entity type: Node, Property: Product (I believe this is the product reference field)

When I attempt to set the Value as the component's Parameter "Product", the action will not accept this—instead it gives this error:

  The data type of the configured argument does not match the parameter's value requirement.

This would be the typical method for fetching nodes by property on an entityreference field but I can't do the same with this productreference field. Any hints would be greatly appreciated.

Have a look at Action "Fetch entity by property" does not allow to fetch by multi-valued properties, which appears to be similar to what your question is about (and has RTBC status).

If I'm right, try the patch attached to it.


How to prepare renderable array for images that are not stored in public or private filesystem, but are delivered statically with module? I have a piece of code that prepares renderable array for my images:

if( !empty($row['image_file_id'])) {
  $row['thumbnail'] = array(
    '#theme' => 'image_style',
    '#path' => _mymodule_uri_by_id((integer)$row['image_file_id']),
    '#style_name' => 'product_thumbnail_small',
    '#attributes' => array(
      'alt' => $row['image_alt'],
      'title' => $row['image_title'],
    ),
  );
}

It works OK:

But I want to add else with image provided within a module. I still want this image to go thorough all image style processing etc. I want my theming colleagues to be able to simply not care if they'll ever decide to add some effects or change resolution. But of course this image is in module directory, not in public://. And it means this will not work:

else {
  $row['thumbnail'] = array(
    '#theme' => 'image_style',
    '#path' => drupal_get_path('module', 'mymodule') . '/frontend/noimage.png',
    '#style_name' => 'product_thumbnail_small',
    '#attributes' => array(
      'alt' => 'some universal stub',
      'title' => 'some universal stub',
    ),
  );
}

It gives:

And browser tries to read that image from http://example.com/sites/default/files/styles/product_thumbnail_small/public//sites/default/modules/mymodule/frontend/noimage.png?itok=-yYlM4ns

This gives nothing (status reports says "access denied"), unless I manually place image in public://sites/default/modules/mymodule/frontend - but I don't want it to be in public file system, I want it to stay in module space. How can I make it work?

Simply put...you can't, unfortunately (well not without changing some core stuff at least)

From the comments for theme_image_style()

  This function does not work with images outside the files directory nor with remotely hosted images.


How to access a field value in hook_preprocess_eck_entity How can I access a field value in hook_preprocess_entity(&$vars)?

I am able to do the following, but it does not seem like the best approach. What is a better approach?

function mymodule_preprocess_eck_entity(&$vars) {
  $myvalue = $vars['content']['field_myfield'][0]['#context']['value'];
}

I found I can get the value with:

  $myvalue = $vars['eck_entity']->get('field_myfield')->getString();


Special characters in email body I'm attempting to send an email from a Drupal 8 module I'm developing, and it works except that special characters (' < >) seem to be getting escaped.

My module has a configuration to select whether the emails are plain text or HTML (using Swiftmailer). In plain text messages, apostrophes get replaced by &#039; while in the HTML messages, all HTML tags receive similar treatment, so the message arrives, but the HTML tags are all shown in the message, rather than formatting it.

Heres an extract from my hook_mail handler:

  $message['subject'] = $params['subject'];
  $body = $params['body'];
  if ($config->get('confirmation.format_html')) {
    // Set up HTML email.
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8';
    $message['body'][] = $body;  // HTML version of message body.
    $message['plain'] = \Drupal\Component\Utility\SafeMarkup::checkPlain($params['body']);  // Plain text version of body.
  } else {
    $message['body'][] = $params['body'];  // Plain text version of body.
  }

It seems there's some escapement of special HTML characters going on, but I can't see where?

Make sure what you're passing in is a renderable array... and render it before assigning it to the message body field:

  $markup = ['#markup' => "We do HTML"];
  $message['body'][] = render($markup);

Note: This makes some sense i guess but i really just stumbled onto the solution, so i'm not sure how correct it is, but it works.

Incidentally, for the plain-text version i recommend doing what Drupal core's PHP mailer does in its format method:

use Drupal\Core\Mail\MailFormatHelper;

// Join the body array into one string.
$message['body'] = implode("\n\n", $message['body']);

// Convert any HTML to plain-text.
$message['body'] = MailFormatHelper::htmlToText($message['body']);
// Wrap the mail body for sending.
$message['body'] = MailFormatHelper::wrapMail($message['body']);


Issues with upgrading I am trying to upgrade from Drupal 6.28 to Drupal 7.22. By following the steps that were available on Drupal community doc, I succeeded in upgrading it to Drupal 7 successfully. I upgraded core, migrated CCK fields as well, but there are issues with the Views module: Various fields are not working. It is showing an error for a missing or broken handler.

The issue is that Drupal 6 had an embedded video field which was not included in Drupal 7. In Drupal 6, the widget type was embedded video, while in Drupal 7 the widget that we get by embedded media selector is media file selector.

How can I resolve this issue?

If you followed all the steps, I assume you have (or can get) a working copy of original 6.x page.

The question is - are your nodes OK?

If they work properly, it means you have data in good enough state. Delete views that include problematic fields and recreate them from the ground. Optionally export them, remove fields that cause problems from exported file, delete from server, import and add fields. That's the easy case
Sadly, if there was changes in the fields you were using in the very nodes, that renders nodes unusable, it will be worse. You will need to export data from 6.x site to some more or less universal format, like csv or xml, and import it anew to 7.x

Delete migrated data and it's content type
Create new content type with new-style fields, that maps 1:1 to old node structure. If possible, keep names
Export node data, using Node Export, Views data export or similar tool
Secure all the files referenced by nodes
If needed, manually upload secured files to new version; see next step
Import nodes using tool like Node Export or Feeds - it may be required for files to be already uploaded, read the manual of your importing tool


How can I sort by last word in the node title field? In one of my content type, we are storing names in the Title field. For example, title is "John Smith". Due to the recent requirement change we now need to sort results by last name.
But since the name is stored in Title how can I sort by last name in the view? Is there a way I can create a field which automatically gets the last word in the title? Or may be some other way that I am missing out?

This is probably not best solution, but it should work:

Try Views PHP. With this module you should be able to create sorting in view which will take only last word of given string (content of your title field) with PHP code (something like this example).

  This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code.


Show sharethis twice on a page with different layouts I'm using Sharethis, is there any way to show sharethis as horizontal counter on the articles content type teaser display and then show it as large chicklets on a block?

You can do it in node.tpl file, by using the sharethis custom code(get it from sharethis.com) and choose your horizontal style

below is the code to display only in teaser(paste this code in node.tpl)

<?php if ($teaser): ?>

<?php endif;?>

for block again choose your style from sharethis.com and paste it in the block

hope you can get ideas from the above!


htaccess 301 redirect everything except /admin I have been scratching my head for almost half an hour already because of this. I don't know what I am doing wrong, might just be under my nose, but i just cant see it. Here's what I have on my .htaccess

  RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
  RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

  RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
  RewriteCond %{REQUEST_URI} !^/admin [NC]
  RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]

When I access example.com/admin, i am still redirected to newsite.com/admin.Can anyone please advise? Thanks!

It depends on RewriteBase /.
I checked your code with this online tool and it was working fine.
Toggling comment for rewritebase line will help but other rules might get affected. Instead, modify your condition and remove the slash. It should work.

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^admin [NC]
RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]


How to access commerce_product field of line-items using Rules to flag the Commerce Product? Related to this question: How to mark product if it has already been purchased by current user?

I have a Drupal Commerce shop, where I'm trying to use the Flag module to mark products to inform users if they have already purchased that particular product.

Now I'm trying to create a rule (using Rules) triggered on "Completing the checkout process" to flag all products that were purchased. Problem is I can't gain access to the commerce_product field (product reference field) of the line item, no matter what I do, and because of that I can't find the info I need to flag the products.

Could someone show how to do this in detail, preferably with example(s)?

Below is a possible approach you can use to solve your question. It provides the details about how I was able to have a set of Drupal messages being shown at checkout time, which look similar to this testcase I used (for a cart with 3 line items):

Current line item has label 'USB-BLU-08' and id '17'
Some details about this product: Product ID = 28, Product SKU = USB-BLU-08, Product Title = Storage 1, Product Creator = Hillary.Trump

Current line item has label 'TSH4-BLK-MD' and id '18'
Some details about this product: Product ID = 53, Product SKU = TSH4-BLK-MD, Product Title = Tshirt 4, Product Creator = Donald.Clinton

Current line item has label 'MES1-BLU-OS' and id '19'
Some details about this product: Product ID = 2, Product SKU = MES1-BLU-OS, Product Title = Messenger Bag 1, Product Creator = Pierre.Vriens

To get this to work, I created a custom rule, which also performs a custom Rules Component. Read on for details about them ...

Step 1: Create a Rules Component

Create a Rules Component which looks like so (use the Rules UI to import it in your own site):

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Some details about it:

Parameters: selected_line_item ( = the line item being processed).
Rules Condition: entity (= selected-line-item) has field (= commerce_product).
Rules Actions:

Fetch entity (= commerce_product) by ID (= selected-line-item:commerce-product:product-id).
Show a Drupal message, starting with "Some details about this product ..." (feel free to remove this Rules Action after you finish QA-testing).

Step 2: Create a rule that invokes the Rules Component from Step 1

Create a rule which looks like so (use the Rules UI to import it in your own site):

{ "rules_access_product_fields_at_checkout" : {
    "LABEL" : "Access product fields at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } },
            { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-item" ] } }
          ]
        }
      }
    ]
  }
}

Some details about it:

Rules Event: After completing the checkout process.
Rules Condition: none.
Rules Action: Create a loop, to iterate over each line item. And for each line item, perform these Rules Actions:

Show a Drupal message, starting with "Current line item has ..." (feel free to remove this Rules Action after you finish QA-testing).
Perform the Rules Component from Step 1 for the current line item being processed.

Step 3: Homework (= your turn)

To actually answer your question, i.e. to flag the product of each line item, you should only adapt the Rules Action in the Rules Component from Step 1. Since you have all data from each line item available at that point, it should be straight forward to tune the Rules Component to fit your needs (i.e flag the product by the current user).


How do you force drupal 7 to make a new revision every time you edit a node? I'd like to make drupal 7 create a new revision every time you edit a node? This was an option in Drupal 6 but not 7.

Just like in Drupal 6, you enable this in the content type settings. At admin/structure/types, click edit for the content type you want to enable this and then check "[] Create new revision" under Publishing options.


use a custom textgroup from t() I've defined my own textgroup using:

function foo_locale($op = 'groups') {
  switch ($op) {
    case 'groups':
      return array('foo' => t('foo strings'));
  }
}

The problem is that when I use t('bar') in a template, the entry generated in the database (e.g when viewing the template in /fr) is associated with the default textgroup. This doesn't allow me to use the foo textgroup I've previously defined, thus all my custom strings are mixed with the other "Built-in interface" ones.

How can I solve this?

t('String') always belongs to the "Built-in interface". If you have t() texts, then you don't need to create textgroups.

They are meant for strings that are not translated with that function, usually content/configuration. The I18n modules define lots of these groups for things like variables, menus, taxonomy terms and so on.


time-based temporary authentication Is anyone aware of a time-based rather than one-time login authentication module for Drupal?

We've discovered a problem where some email servers with advanced security tools will crawl through emails to verify the links in them. In so doing -- they invalidate the one-time login links, preventing some users from using them. Rather than verify on whether the link was clicked once, I want to invalidate it based on time. For example -- the link to login is valid for 1 hr from when it was generated.

In Drupal 7 you can do something like the following:

Set user_password_reset_timeout variable (i.e. in settings.php
i.e. in settings.php:

$conf['user_password_reset_timeout'] = '600000';

Then it will use this time after password generation link, when this much time elapsed the link will be invalidated.

You can follow the thread here


Insert task to Queue only if unique I wanted a way to only insert items into the Queue when it was not already added. I want to have a large queue and work my way through it, simply adding as required. Previously I was deleting the queue and recreating on a set time table.

I couldn't find any way of doing this, or any discussion other than 'it's not possible.

I created the method below. I have not used it for huge queues yet, but I post it here in the hope that better options if available might get posted too.

Create a class to extend the systemqueue. I called mine Unique. This will serialise the data use db_merge to insert only if it doesn't exist.

class Unique extends SystemQueue {

  public function createItem($data) {

    // save doing this twice
    $serial_data = serialize($data);

    // ignoring expire
    $query = db_merge('queue')
    ->key(array('name' => $this->name, 'data' => $serial_data))
    ->fields(array(
        'name' => $this->name,
        'data' => $serial_data,
        'created' => time(),
    ));
    return (bool) $query->execute();
  }
}

You then add the variables to hook_install() or hook_enable().

variable_set('queue_class_[your queue name]', 'Unique');

matching [your queue name] to the queue name, e.g if you used this:

DrupalQueue::get('update_profile_tasks')->createQueue();

the variable would be:

variable_set('queue_class_update_profile_tasks', 'Unique');

Thanks to this for getting me on track. Updated answer to be cleaner thanks to comment suggestions.


Question field in the user registration process I am wondering if there is a module which would enable asking users why they want to join a site - i have a very small forum and want to avoid spam bots.
I am using captcha and require administrative approval for a new user but I would like to have a field which asks "why would you like to join this forum?" and have that display somewhere that I can see it before enabling the account.
Does anyone have any advice?
Thanks,
Amy

Go to admin/config/people/accounts/fields and add the field. In field settings enable "Display on user registration form." - you can hide it everywhere else if is only for your eyes.


Taxonomy description for a custom taxonomy view I have created a custom taxonomy view. When it is disabled, the taxonomy vocabulary term description shows at the top of the taxonomy page for that term, but when my view is enabled, it does not. How do I include in my taxonomy view the description?

Edit your taxonomy vocabulary.

Add the field (or fields) that you want. (Hint: The existing field named "Description" doesn't work, so create a new text-area field if that's what you want. I called my replacement field "Definition".)

From the List tab, edit each term's value for the new field.

Create a new view.

Show: Taxonomy terms of type: your_vocabulary, with a page display

Continue & Edit

Configure the view to display only your new field(s).

Use pager: Display a specified number of items | 1 item

Add a Taxonomy Term contextual filter

Edit the existing Taxonomy Term view.

Click on the "add" button in the Header section

Select Global view type header

Select the new view you created above

Check the "Inherit contextual filters" checkbox

Now when you visit the Taxonomy Term view, your new fields view will be included at the top.


How to restrict direct access to the nodes? How to restrict direct access to the nodes but just allow views to access the required field of the particular node type?

For example in Views Slideshow we are sliding the image field that belongs to particular node type. But we don't want search engines to access & visitors to access the nodes belong to that node type.

Any suggestions?

A simple solution would be to not publish the nodes you don't want to be accessible. Views can still pull the data from those nodes.


How to create a automatic Field value number to display in the lable for an custom content type: Itinerary e.g Day 1, Day 2 I have a content type which I've called Itineraries which lists activities users will do on certain days of the package. I've created a 'day' field which the admin will populate with each day's activities, the value is set to unlimited as some packages have 7 days and others 21 days - how do I get the label of each field to automatically set to the number of values sumbitted by the admin ?

So if the admin enters 3 values it should display the label for each submission as -
Day 1 :
fishing, running ...
Day 2:
camping
Day 3:
drive home

I've looked at the Computed field but lack the php knowledge to implement.

Is there another way of implementing the above ? Thanks for the help in advance.

Using computed field you could do this.

Install computed_field module
add a field into the content type you want to count the field for, and then in the display code box add this (field_slect is the field you want to count)

$display_output = sizeof(field_get_items($entity_type, $entity, 'field_select'));


Create a menu with a list of all groups I have installed the Organic Group module and I created some groups. How can I make a menu which contains a list with all the groups?
Thanks!

I am not clear what is your requirement. If you want to create a single menu page and want to show list of group name , you can do this using views. Create a view page and list your content and select menu type as normal nemu item.

OR

If you want to create list of menu items according to group name, in that case you should try to create custom menu using hook_menu.
check here https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7