Verify an entity is translated I want to add a "add translation now" button on nodes and other entities too. I'm using the Entity translation module, and I added two languages to the site.

I thought about getting the original translation and then loop through the translation data, checking if there is more than just the original language inside.

Is there a better way to do this?

Actually if you are doing field translation then there is no point of having translate now link at Node level. For this there is always translate primary tab for this. see in screenshot.

Still if you want to achieve this functionality, loop through this array within node object.

$node->translations->data

Do this in module file in hook_preprocess_HOOK here it will be hook_preprocess_node and pass a variable to node.tpl.php


Views Sub tab on user account page I am trying to create a menu structure on the user profile page like:

/user/%/content = Main tab (next to View, Edit) on /user/%uid
/user/%/content/published = Sub tab showing published nodes
/user/%/content/unpublished = Sub tab showing unpublished nodes

I have tried using /user/%/content/all as the main default tab.
Tried setting sub tab as default tab and not default.

Ive gotten:

    View, Edit, Published, Unpublished, My Content

    View, Edit, Published
                 -Published
                 -My Content

View, Edit, My Content (with no child tabs)

I can't seem to find the correct settings to get My Content to be the main tab, with Published and Unpublished to be sub tabs to My Content.

I tried swapping the settings for Published and My Content but that didn't work.

Does My Content need to be the default tab? Or does Publish need to be the default tab with My Content as the "parent already exists"?

Any help getting the tab structure sorted out would be greatly appreciated.

Under Page settings, in the view settings, you will find the Menu option; you need to set it to:

Menu tab for user/%/content
Default menu tab for user/%/content/published
Menu tab for user/%/content/unpublished

This is how it appears.

PS

I used the Tracker view that comes with the Views module, and altered it to obtain the desired result.


How to use Rules to set a value for a multi-value field? I'm trying to create an Order reference on Products when ever a new order is created. I have installed the "Order Reference" module and created an Order reference field on my product type.

Next I created the following rule:

Rules Event: After saving a new commerce line item
Rules Conditions:

Data comparison ( [commerce-line-item:type], Data value: Product )
Data comparison ( [commerce-line-item..., Data value: NAME OF TYPE )

Rules Action: Set data value [commerce-line-item..., Value: [commerce-line-item:order]

The above rule works fine as long as i limit the Order Reference field to 1 value, but as soon as it is set to multiple the rule breaks.. i get the following error for the action:

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

I'm new to the Rules module and a kind a lost here. Any help?

Below is the exported rule:

{
  "rules_test_test_order_ref": {
    "LABEL": "test test order ref",
    "PLUGIN": "reaction rule",
    "OWNER": "rules",
    "REQUIRES": [
      "rules",
      "entity"
    ],
    "ON": {
      "commerce_line_item_insert": []
    },
    "IF": [
      {
        "data_is": {
          "data": [
            "commerce-line-item:type"
          ],
          "value": "product"
        }
      },
      {
        "data_is": {
          "data": [
            "commerce-line-item:commerce-product:type"
          ],
          "value": "iq_test_event"
        }
      }
    ],
    "DO": [
      {
        "data_set": {
          "data": [
            "commerce-line-item:commerce-product:field-order-reference"
          ],
          "value": [
            "commerce-line-item:order"
          ]
        }
      }
    ]
  }
}

Looks like you could just use the "Add to list" Rules Action. And since your question is about a multi-value field, for sure you should NOT use a  Rules Action like "Set a data value", which is used to set assign a single value to a field (which seems to be what you've tried, a common mistake when using the Rules module for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...

PS: I'm assuming this question is about D7.


How do I call the menu_rebuild function in Drupal 7? I would like to call the menu_rebuild() function, but I am not sure of where exactly paste the code snippet.

I can't find the update.php file anywhere in my local instance.

The reason I would like to attempt this is that I deleted all the nodes, but they are still appearing under the menu structure.

Drupal 7

If you're using drush, you may run:

drush eval 'menu_rebuild();'

If won't work, see: How to do menu rebuild when having PHP Fatal error?

Drupal 6

drush php-eval 'drupal_rebuild_theme_registry()'

memcached

If you're using memcached, you've to restart it.

On Linux: /etc/init.d/memcached restart

On OS X (if using Homebrew): brew services restart memcached


How to process a textarea as an html list? Is it possible to process a textarea line by line and turn it into an HTML list, and how would you go about it?

Either use the text-field and choose "list" style. Another way is to simply use filtered HTML as your text-format for your text-area. Once you select filtered HTML. use < ul > or < li > in front of each line of text to turn it into a list-item. This can also be accomplished using "Views"


Print raw field data I have a long text (plain text) field connected to my content type. The field contains plain html code.

Is it possible to print this field without sanitizing it's content. I mean raw html output of it's content.

And the main thing is to do that without coding, just from admin area. :)

It is possible to do it without coding from the admin area.(Disclaimer: a bit hacky).

Go to the "admin/config/content/formats" area and disable all the filter formats except "Plain Text".

Go to your content type display settings tab and change the format in the dropdown to "Default" and save the settings.

If you view your node now, you will be able to see its raw content form without all the sanitation.


How to programmatically delete taxonomies when a module is uninstalled? Taxonomy vocabularies are in the CMI as of Drupal 8, but I want to also keep the Taxonomy terms in code. I am programmatically creating terms in a custom module.

function taxonomy_vocab_install() {
  foreach (taxonomy_term_info() as $term_info) {
    $term = Term::create(array(
      'parent' => array(),
      'name' => $term_info['name'],
      'description' => [
        'value' => $term_info['description'],
        'format' => 'full_html',
      ],
        'vid' => 'department',
    ));
    $term->save();
  };
};

Now, I want to delete the terms on uninstall, but taxonomy_term_delete is depreciated. Any help on how to programmatically delete the created taxonomy terms in D8 when the module is uninstalled would be greatly appreciated.

function taxonomy_department_uninstall() {
  // ??
};

I did not test it myself, but as far as I see in the documentation, Term is using Entity::delete(). You might try to load the terms you wish to delete and call this method directly on them:

$term->delete();


Views Infinite Scroll progress Indicator I am using the Drupal 8 Views Infinite Scroll module on my website.

I have a button at the bottom of my view that when clicked, loads more nodes into the view.

How can I manipulate the view to show a progress indicator or loading icon whilst the Infinite Scroll Ajax is making the request?

Currently, there are no options in the pager settings, but I am confused by the documented project as the Animated gif shows the indicator at the top of the view appears once you've clicked the load more button.

Is this only in place for Drupal 7?

I was able to do this as below.

Add the below in your custom.js file

// Sets the fullscreen progress indicator.
(function ($) {
  'use strict';
  Drupal.behaviors.privacyPolicyLinked = {
    attach: function (context) {
      Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
        this.progress.element = $('
&nbsp;
');
        $('body .pager').before(this.progress.element);
      };
    }
  };
})(jQuery);

And in your custom.css , add your styles as below

.ajax-progress-fullscreen {
  background: url($assetsPath + '/images/status-active.gif') no-repeat center center;
  min-height: 16px;
  opacity: .9;
  padding: 3px;
  vertical-align: middle;
  width: 16px;
  position: relative;
}


Custom field widget that displays a button with JS action and a hidden textbox I have no background in working with the Drupal API, so answers will have to explain it like I'm a child.

I am trying to create a custom field module. The widget should show a button with JS onClick action that opens an external form. The user selects through a series of prompts and the external form returns XML to the page that should be stored in a hidden XML field (I'm using the XML Field module). The XML is never shown to the user, but instead powers a JS script on node view.

The formatter for the field should deliver the content of the XML field as a JS variable and not display anything on the page.

I've read through the Drupal API documentation and several tutorials on building custom fields. However, these all assume a working knowledge of the Field API, which I do not possess.

Is this possible in a field module, or should I be looking at a different way of implementing this?

I'm using Drupal 7 and the external form is a client metadata requirement I have no control over.

Welcome here. You're question is complicated with many steps some involving the Drupal API and others involving Javascript and Ajax. Your question is specific to your needs, so you'll likely not find a module that does exactly what you're asking for out of the box.

You're correct that the Drupal API should be able to do this -- but by asking people to show you how to do like your 5; is basically asking someone to do your homework for you. I can outline the tools you'll need. It's up to you to come to a working solution.

1st off -- outline your code outside of the Drupal API and simply thing "how would this form work in psuedocode" using say PHP and JS; building those steps will take you a long way.

Drupal Resources to help you:

The Field API Documentation pages.
The Official Field API Tutorial, which links some 3rd party tutorials as well.
If the above 2 resources aren't enough to understand what the Field API does look at the Examples module for Developers.
It sounded like you wanted AJAX in your form. Read up on the Drupal Javascript API Documentation, specifically the Ajax Forms section, and again if that's not enough look at the Examples module, or google "drupal jquery form" as while Drupal has it's own JS API, Drupal bundles jQuery so you could try to just use jQuery to fulfill your needs mostly without the field api explicitly.

what do I mean by this? Here is a jquery autocomplete tutorial which uses a text field "in" drupal but is simply using jquery's native autocomplete functions. I used Google Translate for that page and View Source in my browser to fill in the tutorial gaps -- to re-engineer this on a site I have.

Lastly, either route you'll take you will likely be integrating with an existing Node form. You probably want to use hook_form_alter to inject your custom business logic into the existing Drupal functionality.


How to restrict node authors from commenting on their own nodes? On my site we have enquiries (nodes) and price quotes (comments). So node authors shouldn't be offered to quote prices to themselves.

That's why I want to disallow node authors comment their own nodes. How can I do so?

Updated: The 'user-compare' option in panels visibility rules could easily allow to achieve what i want. I've used this functionality for other panes i.e. profile fields etc. But  i didn't find 'user-compare' entry in Panels visibility rules for comment form in node template. Why?

I chose the way offered by Pierre.Vriens using Rules because I couldn't  make the code snippet by oksana-c work with Panels. Unpublishing comments with The Rules is not best user experience. Comment Permissions module also didn't help. Any suggestion for unsetting whole comment form for node authors programmatically in Panels environment would be much appreciated.

You'd want to use hook_node_view_alter() in your theme to unset the comment form if the logged in user is same as node author.

function yourtheme_node_view_alter(&$build) {
    global $user;
    // get the uid of logged in user
    $logged_in_uid = $user->uid;

    // if content type is 'your_content_type'
    if ($build['#bundle'] == 'your_content_type') {

        //get node author's uid
        $node_author = $build['#node']->uid;

        // if logged in user is the node author - unset comment form and remove the 'Add comment' links from node display
        if ($node_author == $logged_in_uid) {
            unset($build['comments']['comment_form']);
            unset($build['links']['comment']['#links']['comment-add']);
        }
    }
}

Also, you can check out Comment Permissions module. It does not offer the functionality that you need, but it provides more granular permissions than core comment module.

  The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.


first module, hook_menu/FAPI problem I'm fairly new to Drupal and made my first module. It works. Yay!

What I have: Calling
/form-test/186 (nid)
Nid gets loaded, renders content.

What I want: The same but with an simple submit button at the end, that calls a

function exportIt() {
  // put $output from formtest_page() in email
}

when clicked, not before.

    <?php

/**
 * Implements hook_menu().
 */
function formtest_menu() {
  $items['form-test/%'] = array(
  'title' => 'Export von:',
  'page callback' => 'formtest_page',
  //'page callback' => 'drupal_get_form',
  'page arguments' => array(1),
  //'page arguments' => array(formtest_simple_form),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK, );
  return $items;
}

function formtest_page($nid = NULL) {

  $node = node_load($nid);
  if ($node) {
    $title = $node -> title;
    dpm($node); //Why is this not get displayed?
    drupal_set_title('Klicket Export von: ' . $title);
    $output = '';
    $items = array("<b>titel: </b>" . $title,
    "Where is my beef?" );

    $output .= theme('item_list', array('items' => $items));
    //drupal_get_form('formtest_simple_form');
    return $output;

  }
  return;
}

function exportIt() {
  // put $output from formtest_page() in email
}

//simple submit form
function formtest_simple_form($form, &$form_submit) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Export an Klicket'));
return $form;
}

I'm having basic conceptional issues I guess. I either can render the submit Button or the Output, but not both.

The correct code is similar to the following one.

I will add some notes about the code as I wrote it:

If you use "form-test/%node" (instead "form-test/%"), the node will be loaded from Drupal, and if there are some problems with loading it, it will report an error (404, page not found) to the user; in this way, you don't need to call node_load() as that is already done by Drupal.
There is a callback that returns the title Drupal should use.
I am not sure I translated correctly the strings you were using (I guess it was Swedish, but I am not positive, as I don't know Swedish); I had to translate the strings, as t()'s argument is a string in English, which will be translated in the language set for the site.

function formtest_menu() {
  $items['form-test/%node'] = array(
    'title' => 'Export',
    'title callback' => 'formtest_title',
    'title arguments' => array(1),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(formtest_simple_form, 1),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function formtest_title($node) {
  return t('Export Klicket from @title', array('@title' => $node->title));
}

function formtest_simple_form($form, &$form_state, $node) {
  $form['#node'] = $node;

  $items = array(
    t("Title: @title", array('@title' => $node->title)),
    t("Where is my beef?")
  );

  $form['item_list'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
  );

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

  return $form;
}

function formtest_simple_form_submit($form, &$form_state) {
   // Write the email.
   // If you need the node object, it is in $form['#node'].
}


Custom validation rules for content entity fields So I want to store an entity_type in a string field in my content entity.

Since the list of entities can change over time, I can't use a list_string field with allowed options. I don't know if calling out to entity_manager would even work properly in that context.

So my current plan just to use a string field and somehow validate that the values the system attempts to save are valid entity type machine names.

How can I perform this validation at the field level? At the entity form level, I will obviously have to add a custom select field and interpret/set the value in the (entity form class)::save() method.

list_string can have an allowed_values_callback instead of a list of allowed values, that allows you to return a dynamic list from that callback.

See callback_allowed_values_function(), which has pretty good documentation, that we've refined over multiple issues.

Make sure you're aware of the rules and limitations of what you can return.. for example that not passing an entity should always return all allowed values and passing one it can only limit those and not add more. And that returning new allowed values is not a problem, but not returning them anymore can be problematic as you might end up with data in your database that is no longer valid. The UI doesn't allow you to do that, for example.


How to quickly create multiple Drupal 7 features? I use Features and Strongarm to manage configuration of my Drupal 7 systems.

Until now I was creating features manually but even with Features Tools installed and ajax features status disabled it is a mundane process.

I want a separate feature for each contrib module and a separate feature for each view.

Is there a way to create features automatically or at least more quickly, maybe using drush ?

You can use the Drush features add/export commands (add was removed in the latest version of Features (rc1)).  As there have been a lot of changes recently with features rc1 and drush 5.0, the exact commands will differ depending on your setup, but drush help will list the features commands and drush help fe will show you the details (in this case, how to export [e.g., create] a feature).

If you really needed to create a lot of features, you could script Drush (either extend Drush itself or run Drush via bash script, etc.)


pathauto patterns showing an empty page drupal 7 When loading admin/config/search/path/patterns no content/form is showing up.
Is there any way to show up the content of the patterns...?

Have you tried to flush the site's cache ? Sometimes it just reapear by magic (It happened to me on building a big corporation site).

Another lead in drupal.org, they seems to think that is a "php value memory_limit" problem : https://www.drupal.org/node/1267966


How can I create a time counter by aggregating a view? I need to create a time counter that will take a users input of time in hours and minutes, add them and then display the cumulative results?

I am not sure how to accomplish this. It has been suggested to create a content type with a time field and then aggregate the results.

Any advice/direction will be appreciated.

Disclaimer: I'm a total hack with Drupal

I would use the View type of "Table",  then create a views-view-table--VIEWNAME.tpl.php

You'll see that it's set in to a real easy to read loop through the rows.   Modify the HTML structure to suit your needs,  but also add in a simple $var++; and then place that at the end of your rows.


Writing a migration from non a non Drupal site How can I translate this in a migrate query?

SELECT t.name FROM tags t
    join tag_types tt on (tt.id = 3)
    join story_tags stg on (stg.tag_id = t.id) WHERE story_id = $row_id'

I tried this, but it doesn't work.

->select('story_tags', 'tags')
->fields('tags', array('tag_id'))
->leftJoin('tag_types', 'tt', '(tt.id = tag.tag_type_id)')
->condition('tag_type_id', '3', '=' )
->condition('story_id', $row->id, '=')
->execute()
->fetchCol();

What am I missing?

It might not be the answer you are looking for, as it is not Migrate, but when I did this a couple years ago for a large client this is how I did it.

First, I set up the Feed Import module and a map of column names to desired fields.  Second, on the various non-drupal sites that I was migrating to a single drupal install I exported the data to csv files paying careful attention to the column aliases so they matched the map.  Also, as it totalled a lot of rows, I broke it into several files to run them in batches.  Using an anchored feed import, I was able to run them in batches and subsets of data, to purge and re-import any set as needed, and to group all the difficult international names together by sorting my csv files.

It took a day for every 10,000 nodes I imported.


Altering add_to_cart_form_submit() and random PDOException while adding to cart I have created a customized product with lots of attributes to set for it.
I also altered hook_add_to_cart_form_submit() where I collect all selected attributes and calculate a new price based on the selected and configured attributes.
So in my

function MYMODULE_add_to_cart_form_submit($form, &$form_state) {}

I create a big array and:

if (empty($form_state['line_item']->line_item_id)) {
    if ($attributes)
        $form_state['line_item']->data['context']['attributes'] = $attributes;
    $line_item = commerce_product_line_item_new($product, $form_state['values']['quantity'], 0, $form_state['line_item']->data, $form_state['line_item']->type);
    //   ...
}

I'm not sure if I am doing it right, I just want to store that array in the line-item table.
While adding product to cart randomly I get:

"PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'commerce_line_item-177-0-0-und' for key 'PRIMARY': INSERT INTO {field_data_commerce_unit_price} ..."

error.
Should I use some special format for this $attribute array? Everything is stored as BLOB in commerce_line_item.data field.

When you call commerce_product_line_item_new, drupal is trying to insert an already existant record to the table field_data_commerce_unit_price which has it's primary key defined as :

  PRIMARY KEY (entity_type,entity_id,deleted,delta,language),

Since the product already exists, it fails with a constraint violation error :

  Integrity constraint violation: 1062 Duplicate entry

What you are trying to do could be accomplished by adding a new cost item to the current order based on the attributes you mention, not by modifying the current item price which I guess is what you are trying to do.

So IMHO, you may try to have a base price for your item (or even a 0 price) and once the customer adds it to cart, add another cost item with the charges calculated based on the attributes he sets.


D7 conditional field option? I have a content type that has a taxonomy field with two options. If Option A is selected, I want a further taxonomy field with items from Taxonomy X. If Option B is selected, I want another taxonomy field, but with items from Taxonomy Y.

In Drupal 6 I used Conditional Fields, which was great. However, there exists no stable D7 version yet, and I need this functionality for a project due this week. The project page even says: "Drupal 7 version (3.x): 7.x-3.x is currently in development. It is a complete rewrite of the module that leverages the new entities system and the States API. Not ready for use on production sites yet." So I feel like I'd be really dumb if I put this on a production site and something broke, when the module project page itself specifically tells me not to.

The other option seems to be Field Conditional State, but that's used on a total of 274 sites (compared to the ~18,000 of Conditional Fields).

Are there any other D7-compatible modules that allow forking of field display based on the value of another field?
If not, how stable is Field Conditional State?
Should I just suck it up and write a module that does what I'm wanting?

Many thanks.

Against my better judgement, I've used Conditional Fields to control field display. I'll post back here if I have any issues.

To anyone who arrives at this answer from Google, I made at my decision after looking at the module's usage stats, which paints it almost at parity with the stable D6 version:

It's worth checking out http://drupal.org/node/1551504, which is intended to spur a D7 stable release (The author looks a bit overwhelmed by it all, truth to be told.). I've closed any similar questions and pointed them to that, which seems to have the most traffic.

That all said, it's kinda hard to contribute to a project when the maintainer is MIA...


Commerce: Don't calculate extra shipping for 1st item I have a flat rate of $2.50 for every order.
I have extra +$1 for every extra item added to cart.

So, if I order 1 item, total shipping is $2.50, but if I order 2 items total shipping is $3.50.

My problem is that in 2nd case, I get total shipping of $4.50 for 2 items instead of $3.50. It calculates the +$1 for both items.

I added the rule condition Total product quantity comparison to apply +$1 if quantity is > 1. So if I add only item, it doesn't calculate the extra shipping, but as soon as I add more items, it calculates the extra shipping for initial item.

Here's my calculation rule:

I followed this guide: https://vimeo.com/32813567

From the screenprint of your calculation rule it's hard to tell what exactly the logic is that you implemented (an exported rule, created with the Rules UI, provides ALL the details).

Anyway, it seems that your Rules Loop is adding $1 for EACH line item, so also for the very first line item. While your requirement (in your question) states "+$1 for every extra item" ... If "extra" is to be translated to "but do not add $1 for the very first item", then clearly in your Rules Loop you should not have added $1 for the very first item.

The easiest way to correct this, is to subtract $1 after your Rules Loop is finished (consider it like a discount for the very first item). If you rather want to go for a slightly more complicated solution, then you could use the Conditional Rules module to add an extra test (Rules Condition!) within your Rules Loop to NOT perform that +$1 for the very first line item (I presume you know what such test should look like). My 2 cents: go for the easiest way via the extra correction after the Rules Loop is finished.


Get selected value and submit a form I have a form, and I want to get the selected value of $form['dropdown_third'] and then use the value to create my table.

What should I write in Submit function?

function find_tryk_filter_test_page($form, &$form_state) {

$options_first = find_tryk_filter_test_first_dropdown_options();
$value_dropdown_first = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

$form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'Type',
    '#options' => $options_first,
    '#default_value' => $value_dropdown_first,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'find_tryk_filter_test_ajax_callback',
        'wrapper' => 'dropdown_second_replace',
    ),
);

$form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Producent',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => find_tryk_filter_test_second_dropdown_options($value_dropdown_first),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'find_tryk_filter_test_2_ajax_callback',
        'wrapper' => 'dropdown_third_replace',
    ),
);

if (!empty($value_dropdown_second)){
    $options_second = find_tryk_filter_test_second_dropdown_options($value_dropdown_second);
    $value_dropdown_second = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : key($options_second);
}else{
    $options_second = array();
    $value_dropdown_second = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : key($options_second);
}

//echo $options_second;
$form['dropdown_third'] = array(
    '#type' => 'select',
    '#title' => 'Model',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => find_tryk_filter_test_third_dropdown_options($value_dropdown_second),
    '#default_value' => isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : '',
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
        '#prefix' => '
',
        '#suffix' => '
'
    ),
);

$header = array('Navn', 'Shoplink', 'Brochure');

$options_third = find_tryk_filter_test_third_dropdown_options($value_dropdown_second);
$value_dropdown_third = isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : key(0);
$query = db_query("SELECT node.title, fdfs.field_shoplink_value, fm.uri
    FROM node
    JOIN field_data_field_model AS fdfm ON
    fdfm.entity_id = node.nid
    JOIN field_data_field_producent AS fdfp ON
    fdfm.entity_id = fdfp.entity_id
    JOIN field_data_field_shoplink AS fdfs
    ON fdfs.entity_id = fdfm.entity_id
    JOIN field_data_field_brochure AS fdfb
    ON fdfb.entity_id = fdfm.entity_id
    JOIN file_managed AS fm ON
    fm.fid = fdfb.field_brochure_fid
    JOIN taxonomy_term_data AS ttd
    ON fdfp.field_producent_tid = ttd.tid
    WHERE fdfm.field_model_value = '".$value_dropdown_third."'");

$rows = array();

foreach ($query as $row) {
    $rows[] = array($row->title, $row->field_shoplink_value, $row->uri);
}

$form['webform_results'] = array(
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $header
);

return $form;

}

What should I write in Submit function?

That's up to you, depends what you want to do. It sounds like you're just unsure how to get access to the submitted values. Those reside in $form_state['values'], so:

$value = $form_state['values']['dropdown_third'];


Tokens as a boilerplate? Is there a Tokens module that allows for simple boilerplate embedding? For example, embedding [notification 3] into a node would correspond to an admin setting(notification 3 = "Hello World"). You would then have "Hello World" embedded into all nodes with [notification 3].

There is a module that replace some tokens accepted from the Token module (or implemented using hook_token_info() and hook_tokens() in Drupal 7) in the body of a node, the Token Filter module.

  Token Filter is a very simple module to make token values available as an input filter.

There is then the Token Node Tokens (TNT) module that allows to define new tokens without implementing a module.

  TNT (Token Node Tokens) is a very simplistic module that allows you to create arbitrary tokens without having to create a custom module (i.e. /node/add/token). This was primarily created for use with the tokenize module so that through the UI a user could create tokens for use with CCK.

Unfortunately, this module has been declared unsupported, but looking at its code, you could create your custom module for doing the same thing.

An alternative is the Custom Tokens module.

  It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.

  Versions 7.x-1.x and previours relied on PHP evaluation to build custom tokens.

  The new 7.x-2.x relies on input filters. While still allowing for PHP tokens through the D7 core PHP filter module, administrators can permit only HTML or plain text custom tokens.


SearchApiQuery - possible to remove a filter? The query parameter that is passed to search_api_query_alter has SearchApiQueryFilter member. It contains a protected array of filter elements. I can add to this by calling the createFilter() and filter() methods, but it does not appear that there is a way to remove a filter through the API.
Can this be done?

I found the solution, but be careful: it is very tricky! Ideally, it should be special method in the SearchApiQuery class itself, or method in class-wrapper, which will be used everywhere in code...

My solution based on ability to access private members of classes, passed to __constructor function:

class SearchApiQueryFilterAlter extends SearchApiQuery
{
    public $altered_query;
    function __construct(SearchApiIndex $index, array $options = array())
    {
        if (isset($options['original_query']) AND isset($options['filter_alter'])) {
            $options['original_query']->filter = $options['filter_alter'];
            $this->altered_query = $options['original_query'];
        } else {
            parent::__construct($index, $options);
        }
    }
}

Property $altered_query will contain original query with modified filters.

Usage example:

function product_list_search_api_ranges_minmax_alter($variables, $order)
{
    /** @var SearchApiQuery $query */
    $query = $variables['query'];
    $filters = $query->getFilter();
    $new_filters = $query->createFilter();
    foreach($filters->getFilters() as $filter){
       if(!$filter->hasTag('facet:field_product:commerce_price:amount_decimal')){
            $new_filters->filter($filter);
        }
    }
    $options = array(
        'original_query' => $query,
        'filter_alter' => $new_filters
    );
    $filter_alter = new \Drupal\product_list\SearchApiQueryFilterAlter(new SearchApiIndex(), $options);
    $variables['query'] = $filter_alter->altered_query;
}

In this example all filters has been copied to the $new_filters, except one with special tag. Then, we pass original query and new filters to class constructor through $variables. And empty SearchApiIndex, which is nesesary. Finally, in $filter_alter->altered_query we have the query with deleted filter condition.


Programmatically re-order role weights? I want control over the order in which roles' columns are displayed on the Permissions page..

I want to add code to my module installation file so that, after newly-configured roles' yaml settings have been applied (they list the permissions for each new role), it displays all the roles in the order I want.

How do I do this?

Motivation

The roles' yaml settings are part of a module created by Features.
Enabling the module in the target Drupal 8 system adds the new roles in the wrong order.

It is not possible to include the weights of the anonymous; authenticated and Administrator roles in the feature / module's yaml files as this causes a conflict that prevents the module from being enabled. So the solution is to apply the weights programmatically.

[edit] I mistakenly thought that the order of the roles' columns related to an hierarchy / inheritance of permissions. Corrected by @Berdir, thanks. Nevertheless I still want to display the roles' columns in the way I choose, so I have edited this question to reflect this.

Role weight is only used for some lists in the backend. It has no effect on the permissions that a user has.

The permissions or a user are always the sum of all permissions of all roles that he has, you can not remove permissions with roles.

All "users" either have the anonymous (when they're not a user, basically) or the authenticated user role. You can give anonymous users more permissions than authenticated users. But you can never remove any permission granted by the authenticated user role through another role.

This doesn't answer your question but considering the above, I don't think  you are asking the right question. Whatever problem you are trying to solve exactly, setting role weights is not the answer ;) If this is not enough to solve your problem, then try explain the actual problem that you are trying to solve.

Edit:

Anyway, to actually set the role weight in e.g. hook_install(), you can do this:

$role = \Drupal\user\entity\Role::load('anonymous');
$role->setWeight(0);
$role->save();

Again, keep in mind that this has no effect on the permissions a user has, it just affects how the roles are listed on the role and permission administration pages.


What is the correct way to create a translatable in four languages website logo with slogan? What is the correct way to create a translatable in four languages website logo with slogan?
I am thinking  of creating a custom content type which will be populated in View block. Which when will be inserted in logo region.
Are there any other approaches?

Are you already using the i18n module? The package contains the 'Variable translation' module which allows you to make certain variables language dependent. Since the site logo is also stored in the variables (theme_settings['logo_path'] if I'm not mistaken) you can make that variable language dependent as well.

If you're not using the i18n module (and you're not going to need it soon), I suppose you can also switch between logo images in your theme's template.php.

I wouldn't recommend creating a node type for it. In my experience, whenever you're considering to create a node type that is meant to have a specific number of nodes, there probably is a better solution for what you're doing.


Writing to a custom field in PHP In Drupal 7, using the Field module, Field SQL Storage and Field UI I've created several custom user fields.  I can display them in PHP like this:

global $user;
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_keys_available')) {
   $keys_remaining = $items[0]['value'];

The above example displays the custom keys_available field, a field we use to determine if the user is entitled to software license keys.  I need to decrement field_keys_available in the PHP that issues a license key to a user.  Can someone help with the syntax on this?  I've discovered fifty ways to generate white screens, but haven't landed on the right syntax.

It should be something as simple as

$account = user_load($GLOBALS['user']->uid);
$edit['field_keys_available'][LANGUAGE_NONE][0]['value'] = 'new value';
user_save($account, $edit);

The comments in the user_save() docs have some more details and examples.


7 Ubercart - Notify Customer Shipping when Product Ships For our site, we process payments by performing a Capture on the PayPal site. Soon after, we pack and ship the order.

Does Ubercart provide a means for notifying the customer (via a button click somewhere in the admin site), via a pre-defined email, that the product has been shipped?

There is a group box on each order detail page (e.g., admin/store/orders/123) which looks like the following:

Update order:
ADD AN ORDER COMMENT
[                     ]

After entering some text here (such as, "your order has been shipped"), clicking Update sends the notification to the customer via email.


Create a MySQL view table on one database but fill with results from another database I have 2 databases: myshop (the Drupal db) and myshop_migrate (the Migrate db).  To make things tricky - both databases reside on different AWS instances.

I need to create a mysql view on myshop to hold a SELECT * query from the myshop_migrate database.

Currently, I have:

db_set_active('myshop_migrate_db'); //reference migrate db
$query = db_query('CREATE OR REPLACE VIEW myshop_migrate_stock_commerce AS SELECT * FROM myshop_migrate.stock_commerce');

but this just creates the VIEW table on the myshop_migrate database (as the current active db is referencing myshop_migrate)..

db_set_active(); //default drupal db
$query = db_query('CREATE OR REPLACE VIEW myshop_migrate_stock_commerce AS SELECT * FROM myshop_migrate.stock_commerce');

This wont work because myshop_migrate.stock_commerce doesn't exist on the myshop database!

Completely lost on this.  Can I somehow store the result of the SELECT * from myshop_migrate in a variable? Switch the active db, create a view table on myshop, then import the variable into the table?

Since that view is only a SELECT on that table, try using a FEDERATED table instead.

I never had the chance to use it so far, but it should go like this:

CREATE TABLE myshop_migrate ( exactly like myshop table )
ENGINE=FEDERATED
DEFAULT CHARSET=same of myshop
CONNECTION='mysql://user@host:9306/myshop_migrated/stock_commerce';

where user and host are those of the remote server.

create it from phpmyadmin or mysql workbench, just to have additional options and hints that drupal can't give you.


Modify a variable before it saves to database I have a user profile form.  I'm having trouble modifying a variable before it saves to the database.  I have these hooks in my template.php but the value going into my database is still the same value that was submitted in the form post.

function mytheme_user_profile_form_presave()
{
  if($form['#id'] == 'user-profile-form') {
    if($_POST)
    {
            $ec = 'fooo';
            $form['field_last_name']['und'][0]['value']['#default_value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            form_set_value($form['field_last_name'],array('und' => array(0 => array('value' => $foo))),$form_state);

    }
  }
    return '';
}

function mytheme_preprocess_user_profile_form()
{
  if($form['#id'] == 'user-profile-form') {
    if($_POST)
    {
            $ec = 'fooo';
            $form['field_last_name']['und'][0]['value']['#default_value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            form_set_value($form['field_last_name'],array('und' => array(0 => array('value' => $foo))),$form_state);

    }
  }
    return '';
}

function mytheme_user_profile_form_validate()
{
  if($form['#id'] == 'user-profile-form') {
    if($_POST)
    {
            $ec = 'fooo';
            $form['field_last_name']['und'][0]['value']['#default_value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            form_set_value($form['field_last_name'],array('und' => array(0 => array('value' => $foo))),$form_state);

    }
  }
    return '';
}

what am i doing wrong?

UPDATE

Ok, I added this in my template.php

function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'user-profile-form') {
    $form['#validate'][] = 'mymodule_foo_data';
  }
}

Then I added this to mymodule.module

function mymodule_foo_data(&$form,&$form_state)
{

        $form['field_last_name']['und'][0]['value'] = 'foo';
}

The function mymodule_foo_data gets fired on save.  But the value foo doesn't get written to my database.  Instead, the value that's in the $_POST array is what gets written to the database.  how do I get foo into the databasE?

I don't think your approach is the best. You need to do the following:

Add a custom module.
Implement hook_form_alter in your module and and alter the user
profile form. Form id: user-profile-form.
Add a validation function i. e. $form['#validate'][] =
'my_module_custom_form_validate';.
add an implementation for the function in your module and modify the form values as you wish.

Also, you don't need to use the $_POST variable if you are following the drupal form api.


Geofield Display Format Data Options (Using Bounding Box) I am using Geofield to store point and polygon features. Input works fine with all the different widgets I have tried.

Display formats (GeoJSON, WKT, KML) with Data Options "Use full geometry" and "Use centroid" work fine with either point or polygon geometries. When I use the Data Option " Use bounding box" it does not work with any geometry and get the following error:

Exception: Cannot construct Point. x and y should be numeric in Point->__construct() (line 23 of ....../sites/all/modules/geophp/geoPHP/lib/geometry/Point.class.php).

Is this a known bug? My search did not find any reports. Or is it my configuration?

Drupal 7.20
Geofield 7.x.1.1
geoPHP 7.x.1.7
PHP (MAMP) 5.4.4

i had the same problem and found a quick and dirty solution:
in the referenced file Point.class.php the following function throws the error:

  public function __construct($x, $y, $z = NULL) {
    // Basic validation on x and y
    if (!is_numeric($x) || !is_numeric($y)) {
        throw new Exception("Cannot construct Point. x and y should be numeric");
    }

adding "echo $x;" before the "throw" showed me the problem:
the numbers for $x and $y where in the wrong "local" format.

e.g. 9,34124 instead 9.34124

  public function __construct($x, $y, $z = NULL) {
    $x = floatval(str_replace(',', '.', str_replace('.', '', $x)));
    $y = floatval(str_replace(',', '.', str_replace('.', '', $y)));
    // Basic validation on x and y
    if (!is_numeric($x) || !is_numeric($y)) {
     throw new Exception("Cannot construct Point. x and y should be numeric");
    }

is my dirty fix for this...

regards
nicolaj


I want to save data using ajax. But AJAX callback function replace method not working ? why? THIS MY CODE:

function form_test_permission() {
    return array(
        'submit_form_test' => array(
            'title' => t('Submit_form_test'),
            'description' => t('Submit the form_test form'),
        ),
    );
}

function form_test_menu() {
    $items = array();
    $items['production'] = array(
        'title' => 'Production',
        'type' => MENU_NORMAL_ITEM,
        'access arguments' => array('submit_form_test'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_test_form'),
    );

    return $items;
}

function form_test_form($form, &$form_state) {
    $form['production'] = array(
        '#title' => t('production'),
        '#type' => 'hidden',
        '#value' => '1',
    );
    $form['production1'] = array(
        '#title' => t('production1'),
        '#type' => 'hidden',
    );

    $form['production_date'] = array(
        '#title' => t('production_date'),
        '#type' => 'hidden',
        '#value' => date('Y-m-d'),
    );
    $form['production_time'] = array(
        '#title' => t('production_time'),
        '#type' => 'hidden',
        '#value' => date('H:i:s'),
    );
    $form['production23'] = array(
        '#title' => t('production23'),
        '#type' => 'hidden',
        '#value' => '1',
    );

    $form['button2'] = array(
        '#value' => 'UNDO',
        '#type' => 'submit',
        '#prefix' => '
',
        '#suffix' => '
',
        '#submit' => array('form_test_form_button2'),
    );

    $form['button1'] = array(
    '#value' => '  ADD  ',
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#submit' => array('form_test_form_button1'),
    '#ajax' => array(
        'callback' => 'ajax_example_submit_driven_callback',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'click',
        'wrapper' => 'countvalue',
        )
    );
    return $form;
}

function ajax_example_submit_driven_callback($form, $form_state) {
    $result = db_query("SELECT * FROM  form_test WHERE production_date='2014-02-10' and production_time between '01:00:00' and '02:00:00'");
    $prod_1 = $result->rowcount();
    $form['#tree'] = TRUE;
    $form_state['rebuild'] = TRUE;
    return 'count value is:' . $prod_1 . '';
}

function form_test_form_button1($form, &$form_state) {

    $ft_id = db_insert('form_test')
        ->fields(array(
            'production' => $form_state['values']['production'],
            'production_date' => $form_state['values']['production_date'],
            'production_time' => $form_state['values']['production_time'],
            'production1' => $form_state['values']['production1'],
        ))
        ->execute();
    $form_state['rebuild'] = true;
}

I have to mentioned in wrapper id in page.tpl.php file.

i want to save data using ajax. But i wrote query in AJAX callback function. AJAX Append method is worked fine. But  AJAX replace function not working ? why?

Fun issue here.  I pulled your code out and stuffed it into a test module and the ajax appeared to work once, eg, on first click of the ADD button, it replaced the
foo</foo> I had also stuffed into my page.tpl.php.  But then each successive click put up the throbber without any further apparent change.  Throwing a watchdog() into the callback showed it was indeed being called upon each click and then the voila moment:

return '
count value is:' . $prod_1 . '
';

is needed because it was replacing the original
 with just the count value is.... text, and then when clicked again, the DOM no longer contained a #countvalue for it to replace again :)


How can I make my site stop adding  tags in textareas? For a current project I have a content type’s textarea set to Full HTML. But where I’ve added a <span> tag, Drupal will go ahead and enclose it within a <p> tag which is definitely not what I want!

It’s also adding an empty <p> tag at the bottom of said container.

How and where can that be turned off? Where is the mechanism or module that is doing that?

Sounds like maybe you need to disable the "Convert line breaks into HTML (i.e.
 and
)" filter on your Full HTML text format.

This can be done by navigating to Configuration > Content authoring > Text formats and editors, then editing the Full HTML configuration and un-checking the box for "Convert line breaks into HTML (i.e.
 and
)" under "Enabled filters". Assuming this is Drupal 8 anyway. Drupal 7 has the same setting but the exact location might be different.


How can I automatically rotate a picture? apparently Drupal 7's built in image handling doesn't automatically rotate images based. Is there an option to do that?
If not, how can I make it easy for a user to rotate an image left or right?

ImageCache Actions seems to provide an "autorotate" feature. If server has  Exif PHP extension enabled, and user's camera saved orientation in EXIF data, it automatically rotates image correct side up.


How to fetch list of published webforms from webform module? How can I fetch list of published webforms from webform module?

I want to show all published webforms in dropdown to the user, so user can select one of the available forms.

Cheers
-Zafar

In Drupal 7 it would be something like:

$nodes = node_load_multiple(array(), array(
  'type' => 'webform',
  'status' => 1,
));

Have a look at the docs for node_load_multiple. You could (and probably should) also use EntityFieldQuery as mentioned in the docs. The given examples assumes that you use the default webform content type.

You could then use the $nodes array to build options for a Form API select element:

$webforms = array();
foreach ($nodes as $nid => $node) {
  $webforms[$nid] = check_plain($node->title);
}
$form['available_webforms'] = array(
  '#type' => 'select',
  '#title' => t('Webforms'),
  '#options => $webforms,
);


Dependency injection not working custom form I have a custom module with a form class, where I am trying to inject a custom service to use within it's submit method:

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\my_module\CustomManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

class CustomForm extends FormBase{

  private $custom_manager;

  function __construct(CustomManager $custom_manager) {
    $this->custom_manager = $custom_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
    // Load the service required to construct this class.
      $container->get('my_module.manager')
    );
  }

  .....

  public function submitForm(array &$form, FormStateInterface $form_state) {
      // Test service.
      $this->custom_manager->test();
  }

}

When I submit the form, I get the following error:

Fatal error: Call to a member function test() on null

It seems like my custom service hasn't been instantiated as expected, since the $custom_manager property is null.

Strange thing is when I debug the constructor, the service IS being instantiated properly.

Has anyone had this issue before? I can instantiate the service via the global Drupal class, but apparently doing the dependency injection is best practice.

Thanks in advance!

I accidentally declared the $custom_manager property of my class as private instead of protected, and that's why I was unable to access the custom manager object in the form submission method. Whoops!

MPD's answer is theoretically correct though, as class requiring to access services do need to implement the ContainerInjectionInterface class.

Worth noting though that the class FormBase which we're extending, already implements ContainerInjectionInterface, so we don't need to explicitly do so when creating a custom form.


How to embed Responsive Youtube video in Drupal Bootstrap subtheme? I am trying to embed a Youtube video to a block using Bootstraps .embed-responsive-item class. The Text Format is set to Full HTML.

It’s working just fine on my static html version. However within Drupal the video canvas doesn’t use the full block dimension? What’s the correct way to embed full-size Youtube videos in a Drupal Bootstrap subtheme?

This might help:

responsive-youtube-embed

The essential bit:

  You will need to wrap the responsive youtube embed code with a  and specify a 50% to 60% padding bottom. Then specify the child elements (iframe, object embed) 100% width, 100% height, with absolute position. This will force the embed elements to expand fullwidth automatically.


Commerce- How can I track order details (products, quantities) in PayPal? BACKGROUND

I have an online store.  Previously, I used PayPal "Buy it now" buttons, and I had a button for each product.  I would then periodically export the data from PayPal (download history as CSV) and it would have the following field/value pairs:

Item Title: Type of product (e.g., Nintendo DS)

Option 1 Name: Type of product (e.g., Nintendo DS)

Option 1 Value: Color (e.g., red)

Users were limited to ordering one item per order.  I used this information to analyze what are the top selling products/variations in the store in Excel, and I have a few years of historical data.

DRUPAL COMMERCE

I recently moved the store to Drupal Commerce, although I am still using PayPal for payment (PayPal Payments Standard/WPS) via the Commerce PayPal module.  This works very well, and users are still limited to one item per order.  However, when I export the transaction data from PayPal, it now looks like this:

Item Title: Shopping Cart

Option 1 Name: null

Option 1 Value: null

Is it possible to set the Item Title and options somehow during checkout with Commerce?  If not, how can I analyze my new sales data in Excel in a way that is (at least mostly) consistent with the years of PayPal exports I already have?

Right now, Commerce PayPal does not itemize order information for PayPal WPS. We implemented itemized order details for Express Checkout in the 2.0 branch, but we currently just have a patch in a feature request to add this support to WPS. If you'd like to review it or follow along, the issue is here: https://drupal.org/node/1301570

In the meantime, your alternative could be to create a View inside your Drupal site that uses Views Bonus Pack to generate a CSV in the same format for your completed orders. That might even be a preferable long term solution, as it will work regardless of what payment method a customer uses to buy from you (in the event that you add additional methods).


SSL errors on Heroku (Mixed contents) I have an app via Drupal 7 on Heroku. You know, myapp.herokuapp.com is default with SSL.

But when I try https://myapp.herokuapp.com get many errors in console like this:

 Mixed Content: The page at 'https://myapp.herokuapp.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://myapp.herokuapp.com/modules/system/system.base.css?ngonpd'. This request has been blocked; the content must be served over HTTPS.

I tried to add this code in settings.php but not working:

if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://myapp.herokuapp.com';
}
else {
  $base_url = 'http://myapp.herokuapp.com';
}

How can I fix this?

IMO $base_url in settings.php should work

Alternatively you can try

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

or

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Hosting modules internally Our company is looking to use Drupal as a platform going forward. We plan on making some modules for in house use only i.e. A module to talk to our holiday system. We wanted to know the best way to host these internally so people can browse the modules. Is it possible to get Drupal to report when a custom module is out of date?

If you want somewhere to host modules you could use distributed version control such as Git or Mercurial to store them in a repository.

You can then use drush make to build the site with modules hosted on drupal.org and from your repository.


Views PHP: Getting "Available Variables" I am using Views PHP and having problem in doing a very basic thing.

In my view I added a field which I have to "Exclude from display" and show it only when there is a specific content type being called on Page.

So I used Views PHP, which checks the content type. The only problem is that I don't know how to output this field.

I used

$row -> myfield_name;

but that doesn't work.

So basically, I just need to use "Available Variables". But the $row->myfield_name doesn't work.

I can't use the following as this gives raw field.  I only want to use how this is intercepted in my view and how my view shows it. This is because this field is a video and my view is formatting it with JWplayer and hence calling it will call it as JWPlayer.

$value-> _field_data["body"] ["entity"] -> myfield_name ["und"][0]["value"];

Thanks

The variables (or field) that you need to use as Available Variables must be before the Views PHP variable. Besides that install Devel module and use kpr($row) or kpr($view) or kpr($data) to get the available properties of these variables.
Also in "Output" section you can use var_dump or print_r to print available variables.


Convert your views into a custom module I'm using Views 3 on Drupal 6.

A while back I read an article how you can take your views and put it in your "custom' module folder (granted you've set this up for custom theme functions). I haven't had much need for it lately, but recently I've been doing a lot of work for a client that has needed a bunch of reworking of their Views and CSS related to them. This has turned into a bit of a nightmare trying to make sure that they then take my exported views from my development server to their server and import them correctly (sometimes they rename them, sometimes settings are not exported for whatever reason, etc).

A while back a read an article about converting your views into modules and it seemed pretty straight forward, but now I can't find it. Could anyone point me in the right direction? All I could find is a 50 minute long video tutorial, and I would rather just have an article I can skim.

Thanks!

EDIT:

The below link seems like it should work, but I'm not sure what I'm doing wrong. It just dumps all the views export code at the top of the page. What I did:

Put this into my "sitetheme.module"

function sitetheme_views_api() {
   return array(
      'api' => 3,
  );
}

Created this separate file named "sitetheme.views_default.inc". Which I put in this code:

/**
* Implementation of hook_views_default_views().
 **/
function sitetheme_views_default_views(){
  $files = file_scan_directory(drupal_get_path('module', 'sitetheme'). '/views',     '.view');
  foreach ($files as $filepath => $file) {
  require $filepath;
  if (isset($view)) {
 $views[$view->name] = $view;
  }
 }
  return $views;
}

Then I made a new folder in my sitetheme module called "views", took the export code and saved it something like "myexportview.view" and saved it under the "views" folder.

Then when I upload these files to the client server it just dumps all the code at the top of the admin/build/views page.

Any idea what I did wrong? I seem to be following the directions exactly but I'm not sure what I'm missing...

It appears that I had to put a <?php at the top of the myview.view export file. However, now Drush doesn't work... I get a fatal error from Drush when I try to clear the cache:

  Fatal error: __clone method called on non-object in /Users/mycomputer/Sites/mysite/htdocs/includes/common.inc on line 1733

When the Bulk Export module (part of the Chaos Tools Suite module) is enabled, it exposes a page (admin/structure/bulk-export) where views can be exported.

What you need to do is selecting the views you want to export, enter the short name of the module that will contain the views, and click on the "Export" button.

The page that will appear next contains three text area fields (<module name> is the short name you entered in the previous page):

One is for the content to place in <module name>.info
The second is the content to place in <module name>.module
The last is the content to place in <module name>.views_default.inc

The differences I can see between the code the module tells me to use, and the one you are showing are:

The implementation of hook_views_api() is the following.

/**
 * Implements hook_views_api().
 */
function sitetheme_views_api($module, $api) {
  if ($module == 'views' && $api == 'views_default') {
    return array('version' => 2);
  }
}

The implementation of hook_views_default_views() is the following.

/**
 * Implements hook_views_default_views().
 */
function sitetheme_views_default_views() {
  $views = array();

  $view = new view();

  // …

  return $views;
}

$views is an array of objects of the view class.


Does my Drupal 7 site have transaction support enabled by default? I happen to read through the commented lines in settings.php under the "Database settings" (around line no. 45) the following text:

  Some database engines support transactions. In order to enable transaction support for a given database, set the 'transactions' key to TRUE. To disable it, set it to FALSE.
  Note that the default value varies by driver.  For MySQL, the default is FALSE since MyISAM tables do not support transactions.

My databases array, auto-generated by Drupal Installer, is the following one:

$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'test_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Is it true that my site is not transaction aware until I add a key/value, 'transaction' => TRUE (preferably after 'prefix' => '') to $databases?

Looking at the construction of the DatabaseConnection_pgsql class, I noticed the following code:

$this->transactionSupport = !isset($connection_options['transactions'])
  || ($connection_options['transactions'] !== FALSE);

The code sets DatabaseConnection_pgsql::$transactionSupport to TRUE when the connection parameters don't contain the array index "transactions," which is one you should set in your settings.php file (it's not "transaction"), or when that array index is used in the connection parameters and it is not set to FALSE.
The same code is contained in DatabaseConnection_mysql::__construct(); in this case, the connection parameters (the ones set in the settings.php file) should be set not to use transactions only when the tables used are MyISAM.
Also DatabaseConnection_sqlite::__construct() contains the same code.

In short, the drivers used by Drupal always set the transaction support to TRUE, and users should set it to FALSE when they are using MyISAM tables, or they don't want to enable the transaction support.


How to use a translated taxonomy in autocomplete term-reference fields? When I translate a taxonomy to other languages, I cannot use it in autocomplete term-reference fields.

The auto complete field will show items only in the default language; if I try to fill the form from another language, nothing shows up in the field when I type.

It happens only when I use the autocomplete widget.

I am using Drupal 7.15.

Are you using 'Entity Translation' or the core 'Content translation'?

I think the sub-module Multilingual select (from Internationalization) should handle this for 'Content translation' (didn't test it, though).

But for Entity Translation, this doesn't seem to work (yet): see Entity translation and the Multilingual select i18n submodule interactions and Language aware edit form and autocomplete.


Adding different auction prices for same product I'm having same issue as krystalcode's issue.

First I created a product. Then added the content as auction product. While adding this content, the base price is considered to be the same as the product. So, do I need to add new product before creating an auction item?

It would be great if farhadhf, the owner of this Commerce Auction module will help.

As the author of this module or someone else couldn't reply this question, I'm creating new product before creating the content. Then I create the auction content and choose the related product.


How to prevent user point totals from going below a threshold for a given user? I'd like to set an absolute floor for an individual user points (using the User Points module). Specifically, to make it impossible to have a total number of user points below 1.

In Drupal 6 there was the userpoints_no_negative module in Userpoints_contrib, but this was removed in favour of Rules integration for 7.x (https://drupal.org/project/userpoints_contrib).

The documentation provides an example using rules to evaluate point totals with a condition of "Userpoints - Compare current Userpoints"  (https://drupal.org/node/874390), but I am not finding this condition available.

I'd accept any solution, be it using rules or a custom module.

EDIT 2/4/2014 9:17PM UTC - Example code based on ramesh babu's accepted answer:

/*
 * Implements hook_userpoints().
 * Checks if points at minimum threshold, corrects to 1 if pushed below limit.
 * Based on comments in Userpoints API documentation on D.O. a separate transaction
 * is made to correct for the threshold rather than modifying the points for
 * the existing transaction.  See https://drupal.org/node/206558
 */
function mymodule_userpoints($ops, $params) {
  if ($ops == 'points before' && !isset($params['threshold'])) {
    $future_total = userpoints_get_current_points($params['uid'], 'all') + $params['points'];
    if ($future_total < 1) {
      $params['description'] = 'Minimum point correction.';
      $params['points'] = abs($future_total) + 1;
      $params['threshold'] = true;
      userpoints_userpointsapi($params);
    }
  }
}

The documentation for the Userpoints API on drupal.org is also a helpful resource https://drupal.org/node/206558

Here the solution with custom module implementation:

implement hook_userpoints($op, $params) function in your custom module to check the user points in every transaction with two option called points before and points after.

For your thing check if the points are less than your threshold value, set your threshold value after the transaction.

for more referencehttp://api.worldempire.ch/api/userpoints/functions?page=1 check this.


How to redirect in WebformHandler after submitting Ajax form I'm trying to redirect to a results page after a form that uses Ajax is submitted. The form is a semi long multi step form, so Ajax is enabled for the user experience.
I have created a new WebformHandler and I'm using the confirmForm() method, but I'm having difficulties to make the redirect work. The 'Confirmation' setting in my Webform is set to 'None'. I also don't see errors in the logs.
namespace Drupal\burnout_module\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Send values to the matching API and get results back, redirects to results page
 *
 * @WebformHandler(
 *   id = "matching_api_handler",
 *   label = @Translation("Matching API"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Send values to the matching API and get results back, redirects to results page."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class MatchingApiWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // $result = ... code for calculating results with form values

    $url = \Drupal\Core\Url::fromRoute('burnout.match')->setRouteParameters(array('result' => json_encode($result)));
    $form_state->setRedirectUrl($url);

  }

}

I have also tried other possibilities:

Using a RedirectResponse which gave me a 'Headers already sent' error
AjaxResponse with a RedirectCommand, nothing happens, no errors

Hopefully someone can point me in the right direction.
Kind regards

I got it working with another approach, instead I used the form_alter hook and added an ajax submit callback.
See Webform alter with ajax submit callback - field values are empty in callback


Views profile2 views I hope it's okay to ask a why question here. I've got a profile named Expert Information and a Skills field in that profile. I've got 9 users with the Expert role. Now my problem is: When I make a user type of view and make a relationship to profile, I get all 9 users but nothing shows under Skills; however when I make a profile type of view and make a relationship to user, I get results under Skills but this time I get 4 users. Why is that happening and what is the correct way to fulfill both?

Thanks,

K.

It was my bad, the person who originally made the view did not make the relationship properly. But the weird thing is, it worked properly on a Drupal 7.30 installation and broke on 7.34.


Update a field based on value of another field in node edit form In the node add/edit form, I have a node reference field. When users select a node, I want to update another field with value of a field of selected node.

What's the best and easiest way to do this?

I want to load the value in the edit form, using AJAX or AHAH, so that the users can see it, and edit if necessary, not just updating the field after form is created.

Drupal 7:

Create a custom module. This module should implement hook_node_insert and hook_node_update. Both functions will have almost identical code, and it should go something like this:

/**
 * Implements hook_node_insert()
 */
function mymodule_node_insert($node) {
  if ($node->type == 'my_node_type') {
    // Set the $value variable with value you wish
    // to insert to the referenced node.
    $field = field_get_items('node', $node, 'field_whatever_it_is');
    $value = $field[0]['value'];

    // Grab the referenced node's nid.
    $field = field_get_items('node', $node, 'field_nodereference_field_name');
    $ref_nid = $field[0]['value'];

    // Load the referenced node into a variable. Avoid cached nodes.
    $ref_node = node_load($ref_nid, NULL, FALSE);

    // Update the referenced node with $value
    $ref_node->field_to_update[0]['value'] = $value;

    // Save the referenced node
    node_save($ref_node);
  }
}

If you just want to update the referenced node's node reference field with the current node's nid then you can also just use a module called Corresponding Node References


How to set multiple error messages with form_set_error? I notice I can pass in a message variable to form_set_error().

How can I pass in multiple messages?

I tried calling form_set_error() several times, but always the first one is displayed.

So, to sum up I want to show something like this:

error 1
error 2
error 3

Currently, I can only get:

error 1

Then, once the users correct it, and resubmit it, they get:

error 2

if (strpos($form_state["values"]["body"], "

if (strpos($form_state["values"]["body"], "

If both of these control statements trigger an error, only the first one is shown.
After the user corrects the error, the second error message is shown.

I would change the code to issue a single call to form_set_error() per element:

$errors = array();
if (strpos($form_state["values"]["body"], "<h1") === true)
    $error_messages["body"][] = "Blalalabalbal bablalbabla.";

if (strpos($form_state["values"]["body"], "<h3") === false)
    $error_messages["body"][] = "Do this do that balbablalba.";

foreach ($error_messages as $element => $messages) {
    form_set_error($element, theme('item_list', array('items' => messages)));
}


How to print an entity bundle field from one with multiple values Struggling to find the answer to this. I have an entity called "school objects" which has a bundle called "homepage". One of the fields attached to this is called "Hero banners" and it allows multiple text values.

All I want to do is print each value. I don't need to check for conditions, I don't need NIDs, I just want each value. I am not really a php developer but understand the basics of what it is doing. I was looking into the EntityFieldQuery code, but cannot get anything to print on a tpl file I am using.

The output I need, based on image attached, is simply:

images/symbol.png

Let's make a difference

Start today

All I can find after a lot of searching is complex bits of code checking for conditions and stuff that I do not need. I need some kind of array I think so that my template looks like:

Value[0]

Value[1]

Value[2]

All I got so far is this:

query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'school_objects')
  ->entityCondition('bundle', 'homepage')
  ->range(0, 14);
$result = $query->execute();

I have read the link to this on the Drupal site but cannot understand it or how to print what I need.

Try the following and load the actual entity to get its field values.

The code assumes you have drupals entityTypeManager injected via dependency injection. Otherwise use \Drupal::entityTypeManager() isntead of $this->entityTypeManager()

// Get the entity ids.
$entityIds = $this->entityTypeManager()->getStorage('school_objects')->getQuery()
  ->condition('type', 'homepage')
  // Add more conditions if you need.
  ->execute();
// I assume only one id is returned and reset the array. Otherwise go over
// each Id with a foreach() and do this in a loop.
$entityId = reset($entityIds);
$schoolObject = $this->entityTypeManager()->getStorage('school_objects')->load($entityId);
// Now get the values of your field. I assume the fields machine_name is 'field_hero_banners'. Adjust if needed.
$values = $schoolObject->get('field_hero_banners')->getValue()
// Loop over all values.
foreach ($values as $item) {
  $value = $item['value'];
}


Trigger a pop-up or recenter in Openlayers (version 7.x-2.0-beta5) from outsite the map Is it possible to trigger the pop-up of a marker or center the marker in an Openlayers map through an anchor-tag outside the Openlayers map.

Example:

Create a view that lists some nodes
Click on the title of a node
Recenter the map or open the pop-up of the marker of that node.

I found this solution but they work with an older version of Openlayers and can't get it to work...

If you are using the standard popups that come with OL, you can make use of Drupal.openlayers.popup.popupSelect.clickFeature().

The way I did this was to assign an html attribute "nid" to each node in the list of nodes that you are going to use for the click navigation.  You can grab the nid from the clicked node any way you like, this is just the way I had done it.

So, now you have your list of nodes with an nid attribute and your map full of markers.  Here's one way you can use Drupal.openlayers.popup.popupSelect.clickFeature() to open the popup when you click one of the nodes in your list:

Make sure namespace exists:

Drupal.settings.nid = Drupal.settings.nid || [];
Drupal.settings.getAllFeature;

Make Drupal aware of all layers features:

function my_map() {
  var all_layers = Drupal.openlayers.popup.popupSelect.layers;
  for(var key1 in all_layers) {
    var current_layer = all_layers[key1];
    var all_features_in_layer = current_layer.features;
    for(var key2 in all_features_in_layer) {
      var current_feature = all_features_in_layer[key2];
      Drupal.settings.nid[current_feature.attributes.nid] = current_feature;
    }
  }
}

Function to grab the map object:

function getMap() {
  return jQuery('.openlayers-map').data('openlayers');
}

Click function for each node in your list of nodes:

jQuery('.eachNodeInYourList').click(function(e) {
  var nid = jQuery(this).attr('nid');
  show_popup(nid);
});

Show the popup on the map:

function show_popup(nid) {
  if (Drupal.settings.nid) {
    var feature = Drupal.settings.nid[nid];
    Drupal.openlayers.popup.popupSelect.clickFeature(feature);
  }
}

Make sure a layer is visible: (get the layer name from the "Title" field on the views overlay)

function activate_layer(aLayer) {
  var ol = getMap();
  var layer = ol.openlayers.getLayersByName(aLayer)[0];
  layer.setVisibility(true);
}

Initialize:

if (jQuery('.openlayers-map').length > 0) {
  my_map();
  activate_layer('myLayer');
}


How can one module's template file be overriden by another module? I'm trying to use a custom template file within my Features module to handle a Views exposed form, but have been unable to figure out how to do so. I've seen a couple of other questions on here which seem to be the very same class of problem, but who's solutions have not worked for me.

I have been successful in getting both my template file and a preprocess function to take control, but it appears that they completely disable View's own preprocess function, which is necessary for the form to be generated correctly.

Presently, I am creating a theme hook in my custom module:

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'views_exposed_form__people__page' => array(
      'base_hook' => 'views_exposed_form', // BTW, am I using this thing right?
      'template' => 'views-exposed-form--people--page', // (hook--view--display)
      'render element' => 'form',
    ),
  );
}

I understand that this means my preprocess function will now be called, and I use that to add my template file into the mix:

function mymodule_preprocess_views_exposed_form__people__page(&$vars) {
  $vars['theme_hook_suggestions'][] = 'views_exposed_form__people__page';
}

This works, but now it looks like View's default preprocessor template_preprocess_views_exposed_form(&$vars) in Views' theme.inc isn't firing, and that's bad because that function needs to run for this to work properly.

I'm also struggling to understand the rules behind what functions and templates get used when. The system doesn't seem overly complicated, I've just had to piece how it works together from disparate sources. I may be operating under one or more misconceptions here, so let me know if you want to probe what I think I'm talking about.

Rather than outright overriding the theme item implementation (via your hook_theme()), you could use hook_theme_registry_alter() to add your preprocessing function to the theme item.


How to Print /PDF entire page I was wondering if the Print module can be used to print an entire page, not just nodes. I need to add some blocks to the pdf as well, not just the node content.

Is there any way of doing this, or will I need to manually add the blocks to the node->content property?

LATER EDIT: The problem is that the print module takes the node ID as a parameter. This means I cannot print blocks on those pages.

There is a block version of print links Printer, email and PDF versions. goto admin/structure/block and enable it. next you should goto admin/config/user-interface/print and change Printer-friendly page link setting to Block.


How to get the highest value of a specific field in a multivalue field collection How to get the highest value of a specific field in a multivalue field collection, USING PHP?

This is about displaying the right discount for a marketplace product.

There is a node type Product with two field collection fields:
(1) field_discount which contains:
    - a field for the minimum quantity required for the discount
    - a field for the discount percentage
(2) field_price which contains:
    - a field for the base price
    - a field for the discounted price

The reason why (2) is also a field collection, is because I want to allow the marketplace sellers to show multiple price options. This might be relevant information because it seems that the views reference filter module does not work with field collections. Using that module would have made this issue a lot easier. Instead, this question focuses on using PHP, unless someone has another solution that does not require or requires less PHP coding.

The discount price needs to be built on the fly when a product node is displayed, using the raw quantity value from the URL and calculating the discount. My solution was to use a jump menu view with numbers 1 to 1000, which adds the quantity to the URL, like http://xxxx.com/node/100/5  in which the "5" as product quantity is inserted by using the jump menu. However, this might not be the most efficient method in the context of this issue. You are free to suggest another approach if that serves a more efficient solution to this issue.

STORING DISCOUNT AS VARIABLE
Only after the customer sees the discount price and clicks ORDER  (a flag button), the transaction values are stored in transaction entity fields. Therefore, the transaction values need to be available as variables.

Using PHP code in Global NULL, Session variables.
My current approach is to use a Global Null as views contextual filter, default value PHP code, in order to fetch field values and calculate discount, and to store the values as SESSION variables. Since no transaction entity is created yet, I can't see another way to store these values for further use in the (possible) transaction.

My experience with php and metadata wrappers etc is insufficient, especially with regard to fieldcollections.

WANTED:
the discount percentage, corresponding with the quantity chosen by the buyer. The discount percentage must be within the range of quantities specified by the product owner.
Solutions with either other Drupal modules, or custom php are both welcome. As mentioned above I tried the views reference filter, using an exposed filter referencing quantity values of the field collection, but I couldn't get that to work.

Try the Computed Field module

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!


Create a simpletest test to add additional form elements using the "Add another item" button I am trying to create a test case for my custom module using simpletest in Drupal7.  I want to create a node.  The problem is that the node edit form contains a number of fields which can have multiple values.  Addition values are added by clicking on the "Add another item" button, which adds an addition field (nothing fancy here, just the standard Drupal form behavior).

I would like to create a node with two values for email.  By default the node form only displays one email field element.  To add a second email address I would have to first click the "Add another item" button, and then enter the email address. I am struggling to understand how to recreate this behavior in my test case. Any ideas?

The following is what I have so far:

  // Create a namecards_namecard node using the node form.
  public function testNamecardsNamecardCreate() {
    $this->drupalGet('node/add/namecards-namecard');
    // Create node to edit.
    $edit = array();
    // Enter surname
    $edit['title'] = $this->randomName(8);
    // Enter given name.
    $edit["namecards_namecard_given_name[und][0][value]"] = $this->randomName(8);
    // Enter email address.
    $edit["namecards_namecard_email[und][0][value]"] = $this->randomName(8) . '@' . $this->randomName(5) . '.com';
    // Click "add another item" for another email field.
    $this->drupalPostAJAX(NULL, array(), array('namecards_namecard_email_add_more' => 'Add another item'));
    // Enter another email address.
    $edit["namecards_namecard_email[und][1][value]"] = $this->randomName(8) . '@' . $this->randomName(5) . '.com.cn';
    $this->drupalPost('namecards/add_contact', $edit, t('Save'));
    $this->assertText(t('Namecards namecard @title has been created.', array('@title' => $edit['title'])));
    $this->assertText($edit["namecards_namecard_email[und][0][value]"]);
    $this->assertText($edit["namecards_namecard_email[und][1][value]"]);
  }

The problem was with the drupalPost() method.  I managed to solve the problem by changing the first argument to NULL (e.g. $this->drupalPost(NULL, $edit, t('Save'));), which sets the target to the current page. Still not sure why this works instead of string denoting the path.  Never-the-less it did solve the problem.


How to change Option Label with Hook_form_alter I've added the Cheque module to my Drupal Commerce site so that users can select that payment option instead of paying by credit card.

However, I'm seemingly unable to edit the label for that payment option which currently reads as 'Cheque' next to the radio button.

In hook_form_alter, I'm attempting the following, but all it does is add another radio button and another option...it doesn't change the existing option.

$form['commerce_payment']['payment_method']['#options']
['commerce_payment_commerce_cheque'] = t('Send me an Invoice');

Note: I also tried the above code with ['#title'] at the end and it just gives me another option with the label 'Array' attached to it.

So, how do you change the label text of an option with hook_form_alter?

You're just adding to the existing array of options, when actually you want to clear it and just use your option.

Try this...

$form['commerce_payment']['payment_method']['#options'] = array('commerce_payment_commerce_cheque' => t('Send me an Invoice'));


Multisite - Put one alias in maintenance mode We have one installation (let's call it example.com) with two domains (development.xpto.com and example.com) serving as alias (defined in sites.php) to the main site folder.

We wanted to put one of those aliases (the example.com) in maintenance mode and leave the development domain working np.

What's the best course of action to attain this functionality?

If your multi sites have separate databases than you can simply put whichever (sub)domain you desire into maintenance mode without effecting the other domains.

If you are using the Domain Access Module, you should navigate to that domain's maintenance page and put it in the mode you desire at subdomain.example.com/admin/settings/site-maintenance - see my screen capture


Merging new contents with new functionalities Assuming a situation when you develop a new functionality on a local copy of an already published site for quite a while, during which period the client adds new content over and over again.

How do you then merge the new additions from both sources? Do you use Features or something else? What's the safest way to go?

Use below modules and git

Modules:

1) Backup and migrate(By this module you can take the backup of database from the production site).

2) Features(You can export content types, admin settings and global settings).

3) Drush(You can use this module for the production deployment).

Version control system

1) GIT

Below are the steps how to sync your code and database with the production site.

1) Take the database backup from the production site before you start working on the local machine and import that database into the local machine.

2) Take the updated code base from the git repository of production site.

3) Complete your work whatever you want and in the evening after completion of your work create features(If you have done some changes in content type, permission or any other settings) and pull code from the git repository if there is conflict then resolve it otherwise just commit your code on the git repository and move those changes from git repository to prod server.

4) Test whether it is working fine or not. If it is not working perfectly then revert your changes from git and commit your files and then move your files from git repository to prod server.


Authentication Services module I use services with drupal 7, here the services resources function :

function custom_api_services_resources()
{
    return [
        'res' => [
            'create' => [
                'callback' => 'custom_api_create_user',
                'access arguments' => array('administer access control'),
                'access arguments append' => FALSE,
                    'args' => [
                    [
                        'name' => 'data',
                        'type' => 'struct',
                        'description' => 'data',
                        'optional' => FALSE,
                        'source' => 'data'
                    ]
                ],
            ]
        ]
    ];
}

Here the node access function (empty) :

function custom_api_node_access($op, $data) {
}

For Authentication I use HTTP basic authentication and/or Session authentication

I don't know what I have to do to limit access only for admin. I've tried a lot but never work with authentication.

I feel like it's very easy to use it, but I don't understand it.

I've already posted a message about this issue but differently. Can someone delete the first one, please ?  How do I use the access arguments?

Edit

custom_api.module file :

             'create' => [
                'callback' => 'custom_api_create_users',
                'access callback' => 'custom_api_access_callback',
                'access arguments' => array('administer create field_projects'),
                'access arguments append' => TRUE,
                'access callback file' => array(
                  'type' => 'inc',
                  'module' => 'support',
                  'name' => 'custom_api.resource',
                ),
                    'args' => [
                    [
                        'name' => 'data',
                        'type' => 'struct',
                        'description' => 'data',
                        'optional' => FALSE,
                        'source' => 'data'
                    ]
                ]

custom_api.resource.inc :

function custom_api_access_callback($permission) {
  return user_access($permission);
}

Permission from Database, role_permission table :

Permission : access comments
Module : comment

Permission : access content
Module : node

Permission : access news feeds
Module : aggregator

Permission : access site map
Module : site_map

Permission : create field_credits
Module : field_permissions

Permission : create field_credit_level_1
Module : field_permissions

Permission : create field_credit_level_2
Module : field_permissions

Permission : create field_credit_level_3
Module : field_permissions

Permission : create field_level
Module : field_permissions

Permission : create field_number_of_credit_remove
Module : field_permissions

Permission : create field_projects
Module : field_permissions

Permission : create field_remove_credit
Module : field_permissions

Permission : search content
Module : search

Permission : subscribe to newsletters
Module : simplenews

Permission : use advanced search
Module : search

Permission : use custom search
Module : custom_search

Permission : use custom search blocks
Module : custom_search_blocks

Permission : use text format guestbook_txt
Module : filter

Permission : access comments
Module : comment

Permission : access content
Module : node

Permission : access news feeds
Module : aggregator

Permission : access site map
Module : site_map

Permission : administer custom search
Module : custom_search

Permission : administer custom search blocks
Module : custom_search_blocks

Permission : administer search
Module : search

I have link to add data (client and node : project and client) in drupal website. Only administrators can add data.

Drupal Services is a bit strange in that it doesn't seem to fall back to calling the user_access() function. Instead, I always provide a custom access callback function, and in it usually just make a call to user_access(). Try this:

'doli' => [
        'create' => [
            'callback' => 'custom_api_create_user',
            'access callback' => 'example_access_callback',
            'access arguments' => array('administer access control'),
            'access arguments append' => TRUE,
            'access callback file' => array(
              'type' => 'inc',
              'module' => 'example',
              'name' => 'example.resource',
            ),
                'args' => [
                [
                    'name' => 'data',
                    'type' => 'struct',
                    'description' => 'data',
                    'optional' => FALSE,
                    'source' => 'data'
                ]
            ],
        ]
    ]

Then make a file called example.resource.inc in your module's folder, and place this code into it:

function example_access_callback($permission) {
  return user_access($permission);
}


Imagecache preset table I got my database crashed and fixed it, but some tables missed some of its data. one of these tables are the table that contains the preset values for imagecache (imagecache v 1.6.2.1, Drupal 6.19).

mysql> select * from imagecache_preset;

+----------+-----------------------------------------+
| presetid | presetname                              |
+----------+-----------------------------------------+
|        1 | article_headline_main                   |
|        2 | article_headline_thumb                  |
|        3 | article_headline_node                   |
|        4 | article_behind_the_news_old             |
|        5 | article_main_news_old                   |

By editing any of the above presets, i found that it is UNSET and I have to respecify action, height and width.
I have a dump of my database, but I need to know the table that contains the preset values so I can get them back from the backup. Which database table is it?

Check out the imagechache_action table, that should have the information you are looking for.


How to prevent users from accessing content? Newbie doing tutorial.

I want to deny anonymous access to my site.
My Tutorial (not up to date for V7) says unCheck "Access Content" to disallow access.
This permission does not exist (or I could not find it).
Is unChecking "Access Content" the same as unChecking "View Published Content"?

Have I found the wrong permission?

You want to uncheck the View published content permission for anonymous user. So yes you have found the right permission.


certain drupal modules not working I've installed drupal several times and I'm still having the same problem. Some modules aren't working.

E.g:

Admin menu - They don't always appear. It only shows in random moments.

Wysiwyg and CKeditor - is not visible when I'm creating the content.

These are the modules I have installed and I'm using Marinelli theme:

admin menu
Wysiwyg
IMCE Wysiwyg bridge
IMCE - this is for images
IMCE Mkdir
Pathauto
Chaos tools
insert
Mega menu

You might have a JQuery version conflict. Do you have the JQuery Update module? Or did you include some script not compatible with Drupal's version of JQuery?