Language switcher in a modal window (pop-up) I really got quite far on this issue. Using Drupal 8's Modal API. Having a button in a block that triggers the modal with Drupal's language switcher inside. Everything looks fine EXCEPT for the URLs this modal returns. Every URL gets appended with ?ajax_form=1&_wrapper_format=html which breaks the whole functionality. For example http://d8.dev/fr/node-41-article?ajax_form=1&_wrapper_format=html.

I also tried it with a Controller instead of a Form. But then the URLs look even worse, since then they only take the controller path to create the langswitch URLs.

I already started to guess I'd need to start over using a more independent approach. But maybe you folks know a way to get it working with my current approach? Is there a way I can simply cut off the query? Here is what I have so far:

<?php

/**
 * @file
 * Contains \Drupal\langswitch_modal\Form\LangswitchModal.
 */

namespace Drupal\langswitch_modal\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;

/**
 * Class LangswitchModal.
 *
 * @package Drupal\langswitch_modal\Form
 */
class LangswitchModal extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'langswitch_modal';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    $form['actions']['#type']  = 'actions';
    $form['actions']['submit'] = [
      '#type'  => 'submit',
      '#value' => $this->t('Switch language'),
      '#ajax'  => [
        'callback' => '::open_modal',
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function open_modal(&$form, FormStateInterface $form_state) {

    $block   = \Drupal\block\BlockViewBuilder::lazyBuilder('languageswitcher', 'full');
    $render  = \Drupal::service('renderer')->renderPlain($block);
    $title   = $this->t('Choose language');
    $content = $render;
    $options = [
      'dialogClass' => 'popup-dialog-class',
      'width'       => '300',
      'height'      => '300',
    ];

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

    return $response;
  }
}

Got it! All I needed was a little JS to get rid of the query:

$(document).ajaxComplete(function() {
  var $link = $('a.language-link');
  $link.each(function(i,el){
    $(el).attr('href', $(el).attr('href').split('?')[0]);
  });
});


How to hide a fieldset I am trying to use hook_form_alter() to change the way a form is displayed. The form has 4 fieldsets and I only want to display one of them. How can I make these fieldsets invisible using hook_form_alter()?

It's really simple.

On Drupal 6/7, set the "#access" property of the fieldset to FALSE, or use logic to determine visibility.
This will also hide all the content of the fieldset, and yet keep the values intact so that when the form is submitted they are not cleared, but retained.


CCK E-mail field, display e-mail form in js dialog I set display cck field to 'e-mail contact form'. It lead to page like email/15/field_email.

Is this possible to display that form in modal dialog? Which modules I should use?

You can do this with a few lines of JavaScript.

All you need to do is to create a iframe that links the the clicked link and then open it in a dialog. jQuery UI has support for dialogs. There is modules for integrating jQuery UI and upgrading your jQuery version (if needed).

Once that is done, you can add the JavaScript to your theme to create the wanted effect.


Value or label inside a exposed search form and change input form I've created a three exposed filters:

Search
Choose location
Choose category

Instead of using a label "Search", in input field I want to have a "enter keywords to search" and when the user clicks on that input the letters will disappear. I've seen this in many websites.

Choose location has a label "Choose location" and in drop down menu the first option is "All". Instead of using label, I want the first option (All) to be "Choose location".

Choose category to be exactly like the location desired method.

I'm using Drupal 7.

For adding text to your input field, can be done in one of two ways

    function myhook_form_alter(&$form, &$form_state, $form_id){
        if($form_id == "views_exposed_form"){
         dsm($form); // print $form array on the top of the page
          if (isset($form['title'])) {
            $form['title']['#attributes'] = array('placeholder' => array(t('Enter Keywords to search...')));
    }
  }
}

Or use Compact form

  Compact Forms presents text fields for selected forms in a more
  compact fashion using jQuery.

  The form item/element fields are overlaid with their respective
  labels. When the user focuses a field the label fades away nicely, and
  if the field is left empty the label fades back in again.

For changing the All to choose location

function your_module_name_form_alter(&$form, $form_state, $form_id) {
      if($form_state['view']->name == 'your_view_name') {
        $form['your_dropdown_name']['#options']['All'] = t('- Choose Location -');
      }
}


Creating individual fields from a multi-column Field API widget This references the Addressfield and Views modules.

I would like to have extended Views support for the Addressfield module like the Location module does. Some of the extra fields that the Location module makes available are Country, Longitude, and Latitude by themselves and Proximity or Distance filters and sorts.

I've added longitude and latitude columns to the Addressfield module.

The database for the Location module is fairly straight forward in Drupal 7 but not built using the D7 Field API.

The Addressfield module is built using the Field API and with Views it has a Content: field available and also arguments, sorts and filters based on each of the columns in the Addressfield database table. Views only offers a choice of formatters on a single field.

This is fine because it's just as easy to add a formatter to a Fields API module as it is to theme a view . So I can make a formatter that only shows latitude or longitude. Perhaps, better yet, I can make a formatter that displays the latitude and longitude as a WKT point to be used for an OpenLayers map.

However, what I need is a proximity filter so I'm setting out how to extend the Field API's functionality in Views which isn't very straight forward.

Is there documentation available for the particular case or modules that extend the Fields API which can be used as examples?

I thought the logical thing to do was use hook_field_views_data_alter(). Here is the attempted code and I'm not sure why it doesn't work.

function addressfield_field_views_data_alter (&$result, $field) {
  if (array_key_exists('field_data_field_address', $result)) {
    if ($result['field_data_field_address']) {

      $columns = array();
      $columns = array(
        'field_address_administrative_area',
        'field_address_country',
        'field_address_lat',
        'field_address_lng',
        'field_address_locality',
        'field_address_postal_code',
        'field_address_premise',
        'field_address_thoroughfare',
      );

      $add_fields = array('entity_type', 'delta', 'language', 'bundle');
      foreach ($result['field_data_field_address'] as $column => $data) {
        if (in_array($column, $columns)){
          $result['field_data_field_address'][$column]['field'] = array(
            'field' => $column,
            'table' => 'field_data_field_address',
            'handler' => 'views_handler_field_field',
            'click sortable' => TRUE,
            'field_name' => $column,
            'additional fields' => $add_fields,

            'entity_tables' => array(
              'node' => 'node',
              'node_revision' => 'node',
            ),
            'element type' => 'div',
            'is revision' => FALSE,
            'entity id' => 'nid',
            'base table' => 'node',
          );

          $result['field_data_field_address'][$column]['group'] = 'Content';
        }
      }
    }
  }
}

Here is the solution.

/**
*  Implements hook_field_views_data_alter
*
* @param mixed $result
* @param mixed $field
*/
function addressfield_field_views_data_alter (&$result, $field) {
  if (array_key_exists('field_data_field_address', $result)) {
    $result['field_data_field_address']['field_address_country'] += array(
      'title' => t('Country'),
      'help' => t('The Country name of the field'),
      'field' => array(
        'handler' => 'addressfield_views_handler_field_country',
        'click sortable' => TRUE,
      ),
    );
  }
}

Or if you want to not use a real field in the table such as field_address_country but to instead alias a field you can add a field and table attribute to the field array like this.

function addressfield_field_views_data_alter (&$result, $field) {
  if ($field['type'] == 'addressfield')) {
      $result['field_data_field_address']['country'] = array(
        'title' => t('Country'),
        'group' => 'Bad Ass',
        'help' => t('The Country name of the field'),
        'field' => array(
          'field' => 'field_address_country',
          'table' => 'field_data_field_address',
          'handler' => 'views_handler_field',
          'click sortable' => TRUE,
        ),
      );
   }
}


Programmatically assigning new users to groups I have a specific need where if a user is created and assigned to the role "manager" that user should be automatically subscribed to all groups. I can do this without issues if I hard code the uid. I have problems when i use hook_user_insert and I am not sure why. The problem is that none of my code actually executes. The hook does fire when I load a user object of a hard coded uid however.

Here is my hook:

 function mm_custom_user_insert(&$edit, &$account, $category)
{

    if(in_array('manager', $account->roles)) {

      //get all gids
      $results = db_query("SELECT gid FROM og");
      $gids= array();
      while($record = $results->fetchAssoc())
      {
        $gids[]= $record['gid'];
      }

      foreach($gids as $gid)
      {
        og_group($gid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
            ));
        og_role_grant($gid, $account->uid, 3);

      }
    }
}

My main questions are
a.) are the user->roles not available at this time? how would I find this out?
b.) could it be that the the uid is not available?

Appreciate the help

The user ID is definitely available, as hook_user_insert() is called after the user data has been committed to the database.

I've just put the following code into a test module called foo:

function foo_user_insert(&$edit, $account, $category) {
  dpm($account);
}

Then I created an account through the admin UI and the output from dpm() looks like this:

So as you can see, the roles are available too.

If you're not familiar with the dpm() function, it's part of the Devel module. It will print any PHP variable to the standard messages area and will display objects/arrays like the screen shot above. It should help you with most of your debugging needs.


Organic groups and Workflow How can I create a separated workflow for a content type like "Article" for each organic group?

For example:

"Math Group" has the roles "Author," "Head."
"Article" nodes created by users with the "Author" role in "Math Group" will be visible only by users with the role "Head."
Users with the "Head" role will review "Article" nodes, and then publish it or send it back to "Author" for improvement.

How can I implement it with OG and Workflow?

You create a workflow state called "review" and set it so it is only accessible by Head users. Also set the states so any author can only put workflows into this "review" state - only Head users can actually change this to other workflow states.

So, the Head role can access the Workflow summary in order to review all the article group nodes which have been created in the review state.

If the Head approves it, he can change the workflow state to published which is accessible to all.

If the Head denies, he can change the workflow state to Needs work, which will mean the content remains unpublished.

If you want this to go back to the original author you can set this up with an email using actions / triggers or use the rules module.


How to get translated field_storage_config I need to programmatically set the translated values for several fields on a node. For that I would like to set their values in the fields field_storage_config. Adapted from another question's answer (Manage config translations programmatically) I tried the following, but without success:

$origLang = \Drupal::languageManager()->getConfigOverrideLanguage();
$lang = \Drupal::languageManager()->getLanguage($currentTranslationLanguageId);
$untranslatedStorage = \Drupal::entityTypeManager()->getStorage('field_storage_config')->load("node.$tagsBaseFieldId");
$untranslatedValues = $untranslatedStorage->getSetting('allowed_values');
\Drupal::languageManager()->setConfigOverrideLanguage($lang);
$translatedStorage = \Drupal::entityTypeManager()->getStorage('field_storage_config')->load("node.$tagsBaseFieldId");

I expected to get the field_storage_config of the override language that I set in the languageManager (different from the base language), but if I dump $untranslatedStorage and $translatedStorage after these commands, they are the same. $untranslatedStorage and $translatedStorage are the same object. How is this possible and how can I programmatically set the translations for my field(s).
It is a text list field (the one that translates to a selectbox in the UI).

How is this possible and how can I programmatically set the
  translations for my field(s)?

You can load language overrides with ConfigurableLanguageManager::getLanguageConfigOverride, set values and save:

\Drupal::languageManager()->getLanguageConfigOverride('fr', 'field.storage.node.field_example')
  ->set($key, $value)
  ->save();


Views exposed filters set per content type in same view Sorry for my fuzzy title. The problem I have is that I have a view that lists 2 different content types. Now I want to use a filter that will only filter on ONE of the content types that is listed.

Say I have one content type named "Album", and one content type named "Songs" that gets listed in the same view. Now I still need to have them both listed in the same view, but I want to add the filter "First letter is A" to the songs ONLY.
So the Albums gets listed as before, but the songs that doesn't start with the letter A is removed.

Is there any way to accomplish this?

Create a filter that filters on content type for Album
Create a filter that filters on content type for Songs
Create a filter that filters on title (set it to exposed and set the operator to "Starts with"
Under Filter Criteria instead of add, click on the arrow and choose "And/Or, Rearrange"
Click "Create new filter group"
Now drag the filter created in step 2 and 3 to the new group (Songs and Title)
Make sure the operator between the filter groups is OR and the operators between the filters in a group are set to AND

Your filters should look like


Using feeds and xpath to import multiple images into a node I am using feeds to import a heavily customised wordpress site into drupal using xpath and a custom xml file. All is going well until I try to import multiple images into a node.

The image field is a multi value field (not multiple different image fields)

Only the first image is imported the rest are ignored.

When I have xpath debugging on it correctly shows multiple image URI's and their titles.

Is there a way using feeds and xpath to import multiple images into a node?

This is an example of one item from the feed

<root>
    <item>
        <wordpress_id>85672</wordpress_id>
        <title>.....</title>
        <content>.....</content>
        <created>2017-03-17 10:13:24</created>
        <custom_fields>
            <url type="Website">......</url>
            <url type="Website2">.....</url>
        </custom_fields>
        <attachments>
            <images>
                <item>
                    <ID>85671</ID>
                    <post_author>0</post_author>
                    <post_date>2017-03-08 18:00:00</post_date>
                    <post_title>.....</post_title>
                    <uri>.....</uri>
                </item>
                <item>
                    <ID>85671</ID>
                    <post_author>0</post_author>
                    <post_date>2017-03-08 18:00:00</post_date>
                    <post_title>.....</post_title>
                    <uri>......</uri>
                </item>
            </images>
        </attachments>
    </item>
</root>

The post title and uri from the attachments are the two fields I am trying to map to the node image type

for my xpath I am referencing them using...

image_title => attachments/images/item/post_title
image_source => attachments/images/item/uri

and in my mapping I am using...

image_title (image_title) => Image: Title (field_image:title)
image_source (image_source) =>  Image: URI (field_image:uri)

in the  section I have no trouble mapping website and website2 to to a multi value link field so I am not sure why the image field should be any different.

edit: added xml snippet and mappings and further explanation

The issue was resolved.

Feeds importer was working correctly all along. The problem it seems was with the actual images themselves. I didn't realise, but the in some cases the source images where huge (in excess of 18Mb) It just co-incidentally happened that the large image was the second image for the node. Thus when the feeds importer failed. It actually looked like it worked but only managed to import the first image.

When I resized all the images and then re-imported them, it imported all the images correctly.

There is still an unresolved issue in that the import was failing silently. After a few tweaks import suddenly failed with server 500 errors. That's when the apache logs showed a memory allocation error.

Once I saw that, I was able to determine the issue was related to the source images.

I guess the outcome of this is don't assume the problem is related to something you did.


Programmatically populate a Drupal form I am very new to Drupal and trying to write a module. I have 2 entities - Membership and MembershipRequest and both are fieldable. A MembershipRequest is a request to the admin of the website to create or update (renew/delete) a Membership entity. On the MembeshipRequest form, I want to populate the form elements with Membership entity values that user are requesting to update. For example, on the request form's First name text box, I want to populate the Membership's First name. I have membership_id property in the the request entity. But the First name and other fields are attached to both entities via Field API.

I am not sure which object (and how) - $form, $form_state, $request - I need to modify so that the request form will show up with populated values.

Thanks a lot.

If you insist on programming this, and not use and configure contrib modules -

If fields were added to entity bundle via drupal admin UI

You can use hook_form_alter() or hook_form_FORM_ID_alter, and in the code there have the particular field populated with desired default value.

hook_form_alter() would be invoked for all forms and you would have to have an if condition to target just the desired form id.
hook_form_FORM_ID_alter() would be invoked for particular form.

If field was attached using Field API code (not the case for this question)

You would have an implementation of hook_field_attach_form() to attach fields to your MembeshipRequest entity. It would be in that hook implementation that you would set a #default_value to the desired form field.

Code to use in either of the cases above

$form['foo']['bar'] = array(
  '#type' => 'textfield',
  '#title' => t('foobar'),
  '#default_value' => _func_to_get_default_value($member_id),
  '#description' => t('something something'),
  '#size' => 60,
);
// NOTE: Replace foo/bar with the particular field etc.


Getting IMCE to accept multiple file uploads at one time I am currently using the IMCE module for uploading files but it only allows 1 file to be uploaded at one time.  We have tried the plupload and the imce_plupload modules together but those modules sometimes corrupt the files once uploaded.
The only other module called "IMCE Multiple Upload" that claims that it can work with IMCE as an add-on module to IMCE and allows multiple uploads at one time costs $36.
I don't know if the "IMCE Multiple Upload" module will work correctly since the demo site only allows 5 files at once and once over a certain file size it scales it down.

Has anyone used the "IMCE Multiple Upload" module with IMCE and does it restrict how many files can be uploaded at once and does it restrict the file size?
Also does anyone know of an alternative way of getting IMCE to accept multiple file uploads at one time.

I don't know what version of Drupal you are using, If you are working with Drupal 7 you should take a look at: IMCE plupload that helps you to use IMCE with Plupload .

But in Drupal 7 the best option is Media module.


Completely empty page I need to create a page which is completely empty (no HTML returned at all). I need this for a POST callback (when using jEditable).
I would like to still have access to the global variables (such as $user) and the modules that I have installed as I have a module installed which lets me access my REST service.

However, even though there should be not HTML returned per default, I should be able to return a string.

Does anyone know of a way to do this?

You can do that through a custom module - create a path and instead of returning the output, just print it.

Here's an example:

/**
 * Implements hook_menu().
 */
function YOURMODULE_menu() {
  $items = array();
  $items['custom-url'] = array(
    'page callback' => 'YOURMODULE_blank_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Display the content for your blank page.
 */
function YOURMODULE_blank_page_callback() {
  print 'Your string.';
}


Upgrading to 7.26 - Internal Server Error I recently upgraded from Drupal 7.25 to 7.26 in maintenance mode.  The upgrading did not have any errors.

Now when I go to the homepage I get an Internal Server Error.

I added an echo statement to verify that bootstrap.inc was executing.

I haven't been able to log any PHP errors.

This is the first part of my .htaccess file (the other part that includes rewrites isn't allowed by Stackexchange due to links)

    # Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Multiviews creates problems with aliased URLs and is not needed for Drupal.
Options -Multiviews

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Force simple error message for requests for non-existent favicon.ico.
<Files favicon.ico>
  # There is no end quote below, for compatibility with Apache 1.3.
  ErrorDocument 404 "The requested file favicon.ico was not found.
</Files>

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_initialize_variables() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

Always run the update script each time a module / the site is updated.

IE:  site.com/update.php

It triggers the update hooks in the modules and lets them deal with any db type changes.

After that flush the Drupal caches (admin/config/development/performance/) to clear out any old references.


How do I add multiple custom CSS classes to Views rows? This is a kind of follow up to this question:

I have a view where I added taxonomy tags as custom CSS class for rows of a unformatted list:

I did that using Replacement Pattern [tags] as row class.

The problem is that I need to filter by tags and so every taxonomy tag should be added as a separate class. I would need spaces instead of - so the output would be something like that:

Is this possible with Views GUI or do I have to use Views preprocess function?

if you're using multivalue class token, this bug report may be of interest for you. There's also a patch as a workaround available.

  Currently if a views field token contains multiple space-separated class names, these classes will be combined into one class when the string is run through drupal_html_class(). Attached is a patch to split token classes before they are sanitized for HTML.


Alert 3 months before the ending date I am using the Views and the Views conditional modules to display an alert message 3 months before the ending date is coming, but it does not work. For example the ending date is 12/10/2016(m/d/Y) and I want an alert shows before that 3 months such as 09/10/2016(m/d/Y). So this is my views

This is my Views condition

Looks like you're struggling with the issue about Date comparison not working.

You may want to try the steps explained in Comment # 20, to configure the timestamps.

If that doesn't work, then try what's suggested in Comment # 19, ie:

  Use the Views Date Format SQL module to format the date on the database server, prior to rendering by Views. This will allow for comparisons in Views Conditional.


Get taxonomy term field value? I have some taxonomy terms that have an image field in them. I am trying to get the value of the image field in my templates. How can I do this? The field's name is field_header_image.

I have this so far but it does not work..

$headerimg = field_view_field('taxonomy_term', $term, 'field_header_image');
print render($headerimg);

I'm guessing I need something else for taxonomy_term but I'm not sure what that should be.

You can get it like this :

$term = taxonomy_term_load($tid);
$field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
if ($field_header_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
}
print render($headerimg);

If you want to use an image_style :

$headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'my_image_style', //place your image style here
  ),
));

Here is a contextual answer if you are on your taxonomy term page.

In your file template.php use the theme_preprocess_page function like this :

function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

Then in you page.tpl.php you can print render($headerimg);


How to add custom plugin controls to CkEditor I have made custom plugin for ckeditor in drupal ckeditor module.
The page where I am displaying CKEDITOR is loaded through AJAX and I am doing a replace div to show the CKEDITOR.
the code for replaceDiv is:

function replaceDiv( div )
{
    if ( editor )
        editor.destroy();

    editor = CKEDITOR.replace( div ,
    {
        toolbar : 'Basic'/*'Basic'*/
    });
}

But, the problem is that in this way I am not getting my custom plugin displayed, I tried adding my control name in the toolbar definition in the array but it seems that I am not doing in the right way since it is not working!

In ckeditor.config.js you need something like this:

CKEDITOR.editorConfig = function(config) {
  config.extraPlugins = 'vicheck';
  CKEDITOR.plugins.addExternal('vicheck', '/sites/all/plugins/ckeditor/vicheck/');
  config.toolbar_DrupalBasic = [ [ 'Bold', 'Italic', '-', 'vicheck' ] ];
}

where vicheck is a plugin.

This works for me using an old CKEditor module. I don't know if the latest versions have any change.


Views: redirect to default value URL When you have a contextual filter in Views and the value is not in the URL, how do you make Drupal actually redirect browser to the default value that you provide, so that the value is reflected in the address bar?

Say you have a view of a company affiliates and the path is: company/affiliates/. If I provide a fixed value such as oregon, I would like the user (= the address bar) to be redirected to company/affiliates/oregon upon visiting company/affiliates/. Is there a way to do that?

In the view, set the path to company/affiliates and the contextual filter to taxonomy ID (or whatever) and set the default value to type fixed value of Oregon. So company/affiliates goes to the Oregon page but company/affiliates/New-York goes to the New York page and company/affiliates/Massachusetts goes to the Massachusetts page while after all that the plain company/affiliates and company/affiliates/Oregon goes back to the Oregon page.


I can't get hook_form_alter or hook_form_FORM_ID_alter to add placeholder text to the search input I know this has been asked but so far none of the accepted answers for this issue are working for me. I am attempting to add placeholder text to the default search form block. I am using a theme we'll call MyTheme, which is a copy of Bartik and is otherwise working exactly as expected.

I have tried adding the following functions to MyTheme.theme:

function MyTheme_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['edit-keys']['#attributes']['placeholder'][] = t('Search');
}

And

function MyTheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        // Add placeholder text
        $form['keys']['#attributes']['placeholder'] = t('Search');
    }
}

And many, many variations on those. I have tried both functions with and without "\Drupal\Core|form..." included. I have tried both with 'keys' and 'edit-keys'. I have tried both with and without the empty '[]' after placeholder. Nothing has worked.

In every case, using hook_form_FORM_ID_alter simply fails to do anything at all, while using hook_form_alter causes a 'white screen of death'.

I don't understand what I'm doing wrong.

UPDATE: Now out of the blue Drupal has decided to change the id for the form input to 'edit-keys--2' for some reason. I've tried using that in the functions as well.

This is what eventually worked for me. Posting because other people seem to be having the same issue.

I placed this at the very end of the MyTheme.theme file.

/**
 * Add placeholder text to the search forms.
 */
function MyTheme_form_search_block_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Search this site...');
}

Hopefully this will be helpful for some.


hook_menu/MENU_CALLBACK access denied I am using hook_menu() to generate a series of MENU_CALLBACKS for processing data at various points in my sites operations. However, while these work for the admin, when trying to access the pages I get the following error message:

You are not authorized to access this page.

I am trying to get this so that the pages can be reached by all users (one is used for submitting a form and processing the results), the other is used for logging outgoing data. The code is as follows:

function modulename_menu() {
  $items = array();
   $items['data/update'] = array(
    'page callback' => 'dataupdate',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
   $items['onthewayout/forward'] = array(
    'page callback' => 'register_click',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

I tested out the hook_menu in my local. The hook seems fine. Check if you have added an  access denied code in the callback function

function commons_menu() {
  $items = array();
   $items['data/update'] = array(
    'page callback' => 'dataupdate',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
   $items['onthewayout/forward'] = array(
    'page callback' => 'register_click',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function dataupdate() {
  return drupal_set_message("First one is working");
}

function register_click() {
  return drupal_set_message("Second one is also working");
}

This returns a Access Denied to me even if access callback is true.

function register_click() {
  drupal_access_denied();
  exit;
}


How to display the summary (teaser) over the body in a full content view I want to display a teaser on the top of each article under the title,
as in following “full content” layout:

Title
Teaser (article summary)
Image
Body

Moreover the teaser should have its own formatting (for example italic and a bigger font)

I did not find any way to do that without editing tpl files or core files.

A solution would be to  add a new field "article_teaser" to my content type, then manage display in order to get my layout in “Full content” view. This works, but I do not like to have two teaser-fields in my input content form, because I should type two times the same text.

It seems that I cannot split the field body in its “text” and “summary” parts, but I can only display one or the other, but not both!

Is there any way (a module?) to do that?

(My environment: Drupal 7 with Zen sub theme.)

You can do this with Views.  Create a view that overrides the paths for your content type.  Set the display to Fields and then add the body field twice; set the first instance to display the teaser and the second instance to display the body.  You can add the images in between.  Views will also allow you to customize the CSS of the teaser/body fields easily (by default, Views provides a number of classes, and you can add additional classes if necessary).

For reference:
Node One series of video screencasts on using Views


How do I make batch callbacks as class methods? This is the code I am using.

$serviceClass = \Drupal::service('abcclass.service');
$batch = array(
  'title' => t('Pushing updated.'),
  'init_message' => t('Start Pushing.'),
  'progress_message' => t('Completed @current step of @total.'),
  'error_message' => t('Pushing has encountered an error.'),
  'operations' => array(
    array(array($serviceClass , 'ebook_push_single_pdf'), $node->id()),
  ),
  'finished' => array($serviceClass , 'ebook_push_finished'),
);
batch_set($batch);

But it doesn't work. I checked log file and I get:

  Settings can not be serialized. This probably means you are serializing an object that has an indirect reference to the Settings object. Adjust your code so that is not necessary.

Note that if I implement batch callbacks in same file, it works.

How can I fix the code?

When I use a callback function what live in a class I use, for example:

'finished' => array('\Drupal\my_batch\Form\MyBatchForm', 'finish_function'),

The same with 'operations':

'operations' => array(array('\Drupal\my_batch\Form\MyBatchForm', 'operation_function'), array($node->id())),


How do I disable the taxonomy term page? I would like to disable the taxonomy/term/1 page that list the nodes using that taxonomy term. I have found some modules for older Drupal versions, but I haven't found quite what I'm looking for in Drupal 8.

Is there a configuration setting I am missing? Can I use a hook to disable the taxonomy term page, or does this require a module?

A lightweight solution is to simply edit the taxonomy term view :
/admin/structure/views/view/taxonomy_term

... and restrict the access.


How can I post webform block values to another form? I have a capture form in a block on a panel, and I am trying to get it to post the values to another form, once it is submitted.

How can I achieve this?

First name, last name, and email get posted to example.com/page?fname=XXX&lname=YYY&email=ZZZ.

I am using Drupal 6, and the Webform module version 3.9.

You should be able to use one of the webform hooks to pass $_GET values via redirect.

function YOURMODULE_webform_submission_insert($node, $submission) {
  if ($node->nid == XXX){
    // Grab the values we need and create our get url parameter string.
    $queryString = 'f1=' . $submission['value']['myfield'] . '&f2=' . $submission['value']['myfield2'] . '&f3=' . $submission['value']['myfield2'];
    drupal_goto('PATH/TO/FORM', $queryString);
  }
}

Or you can use a hook_form_alter for that form, add a new submit callback, and in the new function set the form's #redirect with the same syntax.

$queryString = $form_state['value']['myfield'] . '&f2=' . $form_state['value']['myfield2'] . '&f3=' . $form_state['value']['myfield2'];
$form['#redirect'] = array('PATH/TO/FORM', $queryString);

Then in your custom form, check for the $_GET values, and set them as the defaults to the appropriate fields, if they exist.


Does db_query support UNION? I have a query that contains a UNION operator. If I ran my query it runs perfectly straight on the database but I am getting an empty result in Drupal.

Here is a simplified version of the query:

$result = db_query("
    SELECT *
    FROM (
    SELECT
    agent_number
    FROM table1
    WHERE agent_number IN (':agent_numbers')
    UNION
    SELECT
    agent_number
    FROM table2
    WHERE agent_number IN (':agent_numbers')) t", array(
      ':agent_numbers' => $agent_ids,
    )
  )->fetchAll();

Is it that db_query() doesn't support UNION?

Yes, db_query() does support UNION. I had a problem with my query:

WHERE agent_number IN (':agent_numbers')

Should be:

WHERE agent_number IN (:agent_numbers)


Can drupal_http_request be secure (https)? I'm using drupal_http_request to parse some user details between servers.

Is it possible to secure drupal_http_request using https or should I fall back to cURL?

If there's a better way, do tell.

Yes, it can.

case 'https':
  // ***************
  // Note: Only works when PHP is compiled with OpenSSL support.
  // ***************
  $port = isset($uri['port']) ? $uri['port'] : 443;
  $socket = 'ssl://' . $uri['host'] . ':' . $port;
  $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  break;


Change drupal 7 way of hashing password? Hi I am trying to migrate users from a legacy custom CMS site that used "sha256" technique to hash passwords to drupal 7 platform.

Upon further reading I came to know that drupal 7 stores passwords as salted and sha512 hash.

How can I change drupal 7 way of storing password hashes/ authentication of users to sha256 technique? Any direction would be helpful.

This is entirely possible but requires custom code for your alternative solution. For an example see:
https://www.drupal.org/node/1109374#comment-4711644

From the linked thread you may simply:

(1) Create a new module, I called mine projectname_legacy_auth

/**
 * supply alternate authentication schemes
 */
variable_set('password_inc', drupal_get_path('module', 'projectname_legacy_auth') . '/projectname_legacy_auth_password.inc');

function projectname_legacy_auth_uninstall() {
  // put it back the way it was...
  variable_set('password_inc', 'includes/password.inc');
}

function projectname_legacy_auth_disable() {
  // put it back the way it was...
  variable_set('password_inc', 'includes/password.inc');
}

(2) add the authentication mechanisms you need to projectname_legacy_auth_password.inc'.
In this case, it's md5().

/**
 * simplified example for md5, no salting
 */
function user_check_password($password, $account) {
  if ($account->pass == md5($password)) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Simplified example for md5 hashes, no salting
 */
function user_hash_password($password, $count_log2 = 0) {
  return md5($password);
}

/**
 * this is probably a bad idea :-)
 */
function user_needs_new_hash($account) {
  return FALSE;
}


Create node with taxonomy field using services in drupal 7 I am creating node from my android app using services 3. I hit this URL www.mysite/endpoint/node with the following json:

{
    "title": "my act for tax",
    "type": "activity",
    "field_activity_type": [{
        "tid": {
            "tid": "[tid:45]"
        }
    }]
}

field_activity_type is a taxonomy term autocomplete filed.

Node is created successfully but field_activity_type remains empty. I am unable to find a correct way to populate taxonomy field.
Anyone who knows please help me.

Here is the Json format to create node having taxonomy filed

{"title":"my act for tax","type":"activity","field_activity_type":{"und":"termname"}}


Add classes to programmatically added fields I have programmatically created a few content types and fields for said content types in a module I'm building, but I need to add classes to said fields.

So if I have a text field called "background_color", I would like to add a class to it called "color-picker".

Im added the instance of the field to my bundle like:

...
    'background_color' => array(
        'field_name' => $fields['field_background_color']['field_name'],
        'label' => 'The stroke color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    )....

Edit - Here is more of my code (node the full code snippet because there are too many fields)..

        $fields = array(
        'field_map_background_color' => array(
            'field_name' => 'field_map_background_color',
            'type' => 'text'
        ),...

$instances =  array(
    'background_color' => array(
        'field_name' => $fields['field_map_background_color']['field_name'],
        'label' => 'The background color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'settings' => array(
            'prefix' => '
',
            'suffix' => '
',
        ),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    ), ....

  foreach ($fields as $field) {
    field_create_field($field);
  }

  foreach ($instances as $instance) {
    field_create_instance($instance);
  }

Do something like this to wrap this field in a DIV class --

...
    'background_color' => array(
        'field_name' => $fields['field_background_color']['field_name'],
        'label' => 'The stroke color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'settings' => array(
          'prefix' => '
',
          'suffix' => '
',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    )....

You would notice I have added settings along with other properties of the instance, where we can add prefix, sufix, min, max etc. I hope it works..


How to add an additional wrapper div within a Views row? I have a Views page with a format of ‘unformatted list’. For a views row I’d like to add an additional div to act as an additional wrapper. The resulting mark-up would then look like

I’ve looked in the various views template files located in the views module folder within the view module but am not seeing a place to add such a div.

Does anyone know how this can be achieved?

I guess I could use an HTML list and make that work but I’d prefer what i just described above.

This could be done in a couple of ways depending on your requirement.

If you want to add a wrapper div to a particular row: (Note: This will work if you are displaying fields in the view)

Click on that field.
Under style settings select the HTML element, and choose DIV.
You can also add the class to this div with the "Create a CSS class" option.

If you want to add a wrapper to all the rows: (NOTE: This will only work for D7)

The best way to do this is via a views template. Click on the "Advanced" section on the right hand side.
Click on the "Theme information"

Select "Views row style output"
Copy the template content.
Create a template with the name provided against "Row style output" link in the screenshot above. Paste the content into it.
Add an extra div element in the template directly.
Note: The template overrides are provided from "generic" to specific" if you go from left to right. E.g. views-view-fields.tpl.php would get applied to all the rows of all the views, and the specificity of the templates goes on increasing as you go right of the "Theme information".


Node display mode on taxonomy page How do you choose the display mode for a node that is used on an taxonomy page?

As default the nodes are displayed using the node-teaser mode but i would like to create a custom style for nodes that are show a taxonomy page.

I could change the teaser mode to what i need but then that would be changed on every place the teaser view is used.

You can change this be enabling the Taxonomy Term View (I suggest cloning it in case you mess something up) and then you can change the view to suit your needs.


How to customize the 'node content links' block? I'm using Organic Groups to make groups, and have made two content types to be added to the groups. I'm also using the OG extras module, so now I have the 'Node content links' block, where users may add content to the group. I want some of the users to see one of the links to create one content type, and the other users to see the other link to create the other content type.

How am I able to do this? Do I need to use organic group roles? If so, I'm unable to find out where I set this type of role for a member. I know where I can create them, but not assign them.

I was looking for this myself and come across this link:
http://makandracards.com/jan0sch/11463-drupal-organic-groups-extras-add-content-links

If you're using Drupal 7 and Organic Groups (2.x) you probably have the OG extras module enabled.

The documentation to enable the "create content" links for your organic group nodes is sparse. Therefore a short howto:

Enable all needed modules Enable the module entityreference
prepopulate!
Go to "Structure" -> "Content types" and select your
group content type, not your group type.
Click on "manage fields" and edit the field "og_group_ref".
Enable the checkbox labeled "Enable Entity reference prepopulate".
Enable the block named "Node content links".
Now you should be done. Steps 4-5 are needed for every group
content type in case you have multiple content types that can be
posted to groups.


How to move comments section out of its parent div How can we move or override the placement of the comments in a node. Usually the comment section is placed inside its content div. My aim is to place this comment section out of its parent div which is usually the node content.

        Some Node Contents ...

Add new comment

I have my template overrides

field--comment.html.twig
comment.html.twig
page.html.twig

Inside themes/contrib/mytheme/templates

Depending on which container you want to escape, you need to use either node.html.twig (recommended) or page.html.twig (harder, unlike node you can't use {{ content.field_comment }} in page).

If you are using node.html.twig (or somehting like node--BUNDLENAME.html.twig) and you manually render {{ content.field_comment }}, then you can avoid double-rendering of comments by rendering the "normal" content using the without filter {{ content|without('field_comment') }}


Fields for different languages on the same interface I have a node that has many fields but need only the title and body field translated.

This node type has a workflow associated to it and any authenticated user can create that node.

The client requires that fields for language EN/FR are all available on the form

I'm wondering what is the best approach to adopt:
content translation + different fields for each language
or
Entity field translation

I've tried entity field translation but it does not provide the fields for each language on the same interface and it does not seem to work well with workbench moderation.

You must repeat the fields, because the Entity Translation and the Internationalization (i18n) module don't provive the fields for each language in the same interface.


Boostrap Responsive Menu Not Working I'm having an issue with my menu on the responsive size. For some reason my menu doesn't collapse so I cannot see any of my items on my menu on a tablet or a mobile. Using the inspect element I check and all the pages from my menu are in the html but the collapsing part is not working anymore. I'm currently using the Project Bootstrap .

Can anyone provide me some tips on how to troubleshoot this problem?
Any help will be appreciated.

Taking a look at the HTML on your homepage there, I'm seeing you're loading bootstrap in your <head> section, and then calling jQuery from near the footer, way down on line 223 (that'd be the line <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>. That's why I'm at least seeing the error Uncaught Error: Bootstrap requires jQuery.  You want to load jQuery before you load Bootstrap, so ultimately your <head> should include the two lines:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>

I hope this at least gets you closer.


Deny access to URL non-authenticated users I have a drupal 7 site with an academic paper that should be accessible only to authenticated users. At the moment the paper is set up as a hyperlink in the full text field of a biblio page and only authenticated users can reach the page.

However, if non-authenticated users get their hands on the url that leads to the pdf version of the paper, they can download it. How can i redirect non-authenticated users that use the url to an error page?

To control which user can access a download link, you need what is called a "private file system" in Drupal. Public files are directly served to the visitor by the web server; Drupal doesn't even come into play. Private files on the other hand are served by Drupal, so it can check permissions before sending the file.

You do not need additional modules to enable the private file system and upload files to it. The documentation should get you started. If you want to make it easy to create links in the body text to file download URL's, you could try adding the CKeditor and Linkit modules.


How can I recalculate field values of a rendered node? For example on a recipe node, exposing a "yield" field on a rendered node to recalculate ingredient quantity values

I dont think there is any module that you can use, you can try hook_node_view_alter hook to change the rendered.

  If the module wishes to act on the rendered HTML of the node rather
  than the structured content array, it may use this hook to add a
  post_render callback. Alternatively, it could also implement hook_preprocess_node(). See drupal_render() and theme() documentation
  respectively for details.

Check hook_entity_view_alter too

If you want to change in the node create form, there is Conditional Fields Module.

  Define dependencies between fields based on their states and values.
  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.

Installation and Usage


create new image style using javascript I am using fancybox JS library for creating a slideshow from a custom bloc with a multivalue image field.

it works but the images on the slideshow are small because a style have been applied to the images.

I then get the original size image using a substring JS function but it is not entirely satisfying

(function ($, Drupal) {

  $('.bloc-image-gallery img').each(function (){
    var currentImage = $(this);
    var path=currentImage.attr("src");
    var StyleCutPath = path.substring(
      path.lastIndexOf("/") -7,
      path.lastIndexOf("?")
    );
    currentImage.wrap(''); });

  Drupal.behaviors.fancyBoxInit = {
    attach: function (context, settings) {
      $('[data-fancybox="gallery"]', context).once('fancyBoxInit').fancybox({
        buttons: [
          'close'
        ]
      });
    }
  }
})(jQuery, Drupal);

I wonder how i could get the href with an new style applied to it ( bigger image but not original size )

The src takes this form

  /sites/my_site/files/styles/directory_user_photo/public/2018-09/seminary.png?itok=5597asHF

i made it to

  /sites/my_site/files/2018-09/seminary.png

but i would rather have smthg as

  /sites/my_site/files/styles/my_new_style_adapted_to_full_screen_visio/public/2018-09/seminary.png?itok=5597asHF

clive would suggest to create a new Formatter for image type fields that would allow in the render display to select a image style for the image link.

At least i could do "In the field formatter settings you can tell the image to render in one style, but link through to the full image" and clean the code to:

(function ($, Drupal) {

  Drupal.behaviors.fancyBoxInit = {
    attach: function (context, settings) {
      $('[data-fancybox="gallery"]', context).once('fancyBoxInit').fancybox({
        buttons: [
          'close'
        ]
      });
    }
  }
})(jQuery, Drupal);

with in image-formatter--media--image--field-media-image.html.twig

   {% if url %}
      {{ image }}
    {% else %}
      {{ image }}
    {% endif %}


Changing article text and summary with template_preprocess_node() I use Drupal 7.9 with Views module (if the latter is important). I've created a small module for my site that changes transliteration of Japanese words in articles from Latin to Cyrillics and vice versa (yes, I need such a thing). User sees a form with radio button set, chooses transliteration, his choice goes to $_COOKIE and then I change transliteration in article summary and body based on user's choice. Or better to say I'm trying to change it but it doesn't work. The code goes like this:

function mymodule_preprocess_node(&$variables) {
    /* Suppose we have a summary containing only one word 'Yamamoto' that has to be changed to 'Ямамото' */
    $variables['node']->body['und'][0]['summary'] = 'Ямамото';
}

After this code is executed, the changed variable has the correct value of 'Ямамото'. But in the main page for some reason I see the unchanged 'Yamamoto'. What am I doing wrong? Do I change the wrong field? Do I mess up working with parameters passed by reference? Do I use the wrong hook?

I believe that the node has already been rendered by the time template_preprocess_node() is called so changing any values on the node object will have no effect. You can try looking at $variables['node']->content to see if you can modify the text in that (I think this is the full HTML rendered node though, so lots of extra text/markup to deal with here).

You're probably better off using hook_node_load() instead. This gives you a chance to alter the node object directly before it gets rendered.


Disabling update notifications I'm trying to remove the update notifications from the Drupal backend. I tried with Update notifications disable module but it breaks the "module" part of the backend. I can disable the Update manager module but i don't like this solution. Is there any other way to solve this problem?

If you just want to remove them for a less cluttered back end, that perhaps doesn't worry non-technical admin users you could maybe CSS them out?


Programatically change user field (entity reference) in drupalgap with user_save()? We are using DrupalGap to make an app. We have nodes (content type chargingstations) which we want our users to be able to "check" into by pressing a button. Until now I have created a button on the nodes page in DrupalGap which executes a function on an onClick event.

This function takes in a NID which is the node I want the user to check into. I then have a field on the user called "checked_in_chargingstation" which is an entity reference field.

In the DrupalGap documentation there is not much information on user_update. It just says "...". But it seems like you can update a node by passing the NID. So I figured I could do the same for user? But it doesen't seem to work. I get a success alert, but I can't see any changes to the users.

My check in code. Drupal.user.uid gets the current users uid.

function check_in($nid){
  var $field_checked_in_chargingstation = {};
  $field_checked_in_chargingstation["und"] = {
    target_id: $nid,
  };

  var user = {
    uid: Drupal.user.uid,
    field_checked_in_chargingstation: $field_checked_in_chargingstation,
  }

  user_save(user, {
    success:function(result){
      console.log(result);
    }
  });
}

In the console I get:

Looking at the json I can see:

"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "29088"
  }
 ]
},

But this is the wrong id. This is an old node which I have assigned before from Drupal and "edit" user. So it doesen't seem updated. Trying to drush cc all doesen't seem to work either.

If I try to edit the user from the app I only see null values for the entity reference field. One suggestion in the Drupalgap documentation is to make an entity reference view http://docs.drupalgap.org/7/Entities/Entity_Reference which I also did.

Sorry if this is a bit long. And I'm not sure if I should post it here on Stack Exchange or as an issue on DrupalGap.

It depends largely on what Widget you have selected for your entity reference field on your Manage Display page. The easiest widget to work with is the Autocomplete widget, at which point you'd send up this JSON:

"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "... (29088)"
  }
 ]
},

The Services module is coupled with the forms system in Drupal, so as you change the widget on a field, the JSON data you need to send to Drupal may change.


switch views or hide block based on content type I have a block view that gets its contents based on a contextual filter. I only want to use this filter if it's a certain node type being displayed ie. the block would use the contextual filter on basic pages but on article and other pages I would like to set the contextual filter to a default value.

One way I thought I might do this is to change the views display based on the node type and then override the settings in the second display. Is this possible?

I created my second display for the view and I added both blocks to the same region. One of them I set to only display on basic pages. The other one I would like to set to only not display on basic pages. The block system only lets me select which content types to show the block on not which content types to exclude it from. I don't want to keep coming back to this page and having to check more boxes as I add new content types.

Is there any way to exclude a block from being shown on a certain content type?

It's possible with views:

#1 Configure field with images:

#2 Add contextual filter:

#3 Save the contextual settings and then add "No result behavior':

#4 You just need to display a default image in case the other content type than basic page, so you can apply the Unfiltered text, and type the html source of the image:

That's it!


rest namespace not recoginzed in custom REST API class I'm working on creating my first custom REST resource in D8, and following this blog post, I have the following class in the /modules/custom/video_export/src/Plugin/rest/resource directory:

<?php
/**
 * @file
 * Custom Rest resource for video nodes.
 */

namespace Drupal\video_export\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "video_export_source",
 *   label = @Translation("Video Export Source"),
 *   uri_paths = {
 *     "canonical" = "/videos/feed/{site}"
 *   }
 * )
 */

class VideoExportResource extends ResourceBase {
  /**
   *  A curent user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
    * @param array $configuration
    *   A configuration array containing information about the plugin instance.
    * @param string $plugin_id
    *   The plugin_id for the plugin instance.
    * @param mixed $plugin_definition
    *   The plugin implementation definition.
    * @param array $serializer_formats
    *   The available serialization formats.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
    * @param \Drupal\Core\Session\AccountProxyInterface $current_user
    *   A current user instance.
  */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }

  /**
    * Responds to GET requests.
    *
    * Returns a list of video nodes to be imported into the target site.
    *
    * @return \Drupal\rest\ResourceResponse
    *   The response containing a list of bundle names.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
  public function get($site = NULL) {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

However, I'm having multiple problems trying to use this code:

First, my IDE (PHPStorm) is not recognizing the namespace keyword. In addition, in my the rest dir in that path is highlighted in red, and it shows an error message on the resource keyword that says

  Undefined constant resource: declaration of referenced constant is not
  found in built-in library and project files.

I've verified that I have the RESTful Web Services module enabled.

Also, I have the REST UI module enabled, and it lists my resource, but when I try to enable it, it tells me undefined namespace Drupal\video_export\Plugin\rest\resource', which I'm sure is because of the other errors.

I've looked this over and over and can't see what's wrong

As indicated by the comment by @ssibal, I just had to remove the line and then manually add it back in. The second time it took fine, and my resource works now.


Terms for cities and state to build dependent selects I'm adding a "City" field to a content type. I need it to be 2 dependent select lists. I mean, the user will select a state in the first select and the second select will be populated with the cities for the selected state.
In fact those are for Spanish provincias (states) and localidades (cities).

I know I can do this using the 'hierarchical_select' module, but now I need to create the taxonomy Terms for states and cities.

Is there any way to find and import those Terms (Spanish provincias and localidades) into my site? Creating these term is a daunting task.

You can use the module Taxonomy CSV import/export which is very handy to import and create taxonomy terms or vocabulary.


Setting error text in Commerce Alter Form Module I need to validate my form and return a specific error message if the terms of agreement checkbox isn't checked (it's a required field). So I've placed the following code in my CommerceAlter.module. However, it's not working (ie. the error text is still showing the default error text):

function CommerceAlter_form_validate(&$form, &$form_state, $form_id) {
  if (form_get_errors()) {
    $form_errors = form_get_errors();
    $drupal_errors = drupal_get_messages('error');

    // Clear form errors
    form_clear_error();

    foreach($drupal_errors['error'] as $key => $error) {
        if (in_array($error, $form_errors)) {
            // Unset form errors
            unset($drupal_errors['error'][$key]);
        }
    }

    // Rebuild drupal errors
    foreach($drupal_errors['error'] as $key => $message) {
        drupal_set_message($message, 'error');
    }

    // Validate form field and set error message
    if ( $form_state['values']['customer_profile_billing']
['field_i_have_read_and_i_agree_to']['und']['0']['value'] === 0 ) {

            form_set_error('value', t('You forgot to check the required
checkbox. Please try again.'));
        }
      }
    }

Any idea what I might be doing wrong here?

I guess you can obtain the field value using this.

if ( $form_state['values']['field_i_have_read_and_i_agree_to'] == 0 ) {
  //or use this in if statement $form_state['values']['customer_profile_billing']['field_i_have_read_and_i_agree_to']

      form_set_error('field_i_have_read_and_i_agree_to', t('You forgot to check the required checkbox.Please try again.'));
    }

You shouldn't include ['customer_profile_billing'] unless you have set the #tree to TRUE.


How much of Drupal 8 will rely on or be compatible with Symfony? Now that Drupal 8 is being redeveloped with Symfony, and we are just about to go into the code freeze so that early adopters can start playing with it, what will it affect?

Will we be able to write modules and themes like writing bundles? Should we all start brushing up on or learning Twig?

Symfony, as in full stack Symfony, we aren't to be compatible with.

We are using Symfony components so many concepts used there will be useful.


Where can I set the following HTML attribute to my custom field? I'm developing a custom module with an image field.

Where can I set the following HTML attribute to my custom field?

<input type=file
       accept="image/*"
       capture=environment>

I have created the image field and i'm able to process some OCR with an external library uploading the image but I need to use webcam instead and I can't find the way to set the "capture=enviroment" tag to my input form in the field widget file.

Thank you

Solved with formElement, at least form mobile devices. Just was I was looking for.

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['#accept'] = 'image/*;capture=camera';

    return $element;
  }

Thank you!


Security advisories api Is there an api to use to get data from https://www.drupal.org/security?
I'm looking to get for example all vulnerabilities for older versions of a module.

There are three RSS feeds:

Core security announcements
Third-party modules announcements
Public service announcements

Using PHP, you can parse one of those RSS feeds to get the data you need.


Disable Commerce Card on File for Donation Product Type Using Commerce (7.x-1.1), Commerce Card on File (7.x-2.0-beta5), Commerce Recurring Framework (7.x-2.x-dev) and Commerce Donate (7.x-1.0)

I need Commerce Card on File for my recurring product entities, however I do not want the functionality applied to Donation Products.

How do I keep the Commerce Card on File functionality for recurring products, but disable it for donation products?

If you go to the Payment method configuration screen (admin/commerce/config/payment-methods), you'll see that each payment method is a rule. If you click on 'edit' you'll get a rules configuration screen.

Next, click on "Add condition" under the conditions section. Here you can choose the various conditions that allow (or disallow) a payment method to be selected.

You've got the order object here so you can choose 'Order contains a particular product'.

Then enter the SKU of your donation product in the field provided:

Finally, make sure 'Negate' at the bottom of the rule configuration page is checked.

Now that payment option will only show up if the order does not contain that product.


Printing the correct date value in a view I have a content type with a Date CCK field that prints the correct date/time specified in nodes (using the correct timezone, format, etc.). I also created a view that uses this date field, but the time I am getting from the view date data is (+)4 hours off. The date information is being printed in a views template using the $row object (specifically, the raw array key inside of the date field array). This array provides the 'to' and 'from' dates (and time), the timezone, and all other relevant information, but the values are 4 hours off as I said above.

Is there something I need to do when printing these kinds of values in a view in order to get the correct time? I'm assuming the Date module does some sort of processing that the views data isn't getting. Any guidance would be great because I have no idea why this is happening.

Double check that your site's timezone is accurate at: Site Configuration > Date & Time
Double check that your user timezone is accurate in your profile. Perhaps turn off user timezones (on the same admin pages as above.)
Confirm how timezones are handled on the specific CCK field. There are 5 options:
Site's time zone, Date's time zone, User's time zone, UTC, and No time zone conversion.


How to add additional tab in the User Profile page using views I have installed the flag module and it comes with some 2 views that are added to the list of views. One of them will stick to the user page as an additional tab and when clicked will show a list of all the nodes that were flagged by that specific user being previewed. So far so good.

The problem is that in my website I don't use the path "user/uid" for the user pages. I use the path (example) "somethingelse/uid". When I enter the view and edit the path for this tab page with "somethingelse/uid", save the view and reload the user page... the tab with the list of items flagged by the current user disappears completely.

How can I bring that tab back on the user page? I am on Drupal 7.

somethingelse/<uid> is a path alias for user/<uid>. When you set the path for a view, you need not to use path aliases.


CKeditor removes iframes in editor after update to 6.x-1.14 Similar to this issue on the CKeditor project, CKeditor removes embedded iframes after I've updated the module. Though there is a solution in the first comment for Drupal 7, I can't find a solution for this for Drupal 6.

Is there a solution to this?

In ckeditor.config.js, add config.allowedContent = true; to disable the filtering of HTML elements in the editor.

CKEDITOR.editorConfig = function(config) {
    config.allowedContent = true;
}


String Overrides is not overriding the "Read more" string I've filed a support request on drupal.org about this question, but I figured I should ask here as well because someone could know the answer.

I want to change the "Read more" link in teasers so that it says "Full story". I was pointed to the String Overrides module which supposedly makes it very simple to change the built-in strings. The UI isn't very complicated, so I'm not sure what I could possibly be doing wrong, but it's not working. I have saved the settings, flushed all caches, etc.

Do you have any idea?

Might need some tweaking, but you can change the text in hook_preprocess_node(). If you set it to "Read more" you can override it with stringoverrides after, or change it to what you want at once.

In your themes template.php, add:

/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_process_node(&$vars) {
  // Change default text of the read more link.
  if (isset($vars['links']['node']['#links']['node-readmore'])) {
    $vars['links']['node']['#links']['node-readmore']['title'] = t('Read more');
  }
}

Related modules:
http://drupal.org/project/readmorecontrol
http://drupal.org/project/read_more
http://drupal.org/project/linkoutreadmore


How to change "Your name" label in comments form? I have a blog with comments and I need to change the "Your name" field to something different and make it a required field.

Can I do this from hook_form_comment_form_alter() hook in template.php or in a comments template?

You can do it in a hook_form_alter() function like you suggest:

function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $label = t('New label');
  if (isset($form['author']['_author'])) {
    $form['author']['_author']['#title'] = $label;
  }
  else {
    $form['author']['name']['#title'] = $label;
  }
}


How to set up path for library and include files In Drupal 7, I am writing PHP from inside the Front Page module, say:

$page = include_once "templates/page.php";

I put the "templates/page.php" under /sites/all/modules/front and Drupal complains about file missing. Any suggestion where best to put up the files to be included?

Then, after installing the PHP Simple HTML DOM Parser, I wrote the following

$html = new simple_html_dom();

and was complained for Class 'simple_html_dom' not found. I have tried duplicating the library file to the same folder and home, but all cases not working. How to set up the correct path?

Many thanks.

If it's a theme function, guessing from the file name you mentioned, you should use them theme() function to get the themed output.

To get the path of a module relative to the Drupal root, use drupal_get_path() function.

If you want to include or require a file, you can use module_load_include(). However, note that if the including files print anything, they will be printed to the current output buffer (which means they will be printed on user browser).

Given the above available features, I think it's theme() that you are looking for.


How to create a simple shopping cart without Drupal Commerce or Ubercart? I want to make a simple order web site for selling some poster. I don't need to add to basket or complicated order stuff. I need only list my posters in catalog view and when clicked one of them appear detail about poster. And in the detailed page I need an order button and then order form.

What is the best way for this? I mean I use Views for catalog and detail page. My question is How to configure when user click an catalog item and the user goes to detailed page with created views?

Maybe you should just use webform or entityform. With the flag module you can achieve that multiple items can be ordered. If there is no need for payment or checkout like in a 'normal' webshop, do not make it more complicatet than it is: actually you want your visitors to be in contact about one or more items on you website and get their details.


Define states that target only element in multi-value fieldset I am using Webforms in Drupal 8, and I have a checkbox on a webform composite element which basically show/hides an address field.

public static function getCompositeElements() {
  $elements = [];

  $elements['address_same'] = [
    '#type' => 'checkbox',
    '#title' => t('They live at the same address'),
  ];

  $elements['address_postal'] = [
    '#type' => 'textfield',
    '#title' => t('Street address'),
    '#states' => [
      'visible' => [
        ':input[name="spouse[address_same]"]' => array('checked' => FALSE),
      ]
    ]
  ];
}

The issue I have is that this group of fields may have one or more values on the form, and if there is more than one then the states get all confused because they are targeting the wrong field.

This may be the same on Drupal 7, but I can not figure out how to give #states a generic selector for address_same so that it only targets the one just before it.

Most likely I will just go write some custom jQuery for this, just thought there must be a way of doing it.

See the first comment on my question, the Webform module (super-duper) maintainer @jrockowitz committed a change to the module's composite element example which explains how to do this in Drupal 8.

So this is my solution based on the question code:

use Drupal\Component\Utility\Html;
use Drupal\webform\Element\WebformCompositeBase;

class MembershipItem extends WebformCompositeBase {

  public static function getCompositeElements() {
    $elements = [];

    // Generate an unique ID that can be used by #states.
    $html_id = Html::getUniqueId('webform_membership_item');

    $elements['address_same'] = [
      '#type' => 'checkbox',
      '#title' => t('They live at the same address'),
      '#attributes' => [
        'data-webform-composite-id' => $html_id . '--address_same'
      ],
    ];

    $elements['address_postal'] = [
      '#type' => 'textfield',
      '#title' => t('Postal address'),
      '#states' => [
        'visible' => [
          '[data-webform-composite-id="' . $html_id . '--address_same"]' =>['checked' => FALSE],
        ]
      ]
    ];

    return $elements;
  }
}


How do I unfollow an issue on drupal.org? How can I unfollow (i.e. unsubscribe from email notifications) an issue on Drupal.org that I automatically followed when I commented on the issue?

To unsubscribe to the issues for a project, for example the "Drupal.org web masters" project, you need to:

visit the issue page for the project (http://drupal.org/project/issues/webmasters)
click on the "Subscribe" link

In the next page, select "None," and click on "Subscribe."

Unable to unsubscribe to drupal.org issues is an old issue that has been opened in 2006, and it has been marked as fixed. I can confirm that unsubscribing from an issue queue works, as I have done it many times in the last years.


What is best coding practices for providing an upgrade path to a new module version? I'm getting ready to build a new version of a module of mine. The new version can have an upgrade path from the current version to the new version that will be released, but as you know, new major verions come with database restructuring, entity refactoring, and what not.

Is there a standard practice in the way the upgrade path is provided? For instance, should I build code in the install hook of the new version, and update hook, or some stand alone script?

Suggestions welcomed.

Add the install information required for the new module version in the hook_install and hook_schema.

Users upgrading presumably won't be re-installing the module, so you'll need to use hook_update_N for those users. Check if the upgrade path is required for that installation and proceed with the update as needed.


Uploading images in a node with WYSIWYG and TinyMCE 3.4.3 I am trying to put images in a node with the WYSIWYG editor and TinyMCE 3.4.3.
I uploaded an image, and with the editor I inserted the image in a node; the problem is that at first click the image doesn't appear in the node, and I must try another time to see the image.
Is it a bug?

Check your Input Filters field-set while editing your node, in case of filtered html your image would not be presented. Try with full html.


Programmatically load the contents of a Product in a particular product type I am developing an Ecommerce site and I am using Drupal-commerce module for it. I have an issue regarding loading the contents of a product which is: How can I programmatically get the contents of all the products in a particular product type?

This can be done with an EntityFieldQuery:

<?php
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->execute();
  $nodes = node_load_multiple(array_keys($result['node']));
?>


How to detect mobile viewport with in twig? Is there a way to detect screen display with in twig? I have a block and I want to render in a twig template using the twig tweak module, but only in mobile screen. It is surely possible to just hide it in CSS, but can it be done in twig? - https://www.drupal.org/project/twig_tweak

There is a Browser Object in twig which using that you can get some data about user's browser but it does not provide properties like screen width.

its recommended to use css or javascript in these situations but if you want to hide your block in server side so user might access only using a mobile phone then I recommend this steps:

first of all you should provide a value to check if user is using mobile or not, for this you should use a preprocess function (hook_preprocess_page I guess as will fire for any pages loaded) , there use a code like this to detect mobile, then add a boolean value to page which should be TRUE if user is using mobile.
after that in twig you will have that value, check if it is true and display your block


how to add a serial number column in a view? I created a view in drupal and needs some serial numbering as the first column which is not there in the content type on which I created the view. My question is how to add that serial number field in this view like this

cand_name | phone_num | email id

is my view

I want it like this..

sno | cand_name | phone_num | email id

hope I am clear, write comments if it needs still clear explanation.

Thanks in advance

You should use Global: view result counter field defined in a view.

OR if you want a serial field for the content type you can use

the module serial field


Check if form already failed validation I added a validation hook to a node creation form.

For my project, i need this validation only ONE time: basically i just check if a value already exists in the DB and i notify it to the user. If the user still submits the form, i must add it anyway.

i would like to do something like that:

if (form_did_not_fail_validation_before) {
  $form['#validate'][] = 'my_module_validation_hook';
}

in my hook_form_alter, so that validation hook is only called the first time.

I can't find a way to check if the form already failed validation, any ideas?

Two possible solutions: 1) set a session var in your validation script to flag when validation fails, then you can check if that session var is set (validation failed once) then add it anyway. 2) If you can't rely on session var, you can look at adding a custom boolean field to your user to flag this this user has failed validation once, then check if that field if true(failed once)/false(hasn't failed yet) and code accordingly, and you'd want to reset this field to false again once the node has been created in case you need to use it again for another node form.


Stop exposed filters from rewriting url to begin with taxonomy/term/all I have various views that show a limited range of nodes. For example going to collections/country-animals shows nodes with the taxonomy term 'country-animals'.

I have exposed filters enabled on these views, but unfortunately using an exposed filter rewrites the whole URL ignoring the fact that the user was viewing 'country-animals' and wishes to refine the current view by the terms selected. For example refining by 'gold' rewrites the URL to taxonomy/term/all?field_classification_metals_tid[]=89 and shows all nodes with the taxonomy term of 'gold' instead of nodes with the taxonomy term of 'gold' and 'country-animals'.

If I take the URL of the page I was on and combine it with the end of the URL that exposed filters creates (collections/country-animals?field_classification_metals_tid[]=89) I get exactly the view I want all the 'country animals' refined by 'gold'.

How do I make the exposed filters use the correct URL automatically instead of starting each URL with 'taxonomy/term/all'?

I get the same results with and without better exposed filters.

Here is the view settings page:

I am using Drupal 7 and Views 7.x-3.7

Assuming Drupal 7.x and Views 3.x.

Edit the View. In the filter config, make sure the "Allow multiple selections" option is ticked. Without that, you've configured the filter to only allow a single option per filter.

If "country-animals" is setup as a contextual filter, you'll need a patch from this issue to allow multiple terms.

Hope that helps.


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

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


CCK field value count is never less than 1 I have got a CCK field set up so that unlimited values can be entered upon node creation (number of values: unlimited).

When I try to print values in a node with the following code

if ($node->field_tip != NULL) {
  foreach ((array)$node->field_tip as $tip) {
   print "
" . $tip['view'] ."
";
  }
}

or I print count($node->field_tip), the value is never less than 1, and

 is always displayed, even if there aren't values entered in that field.

As far as CCK is concerned, there is still a value, it just happens to be blank (most likely an empty string, depending on what type of field you're using). If you modify your code to check the raw value, you should only see output when there is an actual value:

if ($node->field_tip != NULL) {
  foreach ((array)$node->field_tip as $tip) {
    if (!empty($tip['value'])) {
      print "
" . $tip['view'] ."
";
    }
  }
}


Services json node object There seems to be a problem with the Services module of Drupal 7 when submitting nodes using the node create reosurce, for example I can create nodes just fine, even with custom fields, but the problem is with term reference fields, the values never gets to them, here is an example:

var nodeCust={
node:{
  title: 'undefined test 1',
  type:'noticia',
  name: 'admin',
  body: {
    und: [
    {value:'sdasdasd', format:'full_html'}
    ]
  },
  field_custom:{
und:[ {value: 'test placeholder'} ]
  },

  field_theterm:{
und:[ {tid:"1"}  ]
  }
 }
};

This is the object I send in JSON, and it works great the body has its value, the title and the custom field as well, but the "theterm" field is a term reference field in this content type, and it NEVER gets its value :o( , I tried with all the widgets, autocomplete, list etc but that should not really affect this since this is a REST Services call w/JSON.

Any ideas anyone? Thanks

The structure of what you submit through the API should generally be the same as the structure of the data you submit through the ordinary node form as the resource methods for creating and updating nodes are simply thin wrappers around a form submit. Even the validation and most errors come from the form handlers.

So my suggestion is that you look at how the form submits stuff as that's where you will likely always find the answer.


How to set permissions for cron for other roles (not administrators) Hello I need to set permissions for editor role. The editors need cron to send maillists/newsletters. How do I make cron available for them? It seems there is no way.

The permission to run cron in Drupal 7 is Administer site configuration.

Warning: Give to trusted roles only; this permission has security implications.

It can debated whether it is a good idea to give permission to the editor role, as opposed to running cron automatically every five minutes.

However, in my use case cron does some heavy lifting every time it runs, so running it every five minutes would make my site very slow, creating a bad UX. I've scheduled it to just run cron automatically once per day (at 3 am). I use Notify to distribute newsletters, and it in turn relies on cron, so I permit trusted editors who use the site for sending out newsletters hit cron manually if there is some urgency about getting a newsletter distributed.

The path to the Drupal cron UI is admin/config/system/cron. It is probably a good idea to add this path to some menu the editor has access to make it easy to find.


how to hide a field when adding content through node/add for a content type? I have 7 fields in a content type and the last field value, I am updating programmatically. So it should not be displayed when adding content to it. What should I do.

The way I prefer is to use Computed Field module. Not only it creates a field that's not editable for users, it also takes care about hooks, cache, and lets you simply choose recalculation strategy (on save / on display). All you really need to care with it, is the very code that calculates field's value.


Why doesn't "drush --debug en color" show any output? Running drush en color from the /xampp/htdocs/drupal directory doesn't output anything. The same happens with drush --debug en color. Why?

It seems that your drush installation is broken. So you have to reinstall it again.

The easiest way would be to install Composer and follow the instructions from drush-ops (especially check Windows section). Then check How to configure Drush on Windows 7?

If this is still happening, check your PATH environment variable if it contains the correct directories (maybe you have some non-drush binary within your system list of folders which could cause some conflict).


Is there potential performance loss by using multiple nodeapi calls instead of one? I have a fairly large site with multiple custom modules. I've started to split some of the larger modules out into smaller more maintainable ones.

I have one particular module that I'm splitting into three. It has a hook_nodeapi function that does various different things, would there be much of a performance loss in splitting one nodeapi call into 2 or 3? Has anyone done any benchmarks on this subject?

There is a performance loss with additional modules. Mostly due to more opening parsing and function_exists() and memory use.

Node api in 6 will be called for every node action and called for each node. (in 7 multiple nodes can be used at once and there is a separate hook for each action)

So if you are careful:

Put all your code inside a switch($op);
Check the content types to work on what you need
Keep DB queries to a minimum

there will be little overhead (some but not overwhelming).

If on the other hand your nodapi call, share DB queries (or can share DB queries), have a lot of setup / code which is common, then you may start to be hurting yourself performance wize.

One way round this is to be a bit more selective with the code you include:

mymodule_nodeapi($op, ...) {
 switch($op) {
  case 'load':
    // Insert common code here.
    if ($node->type == 'my_complex_node_type') {
      module_load_include('inc', 'mymodule', 'complex_type');
      mymodule_complex_load($node);
    elseif ($node->type == 'some_other_node_type') {
      module_load_include('inc', 'mymodule', 'other_type');
      mymodule_other_load($node);
    }
  break;
 }
}

Rough pseudo code

You can keep your code in seperate files to aid maintainability and keep load time down as files are only included/parsed when needed.

The downside is you need to manage the include and callback yourself rather than relying on module_invoke_all.


Custom content drupal6 I'm new to drupal, so forgive me if my question will be silly :)
I've a little problem with my first custom content on a drupal 6 installation. My content "biography" is listed in admin/content/types page, but when i click on my type, page reloaded instead of loading /admin/content/node-type/biography

If i force the url in the browser, i'll be redirect to /admin/content/types page again.

Do you know why? I've implemented both the node_info and form hooks, but with no luck.

Thank you in advance and sorry for my english! Have a nice day!

UPDATE

I cant reply on my own post because i still have low reputation, but...

Bingo..Thank you ARUN! I had been deceived by the fact that it had appeared in content type's list without clearing cache!

have a nice day!

That might because of cache. Clear your site cache here /admin/settings/performance. Then try to load your content type edit page /admin/content/node-type/biography.


Price Range in Drupal I am using ubercart where I enter different price ranges.

In the left sidebar, I want to display different price ranges like:

less than 20$
21-40$
41-65$
more than 65$

So that whenever I click on one of these items all products in that price range will show up.

Does anyone have any ideas about how to do this?

Thanks.

use facetapi or faceted_search module i think it helpful..


Payment Information on hook_commerce_checkout_complete I am developing module which connects Drupal Commerce with 3rd party invoicing system. For this purpose I need to send payment information (has it been paid? how much? in what way?) after the order is complete. I guess the hook_commerce_checkout_complete() hook is the best place to do that but I can't figure out how to obtain this payment information from an $order object/entity.

You can see the payment method the customer selected in the $order->data array, and to determine if the order was paid in full you'd use commerce_payment_order_balance(). Any additional information would have to come from payment transaction entities whose order_id match $order->order_id.


How to display the selected value from the drop-down box? The following code is displaying the states, but when I click the submission button, I want to display the selected state and city. I am not able to display it. How can I achieve this?

$form['state1'] = array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' => $options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
);

function _ajaxfunction($form, $form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;
  $query_city=db_select('city', 'c');
  query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  foreach ($city_results as $city_record) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city'] = array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,);

  return $form['city_element_wrapper'];
}

The following code is not working properly:

function form_test_form_submit($form, $form_state) {
  echo $prog_state = $form_state['values']['state1'];
  echo $data1 = $form_state['values']['city_element_wrapper'];
}

form_test_form_submit is called in php that's not displayed to user. Form is processed, it's values saved, and user is taken to desired page. Now you have 2 options:

In submit handler set$form_state['redirect'] to a page you like. Save values to a database. On target page read them and display.
In validation handler add markup elements with selected values, if you want to emphasize selection but leave user on a form.


Path alias and taxonomy term view I have PathAuto providing /term/[term:name] for terms of a specific vocabulary.
If I hover over the link for any of the terms, the path given is the alias.
When a term page is requested, e.g. /taxonomy/term/2, why isn't the page URL replaced with the alias?

Normally the internal links /taxonomy/term/% are not used anymore, because all links Drupal puts on the page are aliased. If you want to prevent having multiple paths for the same page you can install https://www.drupal.org/project/redirect.
From the project page:

D8: Maintaining a canonical path and redirecting alternative URL's    like non-aliased path, path without language prefixes and so on
(Previously provided by Global redirect)


What is the 'System' display option in Views? Could you tell me what the "System" display in views is? (shown in red)

I suppose it's a presentation which is only available programmatically, but I'm not 100% sure.

Thanks.

Today I was in the same situation, so I decided to look and this is what I found:

  So, for anyone stumbling upon this, 'system' displays are only to override core views (which you do through the System Path Settings area in the Advanced section of views) and I should just be using a page display with a path that begins with '/admin/' if I want to make custom admin views.

Here is the link: https://www.drupal.org/node/2539256#comment-10150524