How to store values to field collection or paragraphs programmatically? How do I store values to either a field collection or a paragraphs field  programmatically?

Could somebody please provide a working code example of how you do this?

I would have a field holder containing the following three fields where I want to store down my data:

field_title - (1 value text field)
field_text - (1 value text field - long)
field_sources - (unlimited no of values text field)

Thanks for helping me out.

Paragraphs and field collections are both their own entity and the fields pointing to them are just entity referenced.

So if you want to create a node with a referenced paragraph, you first create the paragraph with all the values you want, save it, then create the node and point it to the paragraph you created.

The Paragraph demo module has example code that does exactly that in paragraphs_demo_install():

  use Drupal\node\Entity\Node;
  use Drupal\paragraphs\Entity\Paragraph;

  $paragraph3 = Paragraph::create([
    'type' => 'text',
    'field_text_demo' => 'Apart from the included Paragraph types, you can create your own simply by going to Structure -> Paragraphs types.',
  ]);
  $paragraph3->save();

  // Add demo content with two paragraphs.
  $node = Node::create(array(
    'type' => 'paragraphed_content_demo',
    'title' => 'Welcome to the Paragraphs Demo module!',
    'field_paragraphs_demo' => array(
      array(
        'target_id' => $paragraph3->id(),
        'target_revision_id' => $paragraph3->getRevisionId(),
      ),
    ),
  ));
  $node->save();


How to import multiple taxonomy terms from csv using Feeds I have a csv with the following structure:

1024    Huwelijk
1024    Communie/Lentefeest
1024    Bedrijfsfeest
1024    Seminarie
1024    Koffietafel
1024    Receptie
1024    Jubileum
1024    Verjaardagsfeest
1024    Doopfeest / Baby borrel
1024    Vergadering

1024 is an ID I have linked to a node and want to use to update taxonomy terms.

When I run this importer , only the last Item (vergadering) is checked on the node.

All terms already exist in the vocabulary.

How can I process this so all items are checked on the node?

Taxonomy CSV import/export

This module will help you to import the taxonomies in system.


How to execute ajax action after image file upload with media widget? I want to prepopulate some node fields with image metadata (using the EXIF module) right after an image is uploaded/inserted in a node image field with media browser widget and before the node is being saved.

By default, the EXIF module updates the node fields with image metadata after the node is being saved. But, ideally, I would like to hook into the file upload process and update the node fields instantly with ajax, so that users can preview and even edit the metadata related fields.

If I understand your question correctly, I believe you can do this with hook_form_alter. You can create a new form submit handler to do anything you want to do the data before it's saved. I'm not sure why you would need ajax.

my_module_form_alter(&$form, &$form_state, $form_id){
    $form['#submit'] = array();
    $form['#submit'][] = 'my_module_submit_handler';
//this makes sure your submit handler is run first
     array_unshift($form['#submit'], 'my_module_submit_handler');
}

Then create a function to make your changes and call the original form submit function...

function my_module_submit_handler($form_id, &$form_state){
     /*
       changes to the values submitted to your form
     */
   }

This is off the top of my head but should put you on the correct path. I believe that your handler will execute and then the default handler will execute.


What is wrong in my XML structure to add nodes using a RESTFul web service POST? I'm using RESTFul Web Services module with Drupal 7. I can log in with basic authentication, get CSRF-token, get nodes, and so on.

The problem is with POST/PUT: I cannot get adding nodes to work. I get a node of type "page" and I use the same xml structure to do the post. But it doesn't work.

I'm using Delphi RAD Studio 2010 and Indy components to connect with RESTFul service. It works good with all restful request. When I do a POST, I get a 200 OK result, but the page is NOT added.

Here is the XML structure I use:

<node>
<body>
  <value>This is a simple test page</value>
  <summary/>
  <format>full_html</format>
</body>
<type>page</type>
<title>Test Page</title>
<language>es</language>
<status>1</status>
<promote>0</promote>
<sticky>0</sticky>
<views>0</views>
<day_views>0</day_views></node>

I send csrf-token with post, and server gives me 200 OK.

My question: Where could be the problem, perhaps the XML structure is incorrect?

After a lot of research about my question I've changed to json format, which works fine.

I still think I have an error in my XML structure, but since it works with JSON now, I switched to using that instead.

UPDATE: With this json data it works fine.

{ "title":"Test page",
  "type":"page",
  "status":0,
  "language":"es",
  "author":1,
  "body":{  "value": "Aptent bene capto euismod ...",
            "summary":"",
            "format":"filtered_html"
         }
}


How do I vary PathAuto paths based on a field? I have a field type called "Venue". If the Venue is in the US, I want the path to be:

/CITY/my-venue

But if it's in any other country, the path must be:

/AU/CITY/my-venue

In other words, non-US venues must get their country code appended to the front.

Is this even possible with the current PathAuto module? Or how can one do this?

The easiest approach is to define a custom token using hook_token_info() and hook_tokens(). Based on the venue, you either return the country code or nothing. If the token has no value, pathauto will automatically clean it up and drop that part.

Pathauto tokens for taxonomy terms except root for example has some hints on how to implement custom tokens.


Remove home page navigation from logo at checkout Usually users can go to front/home page from anywhere by clicking on the logo. But if I see some e-commerce site, they restrict it when we go for any steps of checkout.
I also want to do the same. If somebody clicks on checkout & URL form something like $base_url/checkout*, I want to remove home/front page navigation link from logo.
How can it be done ?

A good method of doing this is with the context module and context layouts.

Context module: https://drupal.org/project/context

You can specify two layouts, one for main and one for checkout.

Heres a vid about it. http://www.youtube.com/watch?v=rzBpjZ_ZRfo


Adding content to Paragraph Date Field Drupal 8 I'm programmatically creating paragraphs using the following code, but I'm unable to get the date value to store correctly within the date field. It seems to store within the database, yet on the edit page/form for the node, it remains as a blank field.

Any suggestions or insight would be appreciated.

//SET THE DATE
$date = new DrupalDateTime('2017-10-24 13:30:00');

//CREATE THE NEW PARAGRAPH
$paragraph = Paragraph::create([
    'type' => 'event_venue',
    'field_tickets' => [
        ["value"  =>  'Adult Update 1|£30'],
        ["value"  =>  'Adult Update 2|£130']
        ],
    'field_date' => array($date->format('Y-m-d H:i:s')),

]);

//SAVE THE PARAGRAPH SO WE CAN ADD THE ENTITY ID TO THE NODE
$paragraph->save();

//LOAD THE NODE
$node = entity_load('node', $nid);

//ADD PARAGRAPH TO THE NODE
$node->field_dates = array(
    array(
      'target_id' => $venue_information->id(),
      'target_revision_id' => $venue_information->getRevisionId(),
    )
);

//SAVE THE NODE
$nid = $node->save();

Use the global constant DATETIME_DATETIME_STORAGE_FORMAT to format the date:

// If the time is in a different timezone then adjust it to UTC before you save it
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));

$paragraph = Paragraph::create([
  ...
  'field_date' => [
    'value' => $date->format(DATETIME_DATETIME_STORAGE_FORMAT),
  ],
]);

Edit

For Drupal >= 8.5: Global constants in datetime.module are deprecated and DateTimeItemInterface has been introduced.


How to gets analyts and generate visual reports from sessions? I'm looking for a technique or approach to get data from user session logs and convert it to a some sort of visual style (bars/charts/whatever).

We'd like to specifically have the users session "arcs" (login->news->something->logout) displayed in a way that makes it easier to analyze the way people use the site.

This is meant for our service as a usability analyser with the idea that we could make out and see the UX/UI problems that users experience, just from the statistics.

Google Analytics and Piwik are cool and have some of the same functionality but we're looking to go a bit further...

Any ideas on how to get started? Also if I missed an obvious way of doing this, feel free to point out!

I don't know of any modules that build this functionality inside Drupal itself. However, there are several tools out there, for which there are Drupal modules, that allow you to visualize the arc that you speak of. Two of my favorites are:
MixPanel: Mixpanel can allow you to create funnels that will help you see how the user is progressing through your website. For example, how many logged in users clicked on a product, how many of those went on to the payment page, and how many of those actually ending up paying. Mixpanel also has a Drupal module for easy integration. Or you could easily integrate this using a custom Mixpanel module with minimal effort. This is how a funnel in MixPanel would look like:

(source: wordpress.com)
Google Analytics: It has a fantastic Visitors flow functionality that will allow you set flows, goals, and track against those too. Again, Google Analytics has a readymade Drupal module. Here's what a flow in GA would look like:


Modules that will allow search for external data using either Apache Solr or Elastic Search I have data within a Teamsite application which we will be indexing within either Apache Solr or Elastic Search (have not decided yet).  I plan on creating search pages within Drupal 7 that will allow the user to search against the external indexed data mentioned above and list the search within a Drupal results page.

Are there any Drupal 7 module that will allow this to done for external data using either Apache Solr or Elastic Search similar to what can be done with Drupal 7 modules that connect to Solr or Elastic Search for Drupal indexed data?

You need Search API with either of the plugin modules. Search API is a fantastic way to abstract out the engine from the logic. Although I've only use the Solr implementation I've spoken with several developers who have switched to Elastic.

https://www.drupal.org/project/search_api
https://www.drupal.org/project/search_api_solr
https://www.drupal.org/project/search_api_elasticsearch

Search API also works with Facet API (which supports the ApacheSolr module too -- the 'competitor' to Search API).
https://www.drupal.org/project/facetapi

In Drupal 8 those two modules (Search API and ApacheSolr) have become one.


Where to place sar module? I want to replace some of the links which I am using in my website, i came to know there is a module called Drush Search & Replace. I have installed also to use this module. But I am not getting where should I keep this module in the drush installed folder or modules folder. I tried by placing this in module folder It will not list out in the modules list because it doesn't have .module file.

I have installed drush in this path

Drush script  C:\Users\name\AppData\Roaming\Composer\vendor\drush\drush\drush

According to the README.txt of this module:

Place the sar directory in ~/.drush/commands (create it if you don't have one)
and run `drush help sar'.

I tried by placing this module in the C:\Users\name\AppData\Roaming\Composer\vendor\drush\drush\commands folder also,but when I use drush help sar command it will say invalid command sar. Please help me regarding this, Thanks in advance..

Have you cleared the drush cache (drush cc drush)?


How to use term id in content paths using path auto? How can I use term id instead of term name in path auto?I have a category field in my content type named "field_article_category" and there is a token [node:field_article_category] for it but it is replaced by term name not term id.is there anyway to get term id instead of term name?

You likely need the Entity tokens module from http://drupal.org/project/entity for now. We are working on adding the more detailed field tokens into Drupal 7.


How to hide "Delete Site" link for a user rather than Admin? I have website created in Drupal LMS "Openscholar". Its a academy site and there are various,they have there on vsite where they can add content as per there role.When user logged in ,there is a link to "Delete Vsite" available on his/her profile,

Therefore,my issue is that he can delete his account without concerning Admin.I tried to hide it using "Display:none" in CSS but it will hide Delete link for admin too. Thus, i want to know how to resolve such issue ?

$global $user
    //Get admin_id from database and add condition
    if ($admin_id == $user->uid){
         add your code here
         }

Hope this idea of code is helpful for you


How to modify existing language's language code? We have found a typo with one of our language codes. We already have content within that language, but would it be possible to update the language code without having to delete/remove the language and then reading it back in?

WE are unable to find a good way to do modify just the language code..

I'm not sure if this will work, so BACK UP YOUR DATABASE FIRST, but I think that you should be able to run the following query to change fix it:

Let's say for example you were wanting to use Japanese. The language code is 'ja', but people often mistake it as 'jp'. If this was your case, and you wanted to change 'jp' => 'ja', you can run the following query:

UPDATE locales_target SET language = 'ja' WHERE language = 'jp'

Then clear your cache.

If this doesn't work, return your database to its previous state using the backup you took at the start (because you took a backup, right?!)


Get out of maintenance mode using database query (without using drush or admin area) I understand there are very many stackoverflow questions on this very topic.

How can get my site out of maintenance mode? for example.

However I've never seen one that explains how to turn off maintenance mode using only a database query. I run a complex site that does not allow you to login directly using /user since it's using a special sso. So there are times when I do not have access to the admin area and I do not have access to the user login either. I don't always have ssh access to run drush, but I do usually have direct access to the mysql database.

I did find an entry in the config table that seems related.

The name is system.maintenance and the data is

a:3:{s:7:"message";s:93:"@site is currently under maintenance. We should be back shortly. Thank you for your patience.";s:8:"langcode";s:2:"en";s:5:"_core";a:1:{s:19:"default_config_hash";s:43:"Z5MXifrF77GEAgx0GQ6iWT8wStjFuY8BD9OruofWTJ8";}}

I see where it shows the message, langcode and hash settings but I do not see where it defines whether it's on or off.

Is there a location in the database that would allow me to turn maintenance mode on and off directly?

It's never the best idea to manipulate the database directly (for the usual reasons), but if you're out of other options, it's not that unsafe:

UPDATE key_value
SET value = '<value>'
WHERE collection = 'state'
AND name = 'system.maintenance_mode'

Where <value> is replaced with a serialised PHP string representing the integer value 1 for enabled, or 0 for disabled, e.g.

$value = serialize(1);

You'll probably want to invoke a cache rebuild after manually updating the variable, it's probably cached somewhere.


How do I get the Subscriber UID in Simplenews to Create Personalized Newsletters? I am using the insert view module to create a personalized newsletter, now I need to pass the subscriber uid as a parameter to the view but I am not finding a way to do that. Any ideas ?

Thanks !

This isn't possible in Drupal 6.

Simplenews 7.x-1.x now provides a simplenews_subscriber variable for the body template. It also automatically switches the global user to the one that is receiving the mail while it is generated.


Changing secondary menu format Secondary menu links are listed with the default theme.

I want to add a hover option to it so that menu links will always pop up when a user hovers on a button.

I already built it with html but I couldnt integrate the existing codes in it.

html

drupal default code

    <?php if ($secondary_menu): ?>

        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Secondary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>

    <?php endif; ?>

  <?php if ?>

FYI: I couldnt locate to function links__system_secondary_menu in any of the files.

You use CSS to style the links. Looking at your code, the secondary menu has an id secondary-menu-links. So target that within your CSS:

#secondary-menu-links a:hover {
  /* your pop-out effect here */
}


Drupal commerce shopping cart pane empty for non-admin users I have added the shopping cart pane to one of my pages so that it would show up on the review page. This works fine for the admin, but for anonoymous or authenticated users, the shopping cart pane shows up empty for the checkout page and the review page.

Is there a permission somewhere which I need to set? I couldn't find one.

You may need to enable the permission for anon at Admin > People > Permissions

"View any product of any type"

You could try first

"View any [type] product"

but the former permission may still be required there.


Is there a way to have a single field behave as a text field and a file upload/browser at the same time? I need an option for users to have a single field behave as both a textfield so they can enter an external url or browse/upload field depending on which one they want to use. Having two fields will be confusing for users. Is this possible?

Somehow the users have to decide what type of data they want to enter. An option would be to let them choose and then show the appropriate field only. The condotional field module could comme in handy here.


Equivalent of created and modified properties for a taxonomy term I am trying to do a query (using EntityFieldQuery) to get taxonomy terms created or modified in the last day.

for nodes, I use $query->propertyCondition('changed',$time_interval, '>=');
but I can't find the corresponding property for a taxonomy term.

Any suggestion ?
I need to be able to detect creation and modification of terms.

That data isn't stored for taxonomy terms, if you want to add it you'll need to write a small custom module to do so. You could look at implementing hook_entity_info_alter() or hook_field_extra_fields_alter() to actually add the extra property to the taxonomy term entity, but I haven't had much luck using that method before.

Instead I would define a table using hook_schema() in the .install file of your module:

function MYMODULE_schema() {
  $schema['taxonomy_term_extra'] = array(
    'fields' => array(
      'tid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'created' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'modified' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      )
    ),
    'primary key' => array('tid')
  );

  return $schema;
}

Then in your module file implement the taxonomy CRUD hooks:

function MYMODULE_taxonomy_term_insert($term) {
  db_insert('taxonomy_term_extra')->fields(array(
    'tid' => $term->tid,
    'created' => REQUEST_TIME,
    'modified' => REQUEST_TIME
  ))
  ->execute();
}

function MYMODULE_taxonomy_term_update($term) {
  db_update('taxonomy_term_extra')
    ->fields(array('modified' => REQUEST_TIME))
    ->condition('tid', $term->tid)
    ->execute();
}

function MYMODULE_taxonomy_term_load($terms) {
  $result = db_query('SELECT * FROM taxonomy_term_extra WHERE tid IN (:tids)', array(':tids' => array_keys($terms)));
  foreach ($result as $record) {
    $terms[$record->tid]->created = $record->created;
    $terms[$record->tid]->modified = $record->modified;
  }
}

function MYMODULE_taxonomy_term_delete($term) {
  db_delete('taxonomy_term_extra')->condition('tid', $term->tid)->execute();
}

Now whenever you have a loaded taxonomy term you'll have access to $term->created and $term->modified. You can also use a normal db_query(), which is much faster than an EntityFieldQuery to get your filtered terms:

$args = array(':time' => strtotime('-1 day'));
$tids = db_query('SELECT tid FROM {taxonomy_term_extra} WHERE modified >= :time', $args)->fetchCol();

$terms = taxonomy_term_load_multiple($tids);


altering form with hook_form_FORM_ID_Alter function dental_form_simplenews_block_form_2_alter(&$form, &$form_state, $form_id)
{
    global $user;
    $form = array();
    $form['#attributes'] = array('class' => array('newsletter'));
    /*$form['subscribe'] = array(
        '#type' => 'fieldset',
        '#title' => '',
        '#weight' => 5,
        '#collapsible' => TRUE
    );*/
    if ($user->uid) {

    }
    else {
        $form['mail'] = array(
            '#type' => 'textfield',
            '#title' => t('Email'),
            '#size' => 20,
            '#maxlength' => 128,
            '#required' => TRUE,
            '#attributes' => array('class' => array('text_ip')),
        );
        $submit_text = t('Subscribe');
        $form['action'] = array(
          '#type' => 'value',
          '#value' => 'subscribe',
          '#attributes' => array('class' => 'submit'),
        );
    }

    return $form;

}

Above is the code i am using to alter form produced by simplenews plugin. But i am getting various error messages.

Notice: Undefined index: #parents in form_builder() (line 1713 of /home/sjd/www/example.com/includes/form.inc).
Warning: implode() [function.implode]: Invalid arguments passed in form_builder() (line 1713 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #tree in form_builder() (line 1743 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #array_parents in form_builder() (line 1766 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: process_input in _form_builder_handle_input_element() (line 1904 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: complete form in form_builder() (line 1723 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #tree in form_builder() (line 1743 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #array_parents in form_builder() (line 1766 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: process_input in _form_builder_handle_input_element() (line 1904 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: process_input in drupal_process_form() (line 817 of /home/sjd/www/example.com/includes/form.inc).

Can anybody tell me where i am going wrong.

You shouldn't reset the form completely by doing $form = array();, since you will delete some of the stuff Drupal expects to be there.

You should instead do something like this:

function dental_form_simplenews_block_form_2_alter(&$form, &$form_state)
{
    global $user;
    // Remove what you don't want..
    unset($form['fields']);
    // Add what you do want..
    $form['#attributes'] = array('class' => array('newsletter'));
   ...
}


Custom block and menu caching I have a custom block building a menu.
The cache works fine until a menu item is enabled/disabled in the menu edit, e.g.

admin/structure/menu/manage/main
toggle the enabled checkbox and save.

The block does not reflect changes until the cache is cleared.

I have:

            '#cache' => [
                'tags' => [
                    'node_list'
                ],
                'contexts' => [
                    'url.path',
                ],
            ],

which picks up the url / menu text changes and also makes sure the block is valid for each node it is on [i.e. not showing the same block content on every node, but this node's version].

What tag do I need to make sure the cache is invalidated when menu item:enabled is toggled?

You have to add the cache tag of the menu, in this case the main menu:

  '#cache' => [
    'tags' => [
      'config:system.menu.main',
      ...


Linkit not working with CkEditor I have installed the Linkit module to a test site.

I have created a profile, set Matchers and created attributes. I have gone into the CKEditor configuration and chosen my Linkit profile, added the Linkit button, saved the configuration and then liberally cleared the cache on my test site (Vagrant running a lamp stack and Drupal 8.)

When I attempt to use the Linkit feature on either a new piece of content, or an existing one, the dialog box appears with all the desired options, however, other than the standard CKEditor link behaviour none of the other attributes work. I cannot set the title, I cannot set the target attribute.

No errors are appearing in the log and I can find no similar problems on line.

Can anyone suggest a reason this is occurring?

If the filter not Full HTML, you will need to edit the filter format and enter the attributes on the anchor tag in the settings. If not, they will be stripped out (for security reasons).


How do I change the ID of a copy of an exposed filter? I'm using answers from Expose a view's filters both in a block, and in the actual view to duplicate an exposed filter as a block and make it appear in another region on every page.

I want to style both form copies a bit differently. When I started to look into the markup, I noticed that I'm getting two forms with identical IDs. Putting aside the styling, that's not good.
The code I am using is the following.

function MYMODULE_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'mysearch':
      $block['subject'] = t('My Search');
      $block['content'] = _MYMODULE_get_exposed_filter_form();
      break;
  }
  return $block;
}

/** Function to get the Exposed filter form **/
function _MYMODULE_get_exposed_filter_form(){
  $view = views_get_view('node_index_view');
  $view->set_display('page');
  $view->init_handlers();
  $exposed_form = $view->display_handler->get_plugin('exposed_form');
  return $exposed_form->render_exposed_form();
}

How do I alter the ID of the copied exposed filter block? If I use hook_form_alter() or hook_form_views_exposed_form_alter() it's going to apply the alteration to both instances.

This issue was discussed and answered in this thread, it includes a patch to fix the issue:

https://www.drupal.org/node/1735096

Another option is to use the module MEFIBS - More exposed forms in blocks


How to restore form values from $form_state['values']? I save the $form_sate['values'] in a data base. When my users come back to the form I want to show the values that they put before. Something like:

function my_form($form, &$form_sate) {
  $form_state_saved = get_form_state_values_from_db();

  $form['my_field'] = array(
    ...
    '#default_value' = $form_state_saved['my_field'];
    ...
  );

  return $form;
}

With a textfield seems that works fine, but I have some custom fields. Is there a way to set the default_value from db? Or should I implement the default_value independently for each field?

Use Form default value:

'#default_value' => variable_get('sitename_textfield', ''),

If you use system_settings_form() you don't need to manually save your variables using a custom form submit function. Note: The variable must have the same name as the form item.

Function details: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_settings_form/7

/**
 * Creates/returns a form to configure the variables.
 *
 * @param array $form
 * @param array $form_state
 * @return array
 */
function sitename_custom_form($form, &$form_state) {
  $form['sitename_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom Textfield'),
    '#default_value' => variable_get('sitename_textfield', ''),
  );

  // Use system_settings_form() to automate saving configuration variables.
  return system_settings_form($form);
}


Select organic group on the user registration form There's a post already on the post installation forum, but I'm not sure if this is a OG bug. http://drupal.org/node/1108884

I am using Drupal 7 and OG 7.x-2.1 version. There is no "Group Audience" in the manage fields page and I think it is replaced with "Group membership", the field type is "Entity Reference" and the widget is "OG Reference". Also there is no input type in the field setting page and I can not find any field that has a "Always show other groups" option. I have checked the option "Show on registration form of that field, but the combo box on the registration form does not have any option. Any suggestion?

I managed to get this working. These very short instructions are indeed correct. But the first few times I tried to follow them I did not have any success. Therefore I thought it would be useful to explain the steps and potential pitfall in more detail.

I have broken this answer up into two parts. You may have already done the work in Part A of these instructions. I have included them so that if you are really struggling you can go back on a new Drupal installation and ensure that you have followed exactly the same steps as me. You may find this unnecessary, if so skim read Part A and check you are at the right stage before skipping to Part B.

Part A: Steps to install OG and Create an Organic Group (Can be skipped if already completed)

Install Organic Groups and enable it and its submodules (Organic groups register, organic groups UI etc.) as normal (You will need the Entity reference and Views_bulk_operations modules installed to enable these modules). You may need to rebuild the permissions after doing this – you should get a warning if required.
Install Organic groups register which is a submodule of Organic groups - You will need to in order to complete the steps
Create the content type that will be your group (Administration > Structure > Content types). I am calling my example content type ‘Special Group’. Important: in the Organic groups section at the bottom of the create content type select the ‘Group’ checkbox to allow this content type to be a group. Save the content type, you can add the other fields you need once you have everything working.
Create a piece of content using your group content type. (Content > Add Content > Special Group) I called mine My test Group.
In a new browser where you are not signed in, view the new piece of content e.g. ‘My test Group’. You should be able to see the ‘Group: request group membership link’.
Clicking on the request group membership asks you to sign in or register, and then you have to go back to the group to be able to join it. It is this step that we want to improve, by allowing a user to join a group from the registration form.

Part B: Steps to enable group sign up during registration

First we need to add the 'Group register' field to your group content type. To do this go to Configuration > Organic groups > OG field settings.

1.a. From the Bundles drop down, in the node section, select your group content type (mine is called Special Group).

1.b. From the Fields drop down select ‘group register

1.c. Click the ‘Add field’ button at the bottom of the page. After this has been done you should be able to see that the field ‘Group Register’ has been added to the list at the bottom of the page.

Next we need to add field to the user registration form.

2.a. Go to Configuration > People > Account settings > Manage fields

2.b. Edit the 'Group membership' field.

2.c. Select the 'Display on user registration form' checkbox and then save.

2.d. You can now see the ‘Group membership’ field in the Account settings field list with a machine name of ‘og_user_node’ and a field type of Entity Reference.

2.e. Warning: Because you have checked ‘Display on user registration form’ there is a temptation to believe that you have completed the task. If you go to register a new account you will be able to see the ‘Group membership’ field, however there will be no groups in the list. Obviously we do want the groups to be listed here. This is where a lot of users were getting stuck. Don’t worry about this. Simply continue to the next step.

Next we need to select which groups appear on the registration page (solving the problem discussed in 2.e.) The default behaviour of the 'Group membership' field that we created in step 2 is set to 'Do not show on registration page' in our group content type that we created in Part A step 2. We need to do two things – change the default so that new groups that are created have the right setting automatically and then update any groups that have already been created.

3.a. First we will change the default so that new groups that are created have the right setting automatically.

3.a.i. Go to Administration > Structure > Content Types and edit the group content type you created in Part A step 2 (mine is called Special Group).

3.a.ii. You can see the Group register field in the list of fields with a Boolean field type (see screenshot 6). Click edit to edit this field.

3.a.iii. In ‘Default value’ change the radio button to ‘Show on registration page’ and click save settings. Doing this means that all new groups that are created will be listed in the drop down on the registration page by default

3.b. Second we need to update any groups that have already been created.

3.b.i. Go to Content and filter the content by the group content type that you created in Part A step 2 (mine is called Special Group).

3.b.ii. You now need to edit each of the groups that have already been created. For each find the ‘Group register’ radio button group and change it to show on registration page.

4.Now you can test that this has worked.

4.a. First we will test our existing groups. In a browser where you are not logged in create a new account. You should be able to see the group that you created in Part A step 3 (mine is called ‘My test group’) in the Group membership list.

4.b. Second we will test that new groups that are created have the group register setting correct by default. Create a piece of content using your group content type. (Content > Add Content > Special Group) I called mine My second test Group. You should see that the ‘Group register’ radio button is already set to ‘Show on registration page’ as you are creating the content. In a browser where you are not logged in create a new account. You should be able to see the group that you just created in the Group membership list.

I have also added these instructions to the Drupal Community Documentation.


How do I print results after submitting a Drupal form? I have a simple Drupal Module setup which has a single textbox.

I can return what was typed in the textbox using drupal_set_message():

function firstmodule_form1_submit($form, &$form_state) {
    drupal_set_message(t("The user is $username"));
}

However echo $username; will not work for me, nothing is printed. How can I return results without using drupal_set_message()?

The normal way to handle this is to implement a multi-step workflow. See drupal_rebuild_form() for more information, but basically you set $form_state['rebuild'] = TRUE; in your submit handler, and in the original form function add a check to see if the form's been submitted. If it has, you have access to the submitted values and can manipulate the form as you see fit.

A very basic example:

function MYMODULE_some_form($form, &$form_state) {
  // If the form has been submitted, output something related to the submission
  if (!empty($form_state['values']['some_field'])) {
    $form['submission'] = array(
      '#markup' => function_to_get_markup_from_value($form_state['values']['some_field'])
    );
  }
  else {
    // Otherwise build the normal form
    $form['some_field'] = array(
      '#type' => 'textfield',
      // ...
    );
  }

  return $form;
}

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


How to tell Stringsoverrides module to replace text only in specific module? How to tell Stringsoverrides module to replace text only in specific module? Are there any alternatives to this module?

String Override works for the strings defined inside t(), t() takes context as one of the parameters, for example

1. t('May', array(), array('context' => 'Long month name')
2. t('May', array(), array('context' => 'Abbreviated month name')

Both the strings are 'May', if you replace it would be changed across, but t() function also takes context, so if you provide the right context, only that instance of sting will be replaced. String overrides also takes the context while replacing the string, you have to make sure the string you want to replace in a moudle passes through t() and with what context.

Other way could be if its a variable then do a variable_set()

What I prefer is to patch the module, keep the patch in patches folder. To me string replacement is not mission critical peace, after next update release we re-do our patch.


How should I configure cron tasks to make them automatically run on GoDaddy? I own a lightweight blog hosted on GoDaddy. I could not get cron to automatically run, so I manually run it when necessary.

How should I configure cron tasks to make them automatically run on GoDaddy?

I don't have much experience with GoDaddy (I prefer BlueHost), but you could use the PoormansCron module instead of running it manually. Also, if you update to Drupal 7 this is included in core.


How do I remove all references to the Sample DB when using the Forena reports module on a server without PDO Sqllite? We have Forena installed on a server that doesn't have the PDO driver for Sqllite and would like to remove all references to the Sample DB repository so that Forena pages don't display an error about the missing driver. The users see a lot of:

PDO driver support for sqlite not installed

I first tried removing permissions on the SampleDB repository as mentioned in one thread in the issue queue. This had no effect and the error message was still displayed.
I have tried using drupal_alter to remove the repos:
function mymodule_forena_repos_alter(&$repos) {
  if(isset($repos['forena_help'])){
    unset($repos['forena_help']);
  }
  if(isset($repos['sampledb'])){
   unset($repos['sampledb']);
 }

}
I then get a new error:

Undefined repositorysampledb
Undefined repositoryforena_help

I have tried patching the Forena module to unset the settings.php variables inside the sampledb folder. That also gives a new error along the lines of "PDO Driver not found".
How do I remove all references to the SampleDB repo? I would also like to remove the Forena Help and Drupal Admin repos if possible.

Quote from Dave's (Forena maintainer) comment in a related Support Issue:

  ... You might uncheck permissions associated with accessing sample reports to make sure other users don't see this error.

Using this approach you should be OK when upgrading to future versions.

Disclosure: I'm a co-maintainer of Forena (and contributed quite a bit of the content of that forena_help repo you seem to be strugling with).


Querying for user's whose birthday is today plus other OR conditions We have a date field attached to the user entity.  It stores values for year, month and day, in the following format (looking at the field_date_of_birth_value column in the DB): 1987-06-08T00:00:00.

We are using EFQ and wish to return users who's birthday is today OR some other conditions on another field also attached to the user entity (field_babys_date_of_birth, which doesn't necessarily have a value for every user and has is stored in the same format as the other field).

Is there a way to compare the stored month and day with the current ones using EFQ? If not, how would you approach this problem?

Pseudocode specification

  FETCH every account where:
    date_of_birth == TODAY (month and day only)  OR
    babys_date_of_birth == TODAY + 6 MONTHS OR
    babys_date_of_birth == TODAY + 3 MONTHS
  END FETCH
  FOREACH accounts as account
    // Custom logic (always the same).
  END FOREACH

Implemented code

<?php
// Fetch users whose birthday is today.
$today = new DateTime('today');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_date_of_birth', 'value', $today, '=');
$result = $query->execute();
$uids = array_keys($result['user']);
foreach ($uids as $uid) {
  $account = user_load($uid);
  // Custom logic (always the same).
}

// Fetch users where babys_date_of_birth == today + 3months.
$after_three_months = new DateTime('today + 3 months');
$after_three_months = $after_three_months->format('Y-m-d\T00:00:00');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_babys_date_of_birth', 'value', $after_three_months, '=');
$result = $query->execute();
$uids = array_keys($result['user']);
foreach ($uids as $uid) {
  $account = user_load($uid);
  // Custom logic (always the same).
}

// Fetch users where babys_date_of_birth == today + 6 months.
$after_six_months = new DateTime('today + 6 months');
$after_six_months = $after_six_months->format('Y-m-d\T00:00:00');
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_babys_date_of_birth', 'value', $after_six_months, '=');
$result = $query->execute();
$uids = array_keys($result['user']);
foreach ($uids as $uid) {
  $account = user_load($uid);
  // Custom logic (always the same).
}
?>

Known problems with the code:

We think it should be better to have only one query to return all the accounts, as the custom logic to be executed is the same for all of them.
The first condition should only check for month and day (excluding year).

Maybe EFQ doesn't support ORed conditions, and we should use something else?

If you want to filter in your efq, you'll have to compare strings:

   $today = new DateTime();
   $today = $today->format('Y-m-d\T00:00:00');

Then add in your query the condition

'field_date_of_birth_value', $today, '='

I can't tell more unless you show us your code.


How to open a node edit form in an overlay (modal window) in Drupal 8 I have a view with nodes of type 'tasks'.
I want to easily view and edit these tasks by using a minimized overlay. When I click on a task title in the view, it needs to open in an overlay.

In D7 this was possible with the core overlay module, in combination with 'Overlay Paths" module.
The core overlay has been discontinued in D8, in favor of a 'back to site' link, which does not serve my purpose to show a minimized popup block. It also needs to be used by authenticated users, not only administrators.

How can this be done in D8?

You can do that by constructing special links with the help of Colorbox and Colorbox Inline. You'll probably have to create your own style for the "minimized" overlay.

There are other libraries that do the same or similar thing as Colorbox, also integrated into Drupal through a module, so you might want to search and investigate others too (Shadowbox, for example).

These modules are also worth checking out: Modal Configuration, Simple Modal Entity Form, Entity Overlay.


Render entity fields retrieved by EntityQuery I'm building a table with TableSort retrieved by EntityQuery like explained in this post.

The result fields vary a lot and I have a hard time to figure out how to render the results of the different field types, like dates, arrays of entities, taxnomomies, etc.

The most simple way to format the rows is just outputting the field values:

$row = [
    'data' => [
        $node->title->value,
        $node->field_date->value,
        $node->field_persons->value,
        $node->field_tags->value,
];

Now I want to output every column in a different way:

titles linked to the node
dates formatted and not as timestamps
persons as list with every person name linked to his node
tags as list with every tag linked to it's taxonomy

I managed to get titles and dates outputted like I wanted, but I can't figure out to do that for persons and tags:

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\NODE::load($nid);
    $link['#markup'] = '<a href="/node/'.$nid.'">'.$node->title->value.'<a>';

    kint($node);

    $row = [
        'data' => [
            \Drupal::service('renderer')->render($link),
            format_date((int)$node->field_date->value,'custom','Y-m-d'),
            $node->field_persons->value,
            $node->field_tags->value,
        ],
    ];
    $rows[] = $row;
}

Is there a more elegant way to output content of individual fields? Or do I have to find out for every field how to output it investigating it's field type and building the result on my own?

How would I do that for persons or tags outputting the list of result with links to their nodes?

Fields have a view() method that accept either a view mode or an array with formatter/display settings (same format as stored in a view display config entity or passed to a base field).

$entity->get('field_date')->view('teaser').

That returns a render array that you can then display.

If you also use #type table then you can make each row a numeric child key and you can directly use the render array.


Is it safe to use php within a Rules condition? Using Rules I need a condition which checks if the logged in user has authored a given content type.

It seems that I need some custom php for this and I found the code below from a post on drupal.org, which works as required and my rule now does exactly what I want it to do.

I had to enable php filter (for User 1) in order to get the code in to my rule. But I have read that php filter should be disabled on production sites but find that my rule ceases to work if this is done.

I am not a coder and am need to know what is the best way to deal this situation?

https://drupal.org/node/2052241

The PHP filter uses eval(). eval() gets a bad rap because it can be used insecurely. This post on SO goes into detail on that.
The answer to your question is that it could potentially be insecure, depending on the input provided, and how you have things configured. So getting rid of PHP filter altogether would be the ideal resolution (as it pretty much always is).
Getting your code out of the database and into version controllable files is extremely desirable, and is always considered better practice than using the PHP filter.
The proper way to provide rules conditions is to create a custom module, and implement hook_rules_condition_info(). If you're not a programmer then that might be a bit daunting, but at that point it's up to you to decide whether the risks outweigh either learning to do it yourself, or paying someone else to do it.


alterations in tpl file work, but not dpm();, dsm(); or drupal_set_message(); This question here at DA has a popular suggestion to check page.tpl.php to see if it says print $messages;. I verified this and this is the case.

I cleared caches many times, btw after which there actually is a drupal message saying the caches are cleared.

I made sure the dpm(), dsm() or drupal_set_message() functions are nicely outside any conditional statement or php logic whatsoever. I also put all these functions on different places in the tpl file. Still no result.

The same theme also has another tpl file that I used before and had some commented dpm(); functions that I uncommented but these didn't work anymore either.

Devel module is enabled and I am logged in as admin the whole time.

You have access to the entire Drupal bootstrap within template files. Template files are loading at the very end of a page request post bootstrap. If dpm() or dpr() is not working it is most likely because you are viewing the site as an anonymous user. The devel module by default does not allow access to it's functionality for anonymous users. Try logging in as admin and you should see the output of your devel module function calls.

As an F.Y.I. template files are not the typical place for a dpm() as you either need to know the variable you are after or put a get_defined_vars() calls inside it which can be quite heavy depending on where you are in stack. It is more common to use dpm()'s in template hooks such as:

template_preprocess_page()
template_preprocess_node()

function template_preprocess_page(&$vars) {
  dpm($vars);
}

Then you can see all the variables that are available to your template files.


Restrict what content can be added to a panel page (using panels & organic groups) We are using Organic groups and Panels with Drupal 7.

We want each group to have one panel node (that is, a node which content type is "Panel"). The group administrator can then use different kind of layouts and display existing content.

I created two groups A and B. I also created panel node (a node which content type is "Panel") for each group and some nodes that belong to group A and some nodes that belong to group B

Now, when admin of group A edits the panel node's content (through a tab "Panel content") of group A and selects Existing node when adding content to a panel pane, he can choose nodes that belong to group B. Is there a way to make panels respect OG access control? So that group A admin could not select contents of group B to be displayed in a panel pane of group A.

The content in the groups still need to be public so that if anonymous user visits content belonging to each group he will be able to see them.

I guess that by:

when admin of group A edits the panel page

you mean edit the group's node that is being viewed through a panel,and not that he can edit the panel's settings,
and when you're saying

selects Existing node when adding content to a panel pane

you mean that selects content through field (entity-reference). That said, you don't need to make panels respect OG permissions -I am not sure if that's possible- but to filter out the content showing in that field based on Group A or B. To achieve that you may use field_get_items, see the contents of the field and check which node belongs to which group (every node belonging to a group has a Group id (gid) by that gid you can node_load the group node and access its fields) and configure set/unset the field's values accordingly or even you may use hook_form_alter to do so.


Change where the theme gets its files from I'm a beginning developer and I am working in this one Drupal 6 website that has multiple websites in the root. To add to the complexity, I am working with the module Mobile_tools to direct users to a mobile theme.

My issue lies with the sharing of images. When users are directed to the mobile theme, I want to find a way to specify where the website grabs it's images from. It seems that by default, it grabs them from the /sites/all/files rather than the /sites/all/themes/theme/files location.

What would be the best way to go about changing this location? I was thinking of implementing a hook override, but have no idea where to or how to begin.

drupal_get_path and path_to_theme are the two functions that will be usefull for u.


Route logged in user to profile on all request to  node I'm attempting to make a simple login page on the front page that once you log in it will route you to your profile. This part I got working with Rules, but if the user clicks the home link on the site at any point, when logged in, I want to route the user to the profile, not the front page.

I tried a similar trigger to the one I got routing a user when they log in. This being on page view trigger when role is not anonymous and URL alias is /node route to user/[account:uid]

When logged in I click the home button and it's not getting triggered. It just sends me to the homepage.

How can I do this with Rules?

It sounds like there's some missing detail (e.g. checking the right alias, token data not available, etc.).

A simple way to do this to do a page redirect action on a Drupal is initializing event with conditions, Data comparison  on [site:current-page:path] & negated User has role(s) on [site:current-user]. Then you can check for the Drupal path that's set for your front page (i.e. '/node').

For example:

{ "rules_login_frontpage_redirect" : {
    "LABEL" : "Logged in Frontpage Redirect to Profile Page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node" } }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/[site:current-user:uid]" } } ]
  }
}


I can't add links to any of my menu I can't add links to any of my menus.

I go to the menu, click on add link, and fill all the required data; I get the message, "Your configuration has been saved." It doesn't seem it is what it is done.

All modules and core are updated to the last versions.

I fixed it. The problem was that the path contained "20%" instead of a space.


connect view to content type I am working on a drupal 7 installation. This has a content type called Team. In Structure > Views there is a view called Team content. In the folder structure there is also a corresponding view file named node--view--team.tpl.php which renders the Team content.

My task is to duplicate the content type to a new content type called Managers. So I created a new content type called Managers with all the same fields as in Team. I cloned the Team view as well. I then copied over the team tpl file into a new file named node--view--managers.tpl.php.

The problem I am facing is that the manager tpl file is not used when drupal renders the content. It falls back to node.tpl.php - however the design of this page is not how I want it.

What am I missing here? Is there any place in the code/ admin interface where I can specify that node--view--manager.tpl.php should be used instead of node.tpl.php?

Any pointers are greatly appreciated!

Your theme may create node--view--CONTENTTYPE.tpl.php but per content type theme suggestions are not provided out of the box. Your theme layer or a custom module typically provides the theme suggestion, there are a ton of tutorials online about this.

I recommend installing Devel Themer to inspect the View theme template file usage on the page for Teams. Then see why/if the Managers is failing by visiting that page.

Then look through your theme sourcecode and custom modules to see what is providing the hook_theme suggestions.


AJAX link error (form API) I have an AJAX link and a callback function. The problem is that when I click the link an error is thrown.

I have absolutely no idea where did I make an error, the debug information unfortunately doesn't help.

As I understand the AJAX and Form API, the TSTDiv should be replaced with the TST link therefore two links should be visible on the page, right? The problem is, it not only doesn't work, but even throws an (really unhelpful) error.

The callback function / menu hook work fine (correct output is rendered when you access the URL (of the AJAX request) directly).

Code:

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

  $items['groups_hierarchy_load_more'] = array(
    'page callback' => '_fmg_agh_hierarchy_load_more',
    'access callback' => 'user_access',
    'access arguments' => array('Can view all groups'),
    'type' => MENU_CALLBACK,
  );
...

  $page_array['l'] = array(
    '#type' => 'link',
    '#title' => 'TEST',
    // Note the /nojs portion of the href - if javascript is enabled,
    // this part will be stripped from the path before it is called.
    '#href' => 'groups_hierarchy_load_more/' . '5' . '/nojs',
    '#ajax' => array(
      'wrapper' => 'TSTDiv',
      'method' => 'replace',
    ),
  );

  $page_array['d'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
  );
...

function _fmg_agh_hierarchy_load_more($group_id, $ajax) {
  $page_array = array();

  $page_array['tst']['data'] = array(
    '#type' => 'link',
    '#title' => 'TST',
    // Note the /nojs portion of the href - if javascript is enabled,
    // this part will be stripped from the path before it is called.
    '#href' => 'groups_hierarchy_load_more/' . 'TST' . '/nojs',
  );

  return $page_array;
}

Error:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /drupal7/?q=groups_hierarchy_load_more/5/ajax
StatusText: OK
ResponseText:
localhost
@import url("http://localhost/drupal7/modules/system/system.base.css?n3277e");
...

While I still don't know where the problem is (it should work this way) I've found a solution.

Instead returning the whole $page_array in callback function and hoping that Drupal will understand it and replace the div specified in '#ajax' => array('wrapper' => 'TSTDiv',... property of the link with it you can simply use ajax commands and 'return' something like this:

$commands[] = ajax_command_replace('#TSTDiv', render($page_array));
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

And vuala it works just fine (and looks more professional at the same time!).

Would still appreciate and answer why the original approach didn't work, though.

BTW: I didn't know the AJAX commands before.


How to make Drupal Commerce send email notification to the author of products sold? I use Drupal Commerce and the rules module to send email which works OK. But it doesn't send the email to author node of product.

Here is an export of my current rule:

{ "commerce_checkout_order_email" : {
    "LABEL" : "Send an order notification e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "4",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "rules", "mimemail", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "mimemail" : {
          "USING" : {
            "key" : "emailrenzo",
            "to" : "[commerce-order:mail]",
            "from_name" : "Regalalo",
            "from_mail" : "info@regalalo.pe",
            "subject" : "Pedido # [commerce-order:order-number] en [site:name]",
            "body" : "\u003Cdiv\u003E\r\n\u003Cimg src=\u0022\/http:\/\/34.214.32.99\/sites\/default\/files\/logo-regalalo.png\u0022\u0022\u003E\r\n\u003C\/div\u003E\r\n\r\nHola [commerce-order:owner]!!\r\ngracias por realizar un pedido en [site:name], su n\u00famero de pedido es # [commerce-order:order-number].\r\n\r\nSi este es su primer pedido con nosotros, pronto recibir\u00e1 otro correo electr\u00f3nico con las instrucciones para acceder a nuestro sitio con su nombre de usuario y contrase\u00f1a. Puede ver su historial de pedidos en cualquier momento ingresando a nuestro sitio web:\r\n\r\n[site:login-url]\r\n\r\nPuede consultar el estado de su pedido en:\r\n\r\n\u003Ctable cellspacing=\u00220\u0022 cellpadding=\u002210\u0022 border=\u00221\u0022\u003E\u003Ctr\u003E\u003Ctd\u003E\u003Ctable cellspacing=\u00220\u0022 cellpadding=\u002210\u0022 border=\u00221\u0022\u003E\u003Ctr\u003E\u003Ctd\u003E[commerce-order:commerce_line_items]\u003C\/td\u003E\u003C\/tr\u003E\u003C\/table\u003E\u003C\/td\u003E\u003C\/tr\u003E\u003C\/table\u003E\r\n\r\n[commerce-order:customer-url]\r\n\r\nPor favor comun\u00edquese con nosotros si tiene alguna duda.\r\n\r\n\u00a1Gracias por comprar en nuestra plataforma! Vuelve a visitarnos aqu\u00ed: Regalalo.PE\r\nSi tienes alguna pregunta acerca de tu pedido, contacta la tienda del producto que tendr\u00e1 el agrado de atenderte. \r\nPara otra consulta de asistencia env\u00edanos un correo a \u003Ca href=\u0022mailto:info@regalalo.pe\u0022\u003E info@regalalo.pe\u003C\/a\u003E\r\n",
            "language" : [ "commerce-order:state" ]
          },
          "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
        }
      },
      { "mail" : {
          "to" : [ "commerce-order:owner:mail" ],
          "subject" : "Pedido # [commerce-order:order-number] en [site:name]",
          "message" : "Hola [commerce-order:owner]!!\r\nGracias por realizar un pedido en [site:name], su n\u00famero de pedido es # [commerce-order:order-number].\r\n\r\nSi este es su primer pedido con nosotros, pronto recibir\u00e1 otro correo electr\u00f3nico con las instrucciones para acceder a nuestro sitio con su nombre de usuario y contrase\u00f1a. Puede ver su historial de pedidos en cualquier momento ingresando a nuestro sitio web:\r\n\r\n[site:login-url]\r\n\r\nPuede consultar el estado de su pedido en:\r\n\r\n[commerce-order:commerce_line_items]\r\n\r\n[commerce-order:customer-url]\r\n\r\nPor favor comun\u00edquese con nosotros si tiene alguna duda.\r\n\r\n\u00a1Gracias por comprar en nuestra plataforma! Vuelve a visitarnos aqu\u00ed: Regalalo.PE\r\nSi tienes alguna pregunta acerca de tu pedido, contacta la tienda del producto que tendr\u00e1 el agrado de atenderte. \r\nPara otra consulta de asistencia env\u00edanos un correo a \u003Ca href=\u0022mailto:info@regalalo.pe\u0022\u003E info@regalalo.pe\u003C\/a\u003E",
          "language" : [ "commerce-order:state" ]
        }
      }
    ]
  }
}

This rule works with user customer but not sellerr or authors, what´s your recommendation?

In short; you should loop over all commerce order line items, obtain the product owner and add it to a list. Then in a new loop, go through the created list to send all product owners a main.

First you need a rules component that checks if a provided line item contains a product field and pushes the author to a given list (enforcing uniqueness makes sure every product owner is only added once). You can import below code on the components tab:

{ "rules_product_on_line_item" : {
    "LABEL" : "get product owner from line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "Line item", "type" : "commerce_line_item" },
      "owners" : { "label" : "Product owners", "type" : "list\u003Cuser\u003E" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "list_add" : {
          "list" : [ "owners" ],
          "item" : [ "line-item:commerce-product:creator" ],
          "unique" : "1"
        }
      }
    ]
  }
}

Now for the main rule, create a new variable of type list of users. This is where we will store all product owners in.

Create a loop over commerce-order:commerce-line-items. In this loop, use the component that was created above. This will fill the list of product owners.

Finally, loop over the list of product owners, and send each of them a mail. The complete rule would look something like this:

{ "rules_mail_all_product_owners" : {
    "LABEL" : "Mail all product owners on an order",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "5",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "product_owner_list" : "Product owner list" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_product_on_line_item" : { "line_item" : [ "list-item" ], "owners" : [ "product-owner-list" ] } }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "product-owner-list" ] },
          "ITEM" : { "productowner" : "Current product owner" },
          "DO" : [
            { "mimemail" : {
                "key" : "mailkey",
                "to" : [ "productowner:mail" ],
                "from_mail" : [ "site:mail" ],
                "subject" : "",
                "body" : ""
              }
            }
          ]
        }
      }
    ]
  }
}


Overriding the search block module output to add a custom wrapper My problem is fairly simple. I have written a theme_form() to override the default but I want it to kick in only in the search block. How can I do this with Drupal 7? Thanks

Put search-block-form.tpl.php into your theme directory, and modify it as you wish.

Another way is using hook_form_FORM_ID_alter().

/**
 * Implements hook_form_FORM_ID_alter().
 */
function HOOK_form_search_block_form_alter(&$form, &$form_state) {
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
}


Is it possible to group taxonomy list items by content type? I'm working on a website which uses a single vocabulary for three different content types. I'm looking for a way to group list items by content type.
To illustrate, I got three content types:

Manual
News
Blog

And I got lots of vocabulary terms which might be used by all three content types:

Rabbits
Cats
Dogs
Frogs

When I select a vocabulary term it will show all the relevant content, sorted by the publication date, like so:
Rabbits

Rabbit escaped from show-ground
Feeding your rabbit
Why do rabbits have such big ears?

However, I'd like to group the items by content type:
Rabbits
Manual

Feeding your rabbit

News

Rabbit escaped from show-ground

Blog

Why do rabbits have such big ears?

I've tried the default 'Taxonomy term' view but found it wouldn't quite work because it affect other vocabularies as well. I also tried the Taxonomy Display module but didn't really understand how it works (I got some configuration options but no view I could change).
Is there a function that could check the vocabulary and the list items' content types and then group them by content type?

I assume you know how to set up the view and have difficulty only with applying the view to the specific taxonomy and letting other taxonomies render by default.

Create a custom module and put this is the main module file:

function MODULE_menu_alter(&$items){
  // change taxonomy view path for certain vocabularies
  $items['taxonomy/term/%taxonomy_term']['page arguments'][] = $items['taxonomy/term/%taxonomy_term']['page callback'];
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'custom_taxonomy_term_callback';
}

function custom_taxonomy_term_callback($term, $callback) {
  if ($term->vocabulary_machine_name == "SOME_TAXONOMY") {
    $view = views_get_view('CUSTOM_TERM_VIEW');
    $view->set_display('default');
    $view->set_arguments(array($term->tid));
    $view->pre_execute();
    $view->execute();
    return $view->render();
  }
  else {
    module_load_include('inc', 'taxonomy', 'taxonomy.pages');
    return $callback($term);
  }
}

This is what the code does:

It alters the path taxonomy is called on, then checks if the path is on your taxonomy that you want to special render. If it is it loads and renders the view for that taxonomy, and if not it passes the call back to the default taxonomy callback.

You need to alter the code to suit your taxonomy machine name and view name. And remember to clear the cache.

For your view you can create just the master view (ie no page with path) that accepts the tid as contextual filter. This view is custom rendered and therefore does not need to be on any path.


How to move node contents from local to server environments? What is the best way to move node contents from a local environment to a server environment?

I don't want to go with the Features modules.

Any examples that we can go with dbscripts?

Consider using module Backup and Migrate. From the modules project page:

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


How to assign a specific color to each taxonomy term in a chart created with the Charts module? I have a view with format "Chart" and I'm using Highcharts as my charting library.

In the settings there is a section to choose the colors of the chart.

My content has a field that can have 3 different values. On the chart, the colors are assigned randomly for that field.

Is it possible, using the Charts module, or in any other way, to assign a specific color for each of the field values (the field is a taxonomy term)?

As you must have noticed, creating charts using the Views UI of the Charts module, you can only select 1 color for each chart.

However, if you would rework your chart to a Combination chart, you could set a color for each of the charts. Here are some more details about how I'd create the combination chart (with 1 color for each taxonomy term):

Use your current chart display as the parent chart for 3 child charts to be added to it (as explained below). Adapt its chart settings where needed, so that it won't get in the way of the 3 child charts to be added to it. For that, I'd make it a "line chart", possibly with some other refinements like color and label of that chart also.
Add a 1st (child) chart display with a views filter that limits the values to only your 1st taxonomy term, and specify a 1st color in its chart settings. Use the chart in bullet "1." as its parent chart.
Add a 2nd (child) chart display with a views filter that limits the values to only your 2nd taxonomy term, and specify a 2nd color in its chart settings. Use the chart in bullet "1." as its parent chart.
Add a 3rd (child) chart display with a views filter that limits the values to only your 3rd taxonomy term, and specify a 3rd color** in its chart settings. Use the chart in bullet "1." as its parent chart.

Here is an example of a column chart created as a combination chart:

And this is a variation of it in the format of an area chart (for "total") with 2 line charts:

As both examples illustrate, for each chart in such combination chart, you can assign any combination of colors ... Which is what this question was about, no?

Note: Using this approach, the parent chart in bullet "1." above will avoid that you run into the issue about "holes" in your X-axis data. Refer to my answer to the question about "How to create a combination chart with the Charts module if some X-axis values are missing?" for more details on that.


What could be causing this error? I am facing an error in Drupal 9 Stripe module. After installing the module and setting the private and public keys, I visited the /admin/commerce/orders/84/payments/add page, and selected my newly created 'test stripe payment' as payment gateway. Then, I selected one of the payment methods that I've added from /user/18/payment-methods (Add new payment method). This redirected me to the Add payment page where there is an Amount field and two radio buttons (Authorize only and Authorize and capture) and an Add payment button. When I click on this button, the site crashes with the following error.

Error : Call to a member function getRemoteId() on null dans Drupal\commerce_stripe\Plugin\Commerce\PaymentGateway\Stripe->createPaymentIntent() (/home/mywebsite/www/web/modules/contrib/commerce_stripe/src/Plugin/Commerce/PaymentGateway/Stripe.php line 430)

The line causing the error belongs to this function. Does it mean $payment_method is null? Do you have any idea on what might be causing this error?
/**
  * {@inheritdoc}
  */
public function createPaymentIntent(OrderInterface $order, $capture = TRUE) {
  /** @var \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method */
  $payment_method = $order->get('payment_method')->entity;

  // Line 430
  $payment_method_remote_id = $payment_method->getRemoteId();
  $customer_remote_id = $this->getRemoteCustomerId($order->getCustomer());

  $amount = $this->toMinorUnits($order->getTotalPrice());
  $order_id = $order->id();
  $capture_method = $capture ? 'automatic' : 'manual';
  $intent_array = [
    'amount' => $amount,
    'currency' => strtolower($order->getTotalPrice()->getCurrencyCode()),
    'payment_method_types' => ['card'],
    'metadata' => [
      'order_id' => $order_id,
      'store_id' => $order->getStoreId(),
    ],
    'payment_method' => $payment_method_remote_id,
    'capture_method' => $capture_method,
  ];
  if (!empty($customer_remote_id)) {
    $intent_array['customer'] = $customer_remote_id;
  }
  try {
    $intent = \Stripe\PaymentIntent::create($intent_array);
    $order->setData('stripe_intent', $intent->id)->save();
  }
  catch (\Stripe\Exception\ApiErrorException $e) {
    ErrorHelper::handleException($e);
  }
  return $intent;
}

Commerce Stripe is a bit of a mess at the moment.  There are lots of issues that need to be fixed as you can see in the project issue queue.
You are probably experiencing the bug described on Stripe\PaymentIntent instance has invalid ID, but there is a longer discussion about how to handle this at [meta] SCA, the Stripe Review pane and recurring payments.
Basically, the issue is that Commerce Stripe does not generate a payment ID unless you go through the review pane first.  That means that if you configure a standard Commerce checkout flow and go through that flow (login -> cart -> checkout, etc.), then the module will probably work.  If not, you will spend hours searching the issue queue to try to debug the module.
Source: Have spent several frustrated hours over the past couple years with Commerce Stripe.
If it helps, I'm currently using the following patches just to get the module to work on my site:
    "drupal/commerce_stripe": {
        "do not load stripe library on every page": "https://www.drupal.org/files/issues/2020-02-03/3083393-21.patch",
        "skip review step by autosubmit": "https://www.drupal.org/files/issues/2020-09-16/commerce_stripe-3171411-2.patch",
        "fix 1112 errors https://www.drupal.org/project/commerce_stripe/issues/3177168": "https://www.drupal.org/files/issues/2020-10-16/3177168-2_commerce_stripe-fix_address_errors.patch",
        "fix TrustedCallbackInterface warning https://www.drupal.org/project/commerce_stripe/issues/3168822": "https://www.drupal.org/files/issues/2020-10-09/PaymentMethodAddForm%20needs%20to%20implement%20TrustedCallbackInterface%20for%20Drupal%209-3168822-14.patch"
    },


Where should I place .htaccess to take effect in a particular site? We have an Apache web server that contains several Drupal 7 installations. Where should I place a .htaccess file in order for its contents to take effect on a particular website?

I tried putting it here /opt/apache/var/www/html/drupal-7.19/sites/thewebsitename but it didn't work.

If you have a multi-site Drupal installation (ie. folders other than 'all' and 'default' in your /opt/apache/var/www/html/drupal-7.19/sites/ directory), then you cannot have a separate .htaccess file for each site, and must place your changes in the common .htaccess which should already exist in /opt/apache/var/www/html/drupal-7.19/. Note that as these changes will apply to all of your multi-sites, you need to ensure your rules don't break sites you're not interested in.

If you have a more traditional installation of one site per one Drupal instance, then you'll still be modifying the same .htaccess file in /opt/apache/var/www/html/drupal-7.19/, but don't have to worry about breaking other sites.


How to show user profle edit tab as a default tab on user profile page? I want to show user profile edit tab as a default, on page load its content must show. Like we have option in quick tab module, in which you can select which tab must show on page load.

How to perform this?

You could use the Redirect module to redirect users from /user/* to /user/*/edit. This could cause problems when other users are trying to view other user's profiles.

You can also do this with Rules. This would allow you to redirect users conditionally.


Display content from a remote URL is there a way to show content from an external URL (e.g. from GitHub) in a page?

I was using PHP code but because of security reasons I would prefer to use a module instead.

$c = curl_init();
curl_setopt($c, CURLOPT_URL, "https://raw.githubusercontent.com/foo/bar/master/file1.txt");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
echo htmlspecialchars(curl_exec($c));
curl_close($c);

I am looking to something similar to https://www.drupal.org/project/url_embed but without WYSIWYG. I just need to add some tags with the URL in the appropriate place on the page to display it.

Creating a custom module for this in Drupal would be quite easy if you focused on your specific use case.  You can find more info on that here:
https://www.drupal.org/docs/8/creating-custom-modules

More specifically, you may want to look at a custom block implementation:

https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks


How to be able to use a content once in a content field? I created a field in to a content. Let's call the content type National Anthem and the field Country. Country is a content type too.

What I'd like to do is to forbid the use of a country which has been chosen already.
*
For example, let's say that we have the country Germany, France and United-Kingdom. If I create a new National Anthem and for the field Country, I choose United-Kingdom. I now create a new National Anthem and I can only choose between France and Germany.

Thank you.

Assuming you are using an entity reference (default reference in Drupal 8, and provided by the Entity Reference module for Drupal 7). You can do this with an entity reference view:

Create a new view that lists content of type Country. Then take the following steps:

Make sure to add a new Entity Reference Display.
Enable the title field as Search field in the formatter settings. (Behind drop down menu.)
Add a relation of type Content using field_country.
Filter content that has no value for ID using the relationship.
(optional), if you reference country from more content types than National Anthem, filter also for the Content type to be of National Anthem; again using the relationship.

This view will select all countries, which are used on nodes with no ID. (Thus are not referenced.)

Finally, make sure you enable the view in the content type's field settings:


Calendar From Multiple Content Types I have a 4 seperate calendars created on drupal; each with their own content type. Each of these need to be able to be viewed on their own but I'd also like to be able to combine all of these calendars into one master view and can't seem to figure it out.

ie. Meetings calendar, Holidays calendar, Staff Events calendar.

Any help would be greatly appreciated. I'm new to Drupal so please be gentle.

Thanks

If you've got the calendar views setup already, there's a few ways to show them all together

Views attachment displays ( maybe )
views_embed_view in a template ( ok, if comfortable with PHP )
Panels ( recommended )

For example, using Panels, you can create a page with a particular layout and simply embed the View displays into the Panel page via the user interface.


How to increase the speed of exposed autocomplete field in views using drupal 6? I have an exposed auto-complete taxonomy filter, It takes time(2sec) to load the values. How to increase the performance to load the values quickly and I'm using views 2.x.

Assuming a Drupal installation configured for a production environment (including Apache and MySQL tuning), there are two things that impact autocomplete latency.

One, is a built-in delay between user input and running searches.  This is baked into misc/autocomplete.js.  The value is set to 300ms (line 245), and get used in Drupal.ACDB.prototype.search (line 287).

The second is that searches will run on a single character.  If your autocomplete result set is large, this can have huge performance impacts.

Unfortunately, there isn't a good way to alter either of these behaviors.  You can add your own Javascript and redeclare Drupal.ACDB to use a shorter delay, eg

Drupal.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 100;
  this.cache = {};
};

and Drupal.ACDB.prototype.search to add in some logic to enforce a minimum number of characters, eg

...
// See if this string needs to be searched for anyway.
searchString = searchString.replace(/^\s+|\s+$/, '');
if (searchString.length <= min ||
  searchString.charAt(searchString.length - 1) == ',') {
  return;
}
...

However, 400 results isn't a huge number.  I have mainly seen the delays this with 10000+ results.  This suggests that you may need to do some additional profiling on your server.


Improve performance by using drush functions instead of Drupal module functions I am trying to improve the import performance of a drupal website we are working on.  The site makes use of the queue api to import individual items.  Currently this process is very slow.  I have hear it mentioned that one way of improving performance is to process items using drush rather than having Drupal do it directly.

What our site does is read the contents of a text file and then add each item to a queue for processing.  The queue worker function just takes the information, performs some processing logic and then saves it as a node.

From what I understand we would want to move this queue worker function out of the current Drupal module and into drush.

I have been searching for general background information on how to do this or some introductory tutorials, but have not been able to find anything about using drush to improve performance of resource intensive tasks.  I am a little surprised that there is so little information on this given that it is supposed to improve Drupal performance.

Queues are defined within Drupal modules, and you can use drush to run those queues:

drush @site queue-list
drush @site queue-run queue_name

Changing the interface to the import code (queue, batch api or a drush command) won't affect drastically the import time.

I'd review the import code to try and optimize it. For example by caching (in memory) any data you may be loading recurringly from the database.


use xmlrpc to authenticate and create a node via services module 3.x and drupal 7 I want to use services module 3.x, drupal 7 and xmlrpc to create a node from a php client. However, I don't know how to deal with the authentication. I enable the session authentication but I don't know what I should do and I get error: HTTP/1.0 401 Unauthorized: Access denied for user anonymous.

ps: I can get session name and session id from user.login

Note: this is valid after SERVICES 3.5 (lower version are deprecated, anyway)

// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

// GET TOKEN
$token = xmlrpc(url($this->endpoint, array('absolute' => TRUE)), array('user.token' => array()), $this->headers);

//INSERT TOKEN INTO HEADERS
$options['headers']['X-CSRF-Token'] = $token['token'];

At this point you should be authenticated and could create nodes at will.


Using jQuery $.ajax() on my site won't work This is the first time for me to use the jQuery $.ajax() in Drupal. The code is a simple test code but it keeps going to the error: section instead of success:. Could my url path be wrong? The .js file and the test-ajax.php file are in the same folder named "code".

    //This is Javascript
    $.ajax({
        url: 'code/test-ajax.php',
        data: 'a=hello&b=world',
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(){
            alert('FAIL'); //Keep getting "FAIL". It's like it can't find the php file.
        }
    });

Nothing fancy inside the file test-ajax.php:

<?php
$a = $_POST['a'];
$b = $_POST['b'];

echo "$a, $b";
?>

EDIT: To avoid confusion on the paths (I keep it organized):

Main theme files: <templatename>/<.info, template.php, style.css, etc.>
Template files: <templatename>/templates/*.tpl.php
AJAX files: <templatename>/code/<PHP and .JS files>

In Drupal, JavaScript files are added via the drupal_add_js() function or in the
theme’s .info file.
A simple example of using jQuery in drupal is

    <?php
    drupal_add_js('jQuery(document).ready(function () {
   jQuery.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });
    });', 'inline');
    ?>

you have to use 'jQuery' instead of $.


One site, two domains We have a single site that we'd like to have two different domains: apply.school1.edu and apply.school2.edu.

The site is at apply.school1.edu and we'd simply like to create a domain apply.school2.edu to point to apply.school1.edu. That way we can use the domain to determine what content to load on the page.

How can we do this?

If you'd like both sites to use the same code/modules and database (thus sharing users and some content), use the domain access module at https://www.drupal.org/project/domain

If you'd like both sites to have the same code/modules but not the database, check out Multisite at
https://www.drupal.org/docs/7/multisite/multi-site-sharing-the-same-code-base


How to apply authentication to rest endpoint URL? I can access the rest endpoint URL for a node in JSON format (e.g. https://192.168.1.235/rest_endpoint/node/1142?_format=json) even if we are not logged-in to the sever.

Is there any way to apply authentication to access this URL?

Since rest callbacks run through Drupal's normal roles/permissions layer, you can just disable the View published content permission for anonymous users, then they won't be able to fetch the JSON for the View.

If you need finer grained control, you'll have to use hook_node_grants().


Inserting NULL value with db_query OR db_write_record I have a table called foo_bar whose fields are as follows

id int(10) unsigned NOT NULL AUTO_INCREMENT
name varchar(255) DEFAULT NULL
amount float DEFAULT NULL

I want to enter the value to this table like this

$name_value = 'Dollar';
$amount = NULL;

db_query("INSERT INTO {foo_bar} (name, amount) VALUES ('%s', %d)", $name_value, $amount_value);

But now when I see the values into the table it showed me

id | name   | amount |
1  | Dollar |      0 |

I tried db_write_record as well like this...

$obj_foo_bar = new stdClass();
$obj_foo_bar->name = 'Dollar'
$obj_foo_bar->amount = ''

But I am getting the same result.

EDIT: 17 Sep 2012

Don't use drupal_write_record for insert/update queries where you want to place the default value to NULL

INSTEAD: Use content_write_record which is used by CCK module to update the database tables were you want to place default value as NULL.

This function says Directly copied from core's drupal_write_record, which can't update a
column to NULL. See http://drupal.org/node/227677 and http://drupal.org/node/226264 for more details about that problem.

The NULL that you're passing is possibly/probably being interpreted as a string, ie. "NULL". When MySQL casts that to a float the result is 0.

If you have a default value for the column you can just leave it out of the query altogether, and you'll get the results you expect:

db_query("INSERT INTO {foo_bar} (name) VALUES ('%s')", $name_value);

or

$obj_foo_bar = new stdClass();
$obj_foo_bar->name = 'Dollar'
// Leave out $obj_foo_bar->amount

drupal_write_record($table, $obj_foo_bar);


Redirect after updating nodes I've to redirect users, after updating a node, to /node/NID path and not to /node/NID/latest (I'm using content moderation).

I've tried to add this on hook_node_update() but have been ignored (without warning or errors):

if (!$entity->isNew()) {
    $path = URL::fromUserInput('/node/' . $entity->id())->toString();
    return new RedirectResponse($path);
}

use \Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  $path = Url::fromUserInput('/node/'.$node->id())->toString();
  $response = new RedirectResponse($path);
  $response->send();
}

You have to use like above. You are just returning the redirect response. You need to send redirectresponse to given path.


Splitting Drupal commerce order for easier shipping During shipping we generally need to split the orders based on the availability of the products. Considering the order contains two products but only one product is available, we would like to split the order such that we can ship one product now and we can ship the the product later. Both split orders will contain same address and other details.

Are there any module that does this?

I'm not sure you need to consider this as order splitting. I'm working on a project currently that will make use of the Commerce Shipment module to handle splitting an order into shipments for fulfillment. It can accommodate either a single shipment per order or multiple if necessary.


Reset Serial module annually I'm a newbie to drupal 7 for a year by now. I'm trying to make a unique id field that would increment per node of content type I create.

The computed fields module + serial module is the likeliest method accomplishing my goal, yet I'd like to restart the serial number starting each year, I'm totally lost, please help.

This is the code I've used.
The output: 20150001, 20150002 and so on.
Is there a method to restart the serial num. back to 0001 again when it's a new year?

Computed Code (PHP)

$entity_field[0]['value'] = $entity->field_serial[LANGUAGE_NONE][0]['value'];

Display Code (PHP)

$display_output = date('Y') . sprintf('%04s', substr(str_pad($entity_field_item['value'], 4, '0', STR_PAD_LEFT), -4, 4));

This is another method I've found, it works on the D6 website, but turns into a blank on my D7 published contents. It's from a field on D6 using php filter module.

<?php
$case_id_query=db_result(db_query("select  max(field_case_id_value) as id  from {content_field_case_id} "));

$case_id = date("Y") . sprintf ( '%04s', substr ( $case_id_query, 4, strlen ( $case_id_query ) - 4 ) + 1 );
return array(
  0 => array('value' =>$case_id),
);
?>

can I transform the method above to D7?

I recommend in the future to peruse the Module issue queue. :)

There are a number of patches in the following issue thread, one of which I've used to reset yearly (and actually modified to reset monthly): https://www.drupal.org/node/2168071


How to show a string once you submit a form in a page reloading the page? I need to create a page with a form and once you enter some values in the form and send it make some calculations and show a string under the form. Something like this image:

I know how to create a page with a form inside and I know how to show a message but in this case I need to show the string (message) under the form.
So, how to show a string once you submit a form in a page reloading the page?

Add the code to calculate and display the result in the form build

  public function buildForm(array $form, FormStateInterface $form_state) {
     $form['number1'] = array(
      '#type' => 'textfield',
    );
    $form['number2'] = array(
      '#type' => 'textfield',
    );

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

    $values = $form_state->getValues();
    if (!empty($values)) {
      $result = $values['number1'] + $values['number2'];
      $form['result'] = ['#markup' => '<p>' . $result . '</p>'];
    }

    return $form;
  }

So that the result can be included in the form rebuild when the input values are filled in.

In submit request a rebuild:

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }


Can I work with hook_user_login() directly within user.api.php? Somewhat new to Drupal... this is probably a softball for all you Drupal pros out there.

I need to update a custom table in the database each time a user logs into Drupal.  I thought I'd be able to do this within user.api.php and specifically within hook_user_login but it's as if none of the code I've put in there works.  To debug I added the following 2 lines to try to email myself details about $account and I never get that either.

$o = print_r($account, true);
mail("art@geigel.com", "Login Output", $o, "FROM: no-reply@geigel.com");

I've also gone into the Drupal admin area and saved the settings page for the modules thinking it was a Drupal caching issue related to its hooks.  That didn't do it either.

Can someone tell me what I'm missing?  I'd prefer to just take care of the database stuff here instead of creating an entirely new module and implementing the hook there.

Thanks in advance.

AG3

The .api.php files are documentation only, they're never included in a request.

hook_user_login() can only be implemented in a module, so you'll need to write one for this.

It's pretty straightforward, the Module developer's guide will get you started quickly.


Installing on CentOS 6 with Apache 2.2.15 I'm trying to install 8.0 RC4 on CentOS6 with Apache2.2.15 and I'm being stopped by this error message:

  Apache/2.2.15
  The minimum version of Apache needed to run Drupal without mod_rewrite enabled is 2.2.16. See the enabling clean URLs page for more information on mod_rewrite.

I've made sure to have this on httpd.conf:
AllowOverride All

And mod_rewrite is in fact being loaded correctly. I tried httpd -M | grep rewrite and I get:
rewrite_module (shared)

I even tried copying the htaccess sample into httpd.conf. I restart apache, and I always still get the same error. Does Drupal 8 simply not support this version of Apache? Could it be the fact that I'm accessing the site via the server's IP rather than a host name?

I tried upgrading to Apache 2.4 but that was an ordeal since the package manager doesn't provide it and the end result gave me even more problems.

Any advice?

Edit: I've installed a wordpress site and tried using SEO friendly URLs, everything works fine. Clearly mod_rewrite has to be working.

If you are sure that mod_rewrite is enabled and working you could try to get past the system requirements check if you change the url during the step "Verify requirements" like this:

Standard URL like this:
core/install.php?langcode=de&profile=standard
change it to:
core/install.php?langcode=de&profile=standard&rewrite=ok

You add

  &rewrite=ok

to the url. This will normally be done through .htaccess. Then reload the page or click try again and you should get past this warning.

But it seems that something is not working as expected with your mod_rewrite, so you might encounter trouble later on.


How to find all inputs that make use of the php input filter to fully disable the php filter module? I want to disable the PHP Filter module on a large website, but going through all nodes, blocks and other fields where you could make possible use of the php filter would take eons.

Is there a simple way or method maybe by running SQL queries to find out where the php filter is used throughout my website?

Rather than re-inventing the wheel, just install the Security Review module, which has the following check:

  PHP or Javascript in content (nodes and comments and fields in Drupal 7)

For blocks you can check the format column in the block_custom table.

The difficult one is Views - I've yet to find a reliable way to locate rogue PHP in Views programmatically.


Where do I set anonymous checkout without users hit the login page? After adding an item to the Drupal Commerce cart, I hit the cart review page. Then I click on checkout and I'm hit with the login page, is there a setting where users don't have to login and just checkout anonymously. And if they already have an account on the site their order would be added to their account in reference to their email.

You aren't just using Drupal Commerce, are you? It sounds like you're using Commerce Kickstart or Drupal Commerce with the Commerce Checkout Redirect module enabled. That's what's responsible for the behavior you're describing. Just disable it and enable the "Access checkout" permission that David Thomas pointed to.


How can I debug/test my custom migrate module? I've written a custom migrate module in Drupal 8. (Based on these instructions: https://github.com/wunderkraut/migrate_source_example/)

The migration reads data from a XML file with the "migrate_source_xml" extension and should write/update the data in a node.

I have a yml config file in /config/install/ and some logic in /src/migrate/source/

When I run the migration with "drush mi --all" I get the correct values in my prepareRow function. Unfortunately, no nodes were create and I get the message "Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored)"

With the prepareRow function I'm able to stop the script at this position. But how can I debug the script afterwards? Does exist a postImport function or something similar?

How do you test your D8 migrations?

Thank you very much for your inputs!

The place you want to step through is the while loop in MigrateExecutable::import() - this is where each source row is received after prepareRow(), run through the processing pipeline ($this->processRow), and saved to the destination plugin ($destination->import()).