Can't use Google Analytics Statistics Module - Impossible to login I'm trying to use Google Analytics Statistics module but it won't accept my login credentials. I know they're correct because I tried them independently multiple times on the same browser to login to Google directly. I've also now try entering them 10's of times in the module and it never takes them. It takes my username but then rejects my password and gives the error 'Invalid Google Analytics login.'

I thought I found the solution, here, and it seemed to work for everyone else, but not for me. https://www.drupal.org/node/1370742

I did the patch - didn't help. I ran cron and clear caches a million times. I re-installed the module. I made sure I was logging in from the same browser where I was already logged into Google.

Note: Google never sent me an email, not once, asking me to confirm my login as the referenced article above suggests it would do.

Turns out this module is no longer supported and it appears many others also have problems authenticating with it. I recommend NOT using it. I also tried Google Analytics Statistics Counter module, and while I was able to get it setup it wasn't as intuitive as I'd hoped so I just used the 'Statistics' core module, even if it's not the 'preferred' choice performance-wise. For now it will do.


Attaching multiple webforms to a node I need not one, but three different webforms for my content type. So far I've seen that the webform module allows for only one webform per node. Any suggestions?

EDIT:

To clarify why I can't use the easy solution using blocks - I need to have each instance of the webform prepopulated with the node title (the node the webform is attached to) and I also need it to open in a lightbox. For making that work with one webform I used this solution, however, adding more webforms to the mix makes it more complicated.

Webform allow embed form as block, so you can build 3 webforms, then show one in main content, and other 2 as blocks...


Views filter has taxonomy term in whole vocabulary I'm trying to use the "has taxonomy term" filter in a view together with Views Populate filters (https://drupal.org/project/views_filters_populate).

The taxonomy filter has not to be exposed because the exposed filter is the one created with Populate filters.

The site admin continuosly add new term to the vocabulary.

Consequently I cannot fill the "is one of" setting for the "has taxonomy term" filter.

I would need some settings like: if the term is in the vocabulary.

Any idea?

It seems strange to me that you cannot use the same input field to search for example in title and in a term reference field.

thank you in advance

I've reached this question while looking for something similar and couldn't find anything relevant. Yet, after searching trough views options, I've managed to achieve something I think is the easiest workaround to our mutual issue, which is why I'm resurrecting this question.

First things first, I've created a View to show all the  taxonomy terms of certain vocabulary and replaced the output as a link to, say, /disciplines/[Term ID]. Afterwards, I've created a view to replace the taxonomy display page and defined the term id as a contextual filter to the url(using the % replacement). Now every time the admin creates a new taxonomy term, the first view will always redirect to the second one with all the good stuff Views can offer.


Import data from remote database I want to import locations from my remote non drupal database. I can't use feed as it does duplication. Is there any custom solution?

Generally the migrate module is very flexible.


How can I create a Views list of all users with either a node OR a comment? I need to do some major user pruning. I run a Q&A site and need to find all users who have written a comment or created a node . Currently in Views I can't figure out how to do this.

Is it possible in Views or do I need a custom query ? What might that query look like?

Thanks!

As far as I know you can't create Views for more than one entity type. You would have to create separate Views, one for nodes and one for comments; you CAN however make them appear in the same page by using Views Field View. You can sort each view by author, and get rid of duplicates by using the Aggregation option.

EDIT:
There IS a way to do two EntityFieldQuery (one for node and one for comment) and then create a single array of authors. Something like this:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node');
$node_list = $query->execute();

$query2 = new EntityFieldQuery();
$query2->entityCondition('entity_type', 'comment');
$comment_list = $query2->execute();

$author_ids = Array();

$nodes = node_load_multiple(array_keys($node_list['node']));
foreach ($nodes as $node) {
  $author_ids[] = $node->uid;
}

$comments = comment_load_multiple(array_keys($comment_list['comment']));
foreach ($comments as $comment) {
  $author_ids[] = $comment->uid;
}

$author_ids = array_unique($author_ids);
dpm($author_ids);

You can then do whatever you want with the list of uid's - for example load  the users and create a table programmatically for display.


Mobile switch more than is mobile is not mobile D7
I am using mobile switch with panels to display different views for different devices, but the only options I see are is mobile or is not mobile. On bigger devices like tablets I would like to display something other than what I would show on mobile phone. Is there any way I can get more option in mobile switch?

People on tablets prefer to browse the Desktop version.

From this page: https://developers.google.com/webmasters/smartphone-sites/tablets:

  If your website has different pages to serve desktop and smartphone
  users and does not have tablet-specific pages, in our experience
  tablet users usually expect to see your desktop site rather than the
  site's smartphone pages.

Mobile switch does not work with caching on.

So I'm using the php code from this site:  http://detectmobilebrowsers.com/

Also see : https://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser.

So if you want more control, you need to write your own module giving the flexibility you need.


How to conditionally load javascript file on view page I'm trying to load some theme javascript only to one view(multiple displays). I've tried to use the views preprocessor funciton, but maybe I'm doing it wrong:

function themename_preprocess_views_view__viewname__page(&$variables){
  this doesn't run on view page;
}

I've also tried it with the function name themename_views_view(). There's not much documentation on this.

This should work:

/**
 * Implements template_preprocess_views_view().
 */
function themename_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'view_name') {
    // Standardize the output for rows.
    drupal_add_js(drupal_get_path('theme', 'themename') . '/js/js_name.min.js', array('scope' => 'footer'));
  }
}


Views and Taxonomy Terms Page Layout I have a view that sorts by a taxonomy term. After the view layout, i need to find a specific way to have that page that's clicked on to be styled with a different background. For instance, this view will show a background of a Football, but I also have a view for other sports. Is there a way to determine the page name? Right now, its just a node-page-profile.  Here's the link.

http://dev-httpwwwrestechsyscom.pantheon.io/profiles-football

Ok, you want to expose your taxonomy to your nodes to change the background.

Using the Context Module

  Add a condition Taxonomy and select your term (football) and the
  reaction Theme HTML add the class (football). As far as I got here you
  will need one rule for each term, you can't use a token directly.

Using a custom module

You can do it with a custom module or just throw a preprocess_page it in your theme:

function my_theme_preprocess_page(&$vars, $hook) {
  if (module_exists('taxonomy') && $vars['node']->nid) {
    foreach (taxonomy_node_get_terms($vars['node']) as $term) {
      $vars['node_terms'] .= ' taxonomy-'.strtolower(eregi_replace('[^a-z0-9]', '-', $term->name));
    }
  }
}

Got from: https://www.drupal.org/node/67587

BTW you should really change the path for the nodes! I know it is still in dev but don't forget it!


How do I make form_set_error() affect the submitted form only? I have a couple of different forms on one page; each has a 'name' field.

Sensibly, on submission drupal processes the submitted form, but in what seems a completely barmy way of doing things, form_set_error() just takes a field name, and appears to have no knowledge of which form was submitted.

So if the name field is invalid on the submitted form, it gets marked as invalid on all the other forms that use a field called 'name'.

Does this mean that every field needs a unique field name, e.g. name-somemodule1 and name-somemod2? This will break user convenience (browser probably knows what to pre-fill for 'name').

Sure I've missed something, but have read a lot of FAPI pages and code comments and am still confused.

In the screenshot below, you'll see 2 forms. The one on the left is the submitted one, with 'invalid-name' in a field called 'name'. The one on the right is not submitted (can only physically click one submit button at once!) and yet it's 'name' field (with 'admin' in it) is also marked invalid.

These are entirely separate forms.

Here's my modules' code (email field omitted, some attrs omitted just to reduce post size)

function mymod_contact_form() {
  $form['comment'] = array(
    '#title'         => t('Enter query'),
    '#default_value' => '',
    '#type'          => 'textarea',
  );

  $form['name'] = array(
    '#title'         => t('Enter name'),
    '#default_value' => '',
    '#type'          => 'textfield',
  );

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

  return $form;
}

function mymod_contact_form_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  if (strpos($name,' ') === FALSE) {
    form_set_error('name', t('Please enter your full name'));
  }
}

function mymod_contact_form_submit($form, &$form_state) {
  $vals = $form_state['values'];
  // …
}

There is definitely a limitation in Drupal core that is causing form fields with with the same name to be styled as "error" even through the validation error happened on a different form that was submitted on the same page.  Looking at the code for Drupal version 6,7,8 (as of now) - they all have this limitation.  The good news is that the patch I put together (for Drupal 6) to fix this problem is fairly minimal and it involves using the form_id to properly scope the form element with the validation error.  I've haven't done much testing with it, so use it at your own risk.  The changes required for Drupal 7 should be similar.

diff --git a/includes/form.inc b/includes/form.inc
index 1529c19..4052133 100644
--- a/includes/form.inc
+++ b/includes/form.inc
@@ -798,29 +798,41 @@ function form_execute_handlers($type, &$form, &$form_state) {
  *   The error message to present to the user.
  * @param $reset
  *   Reset the form errors static cache.
+ * @param $scoped
+ *   Returns the errors scoped with the form_id
  * @return
  *   Never use the return value of this function, use form_get_errors and
  *   form_get_error instead.
  */
-function form_set_error($name = NULL, $message = '', $reset = FALSE) {
+function form_set_error($name = NULL, $message = '', $reset = FALSE,$scoped = FALSE) {
   static $form = array();
+  static $form_scoped = array();
   if ($reset) {
     $form = array();
+    $form_scoped = array();
   }
   if (isset($name) && !isset($form[$name])) {
     $form[$name] = $message;
+    if(isset($_POST['form_id'])) {
+      $name = $_POST['form_id'] . "::" . $name; // Scope it based on form_id
+    }
+    $form_scoped[$name] = $message;
     if ($message) {
       drupal_set_message($message, 'error');
     }
   }
-  return $form;
+  if($scoped) return $form_scoped;
+  else return $form;
 }

 /**
  * Return an associative array of all errors.
+ *
+ * * @param $scoped
+ *   Returns the errors scoped with the form_id
  */
-function form_get_errors() {
-  $form = form_set_error();
+function form_get_errors($scoped = FALSE) {
+  $form = form_set_error(NULL,'',FALSE,$scoped);
   if (!empty($form)) {
     return $form;
   }
@@ -828,16 +840,29 @@ function form_get_errors() {

 /**
  * Return the error message filed against the form with the specified name.
- */
-function form_get_error($element) {
-  $form = form_set_error();
-  $key = $element['#parents'][0];
-  if (isset($form[$key])) {
-    return $form[$key];
-  }
-  $key = implode('][', $element['#parents']);
-  if (isset($form[$key])) {
-    return $form[$key];
+ *
+ * * @param $scoped
+ *   Returns the error scoped with the form_id
+ */
+function form_get_error($element,$scoped = FALSE) {
+  if($scoped && isset($element['#form_id'])) {
+    $form_id = $element['#form_id']; // Try to make the error form specific
+  }
+  $form = form_set_error(NULL,'',FALSE,$scoped);
+
+  for($i=0;$i<2;$i++) {
+    if($i==0) $key = $element['#parents'][0];
+    else $key = implode('][', $element['#parents']);
+
+    if(isset($form_id)) {
+      $key0 = "$form_id::$key"; // Provide the scope based on form_id
+      if(isset($form[$key0])) {
+        return $form[$key0];
+      }
+    }
+    if (isset($form[$key])) {
+      return $form[$key]; // If form_id not found then try without it
+    }
   }
 }

@@ -896,6 +921,7 @@ function form_builder($form_id, $form, &$form_state) {
   $count = 0;
   foreach (element_children($form) as $key) {
     $form[$key]['#post'] = $form['#post'];
+    $form[$key]['#form_id'] = $form_id;
     $form[$key]['#programmed'] = $form['#programmed'];
     // Don't squash an existing tree value.
     if (!isset($form[$key]['#tree'])) {
@@ -2246,7 +2272,7 @@ function _form_set_class(&$element, $class = array()) {
   if ($element['#required']) {
     $class[] = 'required';
   }
-  if (form_get_error($element)) {
+  if (form_get_error($element,TRUE)) {
     $class[] = 'error';
   }
   if (isset($element['#attributes']['class'])) {


How to use commerce_shipping hooks I'm trying to construct a shipping module for UK's Royal Mail (or at least the parts I need right now...!).  I've written PHP code for calculating what methods are applicable based on shipping address and weight, but plumbing this logic into my site is eluding me.  I should add that, as Royal Mail doesn't have an API for pricing, my module bundles the rate-tables for the various methods/services (CSV format) so I need to use code, not Rules, to implement it.

It seems the way to do this is to use the hook_commerce_shipping_* hooks, but it doesn't appear that I'm doing so correctly.

This is my first experience with using hooks (and Drupal on a serious dev level, TBH) but I have successfully implemented hook_commerce_cart_product_prepare() in another custom module, so I think what I'm doing should be working.  In my module I wrote the following, just to test that I'd successfully implemented the hook:

/**
 * Implements hook_commerce_shipping_calculate_rate()
 */
function royalmail_commerce_shipping_calculate_rate($line_item) {
    drupal_set_message(print_r($line_item, TRUE),'error');
}

...and it seems I hadn't, because the message never appeared when I progressed to the shipping pane of the checkout.

I also tried various other "canaries" I should be able to spot evidence of, including but not limited to drupal_exit(), echo, die(), var_dump() and so on, but nothing appears.  Same story for hook_commerce_shipping_collect_rates(), which I actually tried to implement first but ended up doing so with Rules instead while I was scratching my head (though I'd prefer this be in native code too, ideally).

Am I doing it wrong? Thanks in advance.

It looks like you are using commerce shipping 2.x which differs a lot from 1.x in terms of integration.

What you need to do is:

Define a shipping method, use hook_commerce_shipping_method_info.
Define one or more shipping services use hook_commerce_shipping_service_info
When you define the shipping services, you can select a rate callback, if none is selected, commerce shipping will by default try to use SERVICE_NAME_rate, where SERVICE_NAME is the keyed name used in the hook_commerce_shipping_service_info hook. The rate callback have this signature:

function service_name_rate($shipping_service, $order) {
  // Logic here.
  return array(
    'amount' => $amount,
    'currency_code' => $currency_code,
    'data' => array(),
  );
}

You can look at the example module within the commerce shipping module which serves as documentation, or you can look at some of the other shipping methods, like UPS.


Changing position of product fields I'm learning Drupal Commerce with a Commerce Kickstart installation. I understood in part the way products are displayed, with variation types and content types.

Have made some changes like visible/hidden product fields, and change the order product fields are displayed. But didn't get how, for example, in

http://demo.commerceguys.com/ck/bags-cases/commerce-guys-laptop-bag

the bag image stay positioned left side and others product fields right side.

I'm running Drupal 7 and Commerce Kickstart 2

Edit: See that image go left side because the variation type field is images. I've created variation type with variation type field image. If set do that way, the image stay in the same column as the other fields.

If you look at the View Source of the webpage in your browser you will see that the CSS says class=" ... grid-N ... " so part of the answer is that they are using a Grid based CSS framework to layout the node content.

This type of stuff is easily achieveable with Field Group, Display Suite or Fences to layout a content type in this fashion.


Is the ckeditor or other editor supposed to be automatically installed? In a fresh install of Drupal 7, when you create and article or page, is there supposed to be an editor?  When I create an article or page, it's just the text area where you type in the content.  There is no editor so I can bold, upload an image, justify, etc.

Did I do something wrong?

admin/config/text formats, Full html, Administrator; I am the administrator.

No there's no WYSIWYG editor included with Drupal, you need to install one of the contrib modules.

WYSIWYG is the standard solution as it gives you a choice of editors, but there are others like the standalone CKEditor module.


filter based on user reference I have a content type "book" that has an entity reference field that references users and pulls in a name.  Users also has fields for a picture and an author website.

I would like to add a block at the bottom of each book node that shows the author picture and website.

What is the correct way to set up the relatioknship and filter when there is no user ID in the URL?

Set up the relationship. Under the Relationships section click + to add a relationship.

Under "Add relationships" you will see all fields listed.
Drop down the Groups menu and select "Content".
Locate your node reference field, for example 'Content: Reference user (field_reference_user)'. Check the box to the left of it.
Click the Add button.
Check the box labeled 'Require this relationship', and click the Update button.

Add a Contextual filter for Node ID. Set the default value -> get ID from URL
Add a field. Click + next to Fields. Under Groups, select Node, and choose Node: Title. Under Relationship, select your node reference field, e.g., Reference user, click Update.

Create a view on a node reference field will explain you in detail


Adding confirm email field to entityform I am using email field module and entityform for a simple contact form on a Drupal 7 install. I need to add an extra field where the user re-enters their email address (no copy and paste) to prevent typos.

This seems like a simple enough requirement so I'm wondering if I'm just overlooking something in entityform or email field that will help me do this, or perhaps an additional module?

Can anyone recommend a method to achieve this?

Plan B is to use jquery.

Thanks!

You can use CCK Match to achieve this goal.


Programmatically change redirect after logout I'm actually looking for a solution in Drupal 8 to change the redirection destination after visiting /user/logout page. I want to redirect the user on /user/login instead of home page.

Try this but not working, I'm still redirect on home page :

/**
 * @file
 * Contains my_module.module.
 */

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_module_user_logout($account) {
  // We want to redirect user on logout.
  $response = new RedirectResponse("user/login");
  $response->send();
  return;
}

hook_user_logout() doesn't expect a redirect response object and won't respond to it.

One alternative here, if you don't need a programmatic forcing of redirection, is to use the destination query parameter. The path supplied in the parameter will be redirected to upon logout. For example: http://example.com/user/logout?destination=user/login will return a user to the login page following logout.


Drupal 7 views Contextual filters with Page & Blocks I have an issue and i'm hoping to get some advise.

I have a view created that show content based on the url:

eg:

domain.com/item/one

Shows fields for my node with the title one

domain.com/item/two

Shows fields for my node with the title two

etc etc.

The path for the PAGE in views is set to /item

What I'm having trouble with is I need to have a BLOCK (becuase I'm making it collapsable) show under that page with the specific URL show the body field for that node.

eg:

domain.com/item/three

Shows fields for my node with the title three as well as a block that show the body field for node three

I have set the Contextual filter for the PAGE to:

Content: Title

When the filter value is NOT in the URL
Show "Page not found"

Exception value : Empty (All removed)

Under More:
Case : Lowercase
Case in path : Lowercase

Transform spaces to dashes in URL : Checked

This works for the page but please let me know if I have set this up incorrectly.

I have set the same Contextual filter for BLOCK and it works in views preview but not on the page with the URL:

domain.com/item/three

I also tried adding Global: Null Contextual filter before the Content: Title filter which allowed me to put item/three in the preview and it works (before worked with just three). This also didn't work on the actual page.

Any advise on this would be greatly appreciated.

Contextual filters works well for any display type that has a path. A path makes it easy for views to determine what information should be passed into the contextual filters.

The problem with blocks is that they don't have a path. Views does not look at the current url and automatically pass values to the filters because it has no idea which parts of the url to use.

You can get around this by using Default Values (or page manager/panels, but that's a whole other topic).

In the settings for your block contextual filter, you will want to override the configuration and select Provide a default value. Under type choose Raw value from URL and set the Path component to 2 (the path component will be different depending on your URL, but for domain.com/items/node-title the component is 2)

When you assign your block to a region, you probably want to set the allowed paths so this block won't show up anywhere else. The path component is "hard coded" so if your path ever changes you will need to adjust it.


How do I toggle the update warning? I recently used drush to update my site. This is the current drush status:

$ drush status
 Drupal version                  :  7.29
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database username               :  %$^&*(
 Database name                   :  %$^&*(
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  openchurch_theme
 Administration theme            :  seven
 PHP configuration               :  #$%^&*
 PHP OS                          :  Linux
 Drush version                   :  6.4-dev
 Drush configuration             :
 Drush alias files               :
 Drupal root                     :  #$%^&*
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp

But when I visit my admin page, I still get the "You need to upgrade" message. How do I get it to stop?

Here is the update screen:

In this particular case, the issue was that Drupal 7.30 had become available, and the UI of the site was reporting that it had 7.28 installed. This was cached by an out-of-date cache, I believe. Everything was resolved when I updated from 7.29 to 7.30.


Multiple Separators! How? I've got a field called Name (Entity Reference) that sometimes has 2 values. It would require some kind of Rules I guess. Just not sure how it can be done. I created a taxonomy which has 3 values: "none", "backslash", "and".

So what I wan't to do is if there are 2 values and I've chosen "backslash" the output will be "Name1" / "Name2".

If there are 2 values and I've chosen "and" the output will be "Name1" & "Name2".

Am I on the right track here?

This doesn't sound like a Rules problem. (yet)
To re-state the issue: you are trying to output display the values, and use a delimiter when there are multiple values.  Correct?

If so, where is the display taking place, of for example, "Name1" / "Name2"
Is this in a Node, View, Module ... or elsewhere?  Please be as specific as possible.

A Rules problem would sound like "for Trigger X I expect Action Y to take place".


Changing Account password using rules I'm using rules module in my site (drupal 7), i want to create a small form to the user to change his password without going to (account editing page).

This form contain 3 textbox (old passowrd, new password, confirm new password).

Can i make this form using rules?
or is there another module can help me with that?
Thanks a lot.

The best way would be to make a custom page using hook_menu(), and have a submit function on that page that would check the user's authentication, and if it was correct, change the current password.

If you need a bit more information on that, I'm happy to help.


How to limit one role per user? How do I limit one role per user?

I want to see a select form field, instead of checkboxes for roles when I go to /user/#/edit.
So far I tried overwriting the $form['account']['roles'] in template.php, replace the checkboxes with a select dropdown, but failed.

You will be best using hook_form_alter().

You can edit the registration form & user edit form and change the type in a custom module.

function register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id= 'user_register_form') {
    $form['user-register-form']['roles'] = array(
      '#type' => 'radios'
      // …
    );
  }
}


Print search field in template file I need a search field to "pop down" under a search icon ({# Search icon #} in sample code) in my template file.

But how do i print the search block directly into a template file?

I want it to be in my menu--main--site-main-menu.html.twig

    {% import _self as menus %}

          {#
            We call a macro which calls itself to render the full tree.
            @see http://twig.sensiolabs.org/doc/tags/macro.html
          #}
          {{ menus.menu_links(items, attributes, 0) }}

          {% macro menu_links(items, attributes, menu_level) %}
          {% import _self as menus %}

          {% if items %}

          {# List #}
          {% if menu_level == 0 %}

    {% else %}

        {% endif %}

        {% for item in items %}
            {% set item_classes = [
            item.in_active_trail ? 'active',
            ] %}

            {# List item #}
            {% if item.below and item.is_expanded %}

            {% else %}

            {% endif %}

            {# Link #}
            {{ link(item.title, item.url) }}

            {# Submenu #}
            {% if item.below %}
                {{ menus.menu_links(item.below, attributes.removeClass('layout-navigation layout--large-screen-only'), menu_level + 1) }}
            {% endif %}

        {% endfor %}

        {# Search icon #}

    {% endif %}

    {% endmacro %}

One way is to preprocess the menu and inject it as a variable, then print the variable:

use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_menu().
 */
function mytheme_preprocess_menu(&$variables) {
  $block = Block::load('myblock');
  $variables['myblock'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
}

Then in your template:

{{ myblock }}


Use Views to display tabs such as, "Add User Relationship," "Send message," etc In D7, is there a module that allows to display tabs similar to the following ones, in Views?

Add Relationship
edit
Messages
Send Private message

I want to add these tabs as views blocks so I can place them where I want.

I didn't understand your question clearly, where are you getting those tabs from? If its a View you could use the Views Display Tabs module, unfortunately the D7 port still hasn't been started it seems: http://drupal.org/node/985960 - Its a good time to write a patch for it or hire someone to do it for you.


REST Service - 500 Internal Server Error I has been trying to set up a drupal REST Server in my computer (a clean drupal 6  installation). Unfortunately, I could not configure it. When I send a POST message (WITHOUT parameters);
ht.p://localhst/drupal/?q=note/note/retrieve or  ht.p://localhst/drupal/?q=note/user/login, it replies 500 Internal Server Error.
I used this example (I copied and pasted the example to sites/all/modules)  https://drupal.org/node/783460.
It is a drupal 6.28 in a Debian with Apache2. It has not configured clean URLs!
I am using the module Services (6.x-3.4-rc1) and Rest Server (6.x-2.0-beta3).
I checked the /var/log/apache2/error.log

[Sun Jun 23 17:11:24.136866 2013] [:error] [pid 2957] [client ::1:48424] PHP
Fatal error:  Call to undefined function services_resource_uri_formatter() in /var/www/drupal/sites/all/modules/rest_server/includes/RESTServer.inc on line 15

I have another doubt, how is it possible to test these services easily? These error messages for me are  not intuitive. I was using drush with watchdog but
I didn't give more information.
Regards.

The problem was when I used the drush tool. It downloaded and installed the Services module, and the Rest Server module (another no necessary module).
This error was describing this conflict between modules;

[Sun Jun 23 17:11:24.136866 2013] [:error] [pid 2957] [client::1:48424] PHP
Fatal error: Call to undefined function
services_resource_uri_formatter() in
/var/www/drupal/sites/all/modules/rest_server/includes/RESTServer.inc
on line 15

I disabled the Rest Server and restarted the HTTP server.


Display comments according to the users roles I try to create various tabs for my nodes, which show a specific field and the comments of the users according to their roles :

I would like that these tabs are pages, and not in Javascript tabs.

I tried with Views, I created a view of comments, I manage to create pages, to have comments according to the roles, but not to add the desired field (what must be normal because it is about a view of comments and not about contents) :

I could can possibly serve me as templates, with templates suggestions, create a template by page, but I do not know how in the template to display comments according to the roles of the users...

Would you know a solution?

You are almost there. You just have to have new display
for each role. See below.

Set the path as below, per role per display:

It will appear as below in node page:


Insert query using ajax drupal I am totally new to Drupal Ajax. In my projects one simple form with submit button only there for insert "yes" value to Database. so it should be done with Drupal Ajax. So When that button submit the value should be store in Db with out page load and after submit display text " successfully selected" instead of button.

So please anyone can help me for this task

First of all I want to point you to the AJAX Example module. This has some neat examples on how to use it.

For your task what you basically need is the following:

Replace normal submit handler by custom submit handler
Add an AJAX callback and wrapper to your submit button
Do your database queries in the submit handler, force rebuilding the form and define the message.
Replace the submit button of your form with a new one and show the message.

I cannot test the following code right now but it should basically give you the idea:

<?php

function MY_MODULE_form($form, &$form_state) {
  // some form elements

  $form['submit'] = array(
    '#type' => 'submit',
    '#submit' => array('MY_MODULE_form_custom_submit'), // define custom submit handler
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'MY_MODULE_form_callback', // define ajax callback to show the message
      'wrapper' => 'my-submit-button', // define what div should be replaced
    ),
    '#prefix' => '
', // wrap this button in the div that is replaced
    '#suffix' => '
',
  );
}

function MY_MODULE_form_custom_submit($form, &$form_state) {
  // do your db query
  drupal_set_message(t('Something has been done!')); // your message

  $form_state['rebuild'] = true; // rebuild the form. not sure if this is required now.
}

function MY_MODULE_form_callback($form, &$form_state) {
  return $form['submit'];
}

?>

Hope this helps. If the code does not work as it should let me know and I will test it asap.

cheers,
j


Views - Contextual filter -  "page not found" I have a view that uses a contextual filters of type

  Content: Has taxonomy term ID (with depth)

The page display has the following path /objects/%
If I access the site through http://mysite.com/objects/all the view gets triggered and all my objects are listed, http://mysite.com/objects/silver also works fine (now only objects tagged with silver are listed), but if I use http://mysite.com/objects then I get a "Page not found" message, how can I solve this? I wan't the /objects and /objects/all to show exactly the same content.
Of course I could copy the display and add a path for /objects but that don't seem quite right.

This is an unfortunate side effect of how the menu system works. When the paramter "%" isn't available, you match against a different path, and the View won't get called.

I suggest making /objects an alias to /objects/all, I believe this will then interact properly with the menu-system.
If that's not the case, you can force the issue with Path redirect which will redirect the user with an HTTP-response code, and thus land the user at /objects/all.

I minor drawback of using Path redirect is that the redirect logically belongs together with the View, but is now configured somewhere completely different. For that reason, I would prefer to accomplish the redirect and View rendering with Page manager, which will allow you to group the HTTP-response and a Panel together in a more logical manner.


how to create template suggestion for image like image--NODE-TYPE--VIEW-MODE I'm trying to create a suggestion like image--NODE-TYPE--VIEW-MODE, but in mytheme_theme_suggestions_image_alter() $vars i haven't node related info

thanks for help

In the hook_theme_suggestions_HOOK_alter the $variables contain only informations about the theme of entity in this case theme image:
From documentation:

array $variables: An array of variables passed to the theme hook. Note that this hook is invoked before any preprocessing.

if you look at image_theme you can find all variables passed uri, title ...
So to access node related info you can use route params like the following.
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  $suggestions [] = "image__" . $node->bundle();
}

Note: you can't access to View mode in this hook because it's not in the $variables and also the current view mode is not stored in the node object
Take a look at this issue Make the current view mode available on the node object


Making nodes from XLS files I'm trying to add a +2000 video database (stored on youtube) to my website. I have an excel file with on every line the video title, the url and the keywords.

Is there an easy way to automate this process rather then copy pasting +2000 times in to new nodes?

Kind regards!

You can achieve that using the Feeds module

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  PubSubHubbub support
  Create nodes, users, taxonomy terms or simple database records from    import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files

This article might help you to achieve this.


Sporadic permissions issue We are running a Drupal 8 site with 400 or so pages of content.

We have a number of "resource pages" were views generate links to content by topic area. Here is an example of one of those pages.

In general everything is working as intended, however, sporadically we have an issue with clean URLs and the link to content in those views. Specifically, index.php is added to the link presented only to anonymous users. For example, website/mypage becomes website/index.php/mypage, or even website/index.php/index.php/mypage.

This problem never occurs for logged in users, only anonymous users. It is also not consistent. It may happen to 2-3 of the links in a single view, or several across the views on the same page but generally will not affect the entire site or page. It may not happen for weeks and then 4-5 times in 24 hours. In the last few days it appears to be happening every few hours.

It appears to mostly only happen on resource pages (they are a content type) like the one I linked above. We have also some times observed it occurring on other menu links. These links usually still work however...

We have been unable to find a reason for it. Clearing the site cache a few times does fix the issue but it is somewhat unacceptable that this happens regularly.

The views on those specific pages do make use of relationships and aggregation  to generate their content. Several also use re-write rules to generate custom link text. The issue appears to affect both types of views on those pages.

Can anyone suggest what the cause of such an issue could be or give any ideas as to how to stop it occurring?

How this gets started is hard to tell. But once it does it spreads quickly. When a user clicks on a link with /index.php the page will include /index.php in the base url, which then is used for all links generated on this page. The same is the case for search bots, once they hit a link with /index.php they will crawl the whole site with it.

To stop this, redirect the unclean urls. You could use this core patch or Redirect, but as long as the core patch is not committed and the module is not released, you can do this in .htaccess. Place these two lines at the top of the rewrite rules:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteCond %{THE_REQUEST} "^[A-Z]{3,9}\ /index\.php(.+)\sHTTP" [NC]
  RewriteRule "^" "%1" [R=301,NE,L]


How do I use 2 different taxonomy view modes on one node page? On a node page I have a term reference field. This term contains 3 fields

For the term I've created a few view modes:

view_mode_first contains: field_1
view_mode_second contains: field_2, field_3

hook theme suggestions:

  function theme_theme_suggestions_taxonomy_term_alter(array &$suggestions, array $variables) {
    $term = $variables['elements']['#taxonomy_term'];
    array_splice($suggestions, 2, 0, 'taxonomy_term__' . $term->bundle() . '__' . $variables['elements']['#view_mode']);
  }

node field template, where I'm displaying referenced terms:

  {% for item in items %}
      {% set first = item.content|merge({'#view_mode': 'view_mode_first'}) %}
      {{ first }}
  {% endfor %}

  {% for item in items %}
      {% set second = item.content|merge({'#view_mode': 'view_mode_second'}) %}
      {{ second }}
  {% endfor %}

But as a result I'm getting the same templates everywhere: taxonomy-term--name--view-mode-first.html.twig and not a taxonomy-term--name--view-mode-second.html.twig

I found that if I disable render cache in a settings.local file, both templates work:

$settings['cache']['bins']['render'] = 'cache.backend.null';

Is there possibility to disable render cache for specific node and/or fields?

The problem is that the view mode is also part of the cache keys and you would need to update them as well to avoid that both view modes are cached under the same cache id.

  Is there possibility to disable render cache for specific node and/or
  fields?

Yes, this is another possibility, you can disable caching of specific entities, in this case taxonomy terms, by removing the cache keys, which are in the #cache property. It's easier to manipulate this array in PHP, but this should also be possible in Twig. You can try to get #cache with the filter |without('keys') and merge it later with first and second.

You can also try to remove #cache completely from the second rendering

{{ second|without('#cache') }}

because all relevant cache metadata should bubble up already from the first rendering of the taxonomy term.


#ajax-processed not added on a form inside a custom callback (MY_MODULE_deliver_html_page) Ok, a lot of things on the title so I'll try to explain everything on the question.

I'm trying to create a logic inside Drupal 7 to enable modal forms with AJAX.

This is the pipeline:

Render a form with an #ajax callback in a modal (foundation reveal)
Send a form via AJAX and receive Drupal ajax commands.

In order to print the form without the whole themed template I used a custom callback to render plain html.

$items['statusupdate/%statusupdate/delete'] = array(
        'title' => 'Delete',
        'page callback' => 'statusupdate_delete_confirm',
        'page arguments' => array(1),
        'access arguments' => array('delete statusupdates'),
        'weight' => 1,
        'type' => MENU_LOCAL_TASK,
        'context' => MENU_CONTEXT_INLINE,
        'delivery callback' => 'MY_MODULE_deliver_ajax_html_page',
    );

Attempt 1 - not working

function MY_MODULE_deliver_ajax_html_page($page_callback_result) {
    print $page_callback_result;
    return null;
}

Attempt 2 - Create a custom template to load javascript, not working (the logic is on the php side)

function MY_MODULE_deliver_ajax_html_page($page_callback_result) {
    print theme('page-ajax-html', array('page' => $page_callback_result, 'styles' =>'', 'scripts' =>drupal_get_js()));
    return null;
}

This works fine to render only the form in plain HTML but by doing so no ajax logic is applied to the form.

Drupal_render($form) renders the form, but is not adding #ajax-processed.

I tried to render the $form inside the page.tpl.php and AJAX works, so my guess is that rendering the $form in plain HTML some ajax preprocess logic.

Form:

function statusupdate_confirm_form($form, &$form_state, $data)
{
    $form['#id'] = 'statusupdate-confirm-form';

    $form['submit'] = array(
        '#type' => 'submit',

        '#value' => t('Delete'),
        "#ajax" => array(
            "callback" => "delete_statusupdate_callback",
            "effect" => "fade",
        ),
    );
    return $form;
}

Form rendering:

function statusupdate_delete_confirm($statusupdate) {
    $form = drupal_get_form('statusupdate_confirm_form', array());
    $form['submit'] = ajax_pre_render_element($form['submit']);
    $html = '
'.t('Careful').'!
';
    $html .= '
'.t('Are you sure you want to delete %status_id?', array('%status_id' => $statusupdate->status_id)).'
';
    $html .= '&#215;';
    $html .= drupal_render($form, '');
    return $html;
}

HTML Result

<form action="/statusupdate/12/delete" method="post" id="statusupdate-confirm-form" accept-charset="UTF-8">
<input type="submit" id="edit-submit" name="op" value="Delete" class="form-submit"><input type="hidden" name="form_build_id" value="form-muOSqaoWicTDGYZ-IAp149QAmMpsOPKNsq8WXH2XSLI">
<input type="hidden" name="form_token" value="ckXsiTcF2_sINFfKdNj3uK6L9FiJv3krg1jnhKh0Vsk">
<input type="hidden" name="form_id" value="statusupdate_confirm_form">

Any idea?

The problem why the ajax is not working with loaded forms through ajax is because of the missing javascript behaviors attached to the form. These provides all client side code (and which adds the .ajax-processed class on the element).

To be able to add these needed behaviors, you need to make used of the ajax_pre_render_element and attaching these to the page. Also important, is that you print out the JS code by calling drupal_get_js().

This is how I managed to get it working.

function YOURMODULE_form($form, &$form_state)
{
    // Same form build as your example
    $form = array();

    $form['#id'] = 'statusupdate-confirm-form';
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Delete'),
        "#ajax" => array(
            "callback" => 'delete_statusupdate_callback',
            "effect" => "fade",
        ),
    );

    return $form;
}

// Menu callback used to only how the form (standalone) without the theme HTML
function YOURMODULE_page()
{
    // Get the form
    $form = drupal_get_form('YOURMODULE_form');

    // Process the submit button which uses ajax
    $form['submit'] = ajax_pre_render_element($form['submit']);

    // Build renderable array
    $build = array(
        'form' => $form,
        '#attached' => $form['submit']['#attached'], // This will attach all needed JS behaviors onto the page
    );

    // Print $form
    print drupal_render($build);

    // Print JS
    print drupal_get_js();

    return null;
}


How to get the out of the box slideshow to display on a page other than /node? - Corporate Clean/Omega theme I am using a domain access module and currently running two domains. Out of the box, my default domain was displaying a slideshow on the homepage. Using these instructions I created a new front page -

However, now the slideshow isn't displaying. How do I get it back up?

By the way, the reason I went ahead with the front page setup as per the instructions was to avoid the "No front page content has been created yet." message.

If it was displaying the slideshow correctly out of the box (i.e. without any modifications made), then you should be able set the default front page back to its original state (empty... i.e. delete whatever's currently in the box), then add a file in the theme directory called page--front.tpl.php. Inside that file, copy/paste the original code found inside the file page.tpl.php.

Assuming you're using the Corporate Clean theme, scroll down your new page--front.tpl.php file about 220 lines and change this line:

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

... so that it's commented out:

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

... Or, if all you want to do is simply remove the No front page content has been created yet message, you can hide the default message and then print the rest of the content like normal (i.e. instead of changing the line, just add another one right above it):

<?php hide($page['content']['system_main']['default_message']); ?>
<?php print render($page['content']); ?>

Or, you could just delete that line but I assume you'll eventually want some content there (in which case you can go back and undo the commenting out).

After you've completed all the changes, saved all the files, etc, go to admin/config/development/performance and clear all the caches -- the new front page should now appear with the slideshow and without any "No front page content has been created yet" content.

Hope that helps...

:)


displaying a webform in an overlay I want the user defined webform to be popped up in an overlay when a button is clicked. I am using colorbox and colorbox-node modules. I am able to display the whole node. But I am not understanding how to display just the webform instead of the whole node. I used the following code:

 <a class="colorbox-load" href="enquiry?width=600&amp;height=600&amp;iframe=true"><input value="Send Enquiry" type="submit"> </a>

If I need to display webform in popup, then I would use ctools modal.

You can use modal forms module which make use of the modal feature in the ctools module to open some common forms in a modal window.

Supported forms

Log in (modal_forms/nojs/login)
Request new password (modal_forms/nojs/password)
Create new account (modal_forms/nojs/register)
Contact (modal_forms/nojs/contact)
Comment (modal_forms/nojs/comment/reply/%node)
Webform (modal_forms/nojs/webform/%node)

May be this is not answer to your question as you are using colorbox, but I am adding this so that you can check other option.


Custom Submit Handler issue in getting file I have the following custom submit handler.

function example_form_submit(&$form, FormStateInterface $form_state) {
    $file = file_load($form_state['values']['file_fid']);//This works in 7
}

Now I want to have uploaded file information like fid, name etc. in D8. I am not able to get that.

UPDATE:
I have also tried using the following code from here but no luck.

if ($form_state->hasFileElement())
{
  drupal_set_message("This form has a file element.");
  $video_file_file_array = $form_state->getValue('video_file');
  if (is_array($video_file_file_array))
  {
    if (isset($video_file_file_array[0]))
    {
      $video_file_file_id = $video_file_file_array[0];
      $file = \Drupal\file\Entity\File::load($video_file_file_id);
      if ($file != NULL)
      {
        $filename = $file->getFilename();
        drupal_set_message('Filename: ' . $filename);
      }
    }
  }
}

You need to use following code to get it

$target_id =$form_state->getValue('field_name');//get the target_id from it
    $file = \Drupal\file\Entity\File::load($target_id); //load the file and its attribute.
            $file_image= '<img src = "' . \Drupal\image\Entity\ImageStyle::load('large')->buildUrl($file->getFileUri()) . '" />';//load the large image


Invalidate single block cache in D7 I have a custom site-wide block that shows on all pages, which I would like to be heavily cached for anon users but able to be invalidated when I modify its settings, or en/disable it (both drupal variables set in an admin page).

I've managed to achieve this pretty nicely in D8 with Cache::invalidateTags(), as well as some custom Acquia stuff to invalidate the varnish cache. However in trying to port this same functionality to a D7 site I've not managed to find any good method of doing it.

Any help much appreciated, thanks in advance!

You may have a look at Block Refresh, and implement your custom logic on top of it whenever you want to send a Cache-Control: max-age=0 :

//Override external cache max age if set
  if (isset($settings[$block_id]['bypass_external_cache']) && $settings[$block_id]['bypass_external_cache'] != '') {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . intval($settings[$block_id]['bypass_external_cache']));
  }


How to pass node ID argument to Drupal 7 div auto update ajax script EDIT: There seems to be a ready-to-use http://drupal.org/project/block_refresh module available as @albertski indicated, so no need to struggle to develop a new module.

I've implemented the code on https://stackoverflow.com/questions/8144436/refreshing-a-div-in-drupal to get a Drupal 7 node page division auto-updated. Here is the code outputting simple time() function:

Hook menu:

$items['autoupdate'] = array(
'title' => 'Resize',
'page callback' => 'block_update',
'access callback' => TRUE,
'type' => MENU_LOCAL_TASK,
  );

Function itself:

function block_update(){
$html = time();
print drupal_json_encode(array('html' => $html)); exit(); }

Javascript:

    function autoupdate() {
  //alert('autoupdate is running');
  jQuery.ajax(
  {
    type: "POST",
    url: "/autoupdate",
    cache: false,
    success: function(data) {
      var result = JSON.parse(data);
      jQuery("div.autorefresh").fadeIn("slow").html(result['html']);
    }
  });
  //alert('autoupdate is complete');
}
setInterval("autoupdate()", 2500);

However, instead of time() I would like to use node variables and having troubles to make the module to see $node. Even if I put my div on a node page and call menu_get_object() the javascript sees only the content /autoupdate page:

function block_update(){
  $html = arg(0);
  print drupal_json_encode(array('html' => $html));
  exit();
}

shows: autoupdate

I tried to change the path in both hook menu and javascript from autouptade to node/%node/update, but unfortunately javascript doesn't want to recognize %node as argument. I am afraid it recognizes only static URLs. But then how is it possible to pass node ID to javascript?

I probably would have done this differently but than again I'm not a hundred percent sure what you are doing.

In response how can you pass the node id to javascript. Perhaps in hook_page_alter():

$node = menu_get_object();
if ($node) {
  drupal_add_js(array('your_module_name' => array('nid' => $node->nid), 'setting');
}

Then in your ajax code get the nid via:

Drupal.settings.your_module_name.nid


Same day with time range I'm trying to make an events calendar that has events on a day, (e.g. Feb 2), with a start and end time, (1pm - 3pm).

However, the current date module in Drupal 8 doesn't have support for end times and the date module doesn't seem to be ready yet.

How would I such a date field up? I could always use a textbox, but I need to be able to set different date formats for the day of this field.

I see that there isn't a well known option for drupal 7, but hopefully there is a elegant solution for Drupal 8. Worst comes to worst, I'll accept hacky solutions....

Thanks!

You need to enable the Datetime Range module.  It is currently an experimental module in Drupal 8, and not enabled by default.  On admin/modules it's in the Experimental group:

Enable it, and a new field type will appear, Date Range.


"File (Field) Paths" and "Media" modules: files not saved in the intended folder I'm trying to use both the "Media" module (1.4) (to manage uploaded files) and the "File (Field) Paths" (to keep the uploaded files organized in various subfolders).

Basically, I have a content type that has several taxonomy fields and a media field. The taxonomy fields are mandatory and accept only one value each. I want the media file to be uploaded in a folder that uses the various taxonomy fields as a path, and I've configured the file field accordingly (using the "file (field) paths" options). So the file should be saved to e.g.:

sites/default/files/documents/[taxonomy-term-1]/[taxonomy-term-2]/filename.extension

My problem is that, when manually creating a new node and adding a file to it, the file is just saved to the root of the public files directory:

sites/default/files/filename.extension

So the "file (field) paths" configuration for this field seems to be ignored. This also happens if I add a file after the node has been created and saved.
Since I expect the site will have a lot (thousands, maybe tens of thousands) of uploaded files, I fear that storing all of them in the same folder will have an impact on the performance of the site.

What's strange is that when I use the feeds module to import and create nodes in bulk (via a CSV file), the "file (field) paths" configuration is working as intended. The files are saved in the "complex" path.

So why wouldn't it work when creating a node manually?...
Any idea for a solution?

Thanks in advance.

No definitive answer so far, but I should note that I have been able to make this option work again simply by enabling the (very intimidating) option "Active updating" in the field's settings. (So in admin/structure/types/manage/[content-type]/fields/[field-name])

The "File (Field) Paths" developer warns that "This feature should only be used on developmental servers or with extreme caution", but since it's the only solution I've found so far, I'm going to keep this option enabled for now.

Hope this helps someone.


Drupal 7 aggregator module with BBC persian feed I am trying to import the BBC persian feed from http://www.bbc.co.uk/persian/index.xml using the Aggregator module in Drupal 7. For some reason, I always get the same link for the article for all the imported items. I have tried with other RSS feeds form BBC.co.uk; only the Persian  one is not properly imported.

Is this a know issue? Is there a workaround? I presume it is a problem with the RSS parser in the module, and the Persian numerals, but I can't be sure.

After you add new feed, make sure you update the items twice after removing them in the first time.

steps as follow:

add new feed
go to feed aggregator page admin/config/services/aggregator
update items manually by clicking on update items for the added feed
remove items by clicking on remove items for the updated feed
then update feed again update items

these steps worked for me while importing BBC persian and arabic feeds


PHP Fatal error: Call to undefined function chdir() I tried to copy my site to a new sever and since id did that, I get an HTTP-Fehler 500 (Internal Server Error): on certain pages. The log files are reporting:

PHP Fatal error:  Call to undefined function chdir() in /var/customers/webs/something/includes/bootstrap.inc on line 3384
PHP Fatal error:  Call to undefined function max() in /var/customers/webs/something/includes/lock.inc on line 106

I cleared all caches many times with:

drush cc all

and also flushed the cache tables directly with MySQL commands. I disabled APC. I don't think, that this is a problem with the server, because it serves well for other Durpal sites.

EDIT: Here are my php.ini and htaccess.

chdir() and max() are built in functions that always exists in PHP. They are in no plugin, just a core. Even in safe mode both should be defined.

There is one way to disable them and make them non-existent from the script's point of view. disable_functions section in php.ini does the trick. Usually it is used for safety, like this:

disable_functions=exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

and whilst I can see some illusionary* safety in disabling chdir(), disabling max() must have been a mistake. Note that on some configurations you can alter ini settings in .htaccess and via ini_set() too.

*Illusionary due to the same reasons that made Safe Mode deprecated.


Load all Order with Attributes How can I load all order by using sql queries or by using predefined methods. I have attributes like One Month and Three Month. I want to get orders and the selected attribute with each order.

Try uc_order_status_list

Parameters:

$scope - Defaults to all, but you may specify the scope for the order statuses you want listed based on their corresponding order state. Possible values are - all, general, specific, or any order state id.

$sql - Pass this parameter as TRUE to alter the return value for a SQL query.

$action - By default, this is empty. Since order statuses are cached, you can pass in 'rebuild' to reload the contents from the database if you are making changes to statuses on a page load.

Return value:
The return value will be either an array of status arrays (containing the keys id, title, state, and weight) or a string containing an array of status ids for use in a SQL query.


and  tags in a text field of format Full HTML are not rendered in a field based view In latest Drupal 8, I've got a text field of format Full HTML that contains <form> and <input> tags (It's a MailChimp subscribe snippet). As long as I am editing the text in CKEditor in the backend, the form is displayed correctly. But as soon as I view tha page in the frontend, both tags are stipped out. I checked my text format/CKEditor settings to see if tags are stripped out there, but "Limit Allowed HTML Tags" is unchecked.
Does someone know what's happening here?

Edit: after checking out more, I realized that the text field is rendered inside a view (field based). When rendered as a node, the markup is perfectly rendered, just when rendered as a view, then the tags are stripped. I edited the question title to refelct this information.
Any suggestions how to render the tags inside a view?

Edit 2: the text field is rewritten in views (added some wrapper tags).

I confirmed on 8.7 that the following basic snippet is able to be used in Full HTML out of the box:

<form><input checked="checked" name="gender" type="radio" value="male" /> Male

<input name="gender" type="radio" value="female" /> Female

<input name="gender" type="radio" value="other" /> Other</form>

It's possible your particular snippet is being hit by the "Correct faulty and chopped off HTML" Format setting, so try it without that and see if it lets the code stay. Of course, this is not an ideal setting for a commonly used text format filter, so this snippet may be better off in a custom plugin block, or creating a new text format w/ the "Correct faulty and chopped off HTML" turned off, that can be used sparingly as needed.

UPDATE based on Views usage:

If you're using rewrite, it won't be possible out of the box to have it not strip tags, it's something baked into Views. You can override it at the theme layer - if for example you are using the body field, you create a views-view-field--body.html.twig file in your theme, and then put the desired wrapper tags around the {{ output -}}, e.g.:

{{ output -}}

And turn off rewrite in Views UI.


How to display only parent terms of hierarchical terms  in Views field In the Views UI I set up the Relationship "Taxonomy:Parent term" and then a Field "Taxonomy: Term" with that relationship.
But the problem is that It displays the parent terms of all the vocabularies (I have several vocabularies).
I also tried the Field "Taxnomy:All terms" as it can limit the terms by vocabularies but it can't have the Relationship "Taxonomy:Parent term"

Is there any way to display only the parent terms of one certain vocabulary for hierarchical taxonomy in a view field?

I think my answer to a similar question would be useful:

I believe that your problem would be solved by adding a relationship to your view. Here are the steps:

Add Relationship: taxonomy terms on node
Select the vocabulary you want to use.
Add Relationship: parent term

Now you should be able to add fields from any of the terms or their parents, and to use them as contextual filters as well.

Note that this is for Drupal 7


Add custom node content to cache I have added a few custom nodes to my website via the admin CMS. I wanted to know if I would have to explicitly add them to cache or if the nose_save or one of the internal drupal methods would add it to cache? I am using memcache for my caching purposes.

Generally, Drupal caches pages for anonymous users. This is true for all nodes. You can turn this, together with some other caching settings, on and off at admin/config/development/performance

If memcache handles the data that otherwise goes into cache_page, then you will benefit from memcache in returning nodes.


Using a custom template in a theme I have created the custom template page-org.tpl.page in the Zen theme, and I want to include this custom template file in the menu calling; when the user clicks on the Org link it should use the template file page-org.tpl.page.
How can I do that?

Output your $vars in the theme so you can see your candidate templates.

EDIT: I thought you were looking for a content type solution when I first read this :)

Here's a gotcha:
you have to have master templates before you can have ones within it. For example content-field-field_my_content.tpl.php will not work until content-field.tpl.php is in place in the theme.

You may need to place some PHP in your template.php within preprocess_page()

if(!arg(2)) $variables['template_files'][] = 'page-node_'.$variables['node']->type;

(The arg2 check helps make sure this doesn't happen on edit pages.)

Lastly, you can also accomplish this with Context Layout.


Is there a CKeditor / Drupal module that allows for a one-button image upload (without requiring Flash)? Background:
I'm looking to add an image upload button to CKeditor. Ideally, I'd like to automated the click responses to start IMCE and jump right to the IMCE Upload button. In fact, I'd like to put the IMCE upload button on CKeditor's tool bar.

My Question:
Is there a way to put the IMCE Upload button directly onto the CKEditor tool bar just like we have here in side of StackExchange?

What I've seen/tried:
I've seen other methods recommending One Click Upload but this uses SWFloader. The Media module is great but people want a direct upload from inside the editor. They don't want to jump to another screen.

The Insert module should be perfect for this https://www.drupal.org/project/insert

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

  This module was previously known as FileField Insert.


Unusual renewal of subscription products Marketing wants to sell a subscription product at a discounted price of 5 septims a year for 3 years, and then return it to its regular price of 10 septims after that.

In discussion the idea came up to:

Generate 3 new products (SUB_Y1, SUB_Y2, and SUB_Y3 in addition to the existing SUB product)
Set up the renewals notifications for the first 3 products to encourage users to renew
Direct them only to the next product in the series
Offer them the regular product after the first 3 cheap years

However, I know my marketing department; if I do this, they will want more, and by the end of the year I will have 25 different series, each of which having 2 to 5 steps in the process. My /admin/store/products/view will be a nightmare to behold.

Is there a cleaner way of handling this that will not use up much of the 25 minutes actual coding time I am alotted each week?

I've not used UC Recurring Payments and Subscriptions before properly, but if each payment is a fully fledged order then I imagine you could use Conditional Actions to look at the date compared to the initial purchase date and give a discount if that is within the three years. The coding effort is then just creating a new condition using hook_ca_condition() which is not hard, and then after that setting up the pricing rules in the CA interface.


Is hook_init() still used? If it is not anymore used, how do I convert code implementing hook_init()? Looking on Drupal.org API, I noticed that hook_init() is not documented for Drupal 8. Looking at the change records, I found Bootstrap hooks no longer exist, which points to Get rid of all 'bootstrap' hooks, where the bootstrap hooks are said to be hook_boot() and hook_exit(); nothing is said about hook_init().

I searched for hook_init in Drupal 8 source, and I found the following code. The first one is a reference to hook_init() made in a comment; the other two seem a hook_init() implementation, but they both get a parameter I am not expecting.

function overlay_enable() {
  if (strpos(current_path(), 'admin/modules') === 0) {
    // Flag for a redirect to <front>#overlay=admin/modules on hook_init().
    $_SESSION['overlay_enable_redirect'] = 1;
  }
}

/**
 * Implements hook_init().
 */
function phptemplate_init($template) {
  $file = dirname($template->filename) . '/' . $template->name . '.theme';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

/**
 * Implements hook_init().
 */
function twig_init($template) {
  $file = dirname($template->filename) . '/' . $template->name . '.theme';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

I also looked for any function invoking hook_init() but I didn't find any.

Is hook_init() still used in Drupal 8? If it is not anymore used, how do I convert Drupal 7 code implementing hook_init()?

Perhaps this has changed since this question was last answered. But I think the preferred approach to replacing what is going on in hook_init is to create an event subscriber, and adding to the 'request'. Here is how you do that for those that may find it useful.

Example services.yml

services:
  init_subscriber:
    class:   Drupal\mymodule\EventSubscriber\MyModuleSubscriber
    arguments: ['@current_user'] // <- optional args
    tags:
      - {name: event_subscriber} // <- Required Tag

Then you would implement the EventSubscriberInterface (new file in the src/EventSubscriber directory) and in the implemented method getSubscribedEvents you can do something like...

/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = array('initializeMyModule');
  return $events;
}

And add the method accordingly

/**
 * MyModule
 *
 * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
 *   The event to process.
 */
public function initializeMyModule(GetResponseEvent $event) {
  $request = $event->getRequest();
  ...
}


How to add help text to tabs in admin/structure/types/manage/{node-type} I maintain a module (http://www.drupal.org/project/csm) that adds two tabs to the node type settings form at admin/structure/types/manage/{node-type}. I'd like to add some help text to these tabs. In the picture below, there is help text set for the top four tabs, but not for the last three tabs.

I've had a look at the Drupal core code to see if I can work out how to set this help text, but have had no joy so far. How can I set it?

For the record, the code used to generate the last tab in the form is as follows:

$form['cnpt'] = array(
  '#type' => 'fieldset',
  '#title' => t('Node creation page title and status message'),
  '#access' => user_access('change ' . $form['#node_type']->type . ' creation page title'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  //'#tree' => TRUE,
  '#weight' => 101,
  '#attributes' => array('class' => array('csm-form')),
  );

The summaries are dynamic so they're controlled by JS. It should be something as simple as this:

(function($) {
  Drupal.behaviors.csmFieldsetSummaries = {
    attach: function (context) {
      $('fieldset.csm-form', context).drupalSetSummary(function (context) {
        // Make a decision about what summary to display based on your tab's current value.
        var summary = $('input.foo', context).is(':checked') ? 'Input checked' : 'Input not checked';

        // Or static strings are fine too.
        summary = 'Static summary';

        return Drupal.t(summary);
      });

      $('fieldset.another-csm-form', context).drupalSetSummary(function (context) {
        // ...
      });
    }
  };
})(jQuery);


How can i use main-menu items as a fields in selectbox in drupal 7 Helllo,
I have a content type called "Lookbook" in that i want to put one field like "Lookbook For" and this field content select box and main-menu items. I have main-menu list but I want only display submenu items of lookbook menu in select box.
Is it possible that menu links display as fields??
Thanxs..

First, create a view that references the nodes you want - e.g. that have a parent item with node id x (or whatever the criteria is for those nodes). Get that view right, and the rest is easy.

Upload and enable either the references, or the entity reference module http://drupal.org/project/entityreference or http://drupal.org/project/references

In your content type, choose a node reference item and select widget. You can base the option list on your view.


Webform response: "Illegal information. Data not submitted." I have a very simple webform (ie. name, email, comments) that has begun giving this response to any submissions, no matter what they are:

Has anyone seen that before? The results are still saved in the webform but it causes confusion and people also enter their comments multiple times as a result.

It seems that message is triggered by the _webform_submission_spam_check function. Looking at the code, it seems to check the following regular expression:

'/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers

Maybe some of the submissions contain "cc" or "bcc" or "content-type"?


Use a twig template instead of a render array in a custom module admin page I have a Drupal 8 custom module, and I want to display its configuration page using the admin theme.

Usually, for this kind of pages I use, in the _controller property of my route, rather :

a class that extends \Drupal\Core\Form\ConfigFormBase (for a simple form-like config page)
a custom controller that extends \Drupal\Core\Controller\ControllerBase and returns a renderable array

For this module, I need to use complex HTML structure and a Javascript library for its configuration page. Writing all this directly in a #markup property of a render array would be too much work and highly not-maintainable.

Is it possible to write a custom template (twig or not), to render it programmatically and insert the result into a container element or in a #markup property ?
And, as I use the Seven admin theme, I would like to do this without affecting the theme.

[Resolved] Final solution :

Combining leymannx answer and the elements mentioned below, I ended up with something that meet my requirements.

mymodule.routing.xml

mymodule.admin_ro:
  path: '/admin/config/mymodule/readonly'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ReadOnlyController::index'
    _title: 'Module configuration - read only'
  requirements:
    _permission: 'view mymodule configuration'
  options:
    _admin_route: TRUE
    no_cache: TRUE

ReadOnlyController.php

class ReadOnlyController extends ControllerBase {

    public function index(){
        return array(
            '#type' => 'container',
            '#theme' => 'test-template',
            '#test_var' => [ 0, 1, 2, 3 ] // I needed an array type variable
        );
    }

}

mymodule.module

// Implements hook_theme()
function mymodule_theme( $existing, $type, $theme, $path ){
    return [
        'test-template' => [
            'render element' => 'container', // To render a simple container element
            'template' => 'test', // My template file name
            'variables' => [
                'test_var' => [] // Default value for my variable
            ]
        ]
    ];
}

And finally, my test template : templates/test.html.twig

Hello !

{{ dump(test_var) }}

Related doc or posts

hook_theme
Form and render elements | Drupal API
Create custom twig templates for custom module
How can I programmatically display a block?
StackOverflow - Drupal 8 custom block (module) create twig template file

The back-end theme automatically switches by path. So if your route's path begins with /admin it will show the page in the admin theme.

MYMODULE.MYPAGE:
  path: '/admin/config/MYPAGE'
  defaults:
    _form: '\Drupal\MYMODULE\Form\MYFORM'
    _title: 'MYTITLE'
  requirements:
    _permission: 'administer site configuration'

To render a form inside your own template you could simply register a new theme implementation inside MYMODULE/MYMODULE.module.

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'MYNAME' => [
      'render element' => 'form',
      'template'       => 'MYTEMPLATE',
    ],
  ];
}

And in the form you set this as the form's #theme.

$form['#theme'] = 'MYNAME';

And in the MYMODULE/templates/MYTEMPLATE.html.tiwg template you print it like so:

<div class="foo bar">
  {{ form }}
</div>

Any additional library also can simply be #attached directly to the form.

$form['#attached']['library'][] = 'MYMODULE/MYLIBRARY';

Read More

[drupal.org] Create custom twig templates for custom module.


HTML mail without using modules I am trying to use the MailManager class in Drupal 8 to send HTML mail. I got it working, but it isn't parsing the HTML markup. I think something is wrong with the headers of the email.

What I have is a custom module (Custom_forward) that contains a form and that calls Mailmanager::mail() in its submitForm() method, which contains the following code.

        // Email body
        $header = $sender . ' thought you would like to see this page from the website.';
        $personal_message = $form_state->getValues()['message_body'];
        $entity_url_value = 'toString() . '">Go to article';
        $message = $header . '
' . $personal_message . '
' . $entity_url_value;

        // Email
        $langcode = 'en';
        $mailManager = \Drupal::service('plugin.manager.mail');
        $to = $form_state->getValues()['recipient'];

        $params['title'] = 'Forward';
        $params['message'] = $message;
        $result = $mailManager->mail('custom_forward', 'forward', $to, $langcode, $params, NULL, true);

        if ($result['result'] !== true) {
            drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
            \Drupal::logger('mail-log')->error($message);
        }
        else {
            drupal_set_message(t('Your message has been sent.'));
        }

According to Drupal you also need the hook_mail method in mytheme.theme to be able to send message, you can see this method here:

function custom_forward_mail($key, &$message, $params) {
  $message['body'] = [];
  $message['subject'] = [];
  $message['headers'] = array(
    'content-type' => 'text/html',
    'charset' => 'UTF-8',
    'format' => 'flowed',
    'delsp' => 'yes',
    'from' => \Drupal::config('system.site')->get('mail')
  );

  switch ($key) {
    case 'forward':
      $message['subject'] = $params['title'];
      $message['body'][] = '' . $params['message'] . '';
      break;
  }
}

As you can see, I am setting the content type to text/html and that should tell the mail system to parse the content as an HTML, but this is not working for some reasons.

This is a testing email. All the HTML markup is not shown, but also not working.

Bassem thought you would like to see this page from the website. personal message Go to article [1] [1] http://myhost/node/81

Without any module it is not possible to send HTML emails. This is because the default plugin the MailManager class (which is a plugin manager) uses to effectively send emails contains the following code. (See PhpMail.php.)

public function format(array $message) {

    // Join the body array into one string.
    $message['body'] = implode("\n\n", $message['body']);

    // Convert any HTML to plain-text.
    $message['body'] = MailFormatHelper::htmlToText($message['body']);

    // Wrap the mail body for sending.
    $message['body'] = MailFormatHelper::wrapMail($message['body']);
    return $message;
  }

The comment clearly states: Convert any HTML to plain-text.

If you look at MailFormatHelper::htmlToText(), you will see the code that is converting the HTML markup in plain text, in particular the following that changes any  tag as you saw in your test email.

  // Replace inline  tags with the text of link and a footnote.
  // 'See the Drupal site' becomes
  // 'See the Drupal site [1]' with the URL included as a footnote.
  static::htmlToMailUrls(NULL, TRUE);
  $pattern = '@(]+?href="([^"]*)"[^>]*?>(.+?))@i';
  $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  $urls = static::htmlToMailUrls();
  $footnotes = '';
  if (count($urls)) {
    $footnotes .= "\n";
    for ($i = 0, $max = count($urls); $i < $max; $i++) {
      $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
    }
  }

You need a module that defines a new mail plugin using a different implementation of the format() method and make the MailManager class use it. As said in the documentation for MailManager::getInstance(), the class uses the configuration in system.mail.interface. (The array returned from \Drupal::config('system.mail.interface').) In your example, an array value for custom_forward_formard (e.g. 'custom_forward_forward => 'custom_forward_mail', where custom_forward_mail is the plugin ID for the class implemented by your module) would do the trick.


Why my taxonomy term list in content is not using node languages prefererence I have a multilingual website, in which I activated the i18n module and every related modules.

I have a taxonomy vocabulary Colors.

When I create or edit a content, all my colors are displayed. What I mean is, even if my node are in English, I saw every colors (English and French).

Is there a way to displayed my color based on node languages preference?

Check the "translation mode" that you've specified within admin/structure/taxonomy/colors/edit (whereas "colors" is the name of your specific category): by default that is set to "Localize", though it should be set to "translate".

After changing this value, be aware that you then also have to:

enter a translated value for each of the tags and
revisit any of the existing nodes that are already using the specific taxonomy, so that they use the (translated) term that corresponds to the language of the node.


Prevent indexing the article content after 15 lines. I am using search API and Solr .  I need to index only the first 15 lines of each  article .
the remaining lines after 15 lines has content which i don't want to index .
Please suggest if its possible .

Anything is possible :)

You can write a custom module to alter the behaviour of search api.
In the search api module directory there is a file search_api.api.php, which gives information on the functions you can use to alter its behaviour.

For this you would make a custom data alteration like this - replace modulename and ModuleName with the name of your module (case sensitive).

This part goes in your .module file:

/**
 * Define available data alterations.
 *
 * Registers one or more callbacks that can be called at index time to add
 * additional data to the indexed items (e.g. comments or attachments to nodes),
 * alter the data in other forms or remove items from the array.
 *
 * Data-alter callbacks (which are called "Data alterations" in the UI) are
 * classes implementing the SearchApiAlterCallbackInterface interface.
 *
 * @see SearchApiAlterCallbackInterface
 *
 * @return array
 *   An associative array keyed by the callback IDs and containing arrays with
 *   the following keys:
 *   - name: The name to display for this callback.
 *   - description: A short description of what the callback does.
 *   - class: The callback class.
 *   - weight: (optional) Defines the order in which callbacks are displayed
 *     (and, therefore, invoked) by default. Defaults to 0.
 */
function modulename_search_api_alter_callback_info() {
  $callbacks['modulename_character_limit'] = array(
    'name' => t('Character limit'),
    'description' => t('Limit the number of characters that get indexed for a field.'),
    'class' => 'ModuleNameCharacterLimit',
    'weight' => 100, // Probably better for this one to run later than others so they get to run on the full content before you trim it. Can still be reordered via the UI though.
  );

  return $callbacks;
}

This goes in a file named modulename_processor_character_limit.inc that goes in a sub-directory of your module called 'includes':

<?php

/**
 * @file
 * Contains ModuleNameCharacterLimit.
 */

/**
 * Processor for limiting the number of characters of a field that are indexed.
 */
class ModuleNameCharacterLimit extends SearchApiAbstractProcessor {

  public function configurationForm() {
    $form = parent::configurationForm();
    $form += array(
      'char_limit' => array(
        '#type' => 'textfield',
        '#title' => t('Character limit'),
        '#description' => t('The maximum number of characters of the field that will be added to the index.'),
        '#default_value' => $this->options['char_limit'],
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
      ),
    );

    return $form;
  }

  protected function processFieldValue(&$value) {
    // Chop unwanted characters from the value.
    $value = substr($value, 0, $this->options['char_limit']);
  }

}

This goes in your module's info file:

files[] = includes/modulename_processor_character_limit.inc

This will add a data alteration you can configure via the search api UI where you do things like configure the HTML filter.
You can set the number of characters to limit indexing to for our fields. - In your case, set to 15 and away you go.

(Full disclosure - I haven't tested this :))

[Edit]

As per your comment below, if you want to remove all text after a specific string (in this case "The below lines are confidential" you can do away with the char_limit setting and have a setting where you configure the text to check for (I'm calling it search_text) then change the processFieldValue() function to be:

protected function processFieldValue(&$value) {
  // If the text is found anywhere in the value.
  if (($pos = strpos($value, $this->options['search_text'])) !== FALSE) {
    // Cut off everything after that.
    // The $pos is the start of the string so if you want to also
    // exclude the string itself use $pos, otherwise to include the
    // string use $pos + strlen($this->options['search_text'])
    $value = substr($value, 0, $pos);
  }
}

Note that strpos() will return the position of the first occurance if the string occurs multiple times, which I would think is what you would want in this case.

See PHP string functions for more info on these and other string manipulation functions.


Change the pager and the number of elements per page of a specific view I create a view (FO) that lists certain content type. By default, I put a pager (mini) and a number of items per page (content 10 per page).

This view, I integrated into a content type (CFTO) in addition to other parameters.
If I agree, I want to use my other variables to redefine this view without saving it in a database (eg disable the pager / display 3 content page / ...)

I try different hooks as hook_views_pre_view, hook_views_pre_render, views_pre_build, but nothing works.
I can not change the number of a content page. This is my different test :

I wish i could change my view different information as enable / disable pager and more then change the number of elements of the page.

I find a way of hook_views_pre_render(&$views) to change the pager and more. It works well.

function my_views_pre_render(&$view){
//For more
$view->display['page']->handler->options['use_more'] = TRUE;

//For pager
if(!$this_node_pager_value) {
    $view->query->pager->set_items_per_page($view->total_rows);
    $view->query->pager->update_page_info();
}}

Now i wish i could change the number of elements in my page to display, I tested this code in different hook sities previously.

function my_views_pre_render(&$view){
if($this_node_pager_value) {
//TEST 1
$view->query->pager->set_items_per_page(3);
$view->query->pager->update_page_info();

//TEST 2
$view->exposed_raw_input['items_per_page'] = 3;
}}

function my_views_pre_view(&$view, &$display_id, &$args){
//TEST 1
$view->display_handler->display->display_options['pager']['options']['items_per_page'] = 3;

//TEST 2
$view->query->pager->set_items_per_page(3);
$view->query->pager->update_page_info();

//TEST 3
$view->exposed_raw_input['items_per_page'] = 3;
}

function my_views_pre_execute(&$view){
//TEST 1
$view->display_handler->display->display_options['pager']['options']['items_per_page'] = 3;
//TEST 2
$view->query->pager->set_items_per_page(3);
$view->query->pager->update_page_info();
//TEST 3
$view->exposed_raw_input['items_per_page'] = 3;
//TEST 4
$view->display_handler->set_option('items_per_page', 3);
}

function cci_generic_views_pre_build(&$view){
//TEST 1
$view->pager["items_per_page"] = 3;
//TEST 2
$view->display_handler->options['pager']['options']['items_per_page'] = 2;
//TEST 3
$view->display_handler->options['pager']['options']['expose']['items_per_page'] = 2;
}

None works. Would you know what should be done to make it work?

You would know what is the right hook to use? And how to change this value?
thank you for your help

Djik

The following should work in hook_views_pre_build(&$view):

$view->set_items_per_page(5);


Does drupal create new file in image styles? There are many images with 3000X2000 dimensions and I created a view of their content type. I also created a new image style, it is 90X70. This view displays the images in this size, but here is my question, which image size is loaded on the page load?

When you create an image style, a folder is created in /sites/default/files/styles/ that holds processed versions of your image.  When you select to use that style in views or anywhere else, only the processed image is loaded.  It wouldn't load the full size image if you have it set to the 90x70 style.


How do I debug permissions? How do I debug permissions in Drupal 7?

I use core reporting, error logs, devel module error logs, backtrace and node access permission block but sometimes it is not enough.
What else should I check to find out why certain fields, views or blocks are not showing to a user?

I also found there is a module for Drupal 6 for reporting on permissions called  but it is not available for Drupal 7.

I am using various permission related third-party modules:

 - devel node access 7.x-1.x-dev
 - fast permissions administration 7.x-2.0
 - organic groups access control 7.x-1.x
 - profile2 group access 7.x-1.x-dev
 - ur-node access 7.x-1.x-dev

One way you can do is make a custom module, print access info on every page, every node, every block.

menu_get_item() function return a router item which has access_arguments property for current page.

/**
 * Show access permission of current page.
 */
function yourmodule_get_page_access() {

  $router_item = menu_get_item();
  if ($router_item) {

    $access_arguments = unserialize($router_item['access_arguments']);

    $arguments = array();
    foreach ($access_arguments as $access_argument) {
      $arguments[] = $access_argument;
    }
    if ($arguments) {
      $output  = '<p>';
      $output .= t('This page needs user to have %p permission(s) to access', array(
        '%p' => implode(', ', $arguments),
      ));
      $output .= '</p>';
    }
    else {
      $output = '<p>' . t('This page needs no user permissions') . ' </p>';
    }
    return $output;
  }
}

Then you can hook_page_alter, to display the access info on top of every page.

/**
 * Implements hook_page_alter().
 *
 * Display access information on top of every page.
 */
function yourmodule_page_alter(&$page) {

  // Make a new area on top of the page for displaying access information.
  $page['content']['theverytop']['#markup'] = yourmodule_get_page_access();
  $page['content']['theverytop']['#weight'] = -10;
  $page['content']['#sorted'] = FALSE;
}

Next you can display out the block permission info like this:

/**
 * Implement hook_block_alter
 *
 * To display block permission information to the block title.
 */

function yourmodule_block_view_alter(&$data, $block) {
  $delta = $block->delta;
  $output = '';

  $rid = db_query("SELECT rid FROM {block_role} WHERE delta = :delta", array(':delta' => $delta))->fetchCol();

  if (empty($rid)) {
      $output = ' This block does not have any role permission restriction.';
  } else {
      $output = ' This block is viewable for users have role(s): ';
      foreach ($rid as $role_id) {
          $rolename = db_query("SELECT name from {role} where rid = :rid", array(':rid' => $role_id))->fetchField();
          $output .= $rolename . ' ';
      }
  }

  // append the permission info to block title for every block
  $block->title .= $output;
}

And so forth, basically the same concept, you can do the same to node, form, views.
Hope this helps.


How to ignore default roles in drupal roles I don't want to show the default roles to end user and want to ignore anonymous user and authenticated user. How can I remove these two roles from roles array. Shall I hard code the role names and rid say as in example below?

I have used this code.

$ignore = array(1 => 'anonymous user', 2 => 'authenticated user');
$roles = user_roles();
$roles =  array_diff($roles, $ignore);

Thanks for your help.

If you call user_roles(TRUE), the function will not return the anonymous user role.

Drupal always sets the role ID for anonymous user role, and the authenticated user role to the value of the constants DRUPAL_ANONYMOUS_RID, and DRUPAL_AUTHENTICATED_RID.

The following code is executed by user_install() in Drupal 7, and similar code is executed by system_install() in Drupal 6.

// Built-in roles.
  $rid_anonymous = db_insert('role')
    ->fields(array('name' => 'anonymous user', 'weight' => 0))
    ->execute();
  $rid_authenticated = db_insert('role')
    ->fields(array('name' => 'authenticated user', 'weight' => 1))
    ->execute();

  // Sanity check to ensure the anonymous and authenticated role IDs are the
  // same as the drupal defined constants. In certain situations, this will
  // not be true.
  if ($rid_anonymous != DRUPAL_ANONYMOUS_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_ANONYMOUS_RID))
      ->condition('rid', $rid_anonymous)
      ->execute();
  }
  if ($rid_authenticated != DRUPAL_AUTHENTICATED_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_AUTHENTICATED_RID))
      ->condition('rid', $rid_authenticated)
      ->execute();
  }

The following code works also in Drupal 5; the $roles array will not contain information about the anonymous user, and the authenticated user roles.

$roles = user_roles(TRUE);
unset($roles[DRUPAL_AUTHENTICATED_RID]);


Show the first 4 items in a different format I have a current view set up that displays a feed of stories and is sorted in descending order. I now need to have the first 4 stories display as a different style then the remaining ones. I have pagination set to 10. I only want the first 4 to show differently on page 1, and then the current style will show on the remaining pages. Is there a way to do this?

You can use views attachment to have a different styles for the first few item in list. By default, the attachment will be displayed in every pages of list.

If you want to limit the attachment works on the first page only, please implement hook_views_pre_build() in your custom module.

Assuming views name is stories, main display ID is block_1 and attachment display ID is attachment_1.

/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$views) {
  if($views->name == 'stories' && $views->current_display == 'block_1') {

    // if 'page' is not defined, we assume it is the first page.
    if (empty($_GET['page'])) {

      // The offset number y should be equal to the number of items on
      // attachment. If we want to keep the total n items on list, the
      // number of items on main display should be (n - y).
      // Note: get_items_per_page() and get_offset() is not working here.
      $views->set_items_per_page(6);
    }
    else {

      // Remove attachment for other pages.
      $views->is_attachment = TRUE;

      // We don't need to handle the offset anymore.
      $views->set_offset(0);
    }
  }

  // We set the item number again because the it seems
  // be overrided by previous call of set_items_per_page().
  if($views->name == 'stories' && $views->current_display == 'attachment_1') {
    $views->set_items_per_page(4);
  }
}

Below is the steps of using views attachment

Add attachment display

In the attachment display, you need to specify how many items you want to have.

Then you need to attach the attachment display to the main display.

Remember to set the  offset in main display for preventing repeating the item in list.


Error while enabling a core module I need to enable the 'Aggregator' module on my Drupal 7 website. When I do that, I get a error message saying:

  DatabaseSchemaObjectExistsException: Table aggregator_category already exists. in DatabaseSchema

I researched on this and what it means is that the table for the module already exists in the DB. Now in case of contributed modules I can disable them, uninstall it and make a fresh install and re-enable. I am not sure what can be or should be done in case of core modules.

Any guidance is greatly appreciated.

You somehow have aggregator uninstalled with its tables existing, which should not be. By examining aggregator_schema() in aggregator.install you can see that upon installation aggregator will create several tables named aggregator_(something). Table names correspond to the keys of the array returned by aggregator_schema(). If any of those tables exist you must delete them from the database before attempting to enable the aggregator module. As always, back up and understand how to restore your database first before attempting something like this and rehearse on a test system.