How exactly do I package latest dev snapshot of Commons locally? I am trying to build up-to-date instance of Drupal Commons 7.x-3.x-dev. Release notes say to use command: "drush make build-commons-dev.make". I am totally new to drush and am trying to follow that instruction.

Can anyone provide more detailed instructions? That is my basic question.

Thanks, and more details below:

I thought I had figured it out. I can now go to root folder of site and run "drush profiles/commons/build-commons-dev.make" and I get what appears to be current Drupal Commons 7.x.-3.x-dev. However, as I test my instance, I am reporting bugs that Drupal coders say are already fixed and committed to github. So it seems that I am not properly synched.

Maybe I have wrong makefile? I got it from http://drupalcode.org/project/commons.git/tree/1228f4b

When I run "drush update" it says I am using all sorts of dev modules and that my site is 100% current. But I am clearly not current, because I am finding bugs that have already been fixed. Thanks for your help so I can test and contribute to Drupal Commons.

I eventually got the answer straight from ezra-g at Acquia. From a unix-like console you can execute these commands (make sure you have drush and git installed locally):

cd ~
git clone --branch 7.x-3.x http://git.drupal.org/project/commons.git ./commons-profile
cd public_html
drush make ../commons-profile/build-commons-dev.make --prepare-install my_Drupal_Commons_site


Change Field Type from File to Image I created a field with the field type "file" I now have to convert this to "image" field type. The field has already content so I cannot not delete and recreate a new one. How can I do this programatically using the hook_update in my module?

Hook update performs an update on a node, it wont be too useful in your case. When you create a field it creates a table in the DB with appropriate datatypes. You cannot just change the datatype of a field without going down the line and changing all the details, including the data in most cases. which trust me is a huge pain in the ass.

I've had to do this before but what i ended up doing was creating new field with the datatype I wanted, then used View Bulk operations Execute arbitrary PHP script and ran custom php to get the FID from all the File and then add it to the new field. I think there was a user reference for each file as well, so the fidelity is there to transfer your data between fields. Then delete the old field

Worst case scenario, find ways of limiting what types of files(image only) your file upload field can upload.


Add an item to a checkbox in a content type I started working with drupal recently and I have been assigned many small tasks. I would like to know how I can add an item to the following checkbox, I can't understand how:

Thanks in advance!

Click on "field settings" in the top right hand corner of that screen. That's where storage specific options are held.

If you can edit the options there then it's a simple text list. But it may be that field is referencing a taxonomy term or content/entity but that tab will lead you in the right direction to add an item


Is there a way to register on my Drupal site with mobile number and password instead of email? Is there a way to register on my Drupal site with mobile number and password instead of email?

I would like to have my users register on my Drupal site with either mobile number and password or email and password. The confirmation code is sent to the corresponding destination and the user is activated.

Yes, it is possible, but you will have a lot of work to do it.

First thing first, you need a way to communicate with your users. Drupal sends quite a lot of data to users, like password restoration mails. If you want phone numbers to replace mail, you need to be able to send SMS messages. SMS Framework seems to be your friend here. There is no stable version for Drupal 7, but as far as I know it is most stable at the moment anyway.

When you have a way to communicate using their mobile numbers, you need to override mail sending, to convert mails into SMS messages. There are, generally, two ways to achieve this:

SMTP Authentication Support - It is possible to configure mailserver to send sms messages if address is in phone_number@sms.local or similar format. This does not even require any SMS framework in Drupal, really.
Use Mail System and create your own  MailSystemInterface implementation that will detect sms addresses and use SMS Framework instead of whatever mail system you are using.

If you don't want to mess with mail systems, you will need to effectively write user module from scratch and replace core one with your own - it relies on mails too much, writing alters would not be feasible.

Last thing: For all Drupal forms, you need to use form alter and detect required email, changing it into two fields, at least one required. And provide relevant storage. Actually, this seems to be an easy part.

Note pretty much every modern phone can receive emails, so I hardly see a point in this.


Programmatic access to metatag module fields I am wondering how to programmatically access metatag module data.  For example, my node has an entry for metatag description, and I see in the generated page the meta description tag, which is great.  However, it's not clear how I can access this programmatically.

Right now, I am trying the following:

$metatag_manager = \Drupal::service('metatag.manager');
$tags = $metatag_manager->tagsFromEntityWithDefaults($node);
$elements = $metatag_manager->generateRawElements($tags, $node);

Inspecting the data, I see that $tags includes a 'description' entry, but $elements does not.  Is there a better way of accessing this data?

The metatag module includes documentation for programmatically setting data, but unfortunately does not mention accessing the data.

Edit: Alas, it seems I was inspecting the wrong node -- one with the same title as a node with metadata entries.  Working now with the correct node, it seems all I need to use is:

$metatag_manager = \Drupal::service('metatag.manager');
$tags = $metatag_manager->tagsFromEntity($node);

Which returns an array with a description key and the description value entered for that node.

If you have node object loaded, you can access the meta tags as below:

$metaTags = $node->get('field_meta_tags')->value;
if (!empty($metaTags)) {
      $metaTagsArr = unserialize($metaTags);
echo "<pre>";
print_r($metaTagsArr);
echo "</pre>";
}


hook_preprocess_node() or hook_node_view() for html altering the field What's the best way to alter html of an image field? I have imagefield and i want to rewrite it's html from scratch.

hook_preprocess_HOOK will do the job,

You may also take a look at writing your own theme_image_formatter()

It could work in a node_view() but you want to alter the FIELD's HTML.In node_view you would alter the order of fields, hide/show new contents NOT control how they look.. you could absolutely do it, but it will not be the best/Drupal way.

Drupal divides functionality (node_view()) and looks (theme)

In a hook_preprocess_node() you would alter the node template variables, not the field's ones.You would need it to add a class to a node wrapper, to change node templates etc...
you have to go deeper in the theme for this one.

Examples:

// ALL IMAGES get rounded class.
function YOURTHEME_preprocess_image(&$variables) {
  $variables['attributes']['class'] = array('rounded');
}

and for field

// If field_images in FULL view mode of a node, add/edit variables and choose template
function YOURTHEME_preprocess_field(&$variables) {
  if ($element['#field_name'] == 'field_images' && $element['#bundle'] == 'YOUR_NODE_TYPE' && $element['#view_mode'] == 'full') {
 $variables['theme_hook_suggestions'][] = 'field__field_images_YOUR-file-name';
  // Add more variables available in template...
  $variables['toggle'] = 'Read the story';
  $variables['some_text'] = 'Some text';

}


Custom block build function to display wysiwyg body text I am learning to build custom blocks through a module. I am trying to get the build() function to work. I have the code and it works. However, if I edit the configuration of the block as a user it does not print the text in the text formatter.
'#markup' =>
    '<div>' . $this->t('Body: @body', ['@body' => $this->configuration['body']]) . '</div>',

In the rendered block on the page it prints... Body:
But not the text in the wysiwyg.
Any ideas how to get that to work. The tutorials and links I am finding are not relavant.

Assuming you store the block configuration via a text_format form element as in https://drupal.stackexchange.com/a/278811/47547
src/Plugin/Block/ExampleBlock.php
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides an example block.
 *
 * @Block(
 *   id = "mymodule_example",
 *   admin_label = @Translation("Example"),
 *   category = @Translation("mymodule")
 * )
 */
class ExampleBlock extends BlockBase {

  public function blockForm($form, FormStateInterface $form_state) {
    $body = !empty($this->configuration['body']) ? $this->configuration['body'] : [];
    $form['body'] = [
      '#type' => 'text_format',
      '#title' => 'Body',
      '#format' => isset($body['format']) ? $body['format'] : 'full_html',
      '#default_value' => isset($body['value']) ? $body['value'] : '',
    ];
    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['body'] = $form_state->getValue('body');
  }

You would output the wysiwyg content via processed_text:
  public function build() {
    $build = [
      '#type' => 'container',
      'label' => ['#markup' => 'Body: '],
    ];
    if (!empty($this->configuration['body'])) {
      $build['body'] = [
        '#type' => 'processed_text',
        '#text' => $this->configuration['body']['value'],
        '#format' => $this->configuration['body']['format'],
      ];
    }
    return $build;
  }

}


Add a youtube video in the template file using url I've tried using this code <?php print theme('video_embed_field_embed_code', array('url' => $video['http://www.youtube.com/embed/Zz1HPLtecOg'])); ?> but it only displays the url and doesnt show the video. How can I fix this?

<?php print render($content['field_video_url]']);?>

try this


Processing the content generated by a node? What call would I use to modify a node's content. For example, let's say I have the words "12345678" located in various nodes. If I wanted to replace all occurences of this in Drupal 7 with "abcdefgh", I could easily hack it in a template like this:

$content = str_replace("12345678", "abcdefgh", $content);
print $content;

This is probably very bad practice, but hopefully it will demonstrate that I just want to be able to replace the occurrence of any text with some other piece of text.

What is the best way to do that in Drupal 8?

UPDATE

I had a look at template_preprocess_node. But it looks like this will allow me to add more variables to the theme, but not to actually replace specific pieces of text.

In Drupal 8, you can use hook_ENTITY_TYPE_view_alter() (which in this case would be hook_node_view_alter()) to alter the render array for the entity; otherwise, as the documentation for that hook suggests, you can use hook_preprocess_HOOK() (which in this case would be hook_preprocess_node()).

  If a module wishes to act on the rendered HTML of the entity rather than the structured content array, it may use this hook to add a #post_render callback. Alternatively, it could also implement hook_preprocess_HOOK() for the particular entity type template, if there is one (e.g., node.html.twig).

As for template_preprocess_node() implemented by a theme, that is not different from hook_preprocess_node(): It can either add new variables, or change the content of existing variables. In both the cases, the $variables parameter is passed by reference, so any change to the array is passed back to the function/method invoking those hooks.

The other alternative would be implementing an input filter in a module, and add the input filter to the input format used from the content type. This would have the pro of stopping the replacements simply by removing the input filter from the input format, and it would also have the pro of changing in the site configuration which content types would have the text replaced, and document to users the changes done to nodes.
The con is that it cannot be used in fields that don't use input formats, but it works for the body field of nodes. If you need to alter the text that appears in a link field, for example, an input filter would not help (since the link field would ask for a URL and the text to show as link title).


Get values from unlimted field programmatically in node_presave hook I have created class content type and set Allowed number of values to unlimited" to "Division" field
Now I want to get "Division" field values programmatically in node presave hook I'm using below code.

function example_node_presave(Drupal\Core\Entity\EntityInterface $node){
  if($node->bundle() == "class") {
     $getDivison = $node->get('field_class_division')->target_id;
   }
}

If i print $getDivison then I get 739 only.

You can loop over a field object and access each item separately, that's often more convenient than going through getValue():

function example_node_presave(Drupal\Core\Entity\EntityInterface $node){

  if($node->bundle() == "class") {
     foreach ($node->get('field_class_division') as $item) {
       echo $item->target_id;
     }
   }
}

And to access a specific delta (that's what the index in a multi-value field is called in the Field API), you can access it like an array as well, but you need to make sure that the deltas exist:

echo $node->get('field_class_division')[1]->target_id

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a very useful cheat sheet on how to work with the Entity Field API.


Migrate content types and contents from old drupal version to drupal 8 I'm working on a new drupal 8 website.
I have already a drupal 7 installation with severals content type (custom field image, date etc ...) and i dont know what is the best pratice to migrate thoses contents types to my new drupal 8 installation..
Does someone know how to do that properly ?
Regards.

Take a look at this one, it pretty simple to migrate content types, fields, terms, users using below module:
https://drupalize.me/blog/201511/simple-drupal-7-drupal-8-migration

And this module does all the work:
https://www.drupal.org/project/migrate_upgrade


Getting redundant records $result = $query->entityCondition('entity_type', 'node')

    ->entityCondition('bundle', 'mypage')
    ->fieldCondition('field_mymodule_module','tid', 123,'=')
     ->execute();

  $nids = array_keys($result['node']);

  $or = db_or();

  foreach($nids as $nid)

    $or->condition('m.entity_id', $nid, '=');

  $query2 = db_select('metatag', 'm')

    ->fields('m', array('entity_id', 'revision_id', 'language', 'data'))
    ->condition('m.entity_type', 'node')
    ->condition($or)
    ->orderBy('entity_id')
    ->orderby('revision_id')
    ->execute();

  while ($record = $query2->fetchAssoc()) {

dpm($record);

    }

As you can see in above code, I'm trying to get metadata information of each node. Getting nids of them turns out to be easy. However, when I use those nids to retrieve metadata, I get so many identical ones. That problem persists even after I removed "or" statement from the db_select and hard-coded entity_id, it returns like 10 identical records. Can anyone shed a light on the problem and where I am doing wrong here?

$result = $query->entityCondition('entity_type', 'node')

        ->entityCondition('bundle', 'mypage')
        ->fieldCondition('field_mymodule_module','tid', 123,'=')
        ->execute();

    $nids = array_keys($result['node']);
    $array=array();

    foreach($nids as $nid)

{
    $query2 = db_select('metatag', 'm')

    ->fields('m', array('entity_id', 'revision_id', 'language', 'data')) ->condition('m.entity_type', 'node')

->condition('m.entity_id', $nid, '=')
->orderBy('entity_id')
->execute()->fetchAssoc();

$array[]=$query2

        }

$array contains all fields value.traverese this array.
Hope this will give you result.


Anynomus posts in my website drupal im just new on drupal, i noticed that some posts in my content of my website are submitted by anynomus ( not verified ) user , it came with no type or author .
is it hacked ?? or how can i stop these posts on my website.
the role at my website required to be verified   before publishing BUT these posts came published already

plz help here is a screenshot with the black rectangle arround the posts which i mean.

with the Permissions you can deny anything to anonymous (not registered) users you don't want them to do.
Also this may help.


Gallery Formatter Adjusting the Width of Gallery-Thumbs I am using a Gallery Formatter on my site. The thumbnails are appearing below the main image, the size of thumbs-gallery is exactly the same size as gallery-slides. I actually want thumbs-gallery to appear from one corner of the window to the other. My div which contains this Gallery formatter gallery has 100% width of the document, So I gave the thumbs-gallery the width 100% which does what I want but when I am clicking the arrow to scroll the thumbs it at the end of the thumbs gives a large blank space, on clicking again it starts fine from the start.

Please suggest how to achieve my desired result.

Following is the link of my page on which I am getting problem, just click the arrow to scroll twice to see the problem

http://zgphotographydubai.com/content/industrial

make shure the empty li's have no width specified (or are now shown at all). change

to

if you cannot manage that - do it via css

.gallery-thumbs li.empty { width: 0px !important; }


Link to latest poll? I set up my poll tpl file to include the poll fields (form, results, etc) along with a list at the bottom for the previous polls, ordered by date.  What I am trying to do is, from the main menu, link to the latest poll.  In other words, my current latest poll is node/123456/.  I can link to that, obviously.  But when we create a new one, that link needs to be updated.  I'd love to have it so the menu item doesn't need to be edited each time a new poll is created.

Any ideas?

UPDATE

Just so you don't think I'm waiting expecting you to write it for me - this is where I am:

$items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'latest_poll_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

return $items;

/**
 * Find latest poll and redirect user
 */
function latest_poll_find_poll() {
  $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"')->fetchField();
  $latest = is_numeric($nid) ? 'node/' . $nid : '';
  drupal_goto($latest);
}

Create a small custom module that implements hook_menu() and a custom callback that determines the latest poll and redirects the user.  Something like this perhaps (for D6, D7 will be similar):

Drupal 7

MYMODULE.info

name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 7.x

MYMODULE.module

<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = :type', array(':type' => 'poll'))->fetchField();
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

Drupal 6

MYMODULE.info

name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 6.x

MYMODULE.module

<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_result(db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"'));
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

Replacing "MYMODULE" with the name of your custom module and placing those files in your site's modules directory in a folder named MYMODULE (replace of course).


Drupal form API date popup Possible Duplicate:
  How to remove format description in date_popup form field?

Hi I am creating a drupal 6 module and I have used drupal form API date popup fields to allow users to enter date. Everything is going on fine but I am getting a format description for date popup field as FORMAT 23/05/2012. I don't know how to remove this description.As shown in the image below

To make a correct format you can make use of #default_value

See here

  Description: Format a date selection box. The #default_value will be
  today's date if no value is supplied. The format for the #default_value and the #return_value is an array with three elements with the keys: 'year', month', and 'day'. For example, array('year' =>
  2007, 'month' => 2, 'day' => 15)


How to trigger hook_form_alter() on my custom $form? I have written a custom module which builds a custom user_profile_form():

mymodule_user_profile_form($form, $form_state, $user) {
  module_load_include('inc', 'user', 'user.pages');
  $form = user_profile_form($form, $form_state, $user, 'account');
  // doing stuff with $form ...
  return $form;
}

Now, it's working as desired but I noticed a lot of contrib modules are altering the user_profile_form() calling a hook_form_alter() on the $form_id == 'user_profile_form'.

Now, I want all these modifications applied to my custom profile form, too. How to achieve that?

The hacky way would be to go through all modules and change the checks for $form_id == 'user_profile_form' || $form_id == 'mymodule_user_profile_form', but this is a no-go and I would appreaciate a clean way to do this. Any idea?

Update: drupal_get_form() is not the answer as it is not working as desired. This is only returning the $form object without re-building it which causes many issues with theming layer and $form_state['values']. I'm adding this information as requested by moderator, but this is not part of my question. This is the not working code with drupal_get_form() b6d1f1d8 and this is the working code with user_profile_form() d5d43dc0.

You should use drupal_get_form($form_id) to get the form instead of directly calling user_profile_form() and it will ensure that all the form alters are applied before you get the form.

Update:
          Can you explain why you are not using hook_form_alter()?

But if you want to proceed this way, then instead of calling drupal_get_form() you can replace that with the code from drupal_build_form(), except the call to drupal_process_form(),

Replace drupal_get_form() with the following code, copied from drupal_build-form()

$form_state += form_state_defaults();
if (!isset($form_state['input'])) {
   $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
}
$form = drupal_retrieve_form('user_profile_form', $form_state);
drupal_prepare_form('user_profile_form', $form, $form_state);


boost only for front page with cache enabled for other pages? I know that Boost module works only when drupal cache is disabled.

But is there any way to turn on Boost module for front page only, with cache enabled for other pages.

All the node pages either can be added to exception list with Boost or front page.

You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.


Subtheming to add a single template? As a programmer, I know a great deal about Drupals backend functionality, but little about theming. I'm using Corolla as a theme, and I want to add a single Views template to the theme.

Initially, I created a blank subtheme, but some of Corollas settings don't show up on my subtheme's settings page, so apparently this changed functionality.

Now I'm considering simply keeping my template as a local patch to Corolla as that's a way of solving the problem that I understand well.

How would you go about solving this issue?

The theme settings not being inherited by the subtheme is a Drupal core bug. If you simply copy the theme settings from the parent's .info file to the subtheme's .info file, it will alleviate the issue.

However, keeping a local patch of the theme is a reasonable solution in this case. The rule of "dont edit a contrib theme" is really in place just to ease potential updates, etc. for users who may be unaware of the risk of losing their changes upon updating themes/modules.


How to print paragraph field values in paragraph template? I'm trying to output paragraph field values in a sample paragraph template, but it does not work. I created a twig template in paragraph/paragraph--article--default.html.twig

I have a field called field_action and I tried:

{% block paragraph %}
    <div{{ attributes.addClass(classes) }}>
      {% block content %}
        {{content.field_action}}
        {{content.field_action.value}}

      {% endblock %}
    </div>
{% endblock paragraph %}

Nothing happens.

If I write {{content}} everything is fine, but I would like to customize output.

To print out single fields I usually use, {{ paragraph.field_action.value }}. That should also work for you.

In the case of an entity reference field, you need to use {{ paragraph.field_action.entity.field.value }}.


Passing url arguments to views I've created a landing page/portal content type and created a series of views for it. However I have run into a problem, i'm not sure how to pass arguments from the urls to the block views on these portal pages.

Basically, if a user goes to http://mysite.com/portal/action I want action which is a taxonomy term to be used as an argument for the block views on the page. Any ideas?

EDIT:
To help clarify I am trying to create a page which pulls in information from other parts of my site based on a taxonomy term, so for example http://mysite.com/portal/action would go to a page which contains blocks displaying things like latest news posts in the action catgeory etc.

So far I have created a content type called portal that lets the author set the topic of a portal and then a series of text boxes to add some custom content to the page.

I then set up a view with a series of displays which creates the blocks that pull in information from other parts of the site such as news, and also turned the custom fields made during the creation of the content type as blocks on that page.

My issue is setting up the arguments within this view so that it changes based on the url. So if i created a horror portal page at mysite.com/portal/horror the content would be those items tagged with the horror taxonomy term.

Hope this makes sense?

Edit 2 Solved:
Thanks everyone for your help. I ended up adding the following code to the provide default field

    if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(arg(1));
if ($node) {
return $node->title;
}
}

I hope the said page is a view page in itself and you are passing a argument to that page.

If that is the case then you should check "Provide Default" value when you add the view and then select the required property from the dropdown. You would have something like get term id from url or what ever your argument is. Select that and it showup as you want.

If you need more clarification it would be good if you can export the view you have created or explain how you have created the view.


How to make a theme hook suggestion for menu according to region? I'm placing the same menu block in two different regions whereas different html markup for the list is needed. So analog to my previous question "How to make a theme hook suggestion for blocks according to region?" I need to know, how to get the current region inside the function MYMODULE_theme_suggestions_menu_alter, to add my own suggestion.

Joery Lemmens posted an answer to a similar question on Drupal's forums:

use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_HOOK().
 *
 * Pass block region value to content so this can be used in
 * MYTHEME_theme_suggestions_menu_alter.
 */
function MYTHEME_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    $variables['content']['#attributes']['region'] = $region;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Provide region based menu suggestions.
 */
function MYTHEME_theme_suggestions_menu_alter(&$suggestions, array $variables) {
  if (isset($variables['attributes']['region'])) {
    $suggestions[] = 'menu__' . $variables['menu_name'] . '__' . $variables['attributes']['region'];
  }
}

All credit to Joery for this elegant solution.


D8 doesn't create .htaccess for private file system path Following this guide: https://www.drupal.org/documentation/modules/file it says

  "When you specify the private directory in
  admin/config/media/file-system it will automatically create the
  sub-directory & create a simple .htaccess file with Deny from all."

When you edit your settings.php and add the $settings['file_private_path'] = 'sites/default/files/private' after drush rc it doesn't create the .htaccess file in my sites/default/files/private and I do not know how the correct .htaccess should look so I could add it manually?

,

This is a better .htaccess to use:

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# 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>
<IfModule mod_php7.c>
  php_flag engine off
</IfModule>

This .htaccess is the one that should have been placed in your private files directory by Drupal 8 (or 9) core. (Perhaps permissions on the private directory prevented Drupal from creating the file.)

The accepted answer above is adequate to quiet the warning from Drupal status report, but does not actually prevent the remote script execution exploit addressed in the original core security advisory from 2013.


Why doesn't the function taxonomy_term_search exists? I have an autocomplete field in an API Form. The callback function uses the following code to highlight the search query in the list of suggestions.
With a taxonomy vocabulary of 3 levels of hierarchy, about 8,000 terms, it takes a whole eternity of 1 second to offer the suggestions. In a direct SQL query or a EntityFieldQuery it takes just a few tenths of a second. Why doesn't mixed $tid_array = taxonomy_tearm_search(term_name, vid) exists, it would increase the code below in which only taxonomy API is used.

mymodule_providers_autocomplete($brand, $text){
   $selected_providers = array();
   $providers = get_providers_of_type($brand);
   $counter = 0;
   foreach($providers as $nid => $provider){
      if(strpos(strtoupper("." . $provider["title"]), strtoupper($text)) > 0){
           $selected_providers[$provider["title"] . ' (' . $nid . ')'] = str_ireplace($text, "<strong>" . $text . "</strong>" , $provider["title"]);
           $counter++;
           if($counter > 10) break;
       } // if
   }
 drupal_json_output($selected_providers);
} // function

function get_providers_of_type($brand){
   $children_1 = taxonomy_get_children($brand);
   $models_arr = array();
    foreach($children_1 as $key2 => $value2){
        $children_2 = taxonomy_get_children($value2->tid);
        foreach($children_2 as $key => $value){
            $models_arr[] = array("title" => $value->name);
        } // foreach
    } // foreach
}   // if
  return $models_arr;
} // function

Long story short, it does not exist because either no one wrote it, or maintainers found it not suited for inclusion in taxonomy.module for whatever reasons. For most purposes, taxonomy_get_term_by_name is enough. When it's not, there are various search solutions in separate, search oriented modules.

If you think you can write it, and make it good, please do so, and then post entry in issue queue with appropriate patch file.


Default to "no limit" for maximum number of options in field type select The number of cities and sectors "small cities" in Moldova is around thousand,so we have already exceeded the arbitrary 100 limit without half-trying.

The limit causes problems when we translate the options.

We get message translations were saved successfully, however going back to translation noting is saved.

Looking into server logs we found out there is a problem with max_input_vars in php.ini

  2016/02/02 11:37:26 [error] 1310#0: *199007 FastCGI sent in stderr:
  "PHP message: PHP Warning:  Unknown: Input variables exceeded 1000. To
  increase the limit change max_input_vars in php.ini. in Unknown on
  line 0"

We updated the php.ini file and set the max_input_vars = 5000. After that the Error above disappeared, however we are still unable to save the translations and there is no error in the server console logs.

Is there anything we can do about this problem.

Try to increase  post_max_size value or disable the limit by setting it to 0


How to apply dynamic block layout depending upon number of nodes in it (Drupal 8)? I have very challenging task. Can any expert guide me?

(NOTE: This is for Drupal 8)

There is a requirement to show nodes in a block in a way that block must adopt style automatically depending upon the number of nodes in it.

For Example:
If there is only node published under news content type then block must adopt single news article layout in teaser mode, And
If there are published 2 nodes under news content type then block must now adopt the layout of 2 nodes and so on.

and this continues to 10 nodes

I know we can create views but how to apply conditions to check how many nodes are there under any content type and apply block layout accordingly?

Can anybody help?

Thanks
Mithow

Not everything is clear in your question, but there are some approaches for that task.
For example if you are using views module you can count number of views rows in twig template:

{% if rows|length == 2 %}
   {% for row in rows %}
//Here some staff for two rows
   {% endfor %}
{% endif %}

About twig, about views templates

Also you can use jquery $('.some-class-for-every-row').length and add some style using js.


Migrating 301 redirects done in 7 to 8 Drupal 7 to 8 Migration works only on the core, thus doesn't inlcude 301 redirects created in D7 with the Global redirect module.

Is there a workaround to migrate all the 301 redirects to Drupal 8 instead of coping them manually (after the site itself migrated successfully from D7 to D8) ?

The reason I ask this is because if I won't migrate these redirects, search engines that already indexed the old paths, will show 404's and these pages' SEO will most likely damage.

The Global Redirect module doesn't store paths on a per-node basis. That's the role of the core path module which stores aliases that map to system paths in the url_alias table (in both D7/D8).

The Global Redirect module could broadly described as settings (set on its administration page) that drive logic for 301 redirecting (in a hook_init() invocation) while setting the rel="canonical" metatag (a signal that tells the search engine to index that path). Thus, there really isn't anything to migrate from the module besides various globalredirect_settings variables that store redirect settings.

That said, you can run the Migration module which will import your node path aliases (and thus the paths you're concerned with 301 redirecting to) and adjusting the settings for Global Redirect module so that it matches the settings in your D7 installation.


Session Timeout module What's the best module for a session timeout?

I simply want users to be automatically timed out after a period of inactivity.

The Automated Logout module looked like it could to the trick, but it seems like it does a lot more too.  Also, I am using Drupal 7 and it's still in dev.

You have two options in the settings file that should allow you to configure the session timeout however you wish, session.gc_maxlifetime & session.cookie_lifetime.

/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

 /**
  * Set session cookie lifetime (in seconds), i.e. the time from the session is
  * created to the cookie expires, i.e. when the browser is expected to discard
  * the cookie. The value 0 means "until the browser is closed".
  */
ini_set('session.cookie_lifetime', 2000000);


How can I add extra parameter to URL when click "apply" button of Views exposed filter? I need to add extra parameter at the end of the page view URL when "apply" button of exposed filter is clicked.

For example,

normally URL looks like:

my-view?nid=1

But I need to add "my_parameter=1" at the end of the URL and it eventually needs to be:

my-view?nid=1&my_parameter=1

How can I do this?

You can use a hook_form_FORM_ID_alter() to add a hidden form element with the value that you want (1 in your example). You'll have to check the View name and display name to ensure you only affect the right exposed filter.


Rule to create an identical entity to the node created then delete node I have a content type called "article" and an entity type called "article 2", they both have identical fields.

When I create an article node and save it I want a rule to fire that then basically creates an exact copy of this as an entity, article 2. then deleted the original node after that. So I am left with a copy of the node as an entity - all fields etc, and no node.

I can get rules to create an entity quite easily by using "Create a new entity" but I can't seem to map the fields from node to entity?

Wonders never cease, managed to figure this out. For anyone else:

Created a Rule

EVENTS:

After saving new content of type Article

CONDITIONS:

Entity has a field:

Data selector: node

Field: added ONE field from my source node (one seems to be enough) This was called "discipline" in my case. node:field:discipline

Entity is of bundle:

Data selector: node

ENTITY BUNDLE: Article

(so this is my source node again, my original node I am copying from)

ACTIONS: (this is where we create the entity using the information from the node)

Create a new entity:

ENTITY TYPE:

Article CLONE (this is my entity "content type" name, to make it simple)

Set a data value:

Selected data: entity-created:field-discipline (this is the identical field on my newly created entity that I want to add data to.

Data selector: node:field:discipline (this is the field from the node I want to copy to my entity identical field)

Delete entity:node

3rd step deletes the original node that was created. You can add more "set data values" as you'll need one for each field you are copying over.

This works fine. There could be better ways to do this, of course. Hope this helps someone else.


HTTP_RAW_POST_DATA is deprecated When using a field collection feed import, I get this error.

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path: /batch?id=17839&op=do StatusText: OK
  ResponseText: Deprecated: Automatically populating $HTTP_RAW_POST_DATA
  is deprecated and will be removed in a future version. To avoid this
  warning set 'always_populate_raw_post_data' to '-1' in php.ini and use
  the php://input stream instead. in Unknown on line 0 Warning: Cannot
  modify header information - headers already sent in Unknown on line 0
  {"status":true,"percentage":"64","message":""}

I have researched this issue and statistically came up with this solution: change in php.ini always_populate_raw_post_data = -1

I have changed that and also restarted apache.

I still receive that error. Does anyone have any thoughts to this?

You need to edit your php.ini and add or uncomment the following line:

always_populate_raw_post_data = -1

If you've still that error after restarting Apache, you probably edited the wrong file. So as admin, go to Reports/Status/PHP (at /admin/reports/status/php) and double-check your value for always_populate_raw_post_data and your php.ini path.

Note that the above setting will only avoid the warning, see: Changes to PHP-5.6 and this SO post.


how is config saved in nodeapi_example module? In this module, which hook is responsible for saving the user choice (at admin/structure/types/manage/<CONTENT_TYPE>) into the database?

I implemented nodeapi_example_form_alter() function exactly as it is, but it is not saving anything.

My hook_form_FORM_ID_alter() in my .module - this does NOT save the value of my radio - anything missing here?

function followbtn_form_node_type_form_alter(&$form, $form_state, $form_id) {
  // First, check for the node type configuration form.
  drupal_set_message('Entered hook_form_alter ...');
  //if ($form_id == 'node_type_form') {
  if (isset ($form['type'])) {
    // Alter the node type's configuration form to add our setting. We don't
    // need to worry about saving this value back to the variable, the form
    // we're altering will do it for us.
    $form['followbtn_rating'] = array(
      '#type' => 'fieldset',
      '#title' => t('Custom Rating settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
      '#weight' => -1,
    );

    $form['followbtn_rating']['followbtn_node_type'] = array(
      '#type' => 'radios',
      '#title' => t('NodeAPI Example Rating - Custom'),
      '#default_value' => variable_get('followbtn_default_mode_' . $form['#node_type']->type, FALSE),
      '#options' => array(
        FALSE => t('Disabled'),
        TRUE => t('Enabled')
      ),
      '#description' => t('Should this node have a rating attached to it?'),
    );
  }
}

I can see the "Enabled" and "Disabled" radio buttons; when I hit "save Content Type", these do not get saved.

There is no hook that needs to be implemented by the module for that purpose: Saving the value is automatically done by Drupal. In that case, the value for the nodeapi_example_node_type form element is saved in the nodeapi_example_node_type_<CONTENT_TYPE> Drupal variable, which is the variable the module accesses for the default value.

// Compare the following line...
$form['rating']['nodeapi_example_node_type'] = array(
  '#type' => 'radios',
  '#title' => t('NodeAPI Example Rating'),

  // with the following.
  '#default_value' => variable_get('nodeapi_example_node_type_' . $form['#node_type']->type, FALSE),
  '#options' => array(
    FALSE => t('Disabled'),
    TRUE => t('Enabled'),
  ),
  '#description' => t('Should this node have a rating attached to it?'),
);

Similar code is used in locale_form_node_type_form_alter().

  if (isset($form['type'])) {
    $form['workflow']['language_content_type'] = array(
      '#type' => 'radios',
      '#title' => t('Multilingual support'),

      // The variabile name is <FORM_ELEMENT_NAME>_<CONTENT_TYPE>.
      '#default_value' => variable_get('language_content_type_' . $form['#node_type']->type, 0),

      '#options' => array(t('Disabled'), t('Enabled')),
      '#description' => t('Enable multilingual support for this content type. If enabled, a language selection field will be added to the editing form, allowing you to select from one of the enabled languages. If disabled, new posts are saved with the default language. Existing content will not be affected by changing this option.', array('!languages' => url('admin/config/regional/language'))),
    );
  }

As for the purpose of the other node hook implementations:

nodeapi_example_node_delete() is called when a node is deleted
nodeapi_example_node_insert() is called when a node is inserted in the database
nodeapi_example_node_load() is called when a node is loaded
nodeapi_example_node_update() is called when a node is updated
nodeapi_example_node_validate() is called when data entered for a node need to be validated
nodeapi_example_node_view() is called when a node is being show

Notice that hook_node_update() and hook_node_insert() are mutually exclusive: Drupal calls one or the other, but not both the hooks at the same time. The first is called when an existing node is update; the second is called when a node is created.

In your code the error is the mismatch between the form element name (followbtn_node_type) and the name of the Drupal variable you are using (followbtn_default_mode_<CONTENT_TYPE>). You need to change your code in one of the following ways:

$form['followbtn_rating']['followbtn_node_type'] = array(
  '#type' => 'radios',
  '#title' => t('NodeAPI Example Rating - Custom'),
  '#default_value' => variable_get('followbtn_node_type_' . $form['#node_type']->type, FALSE),
  '#options' => array(
    FALSE => t('Disabled'),
    TRUE => t('Enabled')
  ),
  '#description' => t('Should this node have a rating attached to it?'),
);

$form['followbtn_rating']['followbtn_default_mode'] = array(
  '#type' => 'radios',
  '#title' => t('NodeAPI Example Rating - Custom'),
  '#default_value' => variable_get('followbtn_default_mode_' . $form['#node_type']->type, FALSE),
  '#options' => array(
    FALSE => t('Disabled'),
    TRUE => t('Enabled')
  ),
  '#description' => t('Should this node have a rating attached to it?'),
);


How to add code logic to Display Suite fields without PHP in Drupal 8? Twig? Using Display Suite in Drupal 7 I can easily add PHP logic to any custom Display Suite Field. In Drupal 8 PHP is not allowed. How can I program logic in Display Suite fields in Drupal 8?

As an example, I'd like to use a simple if/then statement to show/hide a node field. I have tried embedding Twig into the field but it does not execute. It just renders as plain text.

This is my sample code {# This is a test comment. #}

Showing hiding fields in twig is pretty simple. You can check if a field has a value like so:

{% if node.field_foo is not empty %}
  {{ content.field_foo }}
{% endif %}

You cannot execute raw PHP from a twig file, nor can you inject Twig and parse it out through field formatters (probably not without a lot of work, anyway).

Note the difference between checking the node object and rendering the content array.

You want to do checks against the entity object, and never (in my opinion) the render array. In the above code, if the field has a value, then the condition is true. If you want to check the value for a specific string, it is likely better suited for a preprocess hook.

What if the twig template being rendered is a Paragraph, and not a Node template? Not much difference:

{% if paragraph.field_foo is not empty %}
  {{ content.field_foo }}
{% endif %}

If you need more muscle, I would advise moving your logic to a preprocess hook in mytheme.theme where you can use whatever PHP you want, and inject new variables into your Twig file.

function mytheme_preprocess_node(&$variables) {
  $variables['show_foo_field'] = FALSE;

  // if field ...
  // and maybe some more conditions?
  $variables['show_foo_field'] = TRUE;
  // end if...
}

Then in the twig template...

{% if show_foo_field %}
  {{ content.field_foo }}
{% endif %}

Now, you say you are using Display Suite - I personally don't inject condition or code through the UI like what you are asking. But one thing I do know about Display Suite is it (when I last looked) tends to hijack a majority of the preprocess calls - so check its docs or API for the right preprocess hook to call for nodes.

The current hooks for Display suite can be viewed in its .api.php file.

Definitely enable twig debug to be able to check what the Twig template naming pattern should be (suggestions) in the HTML source, and be aware of mytheme_preprocess_node potentially not firing. You will need to locate the correct DS hook.


Add the same field multiple times to a display suite node display So I'm using display suite with a 2-column layout, and my node has an entity reference field (field_journal). I'm already displaying field_journal as a rendered entity in the LH column, but I'd also like to display a different grouping of fields from the linked entity in the RH column.

I was thinking the best way to do that would be to add field_journal again to the RH column, but I can't figure out how to duplicate fields in display suite.

Is there some way to add the same field to a node display in 2 different places in the layout? Or can anyone help me with a workaround?

Since you're using display suite you can use hook_ds_fields_info for defining a new display suite field that you can use to clone your existing field.

/**
 * Implements hook_ds_fields_info().
 */
function MODULE_ds_fields_info($entity_type) {
  $fields = array();

  $fields['node']['journal_clone'] = array(
    'title' => t('Journal clone'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'function' => 'MODULE_journal_clone',
  );

  if (isset($fields[$entity_type])) {
    return array($entity_type => $fields[$entity_type]);
  }
  return;
}

/**
 * Render a clone of journal.
 */
function MODULE_journal_clone($field) {
  $build = '';
  if (isset($field['build']['field_journal'])) {
    $build = $field['build']['field_journal'];
  }
  return render($build);
}


How do I display the latest post related to another? I'm on d7. I have 12 nodes that I use as groups with the entity relations module. When a user submits a post, they choose one of the groups to put it into. I want to make a views list of all 12 groups that displays the title of the latest post that has been submitted into each of them. Any suggestions? Thanks.

I ended up using the views field view to get the job done.


Custom theme css separate from editor css I have a custom css file in my custom theme folder which has a few changes I made throughout site but does not affect the tinymce editor but probably overrides it making so no changes in text.

I have two problems, one I don't actually know what to put in separate custom css to make buttons work in tinymce editor. I am used to finding a specific div or creating one and then adding the css. I am not familiar with setting up classes for this editor (as it offers in wysiwyg profiles) and correct syntax to do so. Also I would have thought I needed to bring over a generic copy of the css for the editor into my custom theme folder (?) And two I am unclear on how to set the path in define css for the editor profile, if ever I manage to create of find the correct file.

I hope I am making some sense and my question is clear enough.

First, let me add that the answer that I am about to give is the way I would handle it. This could be done in many ways.

Create a separate stylesheet for your text styling (we usually call it style-type.css) and place it somewhere appropriate in your theme (for example /sites/all/themes/your_theme/css/style-type.css), also use this file for your front-end. Only add styling in this stylesheet for textual styling, so for h1, h2, strong, em, etc...

Then use the admin/config/content/wysiwyg admin page to define the CSS in the appropriate format. We mostly don't use the replacement patterns (like %b) and simply fill in the path relative to your Drupal install (of course, the patterns could be applicable in your case): /sites/all/themes/your_theme/css/style-type.css. Make sure Define CSS is the active option above the path.

If you need extra styling for stuff like highlighted text, simply make sure you have that styling in your style-type.css. For example .highlighted { color: yellow; }. And then define it in the CSS Class textarea as follows:

Highlighted=highlighted

Then also make sure you've got the plugin Styles enabled. This will give you a dropdown list on the WYSIWYG editor which allows you to add styling that you defined to texts.


How to hide a field from anonymous users? I've been searching for this for quite some time, but so far I haven't been able to find a good way to hide a field on my custom content type from anonymous users. I want some fields to be visible only to logged-in users. Any idea how I can do this?

Use the Field Permissions module.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


How to change non-color-related CSS after the color module has been used? I haven't used the color module in years, since I try to avoid it because I know it kind of freezes your CSS changes.

I have a client who has been using color module with a customized version of the Scholarly theme, but does not seem to have the color picker enabled for it.

I'm trying to make some CSS changes for them that have nothing to do with changing colors, but my changes are not reflected on the site. It's pulling in an old version of styles.css. I've cleared the CSS cache and made sure aggregation is turned off on development so I'm pretty sure the color module is the culprit.

How do I clear or regenerate Color module's version of my site CSS?

Resave the color settings in the theme; see color_scheme_form_submit().

I'll look into what can be done inside the AdvAgg module: https://www.drupal.org/node/2461039

Edit: I've added this into advagg now. It will regenerate the color css.


Redirect all www addresses to non-www web addresses How can I redirect all traffic from www.domain.com/page to domain.com/page?

I need to disallow traffic to web addresses that include the www. The reason is that I have an SSL certificate that only works with non-www web addresses. If users try to access https://www.domain.com, they get a certificate error.

Uncomment lines 93 and 94 in the .htaccess file that comes with Drupal in the web root.

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewiteRule ^ http://%1%{REQUEST_URI} [L,R=301]

EDIT: If the certificate requires https, edit the second line to read:

RewiteRule ^ https://%1%{REQUEST_URI} [L,R=301]


Form submission not saved when using a dynamic redirect I have forms where I use a form alter to set various form fields on the fly.
One of which is the Thank You page field that a user should go to after submitting.
Example $form['submitted']['thankyou_page']['#value'] = 'my_page';
I use the same form for multiple reasons so setting the thank you page to suit.
After setting these (which work fine) I then enter a function to do some processing of the form fields to a CRM.
The final section of this function is like this
try {
    $result = $client->CreateContact($data);
} catch (Exception $e) {
    $result = $e;
}
  my_submit_handler2($values['thankyou_page']); // redirect
}
}

The processing works fine to CRM but my problem is that the form submission (result) doesn't save in Drupal and the auto-emails after submit fail to send too.
The redirect is done like this
function my_submit_handler2($f) {
  drupal_goto($f);
}

So I guess the submission is being interrupted?
How can I do these redirects without affecting the flow of the form submission?

A form submission handler, as well a form validation handler or a hook to alter a form, should never call drupal_goto() since it outputs a HTTP header and interrupts what Drupal is doing.
The correct way to redirect a form from a form submission handler is setting $form_state['redirect'] in Drupal 7, or calling $form_state->setRedirect() in Drupal 8. The alternative for Drupal 8 is calling $form_state->setRedirectUrl().
For Drupal 7, the following code would redirect the users to node/123?foo=bar#baz.
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);


How to display a Quick Tab with count? I'd like to display the # (count) of Blogs on my quick tab menu. Ex: Blogs (3)

I found a way to overwrite the quicktab titles using the following function with an if statement

   function mymodule_quicktabs_alter($quicktabs) {
if ($quicktabs->machine_name == 'quick_tab_front_page') {
$quicktabs->tabs = array(
  0 => array(
    'machine_name' => 'quick_tab_blogs',
    'title' => 'BLOGS',
    'weight' => '-100',
    'type' => 'qtabs',
  ),
  1 => array(
    'machine_name' => 'quick_tab_news',
    'title' => 'NEWS',
    'weight' => '-89',
    'type' => 'qtabs',
  ),
);
$quicktabs->renderer = 'quicktabs';
$quicktabs->style = 'Arrows';
$quicktabs->options = array();
}
}

I created a view, using the Views module, which contains all the blog titles written by a user.

Now I need to figure-out a way to display the views' count on the quick tab title

I have tried

function mymodule_quicktabs_alter($quicktabs) {
    $view = views_get_view('user_blogs');
    $view->set_arguments(array($account->uid));
    $view->execute();
    $count = count($view->result);
if ($quicktabs->machine_name == 'quick_tab_front_page') {
$quicktabs->tabs = array(
  0 => array(
    'machine_name' => 'quick_tab_blogs',
    'title' => t('Blogs @count', array('@count' => $count));

but it gives me an error of Fatal error:  Call to a member function execute() on a non-object for the line $view = views_get_view('user_blogs');

I don't get why, I am new to php.

Check your view name that you are passing to views_get_view() and also from where are you getting the $account variable from (credits: wolverine).

And get rid off $view->set_arguments(array($account->uid));, you don't need it (credits: No Sssweat).


How to create a custom menu I have created a menu called "navbar". In this menu, there is 4 links at level 1. Each of these links has 3 sublinks (level 2). All links in the menu point to a different page.
For example, I have on lvl 1 "Projects" (that points to /projects). That parent links contains 3  lvl 2 subsections : "News" (projects/news), "Photos" (projects/photos) and "Maps" (projects/maps).
Then I create an article, I check the "Provide a menu link" and I select "News" in the dropdown list.
I have "menu block" installed, and I configured a "navbar" block to be bound to the "navbar" menu. I also installed "menu node" to have a table with the mapping between nodes and menus.
Now, how do I customize the menu to display all lvl 1 & 2 and all associated articles ? What function do I need to create and where ?
I have tried the following code to no avail (where business is my theme's name and 2 is the menu id) :

function business_menu_link__menu_block__menu_navbar($variables)
function business_menu_tree__menu_block__menu_navbar($variables)
function business_menu_link__menu_block__2($variables)
function business_menu_tree__menu_block__2($variables)

What should I do ?

Ok I found what was wrong :
I needed to register the function in the template.php :

function business_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu_tree__menu_block__menu_navbar']['function'] = 'business_menu_link__menu_block__menu_navbar';
}
function business_menu_link__menu_block__menu_navbar($variables) {

}


Going from an installation profile to vanilla Drupal I currently am using the Acquia Drupal installation profile on a site, and I want to convert it to a vanilla Drupal install.  Other than cross referencing the modules that come with the profile, and making sure you download those from drupal.org and putting them into sites/all/modules, are there anymore steps that would need to be taken besides your regular update instructions?

Once a Drupal site is installed, it doesn't really matter which installation profile you used. The only difference is that it's possible to use modules and themes that are located in the profiles folder. So in that sense you are running vanilla Drupal.

If you want to disable the possibility to use the modules from the profile you need to, once you have added the modules to sites/all, set the installation profile to "standard". The easiest way to that is to use drush:

$ drush vset install_profile standard


Request parser best practices for Services 3.x When you create a service endpoint you can enable various request parsers (application/json, application/x-www-form-urlencoded, multipart/form-data...) How should I decide whether to send the request using JSON vs form-data?

Most of the "node create" examples I've seen do something like this (I think this uses form-data):

    //create a node
    $node_data = array(
                      "title"=>"DHC Tool 01",
                      "type"=>"item",

                      "status"=>false, //ensure unpublished
                      "language" => "und", //lanugage neutral
                      "field_webpage"=>array(
                                              "und"=>array(
                                                            0=>array("url"=>"http://berkeley.edu",)
                                                           )
                                             )

                     );

  // Use JSON
  // $node_data = '{"title":"Tool Unpublished 10","type":"item","status":false,"language":"und","field_webpage":{"und":[{"url":"http:\/\/berkeley.edu"}]}}';
    $options['data'] = http_build_query($node_data, '', '&');
    $response = drupal_http_request($base_url . '/node', $options);

Is there any advantage to sending the node create request using JSON?

How would the above code be modified to use JSON?

Thanks!

This code will send a request encoded as JSON:

function toolreq_test_create() {
  $base_url = 'http://example.com/dirt';
  $options = toolreq_service_login(); //this yields $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  if (!is_array($options)) {
    print "error
";
    return;
   }

   //create a node
   $node_data = array(
     'title' => 'DHC Tool 03',
     'type' => 'item',
     'status' => FALSE, //ensure unpublished
     'language' => 'und', //lanugage neutral
     'field_webpage' => array(
       'und' => array(
         0 => array('url' => 'http://berkeley.edu',)
       )
     )
   );

   //use json
   $options['headers']['content-type'] = "application/json";
   $options['method'] = 'POST';
   $options['data'] = json_encode($node_data);
   $request = drupal_http_request($base_url . '/node', $options);
   if ($request->error) {
     print ("Error doing http request");
     print '
' . var_dump($request) . '
';
   }
   else {
     print ("Success doing http request");
     print '
' . var_dump(json_decode($response->data)) . '
';
   }
 }

When considering the best format for your request keep in mind:

JSON is a useful format for Ajax applications because it allows you to convert between JavaScript objects and string values quickly. ref: http://www.ibm.com/developerworks/web/library/wa-ajaxintro11/index.html
https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data


Varnish problem, user logged out for a HIT page Have someone experienced simmilar problem, I've installed Varnish(v3, on Debian 6, Drupal 7), and also Varnish Drupal module, conigured settings php and vcl, and everything seems to work fine, except Logged-in users sometimes get "logged out", ie when they click on link they are redirected to cached Varnish page (HIT). For pages that are MISS everything is fine.

How can in enforce for logged in user to never hit cached page, thus get logged out?

Administrative pages are working well and never express such behaviour, as i followed few tutorials/setting how to setup vcl and config files.

Thanks!

Maybe too late, but I had exactly the same problem, I spent two days looking for what is wrong, then I read in settings.php:

  Without "Vary:Cookie", authenticated users would also be served the
  anonymous page from the cache.

So change 'ommit_vary_cookies' from TRUE to FALSE in settings.php solved the problem.

$conf['omit_vary_cookie'] = FALSE;


Using a View in a tooltip for an image map hover link I have a imagemap with various  tags, it works well in my Drupal instance, I can click on the various areas to get to my pages.

Now I want to hover one area and display a tooltip with information inside (example: if I hover France, I will have a tooltip showing little information on Paris, with a picture). I will find myself how to do it by the way if you can't help with it - that's just my final goal.

Following various sites tutorials, I made a View with contextual filters in order to display the city content by passing an argument to the view. It works like a charm. I also rewrote the output to use tokens for display

I have actually no idea how to display my View in a tooltip - and searching didn't help me either ...

Modules I am using :

Views
Tipsy (or qTip or else, I don't have any preferences, as long as it works)

You can easily use replacement patterns to achieve something similar.
Add the fields you would want as the view and then in replacement pattern you can render a views block or even customize the display via html.


Service API acting strange with Answers module I'm currently developing an Android App that uses REST to communicate with drupal

I've setup the Service module and got it working with normal "post" content type nodes

But, if i post a question node from the Answers module, it would not work.
So, I post an JSON string like this:

{"node":
{
   "title":"REST question",
   "type":"question",
   "language":"und",
  "body":[
  {
     "und":{
        "value":"REST content",
        "format":"filtered_html"

     }
  }
]
}
}

Drupal would respond like this:

Request header:

Request Url: http://www.mubie.com/rest_api/node.xml
Request Method: POST
Status Code: 200 //<- the request is valid...
Params: {}

Respond body:

<?xml version="1.0" encoding="utf-8"?>
<result>
    <nid />
    <uri>http://www.myhost.com/?q=rest_api/node/</uri>
</result>

now, normally, if I post something like a blog post, it would return the node(nid) url, but with a question content type, it returns the url that lists all nodes.
Also, the content is not added to drupal

How do i make it post my question content properly and return a node url?

I've figured it out, basically the answers module was changing the submit form's submit button text value. Doing this would break Service and make it not add any node to the database.
The solution for me was to remove that modification made by answers module by commenting out some lines:

answers.module , line 163
// $form["actions"]["submit"]["#value"] = t("Post your answer");

And everything works fine after saving.


How to get services post data(json format) callback function? I am using services module and rest API its working fine.

But i need to create a menu callback where i get the json post data and save in database.

How to get the json data in menu callback?

Through comments, we determined the OP would like to alter the results
  of the user registration service resource...

To alter the results of user registration data, implement hook_services_request_postprocess_alter() in your custom module, for example:

/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_user_resource_register') {
    $result->foo = 'bar';
  }
}

This will allow the value of foo to be available to your application that is calling the user registration service resource.


Hide menu titles in Omega subtheme Can anyone help me how to delete or hide the menu titles (eg MAIN MENU title)?

I know how it is done when I do it on a static template but I cannot find it in Omega.

If you display menu in block.
Select Configure block from the drop down that appears
On the next screen enter <none> in the Block title and then click Save block at the bottom of the page.
Or you can simply display: none via css.


How to create a child page that has the same content type as parent page? I enabled the Book module on drupal 7 and created 2 new content types. Let said I created a new "content type A" and "content type B", and keep the book module content type as "Book page". The issue I have is that whenever I adding a child page on a "Content type A" or the "Content type B" page, these child pages are "Book page" content type. How to keep these child page the same content type as parent page?

PS: I see there is a "Books" setting under "content > books" tab. But it only allow me to select one content type as child page.

I found a module that does the job, which is Book made simple. This module add the setting on content type and have the option for "SELECT CONTENT-TYPES ALLOWED AS CHILD.", "SELECT CONTENT-TYPES ALLOWED AS PARENT" and "Other Settings". Then a dropdown listbox will be added in the books link like the one on screenshot. I hope Drupal 8 has a similar feature like this.

PS: One of the issue is "Printer" module also print "Add child page" on each page.


global $language not working in custom module I have a custom module which I want to check the language code of the current interface language, So I added a helper function to the mymodule.module file.

It didn't work in mymodule when I call it, It returned nothing. But If I added this function to my template.php in the mytheme directory it works like a charm and return the language code for the current interface.

I am guesting that its related to the current weight of the module in the system table, What do you think?

function language_code(){
  global $language;
  return $language->language;
}

For additional debugging I used dpm($language); after defining global $language; in mymodule it didn't return the language array.

drupal has a function that return default language language_default with the below code

    function language_default($property = NULL) {
  $language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
  return $property ? $language->$property : $language;
}

I suggest you in hook_init(maybe your fuction not called or problem realated to your fuction)  call this function

function yourmodulename_init() {
  dsm(language_default());
  global $language;
  dsm($language);
}

According drupal documentation , $language is global variable , you problem is some strange .

I thnik problem is in your function and method of calling function. by default if you put a function in module and your module enabled(after clear cache) ,the function globaly exist and you can use it everywhere (even in views on anywhere you think).

If dsm in hook_init return $language value  I suggest you test your function

function my_language_code(){
  global $language;
  return $language->language;

}

in very where you want

$lang=my_language_code();
dsm($lang);

test this please


Add a checkbox on registration page for subscription newsletter with Simplenews I'd like to add a checkbox for subscription to a newsletter on the user registration page.

I'm using Simplenews.

How could I do that?

After you have created a Newsletter category, go to admin/config/services/simplenews and click on edit newsletter category next to your newsletter category.

You'll see subscription settings. Select "Default On" or "Default Off" to display a checkbox on user registration form.

see image below for detailed explanation of setting mentioned above


Overlay module does not work I updated my Drupal, but now the overlay module does not worki and everything shows on the center of page.

This is a temporary problem.

do these steps:

1-disable overlay module.

2-click on Save configuration at the end of page.

3-click on modules again

4-enable overlay module Save configuration

its like reseting a computer


add users to og group via vbo doesn't work: record is deleted immediately I like to add users to an OG group using vbo, a custom action and og_group().

I build up a page with a view of users to add (/node/%nid/add_user).

On this view I added a views bulk operations field with the "skip batch" option. (I skipped the batch to get the current %nid from the url).

In the custom code I like to add the selected user to the page shown. I know I can do this also with the standard group forms, but I want to do it this way :-)

So here is my code to subscribe the user to the group:

function mymodule_vbo_actions_users_woform(&$user_node, $context) {
  global $user;
  //dpm($node); dpm($context);return;
  switch ($context['settings']['action_type']) {
    case 'add_user_to_group':
      $nid_page = menu_get_object();
      if (!isset($nid_page)) $nid_page = arg(1);
      $nid_page = $context['page_nid'];
      $account = user_load($user_node->uid);
      //dpm($nid_page);
      $node_page = node_load($nid_page);
      dpm($user_node);
      dpm($account);
      dpm($node_page);

      $aValues = array('entity_type'=>'user','entity'=>$account,'membership type' => 'OG_MEMBERSHIP_TYPE_DEFAULT',);
      $og_membership = og_group('node',$node_page->nid,$aValues,FALSE);
      $og_membership->save();
      dpm($og_membership);

      // get member roles id for selected group bundle
      $result_roles = db_query("SELECT rid FROM og_role o where group_bundle = :bundle and name=:name and gid=:gid;",array(':bundle'=>$node_page->type,':name'=>'bidder', ':gid'=>$node_page->nid));
      $role_id = NULL;
      foreach ($result_roles as $key_roles => $value_roles) {
        $role_id = $value_roles->rid;
        break;
      }
      dpm($role_id);
      og_role_grant('node',$node_page->nid,$account->uid,$role_id);
      break;
  }
}

This code seems to be correct. I watched the og_membership table and the record for the selected user is inserted, but then DELETED immediately!?

So the question is of course: Why is the record deleted?

You might need to grant a OG role to the new member after adding them.

e.g. og_role_grant('node', $node_page->nid, $account->uid, 2);

The magic number on the end determines the type of role granted. 1 = non-member, 2 = member, 3 = administrator member


How to modify a cck field of Node A when Node B (referenced from Node A) is modified Drupal 6 Question:

I have two content types - a Property and a Task. The Task content type has a CCK Node Reference field that references the Property node it belongs to. When I modify a certain field in the Property node, I need to automatically update the "field_task_status" within it's referring Task node to "Complete".

I've been able to accomplish this with Rules 1 and VBO, but It seems like building a multitude of VBO views and triggered rules just to handle switching the Task node's status to "complete" or "pending" is a bit overkill.

Is there a more efficient way of doing this through a small custom module? I've heard that VBOs are heavy on the server, and I don't want to run into problems with the VBOs bogging down site.

I was initially thinking that I could write a query to get the nid of the referring Task node, and use that to load that Task and subsequently modify the value of its "field_task_status" ... I'm not a developer by trade, but I can put the code together if I have some idea of where to start.

Edit: Here's my attempt at coding a custom module, it's not getting me what I want...am I even close?

function mymodule_task_updater($property)
{
 $task_id =db_result( db_query(
 "SELECT tn.nid FROM content_type_task_notification tn,
 content_field_property_reference p, node n
 WHERE  n.nid=p.field_property_reference_nid
 AND tn.field_task_notice_type_value='Realtor Assignment'
 AND  p.field_property_reference_nid='%d' ", $property->nid ));

 $task = @node_load( $task_id );

if($task && $property->field_realtor_reference[0]['value'] == NULL)
   {
    $task->field_task_notice_status[0]['value'] = 'Pending';
    node_save($task);
   }
}

If you are careful you can use hook_node for this. You can check when node type property is saved, and load alter and save the task.

Make sure you put guards in place  otherwise it is easy to end up with recursion.


The correct way to change the name of the language in the language switch I try to change the name of language in language switcher from Chinese, Simplified(简体中文) to 中文. Changing name in admin/config/regional/language/edit/zh-hans affects only English. So the language switcher looks like this:

  en/Chinese, Simplified(简体中文)

I created a function, but on some pages (e.g. node/1), it causes errors.

function theme_preprocess_block(&$variables) {
   $variables['content']['#links']['zh-hans']['title'] = '中文';
}

The error I get is the following one.

  Fatal error: Call to a member function getText() on array in /var/www/mysite/core/includes/theme.inc on line 1697

How can I fix this?

Check, if the variable is set, to avoid the error:

function theme_preprocess_block(&$variables) {
  if (isset($variables['content']['#links']['zh-hans']['title'])) {
    $variables['content']['#links']['zh-hans']['title'] = '中文';
  }
}


Views field: how to add html 'title' attribute to link In views fields like [Content: Title] and [Content: Taxonomy] there is the possibility to have the content displayed as link. Is it also possible to equip these link with a html 'title' attribute?

Alternatively, is it possible to equip all links on a drupal site with html 'title' attributes?

This will add title attributes to most links, depends with some modules though.

/**
 * Add title attribute to any link that doesnt have a title already
 */
function YOURTHEME_preprocess_link(&$vars) {
    // If title set and not empty dont do anything
    if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
        return;
    }

    // Use the link text as the title
    $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}


CDN not working on multilingual site I have a site that is multilingual using path prefix, for example I can have:

example.com/en
example.com/es
example.com/fr

If the user goes to example.com, a language selection page appears (using the language selection module).

But I'm trying to enable the CDN module and it's not working because all resources are pointing to example.com/sites/.../somecss.css instead of example.com/en/sites/...

If I disable the CDN module the resources are pointed to the correct path.  How can I fix this?  I think it's bug in the CDN module.

Using Drupal 7 & Amazon CloudFront.  I don't want to change the site to subdomain for the languages (eg, en.example.com).

Found the issue the Language Selection Page module is causing the issue https://drupal.org/node/2283985. You can see the styles exemption in the code. For you I would add in the advagg and cdn paths to the language_selection_page_blacklisted_paths variable. You should find it under "Paths blacklist" on the admin/config/regional/language/configure/selection_page page.

Gotta run will add in the exact paths tomorrow, but it will be something like

  farfuture/*
  sites/default/files/advagg_css/*
  sites/default/files/advagg_js/*
  httprl_async_function_callback


How to automate the transfer of a registered user from Drupal to LimeSurvey? I have a Drupal site which is using the LimeSurvey Sync module. All is working fine.

Now I want to automate import user in LimeSurvey when user registered in my Drupal site.

Is there any option to do it?

I think you are looking for Rules. There you can check events like "After saving a new user account". And your action would be "Page redirect".


How can I alter the 'submitted by username' for a comment? I am rendering comments on my site. I am using the Zen theme. If I remark out <?php print $submitted; ?> in comment.tpl.php the 'username replied on' part is no longer rendered. But I don't want to remove the whole thing - just the 'replied on' text. I can't work out how to alter this bit. Thanks

In Zen comment.tpl.php it reads: '$submitted: Submission information created from $author and $created during template_preprocess_comment()'. Presumably, somewhere there will be: $author . 'replied on' - and this is what I need to alter.

Solution

A solution is to not use $submitted, but to use $author and $created separately in comment.tpl.php.


Trying to programmatically alter the id of an exposed filter in views This is for Drupal 7.

I am trying to modify an exposed filter's id in views. Basically we've noticed a use-case with multiple simple hierarchical selects on a given page, in separate exposed filter forms will conflict because they're using the same id attribute in the HTML.

The solution we've come up to to solve this is to append a short hash to the end of this id, making it unique across the page.

The problem is that I'm having trouble figuring out exactly where to do this, and the views objects' immense size doesn't help me in tracking down exactly where I have to make this change.

I'm trying things like this (this is in hook_views_pre_view):

$view->display['DISPLAY_NAME']->handler->options['filters']['field_FIELD_NAME_HASH-HERE'] = $view->display['DISPLAY_NAME']->handler->options['filters']['FIELD_NAME'];

$view->display['DISPLAY_NAME']->handler->options['filters']['field_FIELD_NAME_HASH-HERE']['expose']['identifier'] = 'field_FIELD_NAME_HASH-HERE';

$view->display['DISPLAY_NAME']->handler->options['filters']['field_FIELD_NAME']['expose']['operator_id'] = 'field_FIELD_NAME_HASH-HERE_op';

However this only seems to throw an error.

So how do I change the id on a given exposed filter for a view/display?

EDIT - this is the markup I am trying to affect:

 <select class="element-invisible shs-enabled form-select shs-processed" id="edit-field-FIELD_NAME" name="field_FIELD_NAME" style="display: none;"><option value="All" selected="selected"><option></option></select>
<select id="edit-field-FIELD_NAME-select-1" class="shs-select form-select shs-select-level-1 chosen-disable" style="display: inline-block;"><option></option></select>

Everywhere that has FIELD_NAME either has the default field name, or if I change it in Views, the changed identifier, however I can't seem to change any of these names programmatically - even with the answer below, which is what I really need to do.

How do I affect this markup?

Here is my current hook_preprocess_views_exposed_form:

if($vars['form']['#id'] == 'views-exposed-form-reference-views-block-1') {
    $number = <NUMBERHERE>;
    $vars['form']['#info']['filter-field_FIELD_NAME']['value'] = 'field_FIELD_NAME_' . $number;
    $vars['form']['field_FIELD_NAME_' . $number] = $vars['form']['field_FIELD_NAME'];
    $vars['form']['field_FIELD_NAME_' . $number]['#id'] = 'edit-FIELD-NAME-' . $number;
    $vars['form']['field_FIELD_NAME_' . $number]['#parents'] = array('field_FIELD_NAME_' . $number);
    $vars['form']['field_FIELD_NAME_' . $number]['#array_parents'] = array('field_FIELD_NAME_' . $number);
    $vars['form']['field_FIELD_NAME_' . $number]['#name'] = 'field_FIELD_NAME_' . $number;
    $vars['widgets']['filter-field_FIELD_NAME']->id = 'edit_field_FIELD-NAME-' . $number;
    unset($vars['form']['field_FIELD_NAME']);
  }

I think you might be using the wrong tool for the job. It sounds like this is a theming problem, not a views data structure problem (which would use something like hook_views_pre_view().

You can override the template views-exposed-form.tpl.php to override the markup of the exposed form & the preprocess function template_preprocess_views_exposed_form() to override the markup form widgets:

function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // @TODO: alter markup of $vars['widgets']['filter-MYFILTER']->widget.
}

Alternatively, the views UI provides a means to change the id element by changing the Filter identifier underneath the More fieldset which also changes the URL query parameter used as well.


Is it possible to run a Drupal 7 on 2 domains? I'm not sure is it about the server or Drupal. Anyway, my Drupal was installed inside the directory "/public_html" folder. We are pointing "mysiteA.com" and "mysiteB.com" into this directory.

Both urls look the same but only "mysiteB.com" is able to login. And "mysiteA.com" is showing "access denied" after submit the login form. The question is, Drupal is showing "mysiteB.com" domain inside the "configuration > Site information". Is there a way to change it to be "mysiteA.com" or both(not sure is it possible)?

Let's back up and debug this from the top:

Confirm that both sites actually point to the same Drupal installation.

Open up a terminal or command prompt. Ping mysitea.com and mysiteb.com. Confirm that the IP address is the same for both domains.
Create a dummy file test.html in the Drupal root. Confirm that you can access it from both mysitea.com and mysiteb.com.

Confirm both sites actually use the same database

Look in the sites directory. The only two directories should be "default" and "all". If you see mysitea.com or mysiteb.com, it's possible you are using different DBs.

Figure out what Drupal config is causing the error

Confirm that you don't have any domain-related modules installed (domain access).
See if clearing all cookies after switching to the second domain let's you log in. i.e., is the problem that you can't ever log in to one of the domains, or that you just can't log in to them one after another? This could be due to the cookie domain.

Try setting $cookie_domain in settings.php for each site.

EDIT: Now I see that you tagged your post "domain-access", so I'm assuming you are using that module. Why didn't you say that in your post? That's kind of a critical thing to know if your problem is related to accessing a site on two domains ;) I'm pretty sure it's just a misconfiguration or bad permissions related to Domain Access. Try disabling it and see if you can access both sites.


Is this normal to have Drupal Commerce stuck in PENDING status after a completed paypal payment? I'm testing out drupal commance and setup a paypal sandbox seller/buyer account. When I complete a payment with the test accounts, the status of the order says "PENDING" is this what its suppose to do after a successful payment?

I would imagine it would say PAID. I see there are other order status options such as checkout complete. Shouldn't it say that instead of Pending?

Orders aren't being "stuck" here so much as placed here for you to determine what to do with them. When you build a Drupal Commerce site, you should consider what needs to happen to an order after the checkout process has been completed / payment has been received and either implement a manual process or some form of Rules or code based automation to do it. Drupal Commerce leaves it here because we don't make any assumptions about the type of product a Commerce site sells or the business processes involved in taking an order from checkout completion to final fulfillment.

PayPal WPS and related payment gateways are a bit of a special case, too, in that you actually cannot use the "When an order is first paid in full" event to manipulate the order status. Because these orders may not have completed the checkout process when their payment notifications arrive at the site, the checkout router still depends on these orders being in a checkout order status to complete the checkout process after the payment has been processed.

Instead, if you need to update the order status based on payment receipt for PayPal WPS, you should use the "Order balance comparison" condition in conjunction with the "Completing the checkout process" event to update the order status on that event instead if payment has been received. Additionally you can use a "Data comparison" condition to check the order status on the "When an order is first paid in full" event and update the order status if the order is not still in a checkout order status.


AJAX populated filter breaks when Views Dependant Filter module added I have a view with two exposed filters and I want to make the second filter dependant on the first in 2 ways

A user has to select an option from the first filter before the second is available to use. Achieved using Views Dependant Filters
The options within the second filter are dynamically updated so only combinations that will return results are presented. Achieved following this Views AJAX Dynamic Dependent Exposed Filters tutorial and creating a custom module.

I have an example of this view available on this development server.

Select an option from filter one and the second filter becomes available and it's options are updated as expected.

The problem occurs when you select a second different option from the first filter. The AJAX does not fire and the second filter options are not updated.

Code for updating filter two with AJAX is below, but I believe the problem lies on the client side.

I appreciate your suggestions.

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

        $form['#after_build'][] = '_sort_alphabetically';

        if(!empty($form_state['values'])) {
            $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
        }

        $selectedCommodity = $form_state['input']['field_commodity_tid'];
        $form['field_keywords_tid']['#options'] = _get_associative_array_from_view(
            'annotated_bibliography_dependant_keywords', // view id
            'default', // view display id
            'taxonomy_term_data_field_data_field_keywords_tid', // key field id
            'taxonomy_term_data_field_data_field_keywords_name',
            $selectedCommodity // term id of the selected shape
            );
        $form['field_commodity_tid']['#ajax'] = array(
            'callback' => '_update_keywords_callback',
            'wrapper' => 'keywords_wrapper',
            );
        $form['field_commodity_tid']['#ajax']['progress']['type'] = 'throbber';
        $form['field_commodity_tid']['#ajax']['progress']['message'] = 'Updating keywords';
        $form['field_keywords_tid']['#prefix'] = '
';
        $form['field_keywords_tid']['#suffix'] = '
';
    }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_keywords_callback($form, $form_state) {
    return $form['field_keywords_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}

I was able to make the second filter dependant in both ways without the need for Views Dependant Filters by adding additional logic to my hook_form_views_exposed_form_alter.

if($form_state['input']['field_commodity_tid'] === 'All')
    $form['field_keywords_tid']['#disabled'] = 1;
}

Here is the entire working code:

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

        $form['#after_build'][] = '_sort_alphabetically';

        if(!empty($form_state['values'])) {
            $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
        }

        $selectedCommodity = $form_state['input']['field_commodity_tid'];
        $form['field_keywords_tid']['#options'] = _get_associative_array_from_view(
            'annotated_bibliography_dependant_keywords', // view id
            'default', // view display id
            'taxonomy_term_data_field_data_field_keywords_tid', // key field id
            'taxonomy_term_data_field_data_field_keywords_name',
            $selectedCommodity // term id of the selected shape
            );
        $form['field_commodity_tid']['#ajax'] = array(
            'callback' => '_update_keywords_callback',
            'wrapper' => 'keywords_wrapper',
            );
        $form['field_commodity_tid']['#ajax']['progress']['type'] = 'throbber';
        $form['field_commodity_tid']['#ajax']['progress']['message'] = 'Updating keywords';
        $form['field_keywords_tid']['#prefix'] = '
';
        $form['field_keywords_tid']['#suffix'] = '
';

        if($form_state['input']['field_commodity_tid'] === 'All')
            $form['field_keywords_tid']['#disabled'] = 1;
        }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_keywords_callback($form, $form_state) {
    return $form['field_keywords_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}


How to setup gmap maps on nodes (using location fields) I use the gmap and the location to show maps in nodes by adding the location field to the node content type.

Let's say I have 2 content types: Pubs and Restaurants
Each one of them have a location field which allows me to show a map for the nodes.
So far so god.

My problem is that I see no way to setup the map (zoom, marker, ...) in a different way for each one of the content types.

Let's say I want to set the zoom for Pubs' maps to 12 and the zoom for restaurants' maps to 10.

The only way I see to setup the maps is in admin/config/services/gmap, but these setting affects maps in all nodes of all content types.

I need to customize maps for each content type.

Using OpenLayers instead of Gmap you can set up different maps for different fields. It's more complicated, but with more options.


What is the correct token for a multi value field? Oke, so I have this multi value field in drupal 7 and I want to use it's values in a custom php snippet in the rules module.

I found the Array Tokens module to generate an array of the values, but that is for Drupal 6.

Then I found Architecture RFC: Field token architecture, which makes me assume I could use [node:field-name:0] or [node:field-name:value:0] to read the first entry, but I either replaces nothing of throws an error (I have tried various combinations).

Could someone tell me:

What is the right way to read a token with it's delta value?
How to get the delta of the fields so I can start a for loop?

Since the rules module gives you access to the $node object (if triggered on 'after saving content'). I managed to use it like this $node->field_myField['und'][0]['value']. Where 0 is the delta and und (probably) the language.

Since this looks like a multidimensional array I assume one could use a foreach on $node->field_myField['und'], but I did not test this.


HIde node in view when field message is equal Can I hide a node in a view when they have a specific message? Like, if the message: "Please don't show this node" is equal with specific field content then hide him in the view, else show him?

Is there an option for this?

Just an idea if you can try...

As per my point of view you may try to use flags with the timer? whenever the countdown is ended invoke a flag and you can use this flag in views.If the flag is invoked do not show the content else it will be visible.


Escape forward slashes in hook_update_n() descriptions for display on update.php I've created a module update function:

/**
 * Create alias for node/add/video-submission.
 */
function my_module_update_7103()
{
  // magic
}

But on update.php the message shows up without the forward slashes:

  7103 - Create alias for nodeaddvideo-submission.

What can I do to force the forward slashes to display?

Given that line 1161 of includes/update.inc is this:

$description = str_replace(array("\n", '*', '/'), '', $func->getDocComment());

(replaces new lines, asterisks and forward slashes in the doxygen comment with blank strings, everything else is considered to be the update description)

I'd say you have two options:

Use an HTML entity:

/**
 * Create alias for node&#47;add&#47;video-submission.
 */

Patch the offending line with something like:

$description = str_replace(array("\n", '/*', '*/', '*'), '', $func->getDocComment());


How do I create content programatically? In WordPress I can use wp_insert_post() to create content programatically.

Is there any similar function available for Drupal 7, that will allow me to insert posts (and pages) into the database programatically?

you can create a custom function to create a node.

function create_my_node() {
  $node = new stdClass();
  $node->type = 'your content type';
  node_object_prepare($node);

  $node->title = "your title";
  $node->language = LANGUAGE_NONE;
  global $user;

  $newnode->uid = $user->uid;
  $newnode->name = $user->name;
  $newnode->status = 1;     // 1 means published
  $newnode->promote = 0;
  node_save($node);
}