How can I get other content type data in current content type? I want to put one condition in my template file of contenttype1. The condition is if contentype2 contains a field value X then I want to print one block in contentype1. So how can I get contenttype2 field values in contenttype1 template file.  To get more clarity, with the contentype2 fields I am creating a views block. I want to display that block in contentytype1 template file. So I want to check a field condition of contentype2. If that field has any value then only I want to display that views block in contenttype1 otherwise it should not display. Thanks in advance for any suggestions.

What you need to do is make X a taxonomy term.

1) Go to taxonomy and create a vocabulary (ex: Colors)

2) Inside Colors vocabulary, add terms. (ex: Red, Blue, Green, Yellow etc..)

3) Go to contentype1 manage fields and add a new field of type: Taxonomy Term Reference. Then select the vocabulary (colors).

4) Now edit your contentype1 nodes and give them a taxonomy term. Ex: Node 1 blue, Node 2 red, Node 3 blue, ...etc

5) Repeat steps 3) and 4) but with contentype2 this time.

6) Create a block view of contenttype2 (You will see it lists all the contentype2 nodes)

7) Under Advanced, add Relationship of Terms of the node, checkmark Colors and checkmark require relationship.

8) Add a contextual filter of Taxonomy Term and for when filter is not available, set it up like this (using screenshot from another answer):

Once you add the contextual filter, your view preview will go blank, which is normal. Go to a contentype1 node, where you placed the view block, and you should see contenttype2 nodes that have the same taxonomy term as the current contentype1 node that you're viewing.


Primitive Error when saving a custom field with a text_format widget I am trying to make a custom field with one normal textarea and 1 text_format widget.
The textarea functions perfect but if I try to use the text_format widget I get an primitve error when I am trying to save.

This is the error message:

  This value should be of the correct primitive type

This is my formElement:

 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element['date_text'] = [
  '#type' => 'text_format',
  '#title' => 'text',
  '#format' => 'full_html',
  '#default_value' => isset($items[$delta]->date_text) ? $items[$delta]->date_text : NULL,
  '#placeholder' => t('Data Text'),
  '#element_validate' => array(
      array($this, 'validate'),
    ),
];
  $element['date_table'] = [
  '#type' => 'textarea',
  '#default_value' => isset($items[$delta]->date_table) ? $items[$delta]->date_table : NULL,
  '#placeholder' => t('Data Table'),
];
return $element;

}

and this is my schema:

  public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = [
  'columns' => [
   'date_text' => [
      'type' => 'text',
      'size' => 'medium',
    ],
    'date_table' => [
      'type' => 'text',
      'size' => 'medium',
    ],
  ],
];

return $schema;

}

It seems, that text_format returns an array instead of a single value and thus cant be saved in my text column.
The array consists of the text and the format, i dont need the format, so I would need to replace the array with the text value.

How and where could I accomplish this?

Xdebug is not working on scripts that are executed when I click save, so I really have no clue what is really going on.

thanks

Here is what solved the issue:

I used messageFormValues in my Widget.php to override the Array with the text value, so it could be stored in my database.

public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
  foreach($values as $key => $value) {
    $values[$key][date_text] = $value[date_text][value];
  }
  return $values;
}

To unescape the html for my twig template(so it is displayed as html and not as text on the site) I used the raw attribute.

With this solution no Text-Format will be saved, but it was not necessary for my custom field anyway.


Field api - taking responsibility over a field display I am writing a Drupal module that deals with the taxonomy terms, which are (as I understand) fields, taxonomy vocabulary , which are as I understand entities. My module should take over the taxonomy term field and vocabulary entity for mirror language display, meaning that once my user is in X language, he will see the X language value of the term/vocabulary name/description.

Looking at the i18n_taxonomy module code I can see that it implements many fields related functions (i18n_taxonomy_field_attach_view_alter(), i18n_taxonomy_field_formatter_view(), i18n_taxonomy_field_formatter_info(), etc). My questions are:

Once I need to to take over a display of a field, how can I do it?
What functions should my module implement for displaying the fields on menus, widgets, plain view, etc?
Same question, only for the vocabulary: is there any difference?
I have spent my time googling this subject, but I have not really found a good reference. Can anyone refer me to one?

Fields are displayed through formatters (you can have multiple ones, and then you chose which one you want when adding the field to a content type, or any bundle of an entity).
So, hook_field_formatter_info() and hook_field_formatter_view().
Open the core image module: modules/image/image.field.inc in your Drupal install, and use that as an example.

You can use hook_field_formatter_info_alter() to add formatters to existing field types (not declared by your mpdule).


Drupal behaviors with non-core jquery For various reasons I am currently working on a module with a version of jQuery and jQuery UI that is not core. In other words,

scripts[]=js/jquery.js
scripts[]=js/jquery-ui.js

are declared in the .info file. While this gives me the correct look and feel of my module, the form callbacks I used previously with Drupal.behaviors are not working anymore.

My first approach was to remove the (function($) {...})(jQuery); enclosures in the Drupal.behaviors function, to no avail.

My question is then: Is there a way to write these callbacks using standard (non-Drupal) jQuery or do I have to refactor everything 'the drupal way?'

Here is what I have on the .module side:

function        ggent_form($form, &$form_state) {

$form['Input type'] = array(
    '#type'=>'fieldset',
    '#title'=>'Upload your image'
);

$form['Input type']['file'] = array(
    '#type' => 'managed_file',
    '#title'=> t('Upload image'),
    '#description' => t('An optional description'),
    '#upload_validators' => array(
        'file_validate_extensions' > array('gif png jpg jpeg'),
        'file_validate_size'=>array(512*512*512),
    ),
    '#upload_location'=>'public://',

);

$form['Input type']['submit'] = array(
    '#type'=>'submit',
    '#value' =>t('Submit'),
 '#ajax' => array(
            'callback'=> 'ggent_update_image_callback',
            'wrapper'=>'mywrapper'
        ),
);

return $form;
}

///*
// * Form callbacks
// */
function        ggent_update_image_callback($form,$form_state) {
$picture_settings = array(
    'image' => file_create_url($form['Input type']['file']['#file']->uri)
    );
    drupal_add_js(array('ggent' => $picture_settings),'setting');
    return;

Which should send to my .js file to be used as:

    if (input_type === 'image') {
        img.src = '....../standardbg.png';
        Drupal.behaviors.imgupload = {
            attach: function( context, settings ) {
                if (typeof Drupal.settings.ggent.image!=='undefined' && img.src !== Drupal.settings.ggent.image) { //typeof img.src !== 'undefined' &&
                    img.src = Drupal.settings.ggent.image;
                }
            }
        };
    }

But this doesn't work. The Drupal.behaviors event doesn't fire at all! Any suggestions would be greatly valued.
EDIT: Updating my jQuery using the suggested module does nothing.

If for some reason you need multiple versions of jQuery you can use the jQuery Multi module:

(libraries module is also required)
and you put the different version in the libraries directory
then you wrap your JavaScript code in something like this:

(function($) {...})(jqxxxxx);

where jqxxxxx is the version of jQuery you are using (see the documentation of jqmulti for more info)

do not include jquery scripts like you did. JQury Multi will do it automatically for you


Track field dependency with features I modified a field dependency on my Call content type. Features did not track the change automatically. I cannot figure out how to manually add it to features.

This is a way to it:

Add the feature exportable manually to the module.info.
You can check the available features with the drush features-list command. You have to find the field dependency format within that list, it could be a variable that looks like your field name.
If you module.info has the new field dependency, you can update the feature drush fu myfeature_module
Then review the generated files, maybe with git diff. You should see the change.

I am not sure what an exported field dependency looks like, there are different formats, these are examples so that you have an idea of what it would look like:

features[ctools][] = field_group:field_group:1

features[ctools][] = strongarm:strongarm:1

features[features_api][] = api:2

features[field_base][] = field_image

features[field_group][] = group_teaser|node

features[field_instance][] = node-about_page-field_image

features[node][] = about_page

features[variable][] = comment_about_page


add unrestricted html to ckeditor I am having issues with drupal and ckeditor. I would like to saev following code:

However due to ckeditor's filters almost everything gets stripped. I tried various advices - turning off advanced content filter or adding config.allowedContent = true; inside custom javascript configuration window. Nothing what I tried works.
Thank you for any advices.

go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.

If the above does not do it, depending on which one you are using (filter or full html) You need to go to

/admin/config/content/formats/filtered_html

OR

/admin/config/content/formats/full_html

try unchecking the correct faulty and chopped off html box.


What's your trick to document (in the UI?) variables overridden in settings.php? If you define variable overrides in settings.php, there is no visible change to the admin UI. It's easy when overtired (or just inexperienced) to overlook this when changing some config through the UI, and getting an unexpected result.

Have people come up with a trick to document settings.php overrides right in the related admin form? I guess I could write a form_alter every time I define a settings.php override, but is there an alternative clever that devs are using? (I'm using D7, BTW.)

You could implement a hook_help that displays a message on the page where you would set the variable. Would still need to do it manually per variable though.


Modifying only one field with a twig template I have a content type that has multiple fields.   I'm fine with the generic display view for all but one of those fields.   Is it possible to use a twig template to modify only one of those fields?
For example:
Content type: Stuff and Things
with Fields:
Body,
URL,
Notes,
Status,
Peer Review
I want to modify the URL field and leave the rest alone... is this doable, or do I have to render each field in the twig template?

Target the field template instead of node. Enable twig debugger and then inspect element with browser to see all the template files available to use/override.
You'll see you can use field--[field-name].html.twig or field--node--[field-name]--[content-type].html.twig if you want to be more specific.


How can an existing user login to check on previous orders? I see where an existing customer can login during the checkout process for a new order.  But where can they login to check on existing orders?  Or is that even possible?

I tested and it appears that the Drupal site logon is not the same as the Commerce customer login.

The Drupal site login and Commerce login are definitely the same; check the login details again.

Commerce 2 supports checking the details of orders out of the box.

It adds an "Orders" tab to the user profile (/user/UID/orders), and a view (that you can customize if you like) is provided to display the order history (/admin/structure/views/view/commerce_user_orders/edit/order_page).


Panelizer page manager variants not selected I have installed the page manager, panels everywhere and Panelizer. A long time ago I set up a few content types and managed them with Panelizer, it all works fine.
I've made a site_template variant, just once at this time and it all works also fine. Now I wan't to make different site templates for different content types.

So I've made a node_view "Panelizer"-variant for each content type. I've also made the different site_templates variants. Then I select the site_template for each node_view variant. But it din't work's as I expected it!!

It always tooks the site_template variant at the top and not the selected. It seems that the node_view panelizer variant is never selected, because the panelizer overrides the page manager (? !).

Please help me, thanks!

I found a workaround.
In the site_template variants i made a selection rule on the node type. Problem was, that i have pages that arent nodes, just simple pages. I cloned the Variants and removed the selection rule. Then i choosed this site_template in de pages.

Now i've got a lot of site_template variants wich is not so nice, but it works.


Patch drupal.org project (core/module/theme) with issue fork The new fork based merge request (MR) approach is pretty neat to get the patches created/reviewed/merged. However, if you are using the patch via cweagans/composer-patches, we have a few options.
Option 1: we can use the MR  to add the patch like this:
"drupal/message": {
  "3186091": "https://git.drupalcode.org/project/message/-/merge_requests/1.patch"
}

but it means any new change pushed to the fork/branch, would get automatically added. As the patch file gets pulled on composer install.
Option 2:
We could use the fork's branch and commit hash to keep the patch static, but once the MR merged, the fork might get deleted and breaks the build.
Option 3: Obviously we can generate the patch from the MR and upload to the issue comment, but it seems a duplicate effort and hard to keep up with an active core issue (right now, we just need to update the patch file in composer.json or composer.patches.json)
Is there a way to have the current patch file behavior in the new fork based issue queue?
UPDATE: Both option 1 and (probably) option 3 are documented on drupal.org

It has been discussed already in the Opt-in to the Drupal.org Issue Forks and Merge Requests beta thread, see 3152637#comment-13820062.  As of now there is no straight way to integrate commits in composer patch work flow. You need to download the patch file manually by appending .patch to the merge request URL and copy it locally into your project to get it applied in the build process.
"patches": {
    "drupal/foobar": {
        "3200808 - Lorem ipsum": "./patches/3200808-3.patch"
    }
}

You can get additional information on how to generate patch from the commit Id from the guide: Patch files for use with Composer.


Remove row from system table with hook_update_N I've run into some trouble writing a hook_update_N function that will remove a row from the system table. Can anyone point me in the right direction? Finding little documentation..

I think your code should look something like this:

<?php

/**
 * Delete row from system table.
 */
function MODULENAME_update_7001() {
  db_query('DELETE FROM {system} WHERE name = :name', array(':name' => 'FOO'));
}

This should go in the MODULENAME.install file of your module. Of course you'll need to replace MODULENAME with the name of your module and FOO with the name of the row you want to delete.

Relevant documentation can be found at Updating tables: hook_update_N() functions, hook_update_N and Database abstraction layer.


Commerce 2 how to set to live paypal signature API Credentials I have set up a sandbox account and I can take TEST payments without issue but there is nowhere for the live account details.

If I set the app you can create to live it gives different account API settings but no signature.

It seems Paypal has changed the layout and the PayPal module in D8 commerce 2 and has no help docs as of yet for this just help documents for the old D7 version.

Ok I sussed this out quicker than I expected. So for anyone else having this issue do this..

Login to the merchant account NOT the developer account.
Menu on Top right Click Profile > Profile and settings
My selling preferences > API access > update
Under Pre-built payment solution > Manage API permission
Under Option 2  > View API Signature
Under View or Remove API Signature expose the fields to show the Credential API Signature, API Username, API Password.

Add these to your PayPal settings in the commerce payment making sure you set this to live.


Immediate notifications dilema I want to notify users immediately when a node they’ve subscribed to is commented on, but then not send them any more notifications (from any other node either) until they’ve visited the site.  This is because I want users to immediately know when a discussion has a reply, but not have their inbox filled up with unnecessary emails. As far as I know no module can do this.

Im more of a themer than developer but it occurred to me that maybe this could be done with the Rules module. It would work this this:

1) When a node is commented on, send an email to the user if the user doesn't have role of ‘no’, and then add a role of ‘no’ to user.

2) When the user logs in, wait until they log out or are timed out, and then remove the role of ‘no’.

My reason for waiting until the user logs out before removing the role is I don't want them to get emails of comments while they are on the site. These may be emails from a discussion they are replying to several times while still logged in.

One issue could be if a user closes down their browser or leaves it open without refreshing it, but doesn't log out. Then Rules won't send them an email until they are timed out but they won't be aware or any comments made before this. Is there a solution to this?

Does anyone know how other forum software deal with this situation of wanting to have immediate notifications but not send loads of pointless emails to users?

Regarding the "... other forum software ..." near the end of your question: how about using the Flag module and its Rules integration?

Consider "somebody subscribing to some node" as the equivalent of "somebody flagging that node". And if your current technique to "send them notifications" is not flexible enough to do so in combination with the Rules and Flag module, then you may want to consider the Message module (which goes together with Rules and Flag very well also, and which is also used in some of the popular distributions).


How to get rid of the '-' sign before sub taxonomy term? when I choose a taxonomy term with a parent, it shows -termName instead of termName, to indicate it is a sub-category. I checked the database, it only stores the termName, which means that somewhere we can rewrite the output to show just termName.

How can I achieve this?

In Drupal 6, the function that outputs the list of taxonomy terms is _taxonomy_term_select(), which contains the following code.

  if ($tree) {
    foreach ($tree as $term) {
      if (!in_array($term->tid, $exclude)) {
        $choice = new stdClass();
        $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
        $options[] = $choice;
      }
    }
  }

  return array(
    '#type' => 'select',
    '#title' => $title,
    '#default_value' => $value,
    '#options' => $options,
    '#description' => $description,
    '#multiple' => $multiple,
    '#size' => $multiple ? min(9, count($options)) : 0,
    '#weight' => -15,
    '#theme' => 'taxonomy_term_select',
  );

Since it uses theme_taxonomy_term_select(), overriding that theme function is possible to remove those hyphens added at the beginning of the term name.

In Drupal 7, that code is contained in taxonomy_allowed_values().

  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }

Unfortunately, the function calling it (options_field_widget_form()) uses a theme function used for every form element (including the ones not associated with taxonomy terms), for example theme_select().

  switch ($type) {
    case 'select':
      $element += array(
        '#type' => 'select',
        '#default_value' => $default_value,

        // Do not display a 'multiple' select box if there is only one option.
        '#multiple' => $multiple && count($options) > 1,
        '#options' => $options,
      );
      break;

    // …

  }

Fortunately, options_field_widget_form() uses some custom properties that allows to check if the select form element is being output for an entity. In fact, it uses the following code.

$entity_type = $element['#entity_type'];
$entity = $element['#entity'];

This is true also in the case the used form element is checkboxes, radios, or checkbox.
If $variables['element']['#entity_type'] passed to the theme function for the select form element is set, and it is equal to the entity type for the taxonomy terms, then the theme function can assume it is outputting the select element for a taxonomy term, and remove the hyphens at the beginning of the term name.


How to set form type as 'hierarchical_select' programatically? I am using the following code to create a form in Drupal 6. This code displays a drop down filter with which I can select the terms, and apply the filters using the GET method.

function sample_create_form () {
  $vid=2;
  $options = taxonomy_form($vid, $value = 0, $help = NULL, $name = 'sample');
  $form['#method'] = 'get';

  $form['option'] = array(
    '#type' => 'select',
    '#title' => t('Terms for the Website'),
    '#options' => $options,
    '#description' => t('Website category'),
  );

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

  return $form;
}

I want to display the form as a Hierarchical Select type. I tried to use 'hierarchical_select' instead of 'select' in the above code but it didn't work.

Is there a way by which we can get the hierarchical select form?

I am using Drupal 6 and I have hierarchical select module enabled.

Any help highly appreciated.

I think its better to use hierarchical_select for element as it gives a FORM API that is really easy to use. Check the following snippet as reference

$form['hierarchical_select'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#attributes' => array(
        'class' => array('hierarchical-select'),
    ),
);
$form['hierarchical_select']['select_subject'] = array(
    '#type' => 'hierarchical_select',
    '#title' => t('Select the tag you wish to use.'),
    '#size' => 1,
    '#config' => array(
        'module' => 'hs_taxonomy',
        'params' => array(
            'vid' => 13 //The vocab id
        ),
        'save_lineage' => 1,
        'enforce_deepest' => 0,
        'entity_count' => 0,
        'require_entity' => 0,
        'resizable' => 1,
        'level_labels' => array(
            'status' => 1,
            'labels' => array(
                0 => t('Grade'),
                1 => t('Subject'),
                2 => t('Main Topic'),
                3 => t('Sub Topic'),
                4 => t('Standard'),
                5 => t('Sub-Standard'),
            ),
        ),
        'dropbox' => array(
            'status' => 0,
            'title' => t('All selections'),
            'limit' => 0,
            'reset_hs' => 1,
        ),
        'editability' => array(
            'status' => 0,
            'item_types' => array(),
        ),
        'animation_delay' => 400,
        'special_items' => array(),
       'render_flat_select' => 0,
       'path' => 'hierarchical_select_json',
    ),
    '#default_value' => 0,
);

I hope this helps.


Field API isn't saving data I have looked through multiple tutorials and I don't know what I'm missing.

I have created a new field type using the Field API and it's displaying everything perfectly, but when I try to put information in the textfield and hit save, nothing shows up on the form after the submit and nothing gets put in the database.

Can anyone tell me what I'm missing?  Here is an example of the code I've written:

in the module.install file i have:

function cptc_test_field_schema($field) {
 $columns = array(
 'field_test' => array(
   'type' => 'int',
   'unsigned' => TRUE,
   'not null' => FALSE,
 ),
);
return array('columns' => $columns);
}

and in the module.module file i put

function cptc_test_field_info(){
return array(
'field_test'=> array(
  'label' => 'test',
  'description' => 'test crap',
  'default_widget' => 'widget_test',
  'default_formatter' => 'formatter_test',
 ),
);
}

function cptc_test_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$value = isset($items[$delta]['value']) ? $items[$delta]['value'] : '';
switch($instance['widget']['type']){
case 'widget_test':
  $element['widget_test'] = $element + array(
    '#title' => 'Additional Email Addresses',
    '#type' => 'textfield',
    '#default_value' => '',
    '#size' => 60,
  );
  break;
default:
break;
}
$element['#element_validate'][] = 'cptc_test_field_widget_validate';
return $element;
}

There's a lot more to it (obviously), but figured that I shouldn't post everything - for expediency's sake. The other hooks I have implemented are:

hook_field_is_empty
hook_field_validate
hook_field_widget_error
hook_test_field_widget_info
hook_test_field_widget_validate
hook_test_field_formatter_info
hook_test_field_formatter_view

Thanks in advance!

In your function cptc_test_field_widget_form(), change
$element['widget_test'] to $element['field_test']. and make sure your hook_field_is_empty() has the following line of code:

return empty($item['field_test']);


What are best practices for reusing blocks between sites? What's the best way of reusing blocks between sites in Drupal 7? I want to re-use not only the block, but also the block's position in my theme.

Apparently, Features extra is designed for this. However, on the project page, it says that UUID Features Integration is the future of the module.

UUID Features Integration, however, doesn't seem to work (although a patch is available to fix things). Also it has been dropped in favor of Deploy.

Deploy, however,doesn't seem to work with blocks and is designed more for exporting nodes. So, I'm not really sure how it is a replacement for UUID Features.

What is the best practice for what I want to achieve?

PS. this is a new version of the question "Latest Best Practise: Reusing content/functionality between Drupal 7 sites", as I was told to post it as a separate question.

Page Manager, Panels and Features.

The plugin architechture in Ctools, which is the project in which Page manager belongs, is the best way to re-use blocks, among other things.

All my block placements are done with Panels, and then exported to code with features.


What do I have to do to get the Modernizr module to work in Drupal? I would like to use modernizr in drupal to take adcvantage of css media queries, box-shadow and border-radius. I have followed the installation instructions perfectly. I have installed the Drupal Modernizer module and created and properly placed my customized Modernizer build to include support for these three features. Does modernizr just pick up my already existing media queries and css3 styles automatically or do I have to do something else?

Modernizer detects feature support in browsers and adds css classes to the HTML element based on those features.  You use those css classes to target newer features to browsers that support them.  While it will add HTML5 support to older browsers via the HTML5Shiv, it will not add CSS3 support.

To add support for CSS3 features in older browsers, you'll need to add a polyfill  Modernizer has a method called Modernizr.load() that lets you load the polyfill only when you need it.


Responsive lightbox module for drupal Are there any responsive lightbox options for drupal? There are plenty of lightboxes that support fixed widths?

Are there currently any that are designed for mobile in mind?

Lightbox2 Swipe Gestures Support Adds swipe gesture support for Lightbox2. This makes a lot of sense on mobile or responsive pages, because the "Next" an "Prev" Buttons are only visible on hover.

  Adds swipe gesture support to the well known Lightbox2 module for
  mobiles. Just swipe left or right on galleries to show the previous or
  next element!


Public and temporary files error in my "Status Report" I just upgraded to 7.25 from 7.19, and now in my Status Report I have a red X on my "Public Files" and "Temporary Files".

  See http://drupal.org/SA-CORE-2013-003 for information about the
  recommended .htaccess file which should be added to the
  sites/default/files directory to help protect against arbitrary code
  execution.

I go to the address above, but I don't have any user friendly explanation of what to do to fix this. Thanks in advance.

Update: (1/8/14)

The answer below fixes the Public files problem 100%.

It does not fix the Temp files. To fix temp files, I go to admin/config/media/file-system and change the path from /tmp to ../tmp

I will update this if this is fixed in a newer version of drupal, or if there is another fix available. I'm not sure if the ../tmp is the correct solution, but it works.

The easiest method is in the fine print.  If you haven't edited these files, then

browse to admin/config/media/file-system
delete sites/default/files/.htaccess
delete wherever/your/private/files/are/.htaccess as indicated on the page you just browsed to
delete wherever/your/tmp/files/are/.htaccess as indicated on the page you just browsed to
click SAVE

This will recreate the two .htaccess files.  Then visit the status report and double check things.

Otherwise, edit sites/default/files/.htaccess to be

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

and wherever/your/private/files/are/.htaccess and wherever/your/tmp/files/are/.htaccess to be

Deny from all

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Note the difference on line 1 for the private files.  This is what prevents files from being browsed to from the outside world.  It is also beneficial to place your private and tmp file directories outside your DOCROOT if you can, as an added precaution.


emailing users in user reference field with rules I am working on a site for an academic conference. Right now, we have two content types (1) proposal and (2) peer review. In the proposal content type, an author can add multiple presenters to a user reference field. When the node is saved, I have a rule that loops through the user reference field and sends an email notification to all the presenters that the proposal has been submitted. Works great!

Now the question. I want to send an email to that same group of users when someone else posts a peer review. I have figured out how to notify the "author" of the proposal but I want to notify all the users listed in the node reference field.

Right now my rule is set up as follows:
Event: after saving new content
Conditions: content is of type > peer review
Actions: Fetch entity by property:
-Value: node
-Value: node reference
-Data selector: node
Variable label: Fetched proposal
Variable name: fetched_proposal

Then I have a loop:
Data selector: fetched-proposal
Current list item
Variable label: Current proposal item
Variable name: proposal_list_item

Then I have an action to send the mail. Since I've looped over the proposal connected to the peer review, I have available a token for the presenter field which contains the node reference. I've used that token in the "To" value field.

I think this should work but I don't get emails when testing.

When I check my log messages I see this error: The loop Loop () fails the integrity check and cannot be executed. Error: Data selector fetched-proposal: for parameter list is invalid.

Can anyone help me figure this out?

I think you are fetching the user reference wrongly. You should try this:

On the Action:Fetch Entity by ID
Value:User
Data selector :node:field-name:uid (this is your user reference field
Variable label:Fetched entity
Variable name :user_entity

Then you are good to go!


What's wrong in my rule for sending e-mails using VBO? I am trying to send a mail to a set of users when a node is created, so I made a users view including VBO field and a rule for it. You can see the settings below. It's about D7.

But when the rule gets in action, no mails sent and the following messages appear in admin/reports/dblog:

Unable to evaluate loop.
Unable to get variable entitylistem, it is not defined.
Unable to evaluate action views_bulk_operations_action_load_list.
Unable to get a data value. Error: Invalid data value given. Be sure it matches the required data type and format. Value at user():

What is wrong?

Obviously "something" is wrong in what you're trying to get to work. I suggest you enable the typical the Rules debugging (to find more details about what's happening and causing your error), as detailed in "How can I display the value of a variable inside a condition?". If needed, add a copy of the Rules execution log as an update to your question.

Maybe also checkout the tutorial "How to process the results of a VBO enabled view via Rules?".

Plan B

A possible alternative that should work also, is to get the Views Rules module involved in the puzzle you're trying to solve (instead of using VBO). Some details about this module (from its project page):

  Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

Create a view (using Views) so that you have 1 Views result (row) for each user to be eMailed, whereas that view has fields (columns) for each of the fields that you want to use to create your eMail. So your existing view could already be pretty close (if you just remove the VBO field). Important: use a Views display type of "Rules".
Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop".
For each iteration step in your Rules loop, perform a Rules Action to ... euh ... right ... Send an eMail. At that point you'll have all data from each column of your Views results available as so called Rules Parameters. So at that point it's a piece of cake to create an appropriate eMail.
The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). In your case: your existing Rules Event should also be fine. Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Easy, no?

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


What options exist for search result weighting (e.g. promoting same score results higher in the results) I'm impressed with search in core; especially when empowered with the Search Configuration module. However I'm skimming the modules in the search category & not seeing anything that allows for arbitrary result weighting, perhaps the sticky bit could be used for this, but I was looking for something more granular; like a specific content type having a specific taxonomy term would float higher in the results.

Although Search API / Apache Solr Search Integration are popular modules with more flexible control over boosting, the core Search module allows you to add custom scoring via hook_ranking().

There is a code snippet in a comment in the documentation referenced above that at least hints how to do the boosting fpr content types. Boosting on a specific taxonomy term might be a little more tricky because the scoring logic is done in the "score" key, which is effectively a SQL clause. Therefore you have to either get fancy with joining a custom table that has some of your custom scoring logic pre-calculated when the node is indexed, or you will have to add you logic directly in the SQL clause to generate it on the fly. The latter could get messy if you have a lot of conditions.


How do I manually sort articles? I need to know of a way to manually order the articles displayed in the Drupal 8 front page by displaying a title between each piece. For example,

Title A

Article 2
Article 5
Article 3

Title B

Article 1
Article 7

I've tried configuring the front page view and looked into the Drupal 8 article and basic page settings but couldn't determine an effective way by which the above could be achieved. I also looked into whether there are any featured content modules available to suit my above needs but couldn't find any. And also the content needs to be able to be added to any page (not just the front page) as well.

If you anyone could point me in the right direction it would be greatly appreciated

Title a,Title b could be terms of a vocabulary
add this vocabulary as term reference to article
edit your nodes to include desired term
modify front page view to group by term on this vocabulary

to have specific sorting for each of the term articles you can add integer field position to article and use it as sorting criteria in the view

for ordering the terms sort them in the vocabulary term list and use term weight as sorting criteria on view

For sorting one could also use draggable views  and even nodequeue as suggested in the comments


Drupal + Moodle SingleSignOn logout issues Does anyone know how to set cookie_domain to use an IP-Address and not a domain name?

I recently put together a SSO solution between Drupal and Moodle. Drupal is acting as the users repository with Moodle as a subdirectory.

To get the sso working I'm using the moodle-sso module to good effect.

The only problem is that logging out of moodle does not log a user out of drupal.

After much googling, I found articles indicating cookies are the key to solving this problem.

I attempted following moodle-sso cookie_domain instructions but then I can't log into my site anymore because I access my dev site via IP address and not a domain name.

I set cookie_domain as follows: $cookie_domain = 'http://128.79.128.44/drupal-site';

The project structure is http://128.79.128.44/drupal-site/moodle.

Any help is appreciated.

UPDATE:

I added the following data to my /etc/hosts file on my Linode server:

128.79.128.44/drupal-site/ dev.drupalsite.com.

When I visit dev.drupalsite.com I receive the following error:

Forbidden

You don't have permission to access / on this server.

Clearly, dev.drupalsite.com is not a globally recognised URL but how do I use it to access my website on a LIVE Linode server?

$cookie_domain can only be set to a domain that you want the Set-Cookie header to specify. This doesn't include protocol or path, just the domain with a leading dot (e.g. ".example.com"). If you leave $cookie_domain commented out, the browser will default to the domain that you requested it on.

If you need to access a Drupal site by IP when its cookie is set to another domain, you can create a subdomain on your hosts file that maps to the IP.

128.79.128.44 dev.example.com

Once that's saved to your hosts file, you should be able to browse to http://dev.example.com/ and have your web browser send the relevant cookies (assuming the cookies of domain are set to "example.com").


In the Aggregator module, limit number of items per feed I am using the Aggregator module in Drupal 8 to combine several RSS feeds, but I would like to set a limit on the number of items that are shown from any one feed. How can I accomplish this?

This might not be the right way to do it but I solved this by using template_preprocess_aggregator_feed(&$variables) and then slice the items using array_slice().

My items were stored at $variables['content']['items'] but there were two other hashtag variables stored in the beginning of the array so I had to add that to the total count.

function template_preprocess_aggregator_feed(&$variables) {
  $number_of_items = 5;
  $variables['content']['items'] = array_slice($variables['content']['items'],0,2 + $number_of_items);
}


Hook form alter not firing on a custom form that does exist I have a hook form alter function that is not recognizing or firing on a form that clearly does exist on the page. And i’ve tested this function against the Drupal built in form with the id of ‘search_block_form’.
In my template.php file i have this code.

function mytheme_form_alter(&$form, &$form_state, $form_id){
if($form_id == 'search_block_form'){

    echo '<script>alert("whatup?");</script>'; /* for testing purposes */
    drupal_add_library('system', 'ui.accordion');

    $form['search_block_form']['#attributes']['placeholder'] = t('enter burp search terms...');
    }

if($form_id == 'views-exposed-form-browse-albums-page') {
    echo '<script>alert("whatup beeatch?");</script>'; /* for testing purposes */
    drupal_add_library('system', 'ui.accordion');
}

}

As a test first IF statement alters the default Drupal search whose id is  ‘search_block_form’. This part does run and is working.

The second IF statement tests for my custom views form but does not run at all. The form does clearly exist (see attached). I’m stumped at this point and don’t know what to do next. Why is the second IF statement not running?

Before Drupal 8, the form ID is also the name of the PHP function that builds the form itself (or an ID contained in the array Drupal gets from a hook_forms() implementation).
As such, it can only contains those characters a PHP function name can contain. Underscores are allowed, but not so dashes; dashes are used in HTML. The correct form ID is the one with underscores.


Using "access callback" and "access arguments" provided with hook_permission how can I check user's access first based on some permission and if user passed this check then execute access callback function with some parameters in path, some thing like this:

$items['order/add/%node'] = array(
  'title' => 'Place new order',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('order_add_form', 2),
  'access callback' => 'order_add_access',
  'access arguments' => array('place order', 2),
  'type' => MENU_LOCAL_TASK,
  'file path' => drupal_get_path('module', 'order'),
  'file' => 'order.page.inc',
);

Not sure exactly what you mean there but your code already has a custom access callback specified as well as access arguments?

You could have an access callback like this:

/**
 * Add order access callback
 */
function order_add_access($op, $node){

 switch ($op) {
   case 'place order':
   // Return true, if logged in user has administer nodes permission
   // and node status is published.
   if (user_access('administer nodes') && $node->status == 1) {
     return TRUE;
   }
   break;
 }
 return FALSE; // default

}


Drush upwd Changes Database Hash but Login Fails I have a weird one. I have a site that was abandoned for a while and we need to get access to it again. So I tried to use drush to reset the admin password, but it's not working.

I'm using Drush 8.1.17 on what I presume is a Drupal 7.57 site (because of the CHANGELOG.txt file in the docroot).

Syntax for my command is like:
php drush.phar upwd fakeadmin --password="examplepassword123"

I get a message Changed password for fakeadmin success and because I'm literally looking at the users table in my database I can see the hash change in the password field. Yet, when I copy the text 'examplepassword123' (without single quotes) into my login page, it does nothing.

Am I just messing up the Drush 8 syntax? (I'm already more used to Drush 9). What would cause it to not work?

EDIT: Drush just uses whatever DB credentials are in the standard sites/default/settings.php file correct? So if that's correct, then I should be working with the right database. No?

EDIT 2:

1) I tried it without the double quote just in case and that didn't work either.

2) I also tried running the script /scripts/password-hash.sh "examplepassword123" and copied the resulting hash into my database, and nothing happened. (found reading through this: https://www.drupal.org/node/992400)

3) I would almost say I'm using the wrong database at this point except that with another drush command I was able to see it add a new user_role row in an attempt to make another user we have access to an admin. Ideas?

EDIT: Well this was disappointing and weird. Drush was somehow changing the hash but not the password? An employee of ghosts past somehow had it saved on their hard drive, and gave me the password, and it was the same as before. I'm not going to question it....

Check to see if your cookies are being set correctly. It's possible that your login is succeeding, but if the session cookie is not set, then you will be immediately logged out again (or, more to the point, the browser won't get the message about you being logged in and will continue to present an anonymous user to your site).

Check your settings.php file and see if you have any configuration options related to the cookie domain that are not correct.


Twig string variable changing to int(0) I have twig variables inside an array called social_media that contain colors.
When I perform {{ dump(social_media) }} I can see all the information like so

array(10) {
["facebook"]=> string(39) "https://www.facebook.com/myfacebook/"
["facebook-color"]=> string(7) "#2d5f9d"
["twitter"]=> string(33) "https://twitter.com/mytwitter"
["twitter-color”] => string(7) "#51acef"
["youtube"]=> string(56) "https://www.youtube.com/channel/myyoutube"
["youtube-color"]=> string(7) "#e52d27"
["instagram"]=> string(35) "https://instagram.com/myinstagram"
["instagram-color"]=> string(7) "#f77737"
["linkedin"]=> string(83) "https://www.linkedin.com/company/mylinkedin"
["linkedin-color"]=> string(7) "#0077b5"
}

Performing {{ social_media.facebook }} works fine like so

https://www.facebook.com/myfacebook/

but {{ social_media.facebook-color }} outputs

int(0)

In fact every single color variable outputs this same value, while the others work fine. I considered the possibility that the # was causing a problem, but changing the colors to colors like 'Black' or 'Red' as a test, but I received the same outcome. I even tried using

{{ social_media.facebook-color|raw }}

But that did not have any effect. What could possibly cause some of my twig variables to only output int(0) while others output just fine?

It turns out that twig can't handle hyphens in their variable names.
Changing the variable names from

{{ social_media.facebook-color }}

to

{{ social_media.facebook_color }}

resolved the issue


Notifications from Workbench included content type I added a new content type for my drupal 7 site and I have a form in this content type. It has the workbench enabled in this form so that the moderator can approve the submissions and close the forms if they are complete.

The functionality that I am looking to implement now is mailing the user upon the status change of the form. i.e, if the form changes from draft to closed, the user should be notified. I looked for modules or related content for implementing this, but could not find any. What is the best way to do this? Please let me know.

Thanks in advance.

You can do this with the Rules module: http://drupal.org/project/rules

It should be pretty straightforward, once you figure out how to use Rules. (You can find some video tutorials here: http://drupalize.me/videos/basics-rules-link)

Basically, you are going to create a rule that is triggered when a node's workbench moderation state changes. When the rule runs, it will send an email. In that email, you should be able to include tokens (http://drupal.org/project/token) that will be specific to the node that was just changed.

Hope that helps.


How to delete cache after updating/deleting/adding new content using hooks? We have a custom services module and a site in Drupal 7, and I got the task to delete the cache after the editor adds new content or update the existing ones.

I've read about a module called Cache Actions, but, as i said, i need to create the function on my custom module.

Also, I've started reading about Drupal hooks, but still don't have a clue of how to implement this task. Any suggestions? Thanks.

It sounds like you've already got a custom module, but just in case you haven't see the Module Developer's Guide.

The hooks you're looking for are hook_node_insert() and hook_node_update(), and the function to clear the cache will either be cache_clear_all() or drupal_flush_all_caches. The former will let you clear specific cache bins (and even specific cache items), and the latter will clear absolutely everything.

For example:

function MYMODULE_node_insert($node) {
  drupal_flush_all_caches();
}

or to clear only the static page cache after a node has been updated:

function MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid, array('absolute' => TRUE));
  cache_clear_all($nodeurl, 'cache_page');
}


Theming mini panel using MYTHEME_preprocess_panels_pane I'm trying to edit the content of a mini panel using MYTHEME_preprocess_panels_pane but when I use Devel to dsm $variables, I just get data for the pane that holds the mini panel.

Is there a function to get into the mini panel?

At first I thought hook_panels_pane_content_alter might work but I'm getting nothing when I drop it into my template.php

You can get at the content on a mini panel using hook_panels_pane_content_alter.

It needs to be called in a custom module (see https://www.drupal.org/developing/modules/7)


How do I include a JavaScript file and pass the value of a PHP variable with a single function call? I'm trying to pass a PHP variable to my JavaScript file. The file is js/backgroundConfig.js, it's in the theme directory, and this is the content of the file.

(function($, Drupal){
  Drupal.behaviors.backgroundAnimation = {
    attach: function(context, settings) {
      alert(Drupal.settings.variableName);
      alert(Drupal.settings.basePath);
    }
  };
})(jQuery, Drupal);

Drupal.settings.basePath is displayed correctly, but I've no idea how to pass variableName from template.php. I've tried a couple of methods but none of them work.

There are tons of examples on the web but none of them contains the filename and the settings together. Like this one:

drupal_add_js(array('variableName' => 'value'), 'setting');

Alright, but where I should put my filename? I always add my JavaScript file like this.

drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

How do I combine it together?

How to combine it togather?

You don't - Javascript files and settings are two completely different things. Anything you add to the settings will be available on the global Drupal object, which will be available by the time the code in your JS file is invoked.

Your code should be:

drupal_add_js(array('variableName' => 'value'), 'setting');
drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

Or the other way round, it really doesn't matter.


How can I log in as any given user with Drush? How do you login to a Drupal site if you do not have the password of the admin user or user 1 but still have access to the command line? Can I use Drush to log in to the Drupal site?

You can log in to any Drupal site if you have access to the command line and Drush, knowing either the username

$ drush uli username --no-browser

OR the user ID.

$ drush uli --uid 123 --no-browser

This will return you an URL that you can copy paste into your browser address bar and login as that user. You can leave out the --no-browser option when you want the command to directly launch the browser.


Show menu link as expanded when on node pages for a content type? I need to show a menu link as expanded when you are on the node page of a certain content type.

These nodes don't actually have menu link but are navigated to, through a menu link and taxonomy terms.

Menu Trail By Path modules does this is the node's paths are children of the parent.
http://drupal.org/project/menu_trail_by_path


How do I create individual fields on a node? I would like to use individual Taxonomy fields on a node - not a preconfigured Content Type. e.g.

Color: Red
Year: 2015
Project details: Short description.

This is just working fine with the Core Field Module. The downside of it is that it's preconfigured on the Content Type. Users can’t add more fields to a node. I need more flexibility. E.g: Thus, I am using a text field with unlimited Number of values.

Example with Core Text Fields

However I am missing Taxonomy’s term reference feature: People have to type in all data on every node. I hope this makes sense. I’ve created a quick mockup to show what I am looking for. I would love to define individual description and Taxonomy terms.

What’s the best way to get full flexibility?

Have a look at my answer to "How to add new data to a predefined list?", which describes what you can do with the Select (or other) module.

In your case, you could use that module also to define 2 fields, which I'd label something like so (or anything else you'd prefer):

Attribute (with values like Material, Color, Year, ...).
Value (with values like Plastic, Red, 2015, ...).

Obviously, if "I" would then want to add like "Taste = Sweet", I'd just have to add "Taste" to the 1st field, and "Sweet" to the 2nd field.

Sweet enough?


How to theme each field of exposed filter from Views? I have found the theme template for exposed filter form of view.
Template name: views-exposed-form.tpl.php

Inside the template I found the $widgets array and for loop for each $widget display in form.

But it is rendered HTML widget How can I get only values array for each combo box to render output for my combo box as I want?

for instance:

I have one combo called Country:
Country has hierarchy level of list

Asia
- India
- Sri lanka
- thailand
- Indonesia

etc...

So, I would like to make my combo just like this

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

This will identify the parent / child category in combo?
can we do this directly in drupal 7 Views for Expoesd Filters Combo ?
or
How can I theme myself to override its HTML?

You can try to catch it with hook_form_alter(): $form_id is views_exposed_form, and $form contains all the values.

$form['field_custom']['#options'] = array(
  'group1' => array('key11' => 'value11', 'key12' => 'value12'),
  'group2' => array('key21' => 'value21', 'key22' => 'value22' ),
);


Display Suite code field – how to use another image field conditionally In my content type I want to show the main image if the thumbnail field is empty. So I use the Display Suite code field and I enter the following code:

<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    print_r('Thumbnail missing');
    // What code to put here to enable or render another image field
}
?>

When the tumbnail is missing the above code works, but instead of text I want to display another image field, when the thumbnail is missing. I have tried everything I can think of, but the main image dose not show :-(.

It's because you have nothing in renderable format yet.

Look at function field_view_field

  Returns a renderable array for the value of a single field in an
  entity.

Then change your code like this:

<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    $renderable = field_view_field('node',$entity,'field_main_image',array('settings' => array('image_style' => 'thumbnail')));
    print drupal_render($renderable );
}
?>

Note that this is not the only way to get html from field values. You can use theme functions and load that with values you find on $entity object and print that if you wish.


Print image backgrounds and colors from views and blocks I have a problem printing background images and bgd colors in html in views and custom blocks.
For example, when I add HTML code with CSS classes into a custom block (class has bgd image or bgd color style) it is shown on the html page in browser, but not in print preview (print backgrounds is off). Same thing is with the custom html code defined for view field (I created a link field and rewrite output)

Normally HTML code, defined out of blocks and views is, showing both bgd colors and images in print preview even if print background option is turned off in browser.
All CSS styles are defined in one file.

For some reason browser is not reading CSS styles within blocks and views.

Sorry if I haven't understood correctly, but it sounds like you're asking why backgrounds aren't printed when 'Print Backgrounds' is off?

That's a browser setting and is down to the user. If that option is disabled, background images and colours should not be printed as far as I'm aware. So what you're seeing is the correct/expected behaviour.

For webkit browsers you can try -webkit-print-color-adjust with the exact setting, i.e.

-webkit-print-color-adjust: exact;

That should force the background to be printed for the element regardless of the user's setting

  Background colors and images of the element to which this rule is applied are always printed, user's print settings are overridden.


How do I alter the output of an existing views handler? How do I alter the output of an existing views handler?

I want to alter views_handler_field_user_picture() to get the link to the user profile, not the themed picture.

See alter existing handlers (handler overrides). I expect a link like this http://cdn.sstatic.net/drupal/img/logo.png.

function mymodule_views_data_alter(&$data) {
  $data['users']['picture']['field']['handler'] = 'my_custom_handler';
}

module .info

files[] = user_picture_formatter.inc

and user_picture_formatter.inc is like this

<?php
class my_custom_handler extends views_handler_field_user_picture {
  function render($values) {
    if ($picture_fid = $this->get_value($values)) {
      $picture = file_load($picture_fid);
      $picture_filepath = $picture->uri;
    }
    else {
      $picture_filepath = variable_get('user_picture_default', '');
    }
    return $picture_filepath;
  }
}
?>

The short answer is that you can't alter the output of a views handler. But what you can do is:

Create your own handler that is a subclass the handler you want to overwrite.
Add a render method - which will generate the output (this is where your alter code is)
Use hook_views_data_alter to make views use your handler instead where needed.

This will get the wanted effect, where you can alter the output of the original views handler, but in reality to make views use your custom handler.

In code it could look something like this.

class my_custom_handler extends views_handler_field_user_picture {
  function render($values) {
    ...
  }
}

function my_module_views_data_alter(&$data) {
  $data[...]['handler'] = 'my_custom_handler';
}

This code is for Drupal 7, but the method can be used in both Drupal 6 and 7. For Drupal 7 you should create the class in it's own file and add the file to the module's .info file, to make Drupal autoload the file with the class when needed.


how can i get a menu of a parent taxonomy term? I know menus can be made of taxonomies, with taxonomy menu.

But the real huge problem i have is I CANT get taxonomy menu to show only one term's children in the taxonomy list.For example consider this taxonomy vocabulary:

creatures
-insects
--ants
--mosquitoes
-mammals
--rabit
--dog

I want the taxonomy menu to show only mammals links, how can i do that?

If your output should be a block or page, you could do it with Views.
If not, meaning you want to show only that part as a menu itself, you might want to consider writing your own query for it, and adding it as a hook in your template.php


views_embed_view not working with multiple values argument I'm trying to embed views like this:

 views_embed_view('articles_list', 'block_1', '11+13');

If I type 11 in arguments, it does take the argument. It works good if I preview the view and enter '11+13' in "Preview with contextual filters" field... But if I write '11+13' in the views_embed_view() function, it just takes the value of 11. How can I make it work and take both values: 11 and 13?

From views_embed_view doc comment block:

  @param ...

  Any additional parameters will be passed as arguments.

That means any params comes after params $name and $display_id will consider as contextual filer so you should call views_embed_view like:

views_embed_view('articles_list', 'block_1', '11', '13');

Take a look at Twig Views Module do the same.


find all users of a certain role and return that list I am trying to turn this query to drupal EntityCondition query

select u.name, ',', u.mail, ',', r.name , ','
from users as u, users_roles as ur, role as r
where u.uid = ur.uid
and ur.rid = r.rid

This should return a list of all users with their email username and user role

I have this

  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'user')
    ->addTag('role_filter');
  $results = $query2->execute();

So getting all users within a specific role id

function mymodule_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->leftJoin('users_roles', 'r', 'users.uid = r.uid');
  $and = db_and()
            ->condition('r.rid', array(3,4,5), 'IN');
  $query
    ->condition($and);
}

I am not sure how to get the role value based on what I have
is it another entity condition?

The above entityFiledQuery does return the following

{"1":{"uid":"1","name":"admin","pass":"HASHPASSWORD!","mail":"admin@example.com" "roles":{"2":"authenticated user","3":"administrator"},

but
a) I would rather have roles as the value administrator and not this funky array with the "rid" key
b) the hashed password is there, can data be sanitized ?

The name of the role is in the role table so just join that in as well:

function mymodule_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', 'administrator');
}

Note that you want inner joins here, not left, otherwise you'll just get whether they have the admin role or not. You don't need an and as you only have one condition.

The hashed password is added by user_load, not your query, so you'd have to address that separately. I'm not sure there's an easy way to exclude a property from an entity load, it would make for a good follow-up question.


Webform emails threading I have a client Webform and I use a custom template for delivering the submissions to the Gmail inbox. I've set the sender's email to the component e-mail field.

The problem is that Gmail puts all the received emails into one thread as if though the sender is the same for all the emails. So it becomes impossible to manage the clients emails as everything is being mixed up.

Is it a Webform configuration or am I missing something?

This isn't really a Drupal question. Go to https://mail.google.com/mail/#settings/general and look at the Conversation View. This sets whether emails of the same topic are grouped together. So they aren't grouped together based on the from: address but on the title. Just set it to Conversation view off and save the settings.

Alternatively, make the subject of the mail unique. For example by adding the name or email address to it, or a unique key.


How to get user by uid in views_php? i am using the views_php module and i need to get the user by his uid to read out some properties to build a filter. (It is not the currently logged-in user!).
Is there some drupal function like this ?

$myuser = drupal_get_user_by_uid(uid);

The answer is :

$user=user_load($uid);
$username=$user->name;


Best practice for displaying multiple views in a single page I am working on a Drupal 7 website where there are many pages which utilize multiple views.

The way I am doing this right now is by creating a page from Drupal admin panel, and in the edit mode of that page I am calling views_embed_view to display those multiple views.

Other ways I could do this is by creating a template for that page, and putting my code inside the template.

Yet another way is to use View Fields View (https://drupal.org/project/views_field_view) and embed the second view inside the first one.

I want to know, performance wise which is the best practice?

You can try panels to display multiple views on a single page:

  The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Panels includes a pluggable caching mechanism, so it could be a good and easy option for you.


In the File Entity module, what is the purpose of multiple "Enabled displays" and "Display precedence order" for a single display mode? In the File Entity module, what is the purpose of multiple enabled displays and Display precedence order for a single display mode? Or what is the use case where I would need to provide multiple ones and define precedence of one over another?

There is little to no documentation on File Entity (understandably as it is still under heavy development), and I am trying to wrap my head around it a bit more. I just can't think of a use-case where I would need more than one "display" for a single "display mode", where the first would not "validate" and therefore look at subsequent ones that are defined.

I just can't think of a use-case where I would need more than one "display" for a single "display mode", where the first would not "validate" and therefore look at subsequent ones that are defined.

It's not a feature that I expect it used very much, but that is exactly the purpose.

An example, where one looks at the user agent, could be:

Let's say you're showing a video, a video player is your primary option.

Then there's a user agent that you recognize as a screen reader. Suddenly, showing video doesn't make sense. However, the audio still does, so you fall through the first option, to your second, which is an audio player, that only pulls in the audio stream, significantly reducing the bandwidth usage for both server and client.

Finally, a really low powered mobile device comes along, and then you simply default to displaying an image of the videos first frame, together with a link "Mail me this video", making it convenient for the user to find the video again when using a more powerful computer.


date_popup + theme = infinite loop I'm trying to create a templated form including date_popup field in a custom module. There is a very basic example : mkl_variousTest.module ( dependency : date_popup from date API )

<?php

//mkl_variousTest.module

/**
 * Implementation of hook_menu()
 * @return array
 */
function mkl_variousTest_menu() {
  $items = array();

  $items['testFormTemplate'] = array(
    'title' => t('Test form template'),
    'page callback' => 'mkl_variousTest_form_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Implementation of hook_theme($existing, $type, $theme, $path)
 * @param array $existing
 * @param string $type
 * @param string $theme
 * @param string $path
 * @return array
 */
function mkl_variousTest_theme($existing, $type, $theme, $path) {
  $themes = array();

  $themes['formPage'] = array(
    'template' => 'mkl_variousTest_formPage',
    'path' => drupal_get_path('module', 'mkl_variousTest') . '/templates',
    'variables' => array(
      'form' => drupal_get_form('mkl_variousTest_form'),
    ),
  );

  return $themes;
}

/**
 * Implementation of hook_form($form, &$formState)
 * @param node $node
 * @param array $formState
 * @return array
 */
function mkl_variousTest_form($node, &$formState) {
  $form = array();

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Nom'),
    '#lenght' => 60,
    '#required' => TRUE,
  );

  $form['date'] = array(
    '#type' => 'date_popup',
    '#title' => t('date'),
  );

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

  return $form;
}

function mkl_variousTest_form_page() {
  return theme('formPage');
}

?>

Using this way, drupal run in an infinite loop and return this error :

  Fatal error: Maximum function nesting level of '100' reached,
  aborting!

There is a printScreen :

Next, the same function calls between #19 to #37 are repeated until drupal stop the loop.
This append as soon as I have a date_popup field in my form.

So how can I fix it ?

PS : This is my template file mkl_variousTest_formPage.tpl.php :

before

<?php print drupal_render_children($form); ?>

after

Stab in the dark, but I think your problem is probably stemming from the fact that you're building the form from within a theme function, which in turn calls another theme function, then so on and so forth. Logically theming should be after you've built the form.

Replace drupal_get_form('mkl_variousTest_form') in hook_theme() to NULL and in your page callback add the following code.

$form = drupal_get_form('mkl_variousTest_form');
return theme('formPage', array('form' => $form));


Language links shown enabled for pre-translated nodes The current snapshot below is of a node which was edited before I installed i18n. So when I go to edit that node "Translate" tab does not appear.

I've many nodes like this. The problem in such nodes is that in the language switcher block, all languages are shown enabled even though translations aren't available.

What is the solution? Should I simply resave such nodes created before i18n was installed?

So in this current snapshot, all non-English languages should have been shown as striked as I've not enabled translation for this node.

Manually saving those pre-existing nodes does it. Untranslated languages are shown striked out.


Is it possible to hook_form_alter by path? I have a basic hook_form_alter working but the issue is I cannot do it by form id as the id might be different in various environments, i.e. local, dev, production. So the usual method of altering by targeting a form ID is not ideal then.

I figured I could do this by path (as that won't change) but none of the usual methods work. I'd like to keep this in code so that's why I'm not simply changing the UI for this setting.

Here's my basic alter which works:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
}

However, if I do this, it does not work:

function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'];
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}

I'm guessing what I'm trying to do is not even possible and therefore I'll try to figure out a different method.

I think you should use  $_SERVER['HTTP_HOST'] . request_uri();

This will give you the complete path.

So your code should be

function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'] . request_uri();
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}


Replacement Tokens in View Template I have several fields in my view:

Path (excluded from display)
Image
Body
Button (rewritten to use [path])

I need to output the image like so (this is a requirement):

TITLE

I cannot do this using rewrite rules because of  https://www.drupal.org/node/417956 which explains that views runs all rewrites through filter_xss_admin(). This function strips out the style attribute on the a tag.

I am attempting to implement this in a view template, specifically the Field Content: Image (ID: Image) template:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<a href='/' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

I have tried this, [path] remains unchanged:

<a href='[path]' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

and this, [path] remains unchanged:

<a href='<?php print token_replace("[path]", array('node' => $row->_field_data['nid']['entity'])); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

I cannot find the value of the path anywhere in any of the variables. How can I output the value of [path] in my view template?

Can you get the node id you are aiming for? If so, try using drupal_get_path_alias()

$linknid = $fields['field_link_to_content']->content;

$alias = drupal_get_path_alias('node/' . $linknid);

<a href='<?php print $alias; ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

UPDATE - this is how I did it, based on this answer:

<a href='<?php print drupal_get_path_alias('node/' . $row->nid); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>


using panels to create custom page for all blogs I used panels to create static or landing pages, but now I'm wondering if it would be possible and how to create a custom page template for all blogs using panels, so a user would simply have to write a blog and not have to fuss without creating a specific panel variant for every blog page that is created.

thanks,

Chad

If you enable the pre-provided page named node_view, it does exactly what you ask for. It loads any (and every) node then.

You can add what's called selection rules to limit to to certain content types, or based on other arbitrary conditions.


How to show Personal reading rate? I use view & seen module make a bulletin .

How can I survey user "reading rate", I want to know:

if everyone read every article, or
which article specific person do not read yet.

Any help?

Using the Flag module seems like a no brainer to me to get this to work. Combine it with the Rules module to have a custom (not global) flag automatically flag such article, based on whatever rules Event that would fit. And since Flags are fieldable, you could even add an extra field to it to let your user indicate some type of rating, if that's what you want.


Displaying all fields of a custom content I have a page.tpl.php ; where I want to display inside a
 in it the fields of a custom content I've created before :

1)The custom content is called "Slider"

2)It have a field I've added called image (Machine name :"field_image_slider")

I've tried this code but it didn't works :

    <?php
        if (!empty($node)) :
           $fieldImage = field_get_items('node', $node, 'field_image_slider');
           print var_dump($node); //to check the fields
           foreach ($node->field_image_slider['und'] as $item) {
              $val=$item['uri'];
              print '

Hi

';
           }
        endif;
    ?>

I've spent 3 days figuring how to solve this problem , any help would be extremely appreciated .

I think you use wrong theme template. This way you need use node.tpl.php and  exactly is node--slider.tpl.php. You can see template suggestions. Or you don't want use node template i think better you can use hook_preprocess_page()

function YOURTHEME_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $node = $vars['node'];
    $field_images = field_get_items('node', $node, 'field_image_slider');
    //dpm($field_images);
    if (!empty($field_images)) {
      $output = '';
      foreach ($field_images as $key => $images) {
        $output .= '

Hi

';
      }
      $vars['slider'] = $output;
    }
  }
}

and in page.tpl.php

<?php if(isset($slider)): ?>
  <?php print $slider; ?>
<?php endif; ?>


Drupal 7 Can't add date sort criteria I have a view that display a list of nodes of a content type that has a date field.
I'm trying to add a sort criteria based on this data field, I can select it but hust after that I get returned to the main views screen, without the data sort.

I know that data fields are sortable so where can I have more informations about "why" this field is not added to sort criteria?

It will avialable in Format -> Settings -> Check 'Stortable' Check box


Assigning a role based on signup url on a Drupal 7 site? I need to give out a URL that will grant people who sign up at that URL a specific role. If possible I would like to also have the user fill out profile fields as part of user registration.

I think the Profile 2 module does something like this, but this is already set up with normal Drupal fields, is there any way to make this work?

You can do it with Auto Assign Role module, It provide paths that will trigger a specific role when an account is created.

  The Auto Assign Role serves three primary purposes. The first is to
  provide an automatic assignment of roles when a new account is
  created. The second is to allow the end user the option of choosing
  their own role or roles when they create their account. The third is
  to provide paths that will trigger a specific role when an account is
  created. The administrator has full control over these functions and
  can have them working together or independently of each other. Auto
  Assign Role is integrated with the Content Profile module so that you
  can have content types serving as registration pages. You can even
  replace the default user/register page with a customized version of
  your own design.


Unique Identifier of Every Drupal User Instance I've been developing a custom module in my drupal system. One user account can be simultaneously access in different computer/browser. For example:

Username: ghlatorre
Computers accessing my system/module using the username ghlatorre: Computers 1, 2, 3, 4, 5

Is there a unique identifier I could use to differentiate these different system user instances?

If you want to uniquely identify browsers, Drupal tracks browser sessions via the sid & ssid column in its sessions table.

If you're looking to uniquely identify computers, you could try the IP address manager module.

  IP address manager records user IP addresses, and allows admins to
  view which IP addresses have been tracked against a user, and which
  users have been known to use a certain IP address. This can be
  currently used to identify duplicate accounts.

  The aim of this module is to provide a way to identify a user when
  they are not logged in to provide some action or context to their
  presence by maintaining lists of users for some purpose - such as, but
  not limited to, banning them.

The caveats with this approach is, depending on the network setup between the client & host, you might get false duplicate IP addresses for users (e.g. a home network router using NAT).


One view to do everything or a different view per page? If I need to display the last 10 nodes created on my front page regardless of content type and need to do the same in my sub-pages but need to filter by specific content type, is it easier to create several different views or to create one view that does all of that? If I need to create one view, how would I restrict different pages to specific content types?

Personally, I create a view per content type and set up decent defaults and then have displays to handle the different uses.  Special pages and other one offs (like the home page in your case) have specific views.

I find this approach better handles changes that may come down the line.


How do I implement a reverse node reference using References? Using the References module (D7 version), implementing a new field in an article content type for node reference was very easy, but now I cannot seem to figure out how to discern the reverse reference. Just as there is a link shown in my article to the node I have selected in the node reference drop down, I am expecting that on the "linked to" article, I should be able to see a link back to the first article. Has anybody done this? My understanding is that it is part of the D7 version of this module.

You can use https://www.drupal.org/project/cer
You can then setup the reference both ways so when you add a reference on the first piece of content CER can add the back reference to the other piece of content.
Another option is to add a rule which will do this for you but CER is pretty solid when dealing with larger sites.


How to prevent Profile2 fields from loading on user registration? I have a profile2 Profile that's named Driver.
This profile has a Term reference to a vocabulary named Cities that contains over 30.000 terms.

I made a custom user-register.tpl.php by declaring it in my template.php, and in here I display only the form keys that interests me for the account creation.
When I go to driver/register which is the custom page for registering to my profile type, the loading is taking too much time, and I suspect it to be caused by the loading of all the fields of my profile (even those non-rendered) and more especially that vast vocabulary.

I looked into profile2 folders and files trying to comment parts related to the registration but nothing would prevent the loading from happening.
I also tried to unset($form[profile_driver]) in my theme_form_user_register_alter, but it doesn't affect the fact that the profile fields are still loaded before being removed from $form, so I figured it has to be directly in profile2.

Been struggling for quite some days now so if anyone has clues on how to prevent the loading of the whole profile form or ideally specific fields I would be glad to read how to do the trick !
Thanks

7.x-1.4

FINAL EDIT :

I didn't manage to do it programmatically so I ended up setting up a Rule that assigns the Profile & the role to the newly saved user.

Been struggling for quite some days now so if anyone has clues on how
  to prevent the loading of the whole profile form

Looks to me that the magic happens in profile2.module from line 436 to 460

/**
 * Implements hook_form_FORM_ID_alter() for the registration form.
 */
function profile2_form_user_register_form_alter(&$form, &$form_state) {
  foreach (profile2_get_types() as $type_name => $profile_type) {
    if (!empty($profile_type->data['registration'])) {
      if (empty($form_state['profiles'][$type_name])) {
        $form_state['profiles'][$type_name] = profile2_create(array('type' => $type_name));
      }
    }
  }

  // If we have profiles to attach to the registration form - then do it.
  if (!empty($form_state['profiles'])) {
    profile2_attach_form($form, $form_state);

    // Wrap each profile form in a fieldset.
    foreach ($form_state['profiles'] as $type_name => $profile_type) {
      $form['profile_' . $type_name] += array(
        '#type' => 'fieldset',
        '#title' => check_plain($profile_type->getTranslation('label')),
      );
    }
  }
}

Usually I would never hack a contrib module directly, but unfortunately here there is no other option considering you have a profile field that loads 30,000 terms. So comment this out and flush/clear cache.

Just remember if there is ever an update to this module, it will override your changes, so you will have to comment it out again then.


Drupal 6 and file upload problems We have an old site running Drupal 6. When we try to upload a file via the interface, the ajax uploader spins, and reloads the "Choose file" dialogue.
Checking the recent error log I get:

The file upload failed: field_small_banner_0

If I go into the location URL (?q=filefield/ahah/gallery/field_gallery_image/0) I get:

{ "data": "\x3cdiv class=\"messages error\"\x3e\nAn unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (64 MB) that this server supports.\x3c/div\x3e\n" }

I've seen mentions of ModSecurity but this is not active. I've checked the permissions of the files folder and this is 777.

I've checked phpinfo for the temp folder and that's set to /tmp

Many thanks :)

How big is the file? The error msg says you likely exceeded the 64MB limit. Can you upload a 1MB file?

If you can upload a 1MB file, then your solution is going to be to increase the server limits on max upload size (see your php.ini file) to allow files of the required size to be uploaded.


how do you restrict directory path to role? How would you go about restricting a specific directory path to a role?

www.example.com/example1/example3/example4

How do you restrict role access to the directory example1 so that example3 and 4 are restricted automatically?

Thanks!

This depends on what that path is? Drupal has many kinds of paths and default permissions out of the box. If this was a Book hierarchy default permissions exist for books. The same for Taxonomy terms and other types of content. If this was a Views based path, you could configure Access rules in your view.

Without any 3rd party module support I would look at hook_menu if you are defining these paths yourself or hook_menu_alter if they are provided by another module.

Drupal Roles are not a reliable way to deem access to content -- I would alter the access callback for this path to use user_access permission values and create a custom permission such as view my custom site area and give that permission to  desired roles. Then I would an access arguments of view my custom site area so the user_access check works on those paths.

The Workbench Access module can do what you're asking if you define the Access rules using the Menu Scheme and not Taxonomies, but this module only works for Nodes last I checked.

  Workbench Access provide the hierarchical permissions across
  "Sections" of your web site. You can use menus, taxonomy, or create
  your own hierarchical structure for controlling access to a piece of
  content.


Does the drush up command work on multisite? I have to update all sites on a D7 multi-site installation. I normally deal with single installation and I use drush up to update the core, modules and db. I have no prior experience with a multi-site installations.

I read this article on how to install drush for multi-site but I would like to know if running drush -l mysite1.com up will actually work before running it.

Kindly help if you have prior experience in this matter. Thank you.

Yes!  But maybe no!  Be careful!

If you run pm-updatecode on any code in a given Drupal site, it is necessary to run updatedb afterwards in order to make the database schema(s) match the current schema in code.  So, while drush -l mysite1.com will in fact correctly run pm-updatecode followed by updatedb on mysite1, if you have any modules in sites/all/modules that is updated, or if Drupal core is updated, then you will also need to run updatedb on every other site in the multisite install.  If you skip this step, then mysite1 will work, but you might break the other sites in the multisite install.

When dealing with a multisite installation, the safest policy is:

Copy live to dev
Run pm-updatecode on every site in the multisite on dev
Run updatedb on every site in the multisite on dev
Test!  Test!  Test!
Take all of the sites in the multisite offline on production
Push your updated code from all multisites on dev to production
Run updatedb on every site in the multisite on production
Test again!
Bring all of the sites back online

You can avoid doing all sites at once if you know that all of your updated modules are in sites/mysite1/modules, and Drupal core is not updated.  In general, though, it is better to avoid multisite installs so that you do not need to worry about the interdependence of the shared code on multiple databases.


Redirect a view page to another view page with arguments in the url I have a custom view with button in the main tab placed in the local_task tab bar area (Outcomes). I have sub local_task navigation items under that as well that are regular drupal views. (See below)

View | Edit | Outcomes
                     Outcomes Viewer | Custom View | Another Drupal View

When you click on Outcomes you are taken to the Custom View tab or the Default for that custom view. However I want to redirect the Outcomes tab to go to the Outcomes Viewer tab. The Custom View tab is the /default for the menu, so it is s separate link and should work.

However, you can not use /%/ in a redirect. Does anyone have any ideas on how to do this. I have tried the basics but am lost on how to make it work.

Thanks!

So, solving this took a few different directions to figure this one out.
The problem was I needed to redirect a view with an argument in the url (node/%/outcomes) to a new sub-button so there was an actual button. (Yes this is also a UX issue that the user needed to have the button)

So, I created a new panel page and in the content area I created new custom content. I used the module, php filter, this way I can use the PHP input for the wysiwyg. Then I pasted this code to redirect.

global $base_url;
header("Location: %node/:nid");

That redirected and kept the argument so everything would work fine.
Hope that helps someone!


How to make a whole block clickable? I'm trying to make a little block that links to the logged-in user's profile. I've already created a view block with the necessary information, but I don't know how to make it clickable and link it to the user's profile.

How can I achieve this?

Edit: One can find some more details about the code that fixed this problem at https://stackoverflow.com/questions/23552893/how-to-create-a-clickable-block.

Here's a possible solution. In your view, exclude all fields add field 'Global: Custom text'. You may also have to add fields to generate the appropriate path to the user profile.

Then, add the token replacement patterns for the excluded fields. You can either 1) wrap this output in an anchor with the appropriate path /user/[uid] (a field you may have to add, or you may be able to use the user's alias), or 2) in the rewrite section, tick 'Output this field as a link' and specify the path there (also use replacement patterns from UID or the alias).


View: display first value in a single field in field collection Drupal 7, view 3 and field collection.
I have a custom content type with a field collection called personal detail.
Personal detail have 2 fields: name and contact.
Personal detail is zero to unlimited.
In view, I am able to display the values of 'name' field. The problem is there are multiple values for 'name' field. This caused me to have duplicated records (i.e. same node id appears more than once, because the 'name' field)
I only want to display the very first one value of 'name' field which is stored the order of a node.

Solution:
In Go to field collection in view's relationship (right column)

There is a statement: The delta allows you to select which item in a multiple value field to key the relationship off of. Select "1" to use the first item, "2" for the second item, and so on. If you select "All", each item in the field will create a new row, which may appear to cause duplicates.

So select "1" will show the first fields.

This can be done by modifying the Multiple field settings of your name field:

Click on the "name" field in your view (to edit the settings of field)
Navigate to "Multiple field settings" (present just above "Style" settings)
Click on the checkbox: "Display all values in the same row"
Choose "Display type": Ordered list
Below display type, there is one field "Display": Replace "ALL" with 1
Save the settings and the view.


Drush can't connect to local MySQL through socket on WAMP Trying to set up Drush with in a local dev environment on Windows 7 and can't get MySQL properly configured. A test command I've been running via Cygwin, with the resulting error, is as follows:

$ drush sql-query "SELECT * FROM erg_node WHERE nid=3"
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I can run the same SQL statement in phpmyadmin and it works fine. I can run the same drush command with a remote site and it also works, so it seems like it must be related to how MySQL is configured with WAMP and Cygwin. When I check which mysql via Cygwin, I get back /usr/bin/mysql instead of the path for WAMP's mysql. But the WAMP mysql path is set in my system environment PATH variable, so it should be accessible.

I've tried changing my.ini to include host = 127.0.0.1, copied the my.ini file to /etc/my.cnf, and run chmod -R 755 /tmp/. I'm not sure if there's something else I need to do to ensure drush uses the WAMP mysql command? Any help would be appreciated. Thank you!

For anyone else with this problem, it was an issue with the PATH variable. I had to add the path to the version of mysql that I wanted to use (the WAMP version) to the beginning of my PATH variable in my .bash_profile. SO post regarding PATH variable in .bash_profile.


Avoid user to multiple purchase of same product I would like avoid a user to buy the same product twice or more, I'm not speaking about the quantity limitation during the checkout (I've already set quantity to 1 for every purchase)...for example..after a user has bought a product(He has completed the checkout process) I want that he can't buy again this product. Could you help me? Thank you in advance!

The best way to do this would be to use the method (How do I prevent a product from being added to the cart?) but implement custom logic to look for that product being purchased by the customer.

You can do this by using EntityFieldQuery() and loading all of the user's orders and then you can loop through the line items and look for the product...

$orders = commerce_order_load_multiple(array(), array('uid' => $user->uid, 'status' => 'completed'));
foreach ($orders as $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->commerce_product()->sku->value() == 'SOMESKU') {
    //user has bought it
    }
  }
}