In Views, display additional fields from an entity reference I have a content type with a field that is an entity reference to another content type called "URLs", and the "Allowed number of values" is set to "Unlimited", meaning that one record can have multiple URLs associated to it.

When I come to the View for this node, I have added a Field for "URLs", and under "MULTIPLE FIELD SETTINGS" I have ticked "Display all values in the same row", and Display type: Unordered list.

This works well, and I get the the list of associated URLs in an unordered list, like so:

www.domain1.com
www.domain2.com
www.domain3.com

Where it gets complicated, my "URLs" content type has another field called "field_url_type", which is a field type "List (text)". This contains the type of URL, (eg. Production, Development, Staging, Decommissioned, etc).

In the main content type display View, I would like to display this additional field from the URL content type next to the URL values, like so:

www.domain1.com (Production)
www.domain2.com (Development)
www.domain3.com (Decommissioned)

I tried using the Views > Configure Field > REWRITE RESULTS panel to include the REPLACEMENT PATTERNS for both fields, like so:

{{ field_url }} ({{ field_url_type }})

... but this didn't work. I'm guessing it is more complicated than that!

Does anyone know how I can display this additional field from a content type referenced by an entity reference field in a node view?

Many solutions for this but to pick one :)

Download and enable Display Suite https://www.drupal.org/project/ds
Go to admin/structure/ds/fields and a token field (see screenshot #2 for values, adjust according to your field names)
Go to view mode of your Url content type and create a seperate view mode, e.g. called entity_reference_url_view or something (I just picked teaser for this example) . Make sure to select One column layout so Display suite will make your custom token field available to you (see screenshot #1)
add the custom token field you added earlier to the visible section
Now go to your other content type view at e.g. admin/structure/types/manage/your_content_type/display/full and select Rendered Entity as the format and choose your previously created view mode of the URL content type (see screenshot #3
Now view your content type and the entity reference fields should show up in the format you defined in your custom Display suite field

Screenshot #1

Screenshot #2

Screenshot #3


Links on site adding index.php in URL I have a Drupal 8 site and am encountering an issue. When I visit the site as an anonymous user and click a link on the menu, it adds /index.php to the url. Then if I navigate to that page and click another link in adds another index.php (i.e. example.com/index.php/index.php/link1/link2) and therefore the page will not load. This does not happen if I am logged into the site, has anyone encountered this before? I tried a fresh htaccess file and beyond that I am stumped. It is on a shared hosting plan. Any help is appreciated.

I had the same problem.

I have a view with links to content, where the URLs are item/[one content's field value]. One day, I watched the view as anonymous user and noticed that these had been changed to index.php/index.php/item/[one content's field value]. (On the other hand, when I visited as administrator user, it didn't happen.)

I didn't know why it happened, and it was solved by executing drush cc render.

However, the problem would still be left.

The environment is Drupal 8.3.9 and PHP 7.0.25.


OAuth2 login provider - endpoint page I have installed OAUTH login provider and all dependencies to provide authentication service to other web application throug drupal authentication.
The problem is that I still do not manage to test if the drupal auth login provider works correctly. I am not sure what is the URL that I shoud put in the client application to reach the server auth provider.

For example in local development environment if I try

https://localhost/oauth2_loginprovider/

I get a FORBIDDEN response from Apache while if I try to contact

https://localhost/oauth2/ ...

I get a 404 page not found on the server

Could you please help me?

Have you tried https://localhost/oauth2/authorize ? That is the authorization start point for me.


Activate or DeActivate requirement status of field based on another field I want to alter a form in my drupal 7 project.
I want to activate or deactivate requirement status of a field programmatically based on another field value.

if field value is male , military status field must be required but if it is female, military status is not required and also it must be hide.

Please guide me in this issue.

What you could do is make the military field not required. Then add your own validate function to the form with:

$form['#validate'][] = 'my_function_name';

Then in your function you can do a check e.g.

function my_function_name*$form, &$form_state){
  if($form_state['values']['my_gender_field'] == 'male' && empty($form_state['values']['my_military_field'])){
     form_set_error('my_military_field', 'Military field is required');
  }
}

Or you could try using #states from the form API which has a 'required' option:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#states


Adding a class to a region I am working on my theme in Drupal 8 and I want to add a class to my header div. I tried adding this to the region.vars.php file.

if ($region === 'header') {
  $variables[header]['class'][] = 'navbar-right';
}

It's not working, though. This is the complete region.vars.php file.

<?php
/**
 * @file
 * region.vars.php
 */

use Drupal\Core\Template\Attribute;

/**
 * Implements hook_preprocess_region().
 */
function bootstrap_preprocess_region(&$variables) {
  $region = $variables['elements']['#region'];
  $variables['region'] = $region;
  $variables['content'] = $variables['elements']['#children'];

  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Content region.
  if ($region === 'content') {
    // @todo is this actually used properly?
    $variables['theme_hook_suggestions'][] = 'region__no_wrapper';
  }
  // Help region.
  elseif ($region === 'help' && !empty($variables['content'])) {
    $content = $variables['content'];
    $variables['content'] = array(
      'icon' => array(
        '#markup' => _bootstrap_icon('question-sign'),
      ),
      'content' => array(
        '#markup' => $content,
      ),
    );
    $variables['attributes']['class'][] = 'alert';
    $variables['attributes']['class'][] = 'alert-info';
    $variables['attributes']['class'][] = 'messages';
    $variables['attributes']['class'][] = 'info';
  }

  // Support for "well" classes in regions.
  static $wells;
  if (!isset($wells)) {
    foreach (system_region_list($theme) as $name => $title) {
      $wells[$name] = bootstrap_setting('region_well-' . $name);
    }
  }
  if (!empty($wells[$region])) {
    $variables['attributes']['class'][] = $wells[$region];
  }

   if ($region === 'header') {
    $variables[header]['class'][] = 'navbar-right';
  }

}

I got most of this code from the Drupal 8 bootstrap theme. Everything else is working.

What I normally do for all my themes is to add the missing region region-name class to each region by implementing hook_preproccess_HOOK in MYTHEME.theme.

/**
 * Implements template_preprocess_region().
 */
function MYTHEME_preprocess_region(&$variables) {

  // Add missing region CSS classes.
  $variables['attributes']['class'][] = 'region';

  if (isset($variables['region']) && !empty($variables['region'])) {

    $variables['attributes']['class'][] = 'region-' . str_replace('_', '-', $variables['region']);
  }
}


How to subscribe to notifications or alerts via RSS feeds? How would I go about adding the functionality of subscribing to notifications or alerts via RSS feeds for certain pages/documents or images?

You can create custom feeds using the views. This can contain any fields as you want. And use all the filters, relationships and contextual filters to get the exact feed that you are looking for. The you can place feed link where ever you want it to be seen. This would be done using blocks or may be simply by adding it to the page.


How to show kint debug info from a module on a page? In D8 I would like to display an array in the message part of a page. I did several things but could not get it work. What to do?

I installed the devel and kint modules.

I currently have changed  in services.yml the settings into:

debug: true
auto_reload: true
cache: false

In the twig template I added

{{kint("I'm working from the page.html.twig")}}

This is displayed in the browser, so the current theme is displaying it which proves kint is working and the correct theme is used.

So now In my module file I have

$data_array = json_decode($data,true);
kint($data_array);
var_dump($data_array);
return $data_array;

The var_dump gives a lot of data in a array. However the kint is not displayed.

How to get the kint displayed this array?

Try to take a look at this site it has a lot if useful information, print variables using kint.

They say that if you want to output in the message area then you shall use, ksm().


Show parents at first level then child in each page So I made a view and attached it to head of another view, what I want is at the second view page only shows the parent, but when a user click on the parent term, it now show the child terms of that parent.

Parent 1
--Child 1
--Child 2
Parent 2
--Child 3
--Child 4

For instance if anyone click on parent 1, now the view that is attched show Child 1 & Child 2

I found a similar question here but no answer there.

If I am understanding your requirement correctly, you want to display "Parent Term" in top of the view page and when user click on any "Parent term", you want to display child of that term in the same page.

I have created a views and add attachment to display "Parent term" in top of the page. I have added "Taxonomy Vocabulary" filter, so please change filter in views as per your requirement.

Exported version of the view:

$view = new view();
$view->name = 'test_category';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Test Category';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test Category';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Parent term */
$handler->display->display_options['relationships']['parent']['id'] = 'parent';
$handler->display->display_options['relationships']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['relationships']['parent']['field'] = 'parent';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Taxonomy term: Parent term */
$handler->display->display_options['arguments']['parent']['id'] = 'parent';
$handler->display->display_options['arguments']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['arguments']['parent']['field'] = 'parent';
$handler->display->display_options['arguments']['parent']['default_action'] = 'empty';
$handler->display->display_options['arguments']['parent']['default_argument_type'] = 'taxonomy_tid';
$handler->display->display_options['arguments']['parent']['default_argument_options']['node'] = TRUE;
$handler->display->display_options['arguments']['parent']['default_argument_options']['vocabularies'] = array(
  'product_category' => 'product_category',
);
$handler->display->display_options['arguments']['parent']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['parent']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['parent']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  3 => '3',
);
/* Filter criterion: Taxonomy term: Term ID */
$handler->display->display_options['filters']['tid_raw']['id'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['tid_raw']['field'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['relationship'] = 'parent';
$handler->display->display_options['filters']['tid_raw']['operator'] = 'not empty';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-category';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Taxonomy term: Term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['default_action'] = 'summary';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['count'] = FALSE;
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['tid']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['tid']['validate']['fail'] = 'summary';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  3 => '3',
);
/* Filter criterion: Taxonomy term: Term ID */
$handler->display->display_options['filters']['tid_raw']['id'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['tid_raw']['field'] = 'tid_raw';
$handler->display->display_options['filters']['tid_raw']['relationship'] = 'parent';
$handler->display->display_options['filters']['tid_raw']['operator'] = 'empty';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['inherit_arguments'] = FALSE;


How to extract content from database How can I extract my content from the database?  My specific use case is to be able to migrate my content out of Drupal to do a 100% clean re-installation and then restore all my original content, but just in general, it seems to be a huge gap in the design of a content management system that I can put content in to be managed, but I can't get it back out again.

I understand that there are a myriad of variables in this use case such as module-specific tables that may contain some of my content.  I'm asking about the base case without regard to those individual considerations.  I would like to start simple; I can address additional, specific factors as they come up.

In searching online, I've only found workarounds to this issue.  I'm not asking about workarounds (eg. the Features module) or ways to do something else that is similar to my question.  Is it possible to extract my content from the database--at the very least, for the purpose of reloading it into a new, identical installation.

Put another way: in a vanilla installation, in what tables is the content stored?

There's almost certainly no such thing as "no individual considerations" on Drupal sites.

Even on a Drupal 7 site with no contributed or custom modules, this isn't easy to do.  You might have many content types, with all their fields and associated configuration.

Some tables you'll need to look at are node, node_type, node_revision, field_data_*, field_revision_*, maybe taxonomy_*, maybe others.

Migrate module, Feeds module, and others can help with this too, as Ayesh mentioned.


Separate exposed sort form from exposed filter block Is is possible in Drupal 8 Splitting exposed filters and exposed sort & pagination i.e. placing sort & pagination inside a separate block and filters in another block?

Right now there is no out of the box solution to this. In my opinion this would greatly improve user experience.

I didn't see solution for such issues.
But I solved these issue with custom form elements and using the hook_views_query_alter.
In the hook_views_query_alter you can alter orderBy property.


Using a field value as Twig attribute I need to set a field value as CSS class in a page template. How can I do it the Twig way?

{{attributes.addClass('class-name')}} is the way to set the class manually.

I have a list field to let the user set a background color for a part of the site. In Drupal 7 I used this code.

<div class="<?php print render($content['field_background']); ?>">

In Drupal 8, I can print the field with {{ content.field_background }}, but
 doesn't work.

This can be done in a few ways, you can do it all in the node template with Twig or you can create a preprocess function and create a variable for use in the node template. The key to learning what is in the array is to use Devel Kint. Without that, you won't know what is in the array.

First install Kint which comes with the Devel module for Drupal 8. Next, pick your node template (but this can be done in any kind of template) and examine the content variable like so (ideally at the bottom of the template).

{{ kint (content) }}

From this, we get debugging info printed on the page and if you expand the array, you'll see a whole slew of information. Right away, I see my background value and I can construct a path to print this out as

{{ content.field_background[0]['#markup'] }}

Now you can print this as a background style or class in a div

Hello

I've tested this ands it works great, the div rendered the background color I had selected in my field list on node edit.

Now this is not ideal so we probably want to create a variable for this in a preprocess_node in our theme's .theme file.

function MYTHEME_preprocess_node(&$vars) {
  $vars['bgcolor'] = '#' . $vars['content']['field_background'][0]['#markup'];
}

Now that I have a var created, it's much cleaner to print this out:

Hello

One note for above, you should probably wrap this with an if statement to check if it's empty or not.

This would work or structure the if statement where you like it

   {% if bgcolor %}

Hello

    {% endif %}


Payment method differences by subdomain I am trying a configuration where I have drupal commerce setup in different subdomains representing different stores using domain access and domain access entity.

My issues is that when i enable paypal wps rule as payment method, the same information that I have for receiver in one subdomain is copied over to all subdomains. Is it possible to have a unique payment method details by each subdomain? So products purchased from one subdomain are processeed by its own unique payment method details?  Can rules be used to identify which domain the order is from and process it for payment details for that domain?

Looks like the Domain Rules module provides a condition so that you could limit a configuration by a domain.


REST Services documentation for end client After creating a REST services using Services module there is always somebody who develops a client for you endpoint. And this developer must know which services we have, which parameters to pass, which method to use etc.

Is there any automatically generated documentation for Services that are created?
(E.g. something like to WSDL document for SOAP.)

There is indeed:

Services Documentation API

  The Services Documentation module generates API documentation for your site’s Services resources. Most of the documentation is generated automatically, using the resource information contained provided by Services. However, this module provides you with the ability to easily extend that documentation.


2 websites under one domain In one domain I want 2 drupal it as follows:
www.example.com/index.php (not necessarily drupal), just a landing page
On the index page people have to chose between 2 Drupal Sites

www.example.com/salloon1/index.php
or
www.example.com/salloon2/index.php

Can I do this ass follow?
Step 1
Uploading all drupal files to www.example.com/saloon1/
Create Database saloon1_DB
settings.php pointing to saloon1_DB
Step 2
Uploading all drupal files to www.example.com/saloon2/
Create Database saloon2_DB
settings.php pointing to saloon2_DB

index.php
2 images: image 1 pointing to www.example.com/saloon1/index.php
          image 2 pointing to www.example.com/saloon2/index.php

Is this right or is there another solution?

Thanks guys in advance!!
Best regards,
Pieter-Jan Derks

One way to create multiple sites within one drupal instance is to use the domain access module.

https://www.drupal.org/project/domain

Using this you can create different sites with different domains on the same instance. You won't be able to do www.example.com/saloon1 and www.example.com/saloon2 (unless you use the subfolder domain module that extends domain access. Though I'm having trouble getting that module to work)
But you could do saloon1.example.com or saloon2.example.com or you could do saloon1.com and saloon2.com

On all content and blocks you'd be able to specify whether it's available to one domain, the other, or both. You could also restrict user privileges to one domain. You could also apply different themes to each domain.


How to distinguish radio and checkbox type in drupal I have a content type which consists four types of fields. checkbox, radio, select, select multiple

I'm using field_info_instances('node','bundle_name') in my custom module to get filed info for my content type. I need this info to use somewhere.

My question is, how can I distinguish the checkbox type and radio type.same problem for select and multi select also.

Here is the output

I got the solution, I've used field_info_field function, In the return array  I found the difference in cardinality.

The cardinality for checkbox is -1 and for radio button is 1. Similarly for select is 1 and multi select is -1

I found it myself, is there any better solution than this?


How to render a specific page as if the currently logged in user is not logged in? Anyone know how to do this, or have an idea on how to do it?

I want to render a specific page exactly as it looks when the user is not logged in. But the trick is, the user is in fact logged in.

For an anonymous user, the easiest way to do this is to use a second browser and visit the specific page without being logged in. An alternative to that would be to logout (but that seems to contradict with "user is logged in).

For other (none anonymous) roles, you can use the Masquerade module (for sure). You might consider using this module also for "anonymous users". However be aware of this note on its project page:

  Any previous support to masquerade as "anonymous" has always been buggy and hurts performance on larger sites. To masquerade as anonymous users, logout.

My recommendation therefor is: open that page in a 2nd browser, without being logged in.

PS: works for any currently supported release of Drupal.


how to add search box on specific page? I need to show the search box on that page and specific search if sometime type related news then search result appear. I need only the search box for this content type.

If I understand your question correctly, you want to display the 'Search form' block for a specific content type.

On admin/structure/block/manage/search/form/configure you can change the 'Visibility settings' and show the block for specific content types. Below a screenshot where I have selected to display the search form on nodes of my custom content type 'Blog overview':


Node empty fields behave badly when created with Entity Metadata Wrapper Problem

Creating a node with the Entity Metadata Wrapper causes two frustrating results if select fields are left blank. (using #empty_option from the FAPI) .

(My form to create a node is pretty much just a more complicated version of the [create a node in code][1] example).

Display Problem

Typically when a node is created and a select field isn't filled in, the field will not display at all.

However when using the Entity Metadata Wrapper to create a node, if you then view the node the empty field titles still appear.

Indexing Problem

More frustratingly, if the node is indexed in this state it appears to store a blank string, which will appear as a blank option in a facet and throw the following error on ticking the blank facet.

Notice: Uninitialized string offset: 0 in SearchApiFacetapiTerm->addFacetFilter() (line 86 of
/srv/www/mysite/public/sites/all/modules/search_api/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc).

The Question

Both of these problems, disappear if I edit the node and save it. So something is being called in this process, or creating a node normally that isn't called with the Entity Metadata Wrapper.

Has anyone seen this before? What could be being called in a normal node creation that's not being run with the entity metadata wrapper?

Sample Code

This is an extra code for a node with the select field field_area.

function createanode_form, &$form_state){

   $area_field = field_info_field('field_area');
   $area_values = list_allowed_values($area_field);

   $form['field_area'] = array(
     '#type' => 'select',
     '#title' => t('Area'),
     '#options' => $area_values,
     '#empty_option' => t("-None-"),
   );

   .....

  $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Submit'),
     '#weight' => 70,
  );

}

function createanode_form_submit($form, &$form_state) {

    $values = array(
      'type' => 'job_advert',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 1,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    $ewrapper->title->set('Test title');
    $ewrapper->body->set('A bunch of text about things that interest me');
    $ewrapper->field_area->set($form_state['values']['field_area']);

    $ewrapper->save(true);
    entity_save('node', $entity);
}

When an #empty_option is defined, it will be added as a label for the empty option in a select list. The value can be defined as well, it is keyed as #empty_value. See the documentation for form_process_select for more details. You will see that for required fields, the default #empty_value is an empty string.

That value is filtered out in _form_validate. I think it is being unset, and then when you call $ewrapper->field_area->set() you are actually passing FALSE, NULL or something else that PHP lovingly converts to an empty string.

I think you could solve it like this:

if (!empty($form_state['values']['field_area'])) {
  $ewrapper->field_area->set($form_state['values']['field_area']);
}

Or if you manually set the #empty_value to '_EMPTY':

if ($form_state['values']['field_area'] !== '_EMPTY') {
  $ewrapper->field_area->set($form_state['values']['field_area']);
}


Custom Text in Views In drupal 7, I created block in views and add field Global: Custom text, and write some text in this field.

When display this block and inspect show Global: Custom text in span tag.

How to display Global: Custom text but not in span tag.

You can turn them off in "Global: Custom Text" field setting. Just check the "Customize field HTML" and "Customize field and label wrapper HTML", and set both elements to "None" in "Style Settings". See below screenshot for details.


Take messages generated by module and print them inside the node teaser? I have a Pay2Publish module, which gets no support these days, so I have to turn to the community for the help.  I guess this is a simple PHP question:

I want to take the messages generated by Pay2Publish module and display them bellow each node teaser.

Here's the code from the module:

/**
 * Implements hook_node_view()
 *
 * Displays the Message for the author of a node
 */
function ms_paypublish_node_view($node, $view_mode, $langcode) {
  $plans = variable_get('ms_paypublish_plan_' . $node->type, array());
  $pp_node = ms_paypublish_load_node_nid($node->nid);

  if ($pp_node AND !empty($plans)) {
    if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {
      global $user;
      if ($node->uid == $user->uid) {
        switch ($pp_node->status) {
          case 0: // Not Published
            drupal_set_message(
              str_replace(
                '!link',
                l(t('Publish'), 'ms_paypublish/publish/' . $node->nid),
                variable_get('ms_paypublish_not_published_text', 'This content is not published. To publish, please click here: !link')
              )
            );
            break;

          case 1: // Published
            if ($pp_node->expiration_date) {
              drupal_set_message(
                str_replace(
                  array('!days','!link'),
                  array(
                    ms_paypublish_get_expiration_string(ms_paypublish_get_expiration($node->nid)),
                    l(t('Promote / Extend'), 'ms_paypublish/publish/' . $node->nid)
                  ),
                  variable_get('ms_paypublish_published_text', 'This content will expire in !days days. To Promote / Extend, please click here: !link')
                )
              );
            }
            break;

          case 2: // Awaiting Admin Approval
          case 5:
            drupal_set_message(variable_get('ms_paypublish_approval_text', 'This content is Awaiting Admin Approval. It will be published shortly.'));
            break;

          case 3: // Not yet published
            drupal_set_message(str_replace('!link', l(t('Publish'), 'ms_paypublish/publish/' . $node->nid), variable_get('ms_paypublish_publish_text', 'This content has not been published yet. To publish, please click here: !link')));
            break;
        }
      }
    }
  }
}

What do I need to put inside my custom node--content-type.tpl.php so that these messages are displayed below each teaser?

My suggestion is:

Change this line in hook_node_view()
if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {
and add $view_mode == 'teaser' to it. Then you can create a patch and submit to community, if you think that this feature may be needed by other users.
You can create a template file for this content type, store the messages in a theme variable and display them in template file, just use <?php print $VARIBALE_NAME ?> You also have to write a template preprocess function where you will write code to get message body.

I think second option is the best. The requirement is not generic and changing the module is not right in this case. However, you can search the module's issue queue for this.

References

function template_preprocess_node
Drupal 7 Template (Theme Hook) Suggestions


Submit form when field value changed I have a simple form with method GET as follow...

function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
}

GET actuly bypasses the default submit and validation functions, which is ok for me.
I want to submit this form without submit button, when value in 'Categories' field is changed.

function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
    '#ajax' => array(
      'callback' => 'MYMODULE_form_submit',
    ),
  );
}

How should I do this?

Here is how I was able to do this using attributes...

'#attributes' => array('onchange' => 'this.form.submit();'),

So it was just simple ....

function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
    '#attributes' => array('onchange' => 'this.form.submit();'),
  );
}

Now I am able to submit form when field is changed.


How do I set a Node's Paragraph field in a different language programmatically? I have a node that has different translations already and I'm trying to populate Paragraph fields in different languages programmatically. I can edit the node and update the paragraph fields manually and they work correctly, so I know the translation configuration is setup correctly.
However, when using the code below, when I create a new paragraph in, say Dutch, and save it to the translated node object it always overwrites the English translation with the Dutch one.
For example:
English Node->MY_PARAGRAPH_VALUE = "English Paragraph Text"
...run code...
English Node->MY_PARAGRAPH_VALUE = "Now has Dutch Paragraph text "
<?php
  /*
   * $node is an existing Node entity with empty multi-value paragraph
   *  fields to populate in different language below
   */
  $lang_code = 'nl';
  $lang_node = $node->getTranslation($lang_code); // copy En node into Dutch Node

  /*
   * Using a Paragraph View to verify,
   * this part works and creates a paragraph with the correct language
   */
  $paragraph = Paragraph::create([
      'type' => 'images_descriptions',
      'field_product_image' => $img[$key],
      'field_product_description' => $desc[$key],
      'langcode' => $lang_code,
  ]);
  $paragraph->save();

  $current[] = [
      'target_id' => $paragraph->id(),
      'target_revision_id' =>$paragraph->getRevisionId(),
  ];

  $lang_node->set('field_images_descriptions', $current);
  $lang_node->save();

?>

The paragraphs ERR field only contains one (pertinent) bit of info - the relationship to the paragraph entity. The field itself shouldn't be translated, because every time you set it, you're setting the paragraph for every translation of that node.
To provide translations, you translate the paragraph entity itself, e.g.
$node->field_images_descriptions->entity
  ->addTranslation($lang_code, [
    'field_product_image' => $img[$key],
    'field_product_description' => $desc[$key],
  ])
  ->save();


Why does cron run as an anonymous user? I ran into an issue recently where my hook_cron function was failing when triggered by cron. The problem was that I was calling EntityFieldQuery, which  does access checks and since cron runs as an anonymous user, the query would to process correctly. Specifically, I was having this issue: EntityFieldQuery doesn't work correctly in hook_cron

I am trying to understand why cron runs as an anonymous user. Cron clears the cache and so has at least some database access. When writing hook_cron functions now, I have to bypass access checks so that they return results as expected. Does anyone understand why this is the intended behaviour?

Drupal 7

A cronjob should not have to be run by a specific drupal user. It sounds just like a maintenance task that should run sometimes to do something (send a part of a  mail queue, clear some part of cache or whatever).

In some installs (all of mine, for example) run crons via drush/linux cronjob. cron_safe_threshold is set to 0 (never).

  Typical tasks managed by hook_cron() are database maintenance,
  backups, recalculation of settings or parameters, automated mailing,
  and retrieving remote data.


Instantiate and load a block programmatically in twig template I created a simple block that shows some text grabbed from an external source, and it renders as expected when I place it from the back-end (Structure->Block Layout).

But I want to be able to place it via code only inside a twig template from the theme directory. I thought I would use {{ drupal_block('id defined in Block.php') }} from the Twig tweak module but it never works unless the block is first placed from the back-end which assigns it a machine name then I can display it anywhere using that machine name in drupal_block() instead of the id I defined in its source code.

So how can I instantiate it programmatically first and then place it the the twig template I want?

During my search I came across Plugin Derivatives, I don't know if it is the solution I want, or how to use it.

I am sure there are other ways to solve this problem, but here is how I would do it.

Create your block, then go to admin/structure/block and place your block under "Disabled" list. You can then implement hook_preprocess_node in your .theme.php file.

theme file:

/**
 * Implements hook_preprocess_node()
 */

function mytheme_preprocess_node(&$variables) {
 $block = \Drupal\block\Entity\Block::load('block_id');
  if ($block) {
    $variables['my_custom_block'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  }
}

In your template twig file:

{% if my_custom_block %}
 {{ my_custom_block }}
{% endif %}

You just have to make sure that your block_id correct.


Returning the form in form_alter function I have a doubt that is, can i use return $form; in hook_form_alter function. When i used some callback function inside the form, its not calling to that particular function. Thatsy i confused whether the form is returning or not.
i tried this thing but its not calling to custom_form_reset function

function cap_academy_contactus_form_alter(&$form, &$form_state, $form_id) {
       if ($form_id == 'webform_client_form_860'){
        $form['actions']['reset'] = array(
          '#type' => 'submit',
          '#value' => t('Reset fields'),
          '#submit' => array('contact_form_reset'),
          '#prefix' => '
',
                '#suffix' => '
'
        );
        return $form;
      }
    }

    function contact_form_reset($form, &$form_state){
      $form_state['rebuild'] = FALSE;
    }

You can use it, sure. But it won't do anything.

The $form is passed by reference, precisely so that it can be altered in-place. Core never does anything with the return value from form alters, so there isn't much point doing it.

Your code looks right, put a drupal_set_message/dpm in the submit handler to confirm whether it's actually being called or not, or whether it's your one-liner that's not doing what you're expecting.


D7 - Syntax of js custom file added directly to theme Alright, so I've read the documentation of JS framework in Drupal and there is a simple example how the syntax of JS file should look:

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {

    });
  }
};

I can't figure out what should I put instead of "myModuleBehavior" when js file is added directly to theme, not by custom module. Any help?

It just needs to be unique (otherwise you'll overwrite something existing, this is JS after all). So it would make sense to go with

Drupal.behaviors.myThemeBehavior = {

But it doesn't really matter as long you're not elbowing an existing behaviour out of the way.


Reject e-mail address from specific domain in simplenews newsletters e-mails i have a lot of spam users request account with mails  on specific domain,i used the User restrictions module to make e-mails on that domains not allowed, but only to the registration .i want to know how can i do the same to the Simplenews module to reject e-mails from specific domains to register in the newsletter.
thatnks

How are users registering their email addresses? For example, we use simplemail on http://goniseko.com in the footer. It's a signup block that anyone can use.

Is this where your spammers are signing up from?

In my opinion, this is super easy to fix, if you aren't afraid of creating a quick and dirty module that uses hook_form_alter.

In the module you would simply create a validation rule that if the form value submitted contained 'baddomainame.com' it would prevent the form from sending.

function mymodule_hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'my_simple_news_form_id'){
        $form[#validate][] = 'check_domain_callback_validate';
    }
}

function check_domain_callback_validate(&$form, &$form_state){
    if(&$form_state['values']['simple-news-email-value'] == 'baddomainame.com'){
        form_set_error('', 'BAD DOMAINNAME, BAD! YOU NO SIGN UP');
    }
}

of course all of that is pseudo code, but the structure should get you started.  Here is a link to the forms API tutorial that will help if you are not very familiar with FAPI.

http://drupal.org/node/262422


Webform submission redirect to view with node ID I have a view with table of data about a member of a sport club. I've placed a link to webform in the header that adds more rows into that view, which works fine but I'd like to redirect the form to go back to that view with person's ID as the argument/token.
To make it more straightforward: my view is /grade-details/%id, webform pickups the ID and inserts new data into right person table.

How can I make the redirection to go back to the view with same person details?

If it's anything like Drupal 8, tokens are supported if you pick the "URL (redirects to a custom path or URL)" confirmation type.

I'd try entering /grade-details/[token:here]

Some tokens that might work:
[current-page:url:absolute]
or
[current-page:url:relative]


How can I add this image plugin, on a new clean/new texteditor? When I want to add a texteditor admin/config/content/formats
4 editors; basic,restricted,full and plain are pre installed.

The basic.HTML CKEditor is with image plugin installed

When I create a new text format, the image plugin is not enabled and there is no obvious way to open it. How do I get the image plugin when configuring a new text format?

This can be achieved by activating the image plugin for CKEditor.

Drag the following icon from the available icons to the active toolbar:


Comments: "You are not authorized to post comments." I'm using Drupal 7.
I'm trying to add comments to a node but I get this error back:"You are not authorized to post comments".
I can't find in the code which variables are being checked to don't allow me to post a comment.
Can someone tell me where to look in the code?
Thank you very much

Go to: admin/people/permissions

Check de permission:

Post comments

Click button "save permission".


Delete a node and a menu_link I have a simply question, it's possible to delete a node and at the same time delete a menu_links ? For exemple when i will use the button delete of a node of my entity "PROJECT" i want to delete automaticaly a menu_links created before. I found the HOOK_Delete but how to use this function in a particular entity ? Like the HOOK_form_alter we can choose the form_id, there is a HOOK like this ? :

Mymodule_delete($nid) {
    if($entity == "project") {
        delete($nid);
    }
}

Maybe can i change the $form['actions']['delete ??'] in my form alter and use my own function ?

_myfunction_delete_project($nid) {
    $query = "Here get the entity of my $nid";

    if($query == "project") {
        delete($nid);
        delete($my menu links);
    }
}

I hope you understand my request

Thanks

You can do it simply using hook_node_delete.

function hook_node_delete($node) {
  if ($node->type == 'any_content_type') { // for specific content type
    // here your code use $node->nid
  }
}


Node form validates fields with #access = FALSE after ajax image upload I have a node form for a content type rendered using drupal_get_form(), I wanted to hide some fields so I altered this form and set attribute #access to FALSE in order to hide it and not validate it.

Until this point everything goes nice but now I have a scenario that this form has an image field with ajax upload button, after removing / re-uploading the image the form validates the required fields that I already set its #access to FALSE.

I think that the form is rebuilt and all alteration to fields with #access = FALSE gone away. What should I do to avoid this?

You can use hook_form_alter() to hide the fields so that when the form is rebuilt (with AJAX or normal page load) the fields will still be hidden.

Also if you wanna make a field not validate then use the code below in your hook_form_alter() hook.

function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your_form_id'){
    // To hide the field
    $form['your_field']['#access'] = false;
    // To remove validation
    $form['your_field']['#required'] = false;
  }
}


How to display custom table without using views? I have tried it to display the table by using core PHP concept and it display the table but at the top of the page now i need to display inside my page my current display is below

and my code for view is

function testing_db_viewall($form, &$form_state){
    $result = db_select('infobox_new')
    ->fields('infobox_new', array('name','emailid','contactno','nid'))
    ->execute();

    $entries = $result;
    $output ='';
    $rows = array();

    foreach ($entries as $entry) {
    // print_r($entry);
    // echo "<br>";
        $rows[] = array( $entry->name, $entry->emailid, $entry->contactno, l('edit','examples/edit/'.$entry->nid), );
    }
  // Make a table for them.
    $header = array(t('Name'),t('Email id'), t('Contact No'),t('edit'));
    $output .= theme('table', array('header' => $header, 'rows' => $rows));

     echo $output;
}

I want to display my table after my title i.e. "Custom Table View"

Thanks in advance

Instated of "echo"

  echo $output;

You have to write

  return $output;


How to make use of Devel debugging functions on large or complex objects I am having trouble making real use of Devel's debugging functions kint() and dpm() in my modules and twig templates. They work fine for primitive variables, flat arrays and such, but if I want to inspect into some object like an EntityRerefenceFieldItemList they either cause the site to crash (white page) or generate so much data such that the scripts for expanding the list no longer work.

How do I circumvent these problems?

The first problem can temporarily get fixed by changing the max array/object levels Kint will go deep. Currently this still has to be done by changing one line of code in the module. Though there already is an issue https://www.drupal.org/node/2405179 to make this a configurable setting.

In devel/kint/kint/config.default.php change 7 to any number you are fine with. I usually set it to 4.

/** @var int max array/object levels to go deep, if zero no limits are applied */
$_kintSettings['maxLevels'] = 7;

Remember that this number will get reset as soon as you update the Devel module.

Update: Now I found this beautiful snippet to simply be placed in your settings(.local).php. No hacking or patches needed.

// Change kint maxLevels setting:
include_once(DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php');
if (class_exists('Kint')) {
  // Set the maxlevels to prevent out-of-memory.
  Kint::$maxLevels = 4;
}


"See Also" section inline node body text I am not sure the title of my question specifies correctly what I am looking for, but several newswebsites are using some sort of "See Also" or "Don't Miss" sections which appear between the first and second paragraphs on their articles and links to a related article. In my opinion it's a great feature as it can keep visitors longer on the website.

I have been looking to implement this on my D7 website but there seems to be no easy way to add a custom field or something in node body text. Any help would be appreciated

Here are some examples:

http://mashable.com/2017/01/23/hospice-patient-attends-womens-march
http://bgr.com/2017/01/23/ios-10-2-1-release/

Really the best way to do this is with multiple fields. Rather than injecting your related content block in the middle of your body, have 3 separate fields.

1) A teaser field (contains the first paragraph)

2) Related content field (This would likely be an entity reference field. You can render the referenced node with a chosen display mode.)

3) Body field (contains the rest of the post)

The other way to do this would be by dynamically splitting your content (probably with regex) and inserting your other field in the middle. Personally, I wouldn't recommend this second option.


How to invert a contextual filter which is a taxonomy term ID? I have a view that displays a number of nodes according to a taxonomy. I do this by adding a Contextual Filter -> Has Term ID and to get this value from the URL to filter out all nodes related to that taxonomy.

What I need to show in a view is precisely the opposite. I need to show all nodes except the nodes filtered out by the contextual filter of term ID. In a way, I need to show all content NOT tagged with the taxonomy term in the URL.

Does anyone know how this can be done?

I haven't tested this, but at the bottom of the contextual filter form, under 'More" is a button that reads:
Exclude
If selected, the numbers entered for the filter will be excluded rather than limiting the view.

Have you tried this?  Please follow up with a comment for your results.


Why do I have to add main-menu under features[] in the theme info file? I have seen other themes that just define regions and then use drupals theme() function in the page.tpl.php to print the Main menu wherever the developer pleases.

This was not the case for me, and I spent a lot of time figuring out that for some reason I had to both add 'features[] = main_menu' into the theme .info file, as well as going to 'admin/appearance/settings/themename' and enable the feature before it will display.

I'm having trouble understanding why this is the case, and hope someone can elucidate or at least point me towards some enlightening documentation.  Thanks.

The features elements in the .info file are used to add or suppress Drupal core/global theme settings. If you add any features options to your .info file, you must add all of the options you wish to have available to your theme. All of the options are included by default if no features options are added to the theme's .info file.

If you want to set the default setting for any of these features to your theme's .info file, you can use the setting entry. For example, if you wanted to default the "main_menu" option to be on, you would add this to .info:

setting[toggle_main_menu] = 1

More information on all of these topics can be found in the drupal.org Theming Guide


How can I use the Review Order Pane twice in Commerce Checkout? I'd like to be able to use the Review Order pane twice in the Commerce Checkout... first before the customer enters payment and then again when they Confirm the order.

Or do I need to create a new Pane?

Is this possible? How?

I haven't completely tried this out, but you can duplicate the pane by implementing hook_commerce_checkout_pane_info_alter. Something like:

function mymodule_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['my_checkout_review'] = $checkout_panes['checkout_review'];
  $checkout_panes['my_checkout_review']['title'] = '[Duped] Review'; // to differentiate
}

I don't know what the consequences are of having two review panes, but I think this would be a good starting point.


Can I relate a node with a taxonomy term via its description and not its name? I import xml files into Drupal. These files use numbers for location which I want later to be interpreted into names (like Spain, Greece etc). So I would like the taxonomy terms to have the name of the countries but then how could I relate the node to the taxonomy term? I was thinking to use the description or another taxonomy field to relate it with the node instead of the name. Is that possible? Thank you!

If you use drupal 7 you add a term reference field to the content type, and choose which taxonomy terms are related to the node on the add/edit page for the node. There refs are done by term id (tid) not by name/description


import users from 7 to 8 without drush I've been asked to import users from a drupal 7 site into an already-built drupal 8 site. I also need their order history from drupal commerce.

I tried using drush migrate-upgrade --config-only to do this, but as of drush 9, the migrate-upgrade etc commands don't work. There is a bug report about this and several patches, but my understanding of drush isn't advanced enough to properly patch & test.

Is there a way this can be done without needing to use drush?

Is there a way this can be done without needing to use drush?

If you create a custom module with a migration group you don't need to run drush migrate-upgrade --config-only, but if you screw up, you'll have to uninstall and re-install, a bit annoying.

  I also need their order history from drupal commerce.

Custom migration is the way to go.


Mystery "test" text showing on page after views module update I've got an instance of mystery text showing on my blog.

Here's the scenario:
I've just run the security update to 7.x-3.8 on a drupal site running 7.28 on my local machine, and didn't see this issue. When I ran the updates on the live site the issue appeared.

On the homepage blog, at the bottom of every post there is the word "test". I know it's outside of the body field tag, but I have no idea where it's coming from.
Seen here: http://susanhoodbooks.com/

I've checked the code of the view, the templates, the contents of the nodes and I can't find anything.
I'm hoping to ask for some suggestions of where I might look next before I revert the modules.
again, I haven't been able to recreate this on my local.

Please let me know if I need to supply any other information.
Thanks

I can see there is some jquery script adding the string 'Test' for each view row . Look into your code base for the string '.view-id-blog .views-field-body' and you'll find out from what file is it coming.

You may also want to disable javascript aggregation for sometime, and then see the exact file name in the developer tools directly.


How to display a list of nodes in a block? I have a custom block and I want to output a list of nodes of a certain type.

This is what I have so far:

public function build() {

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->execute();

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple($nids);

    return array(
      '#markup' => $this->t('How to display list here'),
    );
  }
}

How do I list the nodes by title and ordered by newest at the bottom of list?

Unless you have a specific issue not mentioned in the question, I would recommend using a view to create this block. This would mean that the criteria remained easily editable.

If you had specific need to output the list of nodes within a custom block, or would like to pass arguments to the view from custom code you could use views_embed_view.


Drupal 7 Ajax Forms - select element I've got a custom module form in Drupal 7. The code looks like this:

function form_example_dynamic_form($form, &$form_state) {

$form['tables'] = array(

        '#type' => 'select',
        '#options' => drupal_map_assoc(array("2012", "2013")),
        '#title' => t('Select year:'),

        '#ajax' => array(
            'callback' => 'form_example_dynamic_myajax',
            'wrapper' => 'abcd',
            'effect' => 'fade',
            'method' => 'replace',
            ),

       );

 return $form;
 }

 function form_example_dynamic_myajax($form, $form_state) {
     return $form_state['values']['tables'];
 }

So this simple code should update #abcd tag with the value of the 'tables' select. And the problem is that it works only for the first selection. If I chose 2013 it returns "2013" text in my #abcd tag. But, when I chose 2012, an #abcd tag stays unchanged. It still apperas 2013.

Here is the example: http://kuzaj.yamandi.com/pl/form_example_dynamic

Does anyone has any idea how to solve it?

The problem is that Drupal is unable to find the element #abcd in the further calls.

Since you are returning the values alone, it will replace the element #abcd with the value; so the element #abcd will be removed from the document, and it will not be available for further processing. That's why it is not updating the values in the second time.

To overcome this in form_example_dynamic_myajax(), you need to return the values like in the following code.

 function form_example_dynamic_myajax($form, $form_state) {
   return '
' . $form_state['values']['tables'] . '
';
 }


Ordering by taxonomy field ascending but leaving those node without taxonomy at the bottom I have a View of products (nodes). They have taxonomy associated, and I am displaying the taxonomy first and ordering by taxonomy ascending. However, I would like to have all with taxonomy ordered first, but I find that the View shows first those without taxonomy, and later those with taxonomy, in this case in the correct order. How could I indicate the View that it must reserve those without taxonomy for the last, i. e.

 A Taxonomy
   - Product 1
   - Product 2
 B Taxonomy
   - Product 3
   - Product 4
 ...
 Z Taxonomy
  - Product 5

  -- Products with No taxonomy -- (this message does not display, it is only for clarification here)
  - Product 6
  - Product 7

...

My suggestion is to modify your main view to list only Product nodes with a taxonomy term selected, then use an attachment to your main view that lists Product nodes with no taxonomy term. The attachment would be displayed after your main view.

Steps

1. Filter your main view to list only Product nodes with a taxonomy term value

In your main view's configuration, under Filter Criteria, add a filter for your taxonomy term field (choose either dropdown or autocomplete), and select "Is not empty (NOT NULL)".

2. Create the attachment that lists Product nodes with no taxonomy term value

Add an Attachment display to your view.

Under Attachment settings, set Attach to to your main view display (in this example the main view is Page), and set the Attachment position to After.

In the attachment display's Filter Criteria, change the taxonomy term filter to "Is empty (NULL)". Make sure to override this setting for the attachment display only or it will apply to the main view as well.

Note about the attachment header

Your attachment view will be displayed right after your main view, so you may want to add a Header to the attachment (make sure to override to the attachment display only).

In this example I used a Text area.

Alternatively, you could add a label to the taxonomy term field. Make sure to override this setting for the attachment display only or it will apply back to the main view.

Results

Your main view should now list your Product nodes by taxonomy term in ascending order, and your Product nodes with no value selected for the taxonomy at the bottom of the list.


Modal Popup in IE submit button does not work We are using the Ctools modal popup for registration.  In every other browser, this works.

In IE8 and IE9, after filling out the popup form, when a user presses "Create Account", the form disappears, and then pops back with all the fields empty.  In other browsers, it reroutes to the registration page.

I tried debugging in F12 developer tools but I'm not sure where to look.

Have a look at http://drupal.org/node/1549934 for a potential fix.


Drupal 6 - form submission data loss from empty required fields Scenario: Content profile node-type has new required fields added after many users have already filled out their profile info.  (this scenario can work for any node-type).  They go back to update their profile, and don't see the need to fill in the required fields, submit the forms, miss seeing the error message, and walk away, thinking that their updates have been submitted successfully.

I've had various versions of this same scenario play out across different websites and situations.  And have tried out various home-made solutions where I have data collected at the validation stage in a nodeapi hook implementation.  But those solutions are painful and flawed.

Anyone know of a simple solution to this pervasive problem?

This is the default behavior, but I agree that it would be a irritating issue.

Perhaps if you did something like a warning message at the top when the user loads a previously edited node that has empty fields that are now required? That would get them looking at it from the get go. form_alter could do this for you.

Adding some pretty CSS on the page to highlight the empty required fields would also help guide them to the fields where their input is required.


Writing unit tests for a method that calls static methods from another class I have a custom service defined by my module and in one of its methods I call a static method from a class defined by a module mine depends on. Since this method is static I do not need to instantiate an object but this also means I cannot inject the dependency. Soooo... How do I mock the static call?

Here is some psuedo code to illustrate:

use some/other/class/called/FOO

...

function myMethod() {
  // Do some things...
  $some_var = FOO::staticMethodToGetValue();
  // Do more things...
  return "something";
}

You can't mock static calls directly.

A relatively easy way to fix this is what core uses in quite some places to mock functions that haven't been converted to objects/services yet. You create a method in your own class that does nothing but call the static method.

Then for your test, you can either mock your own object and only mock that method or create a test subclass that overrides that method and return something else.


Can I limit a view mode to show on the "Manage Display" settings page for only one node type? I have a module that creates a custom node type ("answers") and a custom view mode ("answers_full_node") for that node type.

Now, when I look at the "Manage Display" settings page for any node type, the custom view mode is available.

Is there a way I can restrict it so that it shows up only for my custom node type?

No, view modes are per entity type, not per bundle.


Set All Day checkbox on date field programmatically I am importing events from an iCal feed and have managed to get everything working great except for events that take place all day. Currently they are coming in and defaulting to a xx/xx/xxxx 7:00pm to xx/xx +1/xxxx 7:00pm date when they should fall on the same day without a time. I've tried hardcoding 00:00:00 as the time but that get's ignored. I've also made sure that there are no default time settings on the field.

There is a checkbox for All Day but nothing seems to mark it as checked while I'm trying to create the node and it doesn't appear to be saved in the node object anywhere so not sure how I am suppose to set the checkbox while I'm creating the node.

Current code I am using while looping through each of the events in the feed:

// Use the UID to look up existing events.
if(!in_array($uid, $uids)){

    if(strtotime($startDt->format ( 'm/d/Y h:ia' )) > strtotime("-1 month")){
        try {
            $node = new stdClass();
            $node->type = "calendar_event";
            $node->uid = 1;
            $node->language = 'en';
            $node->title = $eventName;
            $node->body['und'][0]['value'] = stripslashes($eventLocation);
            $node->body['und'][0]['format'] = 'full_html';
            $node->field_uid['und'][0]['value'] = $uid;
            $node->field_date['und'][0]['value'] = $startCom;
            $node->field_date['und'][0]['value2'] = $endCom;

            // this doesn't work
            $node->field_date['und'][0]['all_day'] = 1;

            $node->status = 1;
            node_save($node);

            $values = array(
                'entity_type' => 'node',
                'entity' => $node->nid,
                'state' => OG_STATE_ACTIVE,
                'membership_type' => OG_MEMBERSHIP_TYPE_DEFAULT,
                'field_name' => 'og_group_ref'
            );
            og_group('node', $groupID, $values);
            $newCount++;
        } catch (Exception $e) {
            watchdog_exception('school_calendar', $e);
        }
    }
} else { // uid existed, maybe we want to update if needed.
}

I found a "hacky" way of doing this. A couple things I noticed after investigating further is that the All Day single day events in Drupal are set to the same time on both the start and end dates. So first I changed the time of each date format to 05:00:00, just a random time but the same time for both.

This seemed to trigger the All Day checkbox which is great. But single day events were still showing as if they spanned over 2 days, not 1.

Upon further review of how iCal specifies formatting an all day single event, it wants the DTEND to actually be offset by 1 day, so I it comes in like this for a single all day event:

DTSTART 01/01/2018
DTEND 01/02/2018

So I added this to my DTEND handling:

if(isset($icsEvent['DTEND;VALUE=DATE'])){
    $end = $icsEvent['DTEND;VALUE=DATE'];
    $endDt = new DateTime ( $end );
    $difference = $startDt->diff($endDt);
    if($difference->days == 1){
        $endDt->modify('-1 day');
    }
    $endCom = $endDt->format ( 'Y-m-d 05:00:00');
}

This modifies the end date to offset -1 day, so it ends up being the same day as the start. This is seems work great now for single all day events.

It appears though that I need to also apply this to spans of all day events, like a winter recess break that last all week. Even though it's supposed to be Monday - Friday, because of the offset in iCal, it's stretches to Saturday.

So probably instead of the difference check, I should just offset the endDt all the time by -1 day.

---- Update to Answer ---

The above worked great but I was finding some events that were supposed to be all day, showing as starting at 1am. Not sure why, the timezone looked right but some events started showing as this.

But if I set the date field to "no timezone conversion" first, then do the following with my start and end dates.

// Start Date
if(isset($icsEvent['DTSTART;VALUE=DATE'])){
    $start = $icsEvent['DTSTART;VALUE=DATE'];
    $startDt = new DateTime ($start);
    $startCom = $startDt->format ( 'Y-m-d 00:00:00' );
} else {
    $start = $icsEvent['DTSTART'];
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone("America/New_York");
    $startDt = new DateTime ($start, $UTC );
    $startDt->setTimezone( $newTZ );
    $startCom = $startDt->format ( 'Y-m-d H:i:s' );
}

// End Date
if(isset($icsEvent['DTEND;VALUE=DATE'])){
    $end = $icsEvent['DTEND;VALUE=DATE'];
    $endDt = new DateTime ($end);
    $endDt->modify('-1 day');
    $endCom = $endDt->format ( 'Y-m-d 00:00:00');
} elseif(isset($icsEvent['DTEND'])) {
    $end = $icsEvent ['DTEND'];
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone("America/New_York");
    $endDt = new DateTime ( $end, $UTC );
    $endDt->setTimezone( $newTZ );
    $endCom = $endDt->format ( 'Y-m-d H:i:s' );
}

Basically if there is no time set, and it's just an event that spans as All Day, set no timezone and default to midnight. If it has a time, set the new york time zone.


Retrieving users from Database on to forms I have a webform with a select option type field. I need an authenticated user to view other available users in the website in this list. So, it needs to be dynamic by communicating with the database. What is the best way to do this?

Thanks in advance!

You have to use hook_webform_select_options_info() in your custom module.

I made my first module with that hook because i needed to achieve a similar thing but with people who were linked thanks to module relation. I show you what i did (i change the query to retrieve all users from the site, i'm not an expert in query). It was my first code, so it's not very optimize but it's work.

function my_module_webform_select_options_info() {
  $items['membres'] = array(
  'title' => t('Membres'),
  'options callback' => 'webform_membres_options',
  );
return $items;
}

function webform_membres_options($node)  {
  global $user;
  $store = array();

  $result = db_query("SELECT users.name AS users_name, users.uid AS uid, users.mail AS  users_mail
                      FROM {users} users
                      WHERE (( (users.status <> '0') ))");

 //Store mail|username in an array (good format for select options)
 foreach ($result as $row) {
   $store[$row -> users_mail] = $row -> users_name;
 }
 //All users don't have relationship so we have to check the length of array
 if (count($store > 0)) {
   return $store;
 }
     else {
   return false;
 }
 }

You'll see your list in Load a pre-built option list when you'll build your webform (after selecting "select options") Don't forget to put a default value for the select list.
After you'll see your list in the webform :


Drupal GPL Questions I'm planning a new project that will require a great deal of custom code that must remain proprietary to my client. I found the licensing FAQ http://drupal.org/licensing/faq to be unclear.  I know this is primarily a coder as opposed to legal Q&A forum, but hopefully some experienced Drupal developers can shed more light on this issue.

What constitutes distribution?  For example, if the code is used on two unique domains owned by the same client, is that considered distribution?  Page 533, Chapter 24 of The Definitive Guide to Drupal 7 states "Modules built for ourselves or a single client are not considered distributed", but that isn't very clear.
If a module has been distributed and you have a copy, are you obligated to give me a copy, or is it up to you?  (In other words, could I demand a copy from you?)
If custom javascript is called from a Drupal javascript object (such as Drupal.behaviors), is it considered GPL'd and distributed?  The licensing FAQ Answer #7 states "Drupal's JavaScript, including the copy of jQuery that is included with Drupal, is itself under the GPL as well, so any Javascript that interacts with Drupal's JavaScript in the browser must also be under the GPL or a GPL compatible license."  That's a major non-starter for this particular project.  The client obviously doesn't want competitors walking off with highly specialized javascript that took months to develop with no legal recourse.
What is the legal status of modules that are not for distribution?  Are they license-free, or are they automatically GPL'd even if not intended for distribution?  For practical purposes, in a module that is not for distribution, would the following language have any legal effect:  "This module is copyright Company XXX and is not intended for distribution.  This software is not licensed and you may not use this module for your own purposes."

Apologies if these questions aren't as precise as they could be; I'm obviously not a lawyer.  I really want to use Drupal for this project, but if I can't offer an assurance to the client that the custom code (module code and javascript) will remain proprietary it's a non-starter.

(Disclamer: As usual with legal questions, I am not a lawyer, only a lawyer can give you a definitive answer).

Every Drupal module that is written and every javascript code that directly interacts with Drupal (or any other GPL code, but note that jQuery is dual-licensed and also available under the MIT License, this is not relevant when used with Drupal, though), automatically falls under the GPL. That's why GPL is also called a viral license. Everything it "touches" is GPL'ed automatically.

If you give the source code to someone, then he has every right the GPL grants him, including giving the source code to anyone he wants to, modify it and so on. However, viewing a website alone does not distribute your PHP code. JavaScript is a tricky question, see for example https://softwareengineering.stackexchange.com/questions/125955/using-gpl-licensed-jquery-scripts-on-website-with-ads and http://www.gnu.org/philosophy/javascript-trap.html. As far as I understand these, you always distribute the JS code.

So, obfuscating the JavaScript without providing a way to get the unmodified source code or adding a statement like the one you suggested above is in fact a direct violation of the GPL and someone could attempt to sue you.

Also note that there is an extended version of the GPL, the Affero General Public License, which explicitly includes viewing of a website as distribution. CiviCRM for example uses that license, so if you are required to allow visitors access to your custom adjustments/extensions of your website, when using a software like that.

Given the way the Ajax system in Drupal works, most relevant things usually happen on the server side, so that is usually not a big problem. Also, most GPL related lawsuits are usually related to companies selling products which run GPL software (e.g. routers) which don't provide access to their customized source code. I've never heard of a lawsuit against a website violating the GPL, but that could just be ignorance on my side, don't count on that ;)


how to remove duplicate from views' result page I went through all solutions found on the web.

Both Distinct or Aggregation do not work at all in my case.
Is there a way to remove the duplicates using hook_query_alter() ?

My sql query run in the view is the following:

SELECT node.changed AS node_changed, node.nid AS nid, SUM(search_index.score * search_total.count) AS score
FROM
{node} node
LEFT JOIN {search_index} search_index ON node.nid = search_index.sid
LEFT JOIN {search_total} search_total ON search_index.word = search_total.word
INNER JOIN {search_dataset} search_dataset ON search_index.sid = search_dataset.sid AND (search_index.type = search_dataset.type)
WHERE ((( (search_index.type = 'node') AND (search_dataset.data LIKE '% saadan %' ESCAPE '\\') AND (search_dataset.data LIKE '% goer %' ESCAPE '\\') AND (search_dataset.data LIKE '% du %' ESCAPE '\\') ))AND(( (node.status = '1') AND (node.type NOT IN  ('nodetype')) )))
GROUP BY search_index.sid, score, node_changed, nid
HAVING (( (COUNT(*) >= '2') ))
ORDER BY node_changed DESC
LIMIT 10 OFFSET 0

Last note:

I am also aware of the solution the removes content by hooking into hook_views_pre_render() but I do not really consider this a solution since it cracs up your results.

The query works perfectly if I replace 'GROUP BY search_index.sid, score, node_changed, nid' with GROUP BY nid.
How do I achieve this?

What actually worked is the following

function mymodule_query_alter($query) {

  if (isset($query->alterMetaData)) {
    if (isset($query->alterMetaData['view'])) {
      if($query->alterMetaData['view']->name == 'node_search') {
        $fields =& $query->getGroupBy();
        // Tried various fields to check which was the field creating the problem.
        unset($fields['score']);
        $query->groupBy('nid');
      }
    }
  }
}

Answer found at http://www.brenthartmann.com/blog/how-use-hookqueryalter-drupal-7

PS: In order to check the sql query that produces your view, you need to go to admin/structure/views/settings and enable "Show the SQL query".


How can I use Migrate API to migrate taxonomy with an unknown level of parent child relationships in tact? I have a JSON file with an entry that looks like this:

"taxonomy": "abc/historical_controls/abc2000_2013"

In my YML file I have it mapped like this:

  field_abc_asset_taxonomy_auto:
    -
      plugin: skip_on_empty
      method: process
      source: taxonomy
    -
      plugin: explode
      delimiter: /
    -
      plugin: callback
      callable: ltrim
    -
      plugin: callback
      callable: rtrim
    -
      plugin: entity_generate
      value_key: name
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: abc_asset_taxonomy_auto

This works in that it brings over the terms correctly, but in a flat file. I need them to come over so that each term is a child of the term before it so:

abc
    historical_controls
        abc2000_2013

The problem is there is an unknown number of items. It could be 2, it could be 10.

Is there a way to migrate hierarchical taxonomy with an unknown number of parent child relationships?

Note, I've seen several examples that use a determinant number of sources but this wouldn't work here. The "Migrate Hierarchical Taxonomy" module uses a determinant number as well.  How can I achieve this with the Migrate API preferably without writing a custom plugin?

Maybe too late but for the sake of being complete: I think you'll find the answer here Using Drupal 8's Migrate API, how can I map a nested (hierarchical) taxonomy term to the imported entity?
First migrate the terms without parents. After that update the parent-field.


How can I use the form control in a drupal form? In Drupal forms API there is a control type called "form" which, I think, allows nesting forms inside other forms. There is no usage example out there and the search term is a bit tricky so Google couldn't help. Would you please tell me how can I use this control in my forms ?

Forms can not be nested in HTML. Since Drupal generates HTML, this should not be possible.


Render a view exposed filter in a region without exposing it as a block I have already 20+ view pages that use exposed filter for filtering out content. What i want is to place the filter in the sidebar and not in the top of the page (different region).

I can exposed the view filters as a block and this will work fine but i have over 20+ view pages and that mean 20+ new blocks, increasing the load for the not dev users.

The better approach will involved using a hook to check the views id and if the match (1-20+ ids i will have) then move the exposed filter to a different region.

Is this possible?

That's interesting, there may be a possibility...

This would work if you 1) have the View object, or 2) if you can figure out which view to load via the url path or something...

You would put this code in a preprocess function for your region, or perhaps a template although that wouldn't be recommended.  However you insert it into your region, the following code will generate the exposed filter form markup:

$view = views_get_view('view_name');
$form_state = array(
            'view' => $view,
            'display' => $view->display_handler->display,
            'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
            'method' => 'get',
            'rerender' => TRUE,
            'no_redirect' => TRUE,
            'always_process' => TRUE, // This is important for handle the form status.
          );
          $form = drupal_build_form('views_exposed_form', $form_state);

          $exposed_filter_markup = drupal_render($form);


Programmically displaying imagecache presets no longer works I have noticed that recently imagecache no longer displays images when used programmatically. I have seen this happen on an existing site in which it did work at one time and on a new site (that I am currently developing). I am using the command:

print theme('imagecache', 'listing_thumbnail', $node->field_photos[0]['filepath'],
    $node->field_photos[0]['data']['alt'], 'Listing thumbnail', '');

I have tripled checked that the preset name is spelled correctly, the node attributes field_photos are correct so it should work. I have searched high and low to see if anyone else is having this problem but can't find anything. What am I missing? Why does this no longer work?

I am using Drupal 6.25 and imagecache 6x-2.0rc1

I discovered that the problem in this particular case is that the imagecache 6x-2.0rc1 module has a regression bug in it. Reverting to the previous version restored the functionality and everything works as it should. Hopefully this will be fixed with the next release of imagecache.


How do you rename the "save" comment button? Does anyone know how to rename the "save" comment button? I am trying to change it to "Post".
I am using Drupal 7 and the Zen sub theme.

For Drupal 7, you need to create a custom module that implements hook_form_FORM_ID_alter() using code similar to the following one (replace "mymodule" with the short name of the module you are writing):

function mymodule_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['actions']['submit'])) {
    $form['actions']['submit']['#value'] = t('Post');
  }
}

comment_form() uses the following code, to define the form buttons:

  // Only show the save button if comment previews are optional or if we are
  // already previewing the submission.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#access' => ($comment->cid && user_access('administer comments')) || variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || isset($form_state['comment_preview']),
    '#weight' => 19,
  );
  $form['actions']['preview'] = array(
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#access' => (variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED),
    '#weight' => 20,
    '#submit' => array('comment_form_build_preview'),

For Drupal 6, the code should be the following one:

function mymodule_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['submit'])) {
    $form['submit']['#value'] = t('Post');
  }
}

I added the if (isset($form['submit'])) {} part because in Drupal 6, comment_form() defines the form buttons using the following code, and the button you are trying to change could not be present in the form.

  // Only show save button if preview is optional or if we are in preview mode.
  // We show the save button in preview mode even if there are form errors so that
  // optional form elements (e.g., captcha) can be updated in preview mode.
  if (!form_get_errors() && ((variable_get('comment_preview_' . $node->type, COMMENT_PREVIEW_REQUIRED) == COMMENT_PREVIEW_OPTIONAL) || ($op == t('Preview')) || ($op == t('Save')))) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#weight' => 19,
    );
  }

  $form['preview'] = array(
    '#type' => 'button',
    '#value' => t('Preview'),
    '#weight' => 20,
  );


why ajax not work in this code In callback of custom  menu  wrote function , in function I want to use node_add ,
I have a field that I want add AJAX to it, but when change the  field nothing happened
where is the problem?
I am using Drupal 7

 module_load_include('inc', 'node', 'node.pages');
    $form = node_add('pre_register');
$form['field_course_display_ref']['und']['#value'][]=$nid;
    $form['field_course_display_ref']['#ajax'] = array(
      'callback' => 'myfunction_ajax_change_course',
      'event' => 'change',
      'wrapper' => 'course-schedules-div',
      'method' => 'replace',
      'effect' => 'fade',
    );
    $form['field_course_schedules']['#prefix'] = '
';
    $form['field_course_schedules']['#suffix'] = '
';

I also try

 module_load_include('inc', 'node', 'node.pages');
    $form = node_add('pre_register');
$form['field_course_display_ref']['und']['#value'][]=$nid;
    $form['field_course_display_ref']['und']['#ajax'] = array(
      'callback' => 'myfunction_ajax_change_course',
      'event' => 'change',
      'wrapper' => 'course-schedules-div',
      'method' => 'replace',
      'effect' => 'fade',
    );
    $form['field_course_schedules']['#prefix'] = '
';
    $form['field_course_schedules']['#suffix'] = '
';

but nothing happened :(

EDITED I have two field, one field_course_schedules (will wrap) and field_course_display_ref The field that I want but changing it ajax will be trigger.

type mistaked in code corrected but not worked again

You're trying to modify a form which is already got built/processed!!

node_add function is internally calling drupal_get_form which will return the processed form, so even if you change anything it wont take any effect. i.e. Drupal will consider the things which are available when the form is being built/processed.

To overcome this you should use drupal_retrive_form instead of drupal_get_form.

The same problem is discussed here with different context, sadly the OP took part in that discussion :(


Custom Field Type hook_field_widget_form() not showing #title values I have created a custom field type. When creating a piece of content with this field type I get a select list and a text area like the image below. However, I have stated that the '#title' for the select list is Label and the textarea is Value.

These '#title''s I've given them do not show up. From looking at other modules that provide a field type that has multiple elements on its widget form seem to be doing it the same way but their titles show up.

function civsearch_property_labels_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  if (isset($items[$delta]['label'])) {
    $default_label = $items[$delta]['label'];
  }

  if (isset($items[$delta]['value'])) {
    $default_value = $items[$delta]['value'];
  }

  // We are unserializing the variable_get because the string that was
  // serialized with variable_set was a serialized array. So we need to run the
  // unserialize process one more time.
  $options = array();
  $list_items = unserialize(variable_get('civsearch_property_labels', ''));
  foreach ($list_items as $list_item) {
    $explode = explode('|', $list_item);
    $options[$explode[0]] = $explode[1];
  }

  $labels = $element;
  $labels += array(
    '#type' => 'select',
    '#title' => t('Label'),
    '#options' => $options,
    '#default_value' => isset($default_label) ? $default_label : '',
    '#suffix' => '<br \>',
  );

  $values = $element;
  $values += array(
    '#type' => 'textarea',
    '#title' => t('Value'),
    '#default_value' => isset($default_value) ? $default_value : '',
  );

  return array(
    'label' => $labels,
    'value' => $values,
  );
}

According to hook_field_widget_form() the $element parameter will already have a #title set. If you take a look at the docs for PHP array operators:

  The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Emphasis mine.

So your new #title is currently being ignored.

Try this instead:

$labels = array(
  '#type' => 'select',
  '#title' => t('Label'),
  '#options' => $options,
  '#default_value' => isset($default_label) ? $default_label : '',
  '#suffix' => '<br \>',
) + $element;

The example in hook_field_widget_form() might be a bit confusing as it uses an approach similar to your original one, but if you look closely neither of the properties added exist in the list of defaults that $element will contain, so there's no chance of a collision.


Sort commerce view by calculated price I use commerce, search api and facets. I have a "shop" view with indexed products. It works good and I can filter and sort the view using "search api" facets and "search api" sorts fields.
I can sort the view by an indexed field, like product base price which is a field of a product object. The problem is this base price could change due to rules (discounts, offers, etc), and then, the final price for the customer could be different.
I need to sort the "shop" view by the final customer prices, but I don't know how to do it with this indexed view. Any sugestion? TIA

Although I didn't find how to do it with views, I have found an alternative solution using views hooks.
First I have to unset the pager, because I need all records to sort. Only if it's this view and this sort criteria.

function MYMODULENAME_filters_views_pre_execute(&$view) {
  if (('shop' == $view->name) && ($view->exposed_raw_input['sort_by'] == 'field_product_commerce_price_amount_decimal_desc')) {
    $view->query->set_limit(NULL);
    $view->query->set_offset(NULL);
}}

After this, I reorder the $view->results as I need in another hook:

function MYMODULENAME_views_post_execute(&$view) {

    if (('shop' == $view->name) && ($view->exposed_raw_input['sort_by'] == 'field_product_commerce_price_amount_decimal_desc')) {

    $milista = array();
    foreach($view->result as $clave=>$valor) {
        $prdd = node_load($valor->entity);
        $producto = commerce_product_load($prdd->field_product['und'][0]['product_id']);
        $price = commerce_product_calculate_sell_price($producto);
        array_push($milista,array(0=>$clave, 1=>$valor->entity, 2=>$price['amount']));
    }

    if ($view->exposed_raw_input['sort_order']=='ASC') $ordenado = SortByKeyValue($milista, 2);
    else $ordenado = SortByKeyValue($milista, 2, SORT_DESC);

    $listafinal = array();
    foreach($ordenado as $datos) {
        array_push($listafinal, $view->result[$datos[0]]);
    }

    // Now, the pager
    $itemsperpage = 16;  // default items per page
    if ($view->exposed_raw_input['items_per_page']) $itemsperpage = $view->exposed_raw_input['items_per_page'];
    $page=1;
    if (isset($view->query->pager->current_page)) $page =  $view->query->pager->current_page;

    $indice = $itemsperpage * $page;

    if (($indice>sizeof($listafinal)) && ($itemsperpage!=0)) $indice = sizeof($listafinal) / $itemsperpage;

    $listafinal = array_slice($listafinal,$indice,$itemsperpage);

    // Lastly, I change the view results
    $view->result = $listafinal;
  }
}

To sort the array, I used the next functions:

function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
    if (empty($data) or empty($sortKey)) return $data;

    $ordered = $data;

    if ($sort_flags==SORT_ASC) uasort($ordered,'cmpasc');
    else uasort($ordered,'cmpdesc');

    return $ordered;
}

function cmpasc($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] < $b[2]) ? -1 : 1;
}

function cmpdesc($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] > $b[2]) ? -1 : 1;
}

I hope this solution could help someone with my same use case.


Customizing the form for a field in the content edit form I have configured a taxonomy as field of a content type, but I want to replace the checkbox label (work with iphone) with the image field of that taxonomy. (See the screenshot.)

I only know to alter node.pages.inc at row 290 by adding the following code.

$form['product_label'] = array(
    '#type' => 'checkboxes',
    '#title' => 'Checkboxes Title',
    '#title_display' => 'before',
    '#default_value' => array(0,2),
    '#options' => array(
      0 => 'option one',
      1 => 'option two',
      2 => 'option three',
    ),
    '#theme' => 'testmodule_checkboxes',
  );

product_label is the checkbox name. The above code is to override the current checkbox field.

I think this not the best way. Can anyone provide any direction? What module can do it?

Here is the dump of the checkbox field of the form.

array(6) { ["#type"]=> string(9) "container" ["#attributes"]=> array(1) { ["class"]=> array(3) { [0]=> string(34) "field-type-taxonomy-term-reference" [1]=> string(22) "field-name-field-icon1" [2]=> string(28) "field-widget-options-buttons" } } ["#weight"]=> string(1) "2" ["#tree"]=> bool(true) ["#language"]=> string(3) "und" ["und"]=> array(18) { ["#entity"]=> object(stdClass)#91 (12) { ["uid"]=> string(1) "1" ["name"]=> string(5) "admin" ["type"]=> string(7) "product" ["language"]=> string(3) "und" ["title"]=> NULL ["status"]=> int(0) ["promote"]=> int(0) ["sticky"]=> int(0) ["created"]=> int(1344929691) ["revision"]=> bool(false) ["comment"]=> string(1) "1" ["menu"]=> array(12) { ["link_title"]=> string(0) "" ["mlid"]=> int(0) ["plid"]=> int(0) ["menu_name"]=> string(9) "main-menu" ["weight"]=> int(0) ["options"]=> array(0) { } ["module"]=> string(4) "menu" ["expanded"]=> int(0) ["hidden"]=> int(0) ["has_children"]=> int(0) ["customized"]=> int(0) ["parent_depth_limit"]=> int(8) } } ["#entity_type"]=> string(4) "node" ["#bundle"]=> string(7) "product" ["#field_name"]=> string(11) "field_icon1" ["#language"]=> string(3) "und" ["#field_parents"]=> array(0) { } ["#columns"]=> array(1) { [0]=> string(3) "tid" } ["#title"]=> string(4) "icon" ["#description"]=> string(0) "" ["#required"]=> bool(false) ["#delta"]=> int(0) ["#type"]=> string(10) "checkboxes" ["#default_value"]=> array(0) { } ["#options"]=> array(1) { [14]=> string(16) "Work with iphone" } ["#value_key"]=> string(3) "tid" ["#element_validate"]=> array(1) { [0]=> string(29) "options_field_widget_validate" } ["#properties"]=> array(4) { ["filter_xss"]=> bool(true) ["strip_tags"]=> bool(false) ["empty_option"]=> bool(false) ["optgroups"]=> bool(false) } ["#after_build"]=> array(1) { [0]=> string(30) "field_form_element_after_build" } } }

The problem is that I can't find the image (filename) which is a custom field of the taxonomy. I want to replace "work with iphone" with the uploaded image. How can I do this?

first of all use hook_form_alter to alter any form. so in your custom module something like this

function CUSTOMMODULENAME_form_alter(&$form, $form_state, $form_id){
   if ($form_id == 'FORM_ID'){
     --
   }


Validating and Modifying Form Data Simultaneously I have a custom phone number field that I would like to be able to validate and modify simultaneously.

I want to make sure the field has a total of 10 digits regardless of the formatting.

The following values should all be 'valid'

555.555.5555
(555) 555-5555
(555) 555.5555
555-555-5555
5555555555

Can I have a validate function return a new value upon success? In essence, as long as there are exactly 10 digits present the validate function should return '5555555555' for every value above.

The $form_state variable is passed to your validation function by reference. This means you can indeed alter the value while validating it.

function mymodule_myform_validate($form, &$form_state) {
  if (...) {
    // Value is valid
    $form_state['values']['my_form_element'] = NEW VALUE;
  }
  else {
    // Set form error.
  }
}


Select node if there periods overlap I have a content type that has a start_date and end_date fields.

I need to make a view with a filter: start_period - end_period

The view should select all nodes where the two periods overlap, for example:

node: 1 jan 2015 - 31 Dec 2015

filter values to select this node could be:
1 oct 2014 - 1 feb 2015
1 oct 2014 - 1 mar 2016
1 apr 2015 - 1 may 2015
1 apr 2015 - 1 mar 2016

Filter values that do not select the node could be:
1 oct 2014 - 1 dec 2014
1 jan 2016 - 1 mar 2016

Is there a module to do that?
thank you in advance

Try contextual range filter module that lets you define a range filter applies that rule

Start value <= Filter value >= End value.

For your case you have to define two filters.
for start date with that rule

filter start date <= node start date >= filter end date.

for end date with that rule

filter start date <= node end date >= filter start date.