How to use "content entity" type in a View? I have used the "content entity example" coming from the example project.
This example module/:

defines a "Contact" entity; it can have extra fields, displays can be configured (web/admin/structure/content_entity_example_contact_settings),
gives the user the form to add content (contact info) to it. (/web/content_entity_example_contact/add)
shows a list of the contacts (/web/content_entity_example_contact/list)

I want to make my list as a View, but this content entity type "Contact" is not there to select it. (I see only the node content types, users, taxonomy etcI
How can I use this content in a View ? What do I have to do to make this content available in the Views UI ? Where can I find the content entity types to create a view ? Or how can I add those ?

Add a views_data handler to the entity type. Either the core standard EntityViewsData
content_entity_example/src/Entity/Contact.php
  *   handlers = {
  *     "views_data" = "Drupal\views\EntityViewsData",

or a custom handler:
content_entity_example/src/Entity/Contact.php
  *   handlers = {
  *     "views_data" = "Drupal\content_entity_example\Entity\ContactViewsData",

content_entity_example/src/Entity/ContactViewsData.php
<?php

namespace Drupal\content_entity_example\Entity;

use Drupal\views\EntityViewsData;

/**
 * Makes the content_entity_example entity available to Views
 *
 * @ingroup content_entity_example
 */
class ContactViewsData extends EntityViewsData {

  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = parent::getViewsData();

    // $data from the parent is enough to make it work but modify as required.

    // Give it a more description name in the dropdown when creating a new view.
    $data['contact']['table']['base']['title'] = $this->t('Content Entity Example Contact');

    // Make the Name field appear to Views as Last Name
    $data['contact']['name']['title'] = $this->t('Last Name');

    return $data;
  }

}

To apply this code to the example module use the patch from this issue https://www.drupal.org/project/examples/issues/2725833


Is it possible to exclude module settings when migrating database? Our dev server is on an internal network that is not connected to the WWW. As such, I have the Google Analytics module turned off on the dev server, because it really slows down page loads when enabled, since it can't reach the Google servers.  Occasionally, when I migrate site changes up to the production server, I will forget to enable the module on the live site.  It gets disabled because it's disabled on dev.  Is there a way to exclude module settings from a database backup?  (We're using the Backup and Migrate module.)

It probably is possible, but not with Backup and Migrate. BaM only enables you to exclude whole tables, and enabled / disabled status is a row.

Worse, your devel environment contains different set of scripts than production one. This may have various side effects, bugs you will only see after migrating your changes to production. That's exactly what you want to avoid, so consider other options:

Test site in environment that can connect to WWW, either by switching your dev server, or by creating dev/staging machine connected to www-enabled testers' workstations. In this latter case, you will catch if you forgot to enable something.
Store GA JavaScripts on some local place, and use hosts file or local DNS to fake traffic. It would be pretty safe to just make needed JS files available, I nothing changed recently you don't need to care about actually doing anything with data GA is trying to send to Google.


Rules UI, accessing a Variable created in another rule Any idea how to access a Variable created in another rule. I am trying to use the Data Comparison in the conditions section. Is doing this even possible or are Variables only visible within the Rule they were created?

Thanks

The variable you created in one rule will not automatically be available to other rules.

However, if there is a rule that creates a variable that you may need to reuse frequently, one thing you can do is create it as a rules component.  Then you can reuse that setup multiple times.  It can also keep your rules leaner and cleaner!


Grouping items arbitrarily in Views I have a taxonomy vocabulary with 4 terms. One of the content types has a term reference field to tag a node with a single term from that vocabulary. Now, I want to have Views (3.5) generate a navigation block for me which would list the terms in the following way: skip item 4 and merge item 2 & 3 into a custom item labeled, say "Item 2 & 3", as in:

Item 1
Item 2 & 3  [linked accordingly: taxonomy/term/2+3]

Of course, with eventually 2 items in a block, I could do that statically, I know. However the vocabulary may grow and would like to have a scalable, dynamic solution. Hence my question: is that possible?

I think the easier and simpler solution would be to create a custom block from your custom module using hook_block_info and hook_block_view.
By using these hooks, your block will be listed in the block administration page - admin/structure/block.

<?php
    /*
     * Implementation of hook_block_info()
    */
    function mymodule_block_info() {
        $blocks['yourblock'] = array(
        'info' => t('Your Module Name'),
        'cache' => DRUPAL_NO_CACHE
        );
        return $blocks;
    }
    /*
     * Implementation of hook_block_view()
    */
    function mymodule_block_view($delta = '') {
        $block = array(); # Declare array

        switch ($delta) {
            case 'yourblock' :
                // Block View
                $block['subject'] = 'Your Block Title';
                $block['content'] = _mymodule_taxonomy_content();
            }
        }
        return $block;
    }
    /*
     * Create block content as you need
    */
    function _mymodule_taxonomy_content( ) {
        $result = $query = db_select('taxonomy_term_data', 't')
                            ->join('taxonomy_vocabulary', 'v', 't.vid = v.vid')
                            ->condition('v.machine_name', 'your_tag_machine_name')
                            ->orderBy('t.tid')
                            ->execute();
        $content = '';
        foreach ($result as $term) {
            // you now have $term['vid'], $term['name'], etc. here
            // loop and build conditions here to suit your need
            // Item 1
            // Item 2 & 3  [linked accordingly: taxonomy/term/2+3]
            // For example,
            // $content .= l($term['name'], 'taxonomy/term/'.$term['vid']);
            // This is up to you.
        }

        return $content;
    }


Dropdown menu to filter view I am creating a document library. I've made a custom content type of "document" and a taxonomy for document categories. I've added the categories as a field in the document view. I want to display the document list, and at the top, have a dropdown menu where you can choose a category, and then have the view update to show you just the documents in that category.

I know that you can create a filter and then "expose" that filter to the user, but when I do that with this example, it makes a text entry box, not a dropdown box.

You can give drop down menu using Filter Criteria option.

In Filter Criteria in the field which you added for filtering Check the checkbox called

  Expose this filter to visitors, to allow them to change it


"Create a new account for an anonymous order" Rule issue with required field I am using Drupal Commerce.
I have enabled the anonymous user to access checkout and place an order.
There is this rule available in Drupal commerce("Create a new account for an anonymous order") that creates an account for user's who do not have an account and checkout anonymously.

The Problem is that there is an image field which is required in the user account form. So due this, it is having issue creating a new user, as I am not able to supply a value to it. I have set a default image, but its still having the same issue.

Anyone knows how to set this default image or make it non-required to add image while creating account through rules?

?

Two options:

Make the field not required at the field level but then use a Form alter hook to make it required when presenting the form.
Make the logo point to the default image by setting the data value to public://your-file-here.png inside of the rule.


How to get and display menu items except the parent item? Let's say my menu tree is like below:

Parent

Sub-Parent

Child

I want to get the Sub-Parent title and all child's title and url.

How can I do it in Drupal 8?

I have looked at this answer but it just for getting the parent, it is not the one I'm looking for.

You can do this by configuring the Menu levels on your Menu Block and placing that Block in a region of your theme. Additionally configure the Visibility of the block so it only appears on pages where you want it.

You can learn more about the Menu levels configuration here: Drupal 8 Navigation Menu Blocks configuration.

In your case you want the Initial visibility level and Number of levels to display to be either:

1 and 3

OR

2 and 3

AND

you'll want the Expand all menu items to be checked, unless you have all the items Expanded under Menu settins.


Views don't display any result until the exposed form is submitted I have a view that display content on my website, but now (i don't know why) my view show results only when i submit the exposed form.

I would like my view display all result by default.

Any idea ?

I think you have marked the exposed filter as required.

Uncheck the "Required" checkbox right below the "Expose this filter to visitors, to allow them to change it" checkbox.


How to modify the query that the views integration with the chart API module provides? I am using Google Charts API module to generate a pie chart of a content type with the fields Blood-group and count representing the sectors.

For this I need to completely alter the query (= select from a different table) that the views integration provides.

My question: Can I use hook_views_query_alter?

To create charts in Drupal, there are plenty of modules available. Refer to the comparison of charting modules for an overview. After doing so, it should be clear that the names (and namespaces) of various charting modules are pretty confusing. Therefor I suggest you add a link to the exact 'Google Charts API' module this question is about.

Moreover, if I correctly understand the question, it seems to me that this is a rather straight forward requirement that can be easily addressed with (at least) the Charts module, i.e. the views integration of it (provides a new views style plugin to transform tabular view results into a chart). I recently created quite a lot of new Charts documentation that should help to get started with it.

The Charts module ships with out-of-the-box samples which are straight forward to adapt to fit your needs, e.g. by cloning these samples in a new views display or a new view. Of course there are other alternatives in that comparison that might be a better fit for this specific case.

Be aware: I'm a new (co-) maintainer of both Chart and Charts (confusing module names, I didn't invent them), and the author of the comparison of charting modules.


Adding contents to custom blocks I have created a custom region regions['my_region'] in mytheme.info file. I have added a block myblock to the region. Now how can I add contents to this block? Currently I have created a template file region--my_region.tpl.php and added contents there. Is this the right way? How can a normal user will be able to edit these contents?

Blocks are considered configuration, not a content. Thus, there is no separate privilege you can give your "normal users" to allow them to edit blocks.

There is another way round. You can make some of content to be a blocks with Nodeblock or one of it's competitors:

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

That way you can create content type Block, and apply node permissions to it. All of them, including "edit own block" or "edit any block".

Just be sure no one have "delete" permissions on them, as it would remove block you placed from your page, and that should be admin-only task.

Other way is to use Views module. With Views, you can define a block and make it to show user's content, using various filters and orders. You could, for example, make a Views block that displays content of type news from users with role reporter, unless it's Friday in Iceland, and when it is, display content of type joke. Order by random, by date, by user's reputation, by anything you want :)


Domain access domain menu show default values The problem:
We have a main site with 70 subsites. On these subsites are users who have access to the menu settings. When they add a menu item they need to check the box near their own subsite.
If they forget this the menu item will be shown on all the other domains. Sometimes resulting in multiple menu items with the same title.

The proposed solution:
Alter the menu_edit_item form so that the $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] is set to the domains the current user has access to.

My question:
How do I set the default value for these checkboxes?
Here is my code:

// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $domains = array();
    if($user->uid > 1){
      $form['domain_menu_access']['manage']['#collapsed'] = false;
      foreach($user->domain_user as $domain){

    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array((string)'d'.$domain);
  }
}

I have tried several variations with the $domain. (array($domain), array($domain => $domain), etc)

I found a workaround. I just rebuild the options array with the domains the user has admin access to.
Here is my code:

// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $form['domain_menu_access']['manage']['#collapsed'] = false;
    $domains = array();
    if($user->uid > 1){

  // We don't need to hide any menu items on other domains so we don't show this option.
  $form['domain_menu_access']['manage']['domain_menu_access_hide']['#access'] = false;

  // Loop the user object for all the domains current user is connected to
  foreach($user->domain_user as $domain){
    // Get the domain data
    $domains[] = domain_lookup($domain);

    // First unset all the options of the form element so we can rebuild it with our own values
    unset($form['domain_menu_access']['manage']['domain_menu_access_show']['#options']);
    //Rebuild the #options array
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#options']['d'.$domain] = $domains[0]['sitename'];

    // Set the default value(s)
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array('d'.$domain);
  }
}

}


Commerce Feeds: Multiple values in one field or multiple fields? Goal
What I'm trying to ultimately accomplish is create tiered pricing based on quantities.
The client is selling different prices depending on quantity. I'm trying to figure out what is the simplest way to store, access and represent this data using fields. While at the same time i'm importing them through commerce feeds.
About my feed/data
I have a CSV table header with the columns "P1 Price," "P2 Price," and "P3 Price." There are also "P1 Qty," "P2 Qty," and "P3 Qty."
Thus, P1 Price corresponds to P1 Quantity, etc.
My question
Would it be simpler, in terms of less complex rules or views configuration, in the long run if i created separate fields to store each price/quantity, or if I combined them into one field that stores 6 different values?
My primary considerations include, scalability, maintainability, etc.

It sounds like what you need is commerce price table. There isn't a stable release for it yet, but I have seen it demoed where it worked great.


What is the "Category" argument in user_save for? I'm working on a custom module that edits the user's details. I'm using

user_save($user_entity,$new_field_values);

But I see there is a third argument in user_save called "category". What exactly is it for?

As you see in user_save function it tells that

  category: (optional) The category for storing profile information in.

It basically used in below lines of code inside user_save function

user_module_invoke('presave', $edit, $account, $category);
user_module_invoke('update', $edit, $account, $category);
user_module_invoke('insert', $edit, $account, $category);

So, the information is just passed to all presave, update, insert hooks so that they can take contextual actions.

In user_module_invoke function $category is defined as

  $category: The category of user information being acted upon.

So, from above it clarifies that is used as a value to tell all hooks that we are saving user details and on which part of user information we are acting upon. Something like if we change the user organic groups that he belongs to then we can specify that $category as "organic_group" .

For Example if you see hook_user_presave in user module

/**
 * Implements hook_user_presave().
 */
function user_user_presave(&$edit, $account, $category) {
  if ($category == 'account' || $category == 'register') {
    if (!empty($edit['picture_upload'])) {
      $edit['picture'] = $edit['picture_upload'];
    }
    // Delete picture if requested, and if no replacement picture was given.
    elseif (!empty($edit['picture_delete'])) {
      $edit['picture'] = NULL;
    }
    // Prepare user roles.
    if (isset($edit['roles'])) {
      $edit['roles'] = array_filter($edit['roles']);
    }
  }

  // Move account cancellation information into $user->data.
  foreach (array('user_cancel_method', 'user_cancel_notify') as $key) {
    if (isset($edit[$key])) {
      $edit['data'][$key] = $edit[$key];
    }
  }
}

You can see the use case of $category above where they check for account or register !

In your case just make it as an optional and don't assign any value :-)


Drupal nginx configuration. PHP files being downloaded Problem

I'm trying to configure my nginx server. I've been building from the default rather than jumping straight into Perusio's because I don't understand a lot of it.

I'm trying to deny access or require authentication to access update.php, install.php and apc.php.

I think they're locked down but on navigating to the file it's downloaded instead of being run.

For example after entering my authentication for apc.php it downloads to my computer. The same thing happens for update.php.

I've taken a lot of the configuration from another excellent post on here: Is there a common nginx conf for Drupal 7 sites?

My Server Config

server {
      listen 8080;
        server_name website website.com;
        access_log /srv/www/website/logs/access.log;
        error_log /srv/www/website/logs/error.log;
        root /srv/www/website/public;

        location / {
           index index.php index.html index.htm;
           error_page 404 = @drupal;
        }

        ##drupal rewrite rules
        location @drupal {
            rewrite ^(.*)$ /index.php?q=$1 last;
        }

        ##secure private file directory
        location ~* /privatefiles {
             internal;
        }

        ##Add headers to advagg
        location ~* files/advagg_(?:css|js)/ {
            access_log off;
            expires    max;
            add_header ETag "";
            add_header Cache-Control "max-age=290304000, no-transform, public";
            add_header Last-Modified "Wed, 20 Jan 1988 04:20:42 GMT";
            try_files  $uri @drupal;
        }

        ## Replicate the Apache <FilesMatch> directive of Drupal standard
        ## .htaccess. Disable access to any code files. Return a 404 to curtail
        ## information disclosure. Hide also the text files.
        location ~* ^(?:.+\.(?:htaccess|make|txt|log|engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
            return 404;
        }

        location ~ \..*/.*\.php$ {
            return 403;
        }

        ##deny access to update and install for everyone except the server
        location ^~ /update.php {
            allow 127.0.0.1;
            deny all;
        }

        location ^~ /install.php {
            allow 127.0.0.1;
            deny all;
        }

        ##authentication required to access apc.php
        location ^~ /apc.php {
            auth_basic "Restricted access"; #realm
            auth_basic_user_file /srv/www/website/public/.htpasswd-users;
        }

        ##rules for running php
        location ~ \.php$ {
            try_files $uri =404;
            include /etc/nginx/fastcgi_params;
            if ($uri !~ "^/default/files/") {
                fastcgi_pass 127.0.0.1:9000;
            }
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /srv/www/website/public$fastcgi_script_name;
         }

 }

I created a really long guide on how to set-up Perusio's nginx config. (EDIT: We turned it into a wiki so anyone can add. Also I forgot to link.) The config itself is excellent and well worth a look. If you couldn't get it working before, hopefully my guide will help.

Ok so here we go.

When you use either of the following expressions for a location block in nginx:

=
^~

Then it will stop searching for more matches immediately after it hits one of them. It checks = with priority then all the other 3 expressions at the same time in the order of the nginx config file.

So in my case it was finding ^~ on update.php and install.php and stopping the search immediately. This means it never runs php processing on the files and so they're downloaded instead of opening. Adding the php logic to the location blocks, means nginx then runs the php as well as blocking them for all bar me.

      location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        if ($uri !~ "^/default/files/") {
            fastcgi_pass 127.0.0.1:9000;
        }
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/website/public$fastcgi_script_name;
      }

      location = /update.php {
          allow 127.0.0.1;
          deny all;
          fastcgi_param SCRIPT_FILENAME /srv/www/mysite/public$fastcgi_script_name;
          fastcgi_pass 127.0.0.1:9000;
          include /etc/nginx/fastcgi_params;
      }

      location = /install.php {
            allow 127.0.0.1;
            deny all;
            fastcgi_param SCRIPT_FILENAME /srv/www/mysite/public$fastcgi_script_name;
            fastcgi_pass 127.0.0.1:9000;
            include /etc/nginx/fastcgi_params;
      }

You might note that I've also changed to = from ^~. This is because = is always picked with priority and prevents me from accidentally breaking this later. Choose = and avoid the difficulties I'm about to mention below.

Another useful point: I don't think nginx can ever match two location blocks. It'll pick the more specific one.

Stuff that doesn't quite make sense

Lastly I don't quite understand the priority order of the 3 expressions. If I put *~ in the update block in the example above, it chooses the php block (which has ~), apparently case sensitive overrules the more specific match? This seems weird and isn't mentioned in the docs. If I use ^~ it works as expected.

If anyone has found a great explanation of location I'd love to see it because I'm not sure the docs make perfect sense.


Redirect to the front page with a different language i have a question about redirecting to a page with a different language. I found this old post for drupal 7 but I doesn't really help me - https://www.drupal.org/node/1280468

Now we are in Drupal 8 and the redirect works like this:

return new RedirectResponse(\Drupal::url('<front>'))

But how can I set the language for the redirect? In my code I have the languagecode like NZ for New Zealand.

You can try this code

 <?php

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

 $language = Drupal::languageManager()->getLanguage('vi');
 $url = Url::fromRoute('<front>', [], ['language' => $language]);
 $response = new RedirectResponse($url->toString());
 $response->send();


How to access the order total amount in Drupal commerce? I'm trying to make a block with an image that would change when there is something in his or hger basket (empty basket image when basket is empty, full basket when it's full)
My understanding of PHP is weak, but I found this topic :

http://www.drupalcommerce.org/discussions/787/simple-shopping-cart-summary

and I wrote that:

<?php
global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_total = $wrapper->commerce_order_total->value();
if ($order_total['amount']>0) echo ('   ');
else echo ('   ');
?>

Now on my home server everything worked as expected. On the reomte one i got several show-stopping errors.

If i put the whole thing, I get

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. w EntityDrupalWrapper->set() (line 744 of /profiles/commerce_kickstart/modules/entity/includes/entity.wrapper.inc).

By trial and error, I detected that leaving the first two lines

global $user;
$order = commerce_cart_order_load($user->uid);

are 'innocent'. It's the third one

$wrapper = entity_metadata_wrapper('commerce_order', $order);

that generates the error.
So actually it's the code from that commerce thread that seems to generate the error. To me it seems pretty innocent, though.

As I said, I know very little about PHP, not to mention the internals of Drupal Commerce. I'd be grateful for any suggestions.

Try this

global $user;
$image = theme('image', array('path' => url('sites/default/files/basketempty.png', array('absolute' => TRUE))));
$order = commerce_cart_order_load($user->uid);

if ($order) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $line_items = $wrapper->commerce_line_items;
  $total = commerce_line_items_total($line_items);
  if($total['amount']){
    $image = theme('image', array('path' => url('sites/default/files/basketfull.png', array('absolute' => TRUE))));
  }
}

echo l($image, 'twotrees/cart', array('html' => TRUE));


add flag to product display view I have a product display using facets that I have tried in vain in views to add a flag/unflag link to with views I already built a separate comparison view with the relationship to flag and the ability to unflag but I want to be able to flag products from the facets display (if it's even possible) rather than a second display that looks the same as the facets display except that it uses content linked to the product entity and wont show the facets

Does anyone know if it's even possible to add a flag to a view of type "Product Display"?(Correction: "Product Display" was the name of my search api index being exposed to views)

For now I have this working by exposing the flag link on the product displays themselves which is a pain in the neck to flip back and forth and some users probably aren't going to be able to be techie enough to figure it out

I am having the same problem. It seems like there is no way to add 'flag' relationship in view used by facets..
The way I have done this is:

I installed the module 'Views PHP'
(https://drupal.org/project/views_php)
Added a 'global PHP'
field in my faceted view.
called the function to create flag
link and printed the link in the global php field: print flag_create_link('bookmarks', $data->entity)

Dont know why, my php view cudn't render $row->nid, thus I used $data->entity for node id.

Remember to enable php filter once views php is installed.

Hope It helps.


Node content is not shown I installed DrupalGap. Everything works fine so far, except that the node body is not displayed. I have none of the mentioned interfering modules installed. I also tried with a fresh Drupal 7 installation in a new test environment with the same result.

I ask for advice or hints.

Note: values are handed over. I can display the body instead of the title. But after clicking a node title, in the sub sequent page only the titel and the comments are shown.

Additional information: the edit mode of a node shows the html content. Only the view does not show the content (body)

10th of Jan 2020: I made a clean Drupal 7.69 installation with minimum modules (in order to exclude module interferences) with DrupalGap 7.x-1.17 on my localhost. Same effect - not showing the node body in View mode. I wonder what configuration the DrupalGap demo does have? There it works.

The problem was that the Body field was not added to the DrupalGap Display Mode for the content type:

  By default, there are no fields displayed using the DrupalGap Display
  Mode. We need to specifiy which fields, labels and formats will be
  used when our nodes are displayed in the mobile app. Do this for each
  content type.


How to show a variable of node in page template I have created a content type with some fields in Drupal 7. It output in node.tpl.php of course. But I wonder if I want to display some fields somewhere within the page.tpl.php, how to go about it. e.g. output a content types' field in the header/footer in page.tpl.php or anywhere.

This question is more or less a duplicate of https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field. But I'd rather see the answer and question here on Drupal.stackexchange.com.

This goes into your template.php or in a module included file.

function THEME_OR_MODULE_preprocess_page(&$vars) {
  $vars['VAR_NAME'] = '';
  // Get the object and do some other checks based on what you need.
  if (($node = menu_get_object()) && $node->type) {
    // Generate a render array for the node.
    $view = node_view($node);
    // "Create" a new variable for the page.tpl.php.
    // This will expose $VAR_NAME in the page template.
    // You will most likely have to clear your cache.
    $vars['VAR_NAME'] = drupal_render($view['FIELD_NAME']);
  }
}

And then in your page.tpl.php:

HTML
<?php print $VAR_NAME; ?>
HTML

You might also have to hide the field in your node template, if you don't want to print the field twice. Check at hide() for that.


Using Rules to block system email or prevent from sending? I have a unique use case. I am currently using mailcontrol module to disabled the sending of emails when news users are created. However I got to thinking about this, and I was wondering if there is a way to create a Rule to prevent the email from sending so I wouldn't have to use the mailcontrol module.

Maybe a custom module and lines in the setting.php?

Here is a simple tutorial showing how $message['send'] = FALSE; can stop it. Of course, you can also use if statments to add conditions.

Note: The developer does mention that you shouldn't use it on production...


Deleting the "Language" module - a dangerous move? Drupal 8 comes natively with a module called "Language". This module will be installed even in English websites.

Uninstalling this module from UI or from drush pmu language --- is it a dangerous move?

I ask since when I did drush en language I got the message:

  language was installed successfully
  language defines the following permissions: administer languages

I wasn't sure if that's something good because I then remembered that the module comes natively with the system so I removed it with drush pmu language.

I was afraid this "radical" move could do some damage at least in time being. From a Drupal programmer's standpoint, can this be dangerous or cause wired behaviors in time being?

The Drupal 8 language module is disabled by default.  Uninstalling it just sets it back to its default state.  This is not "dangerous".


Download file field dependent on user role vs role field values I have a type downloadable_item which has a field field_roles_allowed that is based on the Role Field Module.

My goal is to have a field_download of file type that will show the file for download if the user in a role selected in the field_roles_allowed and a message that they need to request access otherwise.

I am attempting to add a formatter for the file field type using the Custom Formatters Module. I found this tutorial on how to use the Custom Formatters module, however, they use the "HTML + Tokens" option. I will need to use the PHP option to be able to output either the download button or a message depending on whether the user is in a role in the field_roles_allowed.

I cannot figure out how to get the roles that are allowed, download file information, and current user's roles for comparison.

My question is really "How do I do these things that I cannot figure out?", but if someone believes I am going about this totally in the wrong way... I am open to another way.

EDIT: I solved my own problem below, but not really in a preferable way. How could this be done without writing PHP logic in field?

After some digging... I found that I am able to get field information like...

$variables["#object"]->field_roles_allowed["und"]; //array containing id's of roles allowed
$variables["#object"]->field_download["und"]; //array containing information about the file

and that I can get the current user's roles like...

global $user;
$user->roles; //array containing current user's roles

Then I can compare the field roles allowed with the current user's roles and determine what to output from there.

Still not very happy with this, I would prefer something where I don't have to write PHP logic in a field.


Fatal error: Cannot redeclare uc_order_views_data() After clicking Continue @ /update.php, we receive:

Fatal error: Cannot redeclare uc_order_views_data() (previously
declared in
/home/user/public_html/sites/all/modules/ubercart/uc_order/views/uc_order.views.inc:13) in
/home/user/public_html/sites/all/modules/contrib/ubercart/uc_order/views/uc_order.views.inc
on line 708

When I remove either version of the ubercart directories, the /update.php process complains that the directory is missing.
I can't see a double-up of modules in /admin/modules
The two ubercart directories both contain the same subfolders.
I did not develop the website, but took over maintenance of it.

"When I remove either version ..."
"I can't see a double-up of modules in /admin/modules"
"The two ubercart directories both contain the same subfolders."
It sounds like you have two copies of Ubercart on your server. THAT IS NOT ALLOWED for ANY Drupal module. You must have one, and only one, copy of each module.
The correct way to update a Drupal module is to completely remove the old version of the module code first, then replace it with the new version of the code. Then you can run update.php.


Does having more enabled modules make the site slower? Does having more enabled modules make the site slower?
I have installed 30 modules for my site, and I am afraid that it will become too slowly.

Yes.
However, 30 is nothing to worry about. You're in trouble when you go over 100 ;)

Install a bytecode cache (APC or XCache) to eliminate most of the slowdown of including many files, and make sure to periodically remove unused modules (usually every project gathers modules that get unused at some point during development)


Adding Rules to Canada Post and UPS (Ship-by-weight) I've a site with Drupal Commerce. I'm utilizing both the Commerce UPS and Commerce Canada Post modules. However, these modules are pulling the shipping cost directly from Canada Post and UPS using their API's.

I want to implement a rule that does the following:

Per Ounce
Base Charge: $13.35
Minimum Amount: $0.00
+  $0.00  per ounce on weight less than  21 oz (pivot-weight)
+  $0.30  per ounce on weight greater than 21.00 oz

How do I do this within the Commerce Canada Post and Commerce UPS modules?

I doubt you'll be able to "create a rule" using either Commerce Canada Post or Commerce UPS (as in your question). Because creating rules is mostly commonly done with the module ... euh ... Rules.

Even though I'm a fan of Rules, I'd rather first try a NOT commonly known/used solution to answer this question, i.e. the Math Field module. It is a fairly new D7 module, released only this year. Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

The reason why I think the Math Field module might be a solution (or at least worth giving it a try), is because of the various fields that appear to be used (as a prereq) for using either Commerce Canada Post or Commerce UPS.


How can I restrict access to a static HTML page served from a subfolder of my site to authenticated users only? I have a Drupal 8 site that has all roles and permissions necessary for authenticated users. One of the new requirements is to serve a static microsite (like a campaign site, totally different design compare to Drupal site) which is a single folder with all the static assets (HTML, CSS, JS , images). We have to serve this site under the same domain drupal is hosted and should be accessed ONLY by authenticated users.

I tried to host it under sites/default/files/ directory, but it means it is public and anyone can access it.

One of the options to achieve this is using drupal's private file system. Drupal core out-of-box provides a way to access private files in a secured URL. Here are the steps:

upload the directory (e.g. foo-bar) to drupal's private file scheme. (you can find it under  Administration->Configuration->Media->File system)
Create a hook_file_download($uri) in a custom module and check for necessary access conditions:

function mymodule_file_download($uri) {

  // Check user permission only if the requested
  // file is under foo-bar directory.
  if (strpos($uri, 'foo-bar') !== FALSE) {
    if (\Drupal::currentUser()->isAnonymous()) {
      return -1
    }

    // Return a header to inform access is granted.
    return ['Cache-Control' => 'private'];
  }
}

Now the directory is available for authenticated users at www.example.com/system/files/foo-bar/index.html.

Check Drupal\system\FileDownloadController::download() for more details

This would work for both Drupal 8 & 9. I haven't checked 7.


Print watcher link in a block I found the code below to print a watcher link in a block, but it is for Drupal 6.

<?php
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $node = node_build_content($node, false, true);
    print $node->content['watcher']['#value'];
  }
?>

Does anyone know how to get the same thing done for Drupal 7?

This depends on if you are trying to get the value of the field or the rendered output of the field.

If you just want the value of the field you can do this in the same way in Drupal 7. Instead of

 $node->content['field_name']['#value'];

you need to specify a language and the a number for the field value you want (even if the field doesn't accept multiple values).

 $node->field_name[$node->language][0]['value'];

If you have the entity api module installed you can use the entity_metadata_wrapper function which is a little cleaner: http://drupal.org/node/1021556

If you want the rendered output, use node_view:

 if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_view(node_load(arg(1));
    print drupal_render($node['field_name']);
  }

The rendered output will give you the properly themed output, something closer to:

"

field value

"


How can I make a condition for currently viewed language on a template file? I have a template called page-my-view.tpl.php that overrides a view page my-view.

I have directly put the title tags, description and h1 on this template file.

However I need different texts for these tags per language to avoid duplicated tags.

I have 2 languages on my site English and Japanese.
Japanese is the default one with no prefix and English is with prefix "en".

So how can I make a condition on this template for currently viewed language?

In your template file global variable $language is avaible,with below properties

'language' => 'en',
'name' => 'English',
'native' => 'English',
'direction' => 0,
'enabled' => 1,
'plurals' => 0,
'formula' => '',
'domain' => '',
'prefix' => '',
'weight' => 0,
'javascript' => ''

You can achieve your jobs with something like this
// if global variable $language  not avaible uncomment first line

 //    global $language;
if ($language->language == 'en') {
   // do your desires
  }


How to autoload, so composer packages work correctly? I'm trying to load in a composer package: archwisp/php-encrypt-data, and while I'm able to use it in a test php script, using it in Drupal itself doesn't seem to be working.

This is the test script:

require __DIR__ . '/vendor/autoload.php';

$encryptionKey = 'IyJQdVtyNClqQ+ybuxHWNhJnw93ocxJuLruRztQPNI0=';
$macKey = 'pbJqXp4YhhtRYv/Ntt/i+O4KbO1F4/2bktO08m0+Exo=';

$phpcrypt = new \PHPEncryptData\Simple($encryptionKey, $macKey);

$ciphertext = $phpcrypt->encrypt('Foobar');

echo $ciphertext . "\n";

echo $phpcrypt->decrypt($ciphertext) . "\n";

But, I don't understand what I have to do in a Drupal class to make this work.  I tried to use archwisp\PHPEncryptData; at the top of the file, and I tried doing require DRUPAL_ROOT . '/vendor/autoload.php'; as well, but no matter what, it always says: Call to undefined function PHPEncryptData\\mcrypt_get_key_size()

Is it because it didn't do the autoload the same way, or is it getting mixed up because of namespaces?  The error is coming from the composer package itself, so it is locating that, but for some reason it's not calling the mcrypt function correctly, even though the extension is enabled and working in the test script.

Call to undefined function PHPEncryptData\mcrypt_get_key_size()

mcrypt is a php function of the mcrypt extension. Autloading is working perfectly fine, or you wouldn't get that far. You're simply missing that extension.

The error message is a bit confusing because PHP always looks for functions in the global namespace and in the namespace the code is in and then prints the error for the one with the namespace.


Extending a CCK field formatter I've created a custom formatter (display) for filefield but I'd like to add a settings page per field for width and height.

Currently my code only consists of the bare minimum to get the formatter to work (which it does). However I'm currently hardcoding width and height at the hook_theme() level.

I've not found any examples of setting pages for formatters only for custom fields. I suspect that it's not possible to do this for a formatter and I'd have to define my own field rather than formatter. I could create a global admin page and loop through all fields and set the settings as a variable but that might become an issue when upgrading it to 7.

Any feedback or ideas would be great.

D7 has this baked into the field formatters. You could look at how that is done and emulate it. But I suspect that would be quite a lot of work. How far off is D7 for you? It could be worth waiting till then to allow field settings.


What other PHP memory_limit restrictions could there be besides php.ini? I have been facing some weird memory limit issues on a managed dedicated server and spent alot of time trying to fix this other with the server admin. phpinfo() is showing the correct overridden memory_limit values.
Everything is cool, except when I use drush to do drush en module or Views Bulk Operation execution. If anyone has experienced this before, I will really appreciate if you can share with us the steps needed to fix this.

In my php.ini :memory_limit = 256M ;

In sites/default/settings.php: ini_set('memory_limit', '256M');

The WSOD message after executing a Views Bulkd Operations on ONE entry:
Fatal error: Out of memory (allocated 131334144) (tried to allocate 5 bytes) in /public_html/includes/cache.inc on line 401
Memory used at: devel_boot()=5.02 MB, devel_shutdown()=82.06 MB, PHP peak=82.25 MB.

In SSH, using drush cli. After running drush en languageassign:
The following extensions will be enabled: languageassign
Do you really want to continue? (y/n): y

Fatal error: Out of memory (allocated 76021760) (tried to allocate 72 bytes) in /public_html/sites/all/modules/views/includes/base.inc on line 84

Drush command terminated abnormally due to an unrecoverable error.                      [error]

Error: Out of memory (allocated 76021760) (tried to allocate 72 bytes) in
/public_html/sites/all/modules/views/includes/base.inc, line 84

Try including "RLimitMem 128000000" in your .htacess file.


Replacing display page with views in template.php since yesterday I can not solve the problem with function preprocess_views_view:
In the views named 'Calendar' I have a few display page(page_classic, page_mobile) and I would like to change preprocess_views_view function in mobile version of the site, which replace default display page(page_classic) with page_mobile. Below function, does not work:(

function mobiletheme_preprocess_views_view(&$vars){
    dpm($vars);
    $view = views_get_view('calendar');
    if($view->name=='calendar'){
        $display_id = 'page_mobile';
        $view->current_display = $display_id;
    }
}

Any ideas?

Views' hooks are called whenever a View is called, yet you are calling the creation of the View once again inside of it, and then trying to change that View, not the original one.

Instead, you should be doing something along the lines of...

function mobiletheme_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  switch ($name) {

     case 'calendar':

       // process it here, eg change/add $vars['foo']
       break;

     // other Views here

  }

}

Now, that, changing template variables, doesn't appear to be what you want to be doing, so you will have to look into some of the other Views hooks, most probably views_pre_view to change the display, eg, something like...

function mobiletheme_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='calendar' && display_id=='page_classic') {
    $view->set_display('page_mobile');
  }

}

Addition/Caveat:  This appears to have to be called from a module, not a theme (at least in D6), so you may need something like this...

function mobilemodule_views_pre_view(&$view, &$display_id, &$args) {
  global $theme;

  if ($theme=='mobiletheme' && $view->name=='calendar' && display_id=='page_classic') {
    $view->set_display('page_mobile');
  }

}

...inside a small module.


add link in Colorbox caption In my gallery, what i write as image title is the caption of my image and that is great.
Now I would like to add a link (external url) to my caption, how can i do that?
I already try to write normal url and html a tag but is always ignored.

I see two option in Colorbox configuration related some link, i play a bit with that but I didn't really understand what i'm supposed to do with that

How did you do?

EDIT: Add screenshots step by step adding link for title

My Colorbox gallery is placed in custom 'Photo Gallery' Content type. Here there are a list of images with Alt and Title.
This images are automatically grouped thanks another view "Gallery Photo" which display the first image and then thanks to colorbox open all the other inside it as a gallery.

http://loungesquatt.com/drupal734

You need to do it with JQUERY,there is another way as patching colorbox,but by default color box dont support link as title

   $('#cboxTitle').html('title');


How can I install composer packages with drush make? How does one include composer package in a drush make file?

The more general answer, the better. There's already a composer drush module allowing drush dl to handle composer packages, but that requires a shell command for every dependency.

Given our future use of Symfony, composer and other Symfony bundles is likely to become more important in the future.

You should use yoursite.make to download the Drupal module and composer.json for composer.

There is the Composer module that integrates Composer with Drush.

I hope that soon .make is going to disappear, replaced by composer.json; for that to come true, some issues need to be resolved, such as version number.

Composer packages are stored in the git repository; you can't use a composer package, but you can download the code. For example, for https://packagist.org/packages/symfony/symfony you can use the following.

libraries[symfony][download][type] = "git"
libraries[symfony][download][url] = " https://github.com/symfony/symfony.git"
libraries[symfony][destination] = "lib/symfony/"

Composer can build stuff recursively; of course, this will not work here.

See: http://cgit.drupalcode.org/drush/plain/docs/make.txt

Their is also https://github.com/composer/installers than can do the invert (install drupal module with composer).


Running Drupal API Scripts offline I want to run some maintenance scripts against a Drupal 7 system. These scripts will call the Drupal API to use things like EntityFieldQuery, node->save and so on. I could create a module called maintenance_scripts which has a forms interface to launch the scripts with and to display their output, but I'd rather just run a script from the command line. Is this possible?

It is not necessary to write an entire Drush command just to run some php code.  Use:

drush php-eval '$a = callSomeFunction(); print $a;'

or:

drush php-script /path/to/script.php

Drush will bootstrap your site and run your code.


Save image from URL to a field from a custom module With a custom module, I'm trying to create a new node, save an image to a node's image field from URL and save the node as well. However when I'm trying to save the node, this error messages comes up

  Notice: Trying to get property of non-object in file_field_presave()
  (line 220 of
  /var/www/clients/client1/web20/web/modules/file/file.field.inc).

  Notice: Undefined property: stdClass::$uri in file_save() (line 566 of
  /var/www/clients/client1/web20/web/includes/file.inc).

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '' for key 'uri': INSERT INTO {file_managed} (filesize, status,
  timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0
  [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] =>
  1373886933 ) in drupal_write_record() (line 7136 of
  /var/www/clients/client1/web20/web/includes/common.inc).

This is the code I wrote for saving the image into a folder, saving it into a node field and save the node:

      $node = new stdClass();
      $node->type = "flickr_image";
      node_object_prepare($node);

      $node->title    = $photo['title'];
      $node->language = LANGUAGE_NONE;

      $node->uid = 1;

      $url = $image[10]['source']; //URL of the image
      $directory = file_build_uri('flickr_images/');

      $file = system_retrieve_file($url, $directory, TRUE, $replace = FILE_EXISTS_REPLACE);
      file_save($file);

      $node->field_image[LANGUAGE_NONE] = $file;

      if($node = node_submit($node)) {
          node_save($node);
      }

What am I doing wrong? I've looked up several similar questions here, but I don't understand what's the problem. The messages only come up when I use node_save(). When I comment it out, the messages disappear.

Hope this will help  you,

In Drupal 7,  for your requirement I made some changes.

As system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

$node = new stdClass();
$node->type = "node_type";
node_object_prepare($node);
$node->title    =  'your title here';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$url = 'https://ssl.gstatic.com/gb/images/k1_a31af7ac.png';
//I have used picture folder to store images using image field settings
$file_info = system_retrieve_file($url, 'public://pictures/', TRUE);
if($file_info->fid){
    $node->field_image[LANGUAGE_NONE]['0']['fid'] = $file_info->fid;//assign fid
}
$node->field_test_field[LANGUAGE_NONE]['0']['value'] = 'test';//other fields
if($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('submitted successfully');
}

Make changes as per your requirement.


How to round the total price, display without decimal? I need to count on decimal places (tax, promotion, fee ...), but the total price must be mathematically rounded without decimals.
Example:
2 x product1 CZK 424.00
1 x Product2 CZK 408.00
Subtotal CZK 832.00
Shipping CZK 99.00
Discount CZK -41.60
10% VAT CZK 71.86
21% VAT CZK 17.18
-Total CZK 889.40- remove
Rounded CZK - 0.60 it is not necessary to display
Total CZK 889.00

this solved my problem: https://www.drupal.org/project/commerce/issues/3076196
my module:
roundingmodule.info
name: Commerce rounding module.
type: module
description: Rounding.
core: 8.x
package: Custom

roundingmodule.services.yml
services:
  roundingmodule.rounding_order_processor:
    class: Drupal\roundingmodule\RoundingOrderProcessor
    tags:
      - { name: commerce_order.order_processor, priority: -10 }

roundingmodule.commerce_adjustment_types.yml
rounding:
  label: 'Rounding'
  singular_label: 'rounding adjustment'
  plural_label: 'rounding adjustments'
  has_ui: true
  weight: 20

src/RoundingOrderProcessor.php
    <?php

namespace Drupal\roundingmodule;

use Drupal\commerce_order\Adjustment;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;

/**
 * Processes the order's shipments.
 */
class RoundingOrderProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {

      $rounder = \Drupal::service('commerce_price.rounder');
      $order_total = $order->getTotalPrice();
      $rounded_total = $rounder->round($order_total->divide(100))->multiply(100);
      $difference = $rounded_total->subtract($order_total);

      $order->addAdjustment(new Adjustment([
        'type' => 'rounding',
        'label' => 'Rounding',
        'amount' => $difference,
      ]));
  }

}


How To Open The Comment Form In Modal Form I want To Provide The Link "Add Reviews" For Content Type Example "Doctor". Then How I can Use the Comment Functionality For That. So that When the user Click on the Add reviews Link A modal Form  Appears  Having Text Field with "Rating Star". so that user can submit Reviews For that Content Type.

You can use Colorbox Node.

So you should have this link in your node.tpl.php:

print l(t('Review'), 'comment/reply/' . $nid . '?width=600&height=600', array(
          'attributes' => array(
            'class' => array('colorbox-node')
                )));


How to resolve error 'Unresolved dependency System ...' encoutered when trying to upgrade Drupal core? I'm trying to update Drupal core from 7.28 to 7.36. (not using Drush)

When running update.php I get:

  Unresolved dependency  System (Version >=7.33 required)
  Relation requires this module and version. Currently using System version 7.28

It seems like the Relation module wants a version 7.33 or higher, and yet it won't let me upgrade to a version 7.33 or higher. Not quite sure how to get past this.

Relation ver. 7.x-1.0-rc7  (It didn't seem to have any trouble when I upgraded to 7.28).

How can I resolve this?

The reason for your error is because of the last line in the info file of the Relation module, i.e.:

  dependencies[] = system (>=7.33)

In regular English it is something like "This version of the Relation module requires Drupal core to be at a level which is at least 7.33".

To resolve it perform these steps:

Disable of the Relation module.
Retry your core upgrade again (that error should not show up anymore, as per step "1.").
Re-enable the Relation module again.

I'd be interested to hear what result you get in that scenario ...

Note: since your site is pre 7.32, you may want to also work on things such as what is in suggested in the answers to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?


How to edit/extend/remove pager in the admin back-end? For example I just applied Mollom for antispam and everything, because the site got like 500 spam comments and 500 spam users. Now I can delete them only by selecting 50 users per page in the admin/people list and that is taking up really lots of time. I will have to remove comments and forum threads like that too page by page, 50 at the time? Would be nice to somehow extend those admin back-end pagers for various lists, like amdin/people or admin/content so I could select them all at once, or select at least 100 per each or something like that.

Maybe there's a module or something?

Views Bulk Operations was written to handle such situations:

  This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

You can build a View to filter users by whatever criteria makes sense, and use VBO to delete them all (not just those on the current page) in one go.


Display images twice in a node with different image cache settings I have a node type where I'd like to display images as both thumbnails and full size images, so I'd like to use different image cache settings on the two image types. I don't want to use views to do this. I know that I can output a field twice using "print render($content['field_name']); " in my node.tpl file, however I wouldn't be able to manage the display separately on the two outputs.

Does anyone have a solution?

You can get the image path by using following code:

<?php
var_dump($node);
?>

Now find the path of the image and write the following code:

<?php
theme('image_style', array('style_name' => 'stylename', 'path' => 'image path', 'alt' => 'image alt', 'title' => 'image title', 'width' => 'some width', 'height' => 'some height')));
?>

Where you can define your own style name. I hope you know how to create image styles.
Just Goto admin/config/media/image-styles and add your style and use it in above code. Use above code twice to print images in two different style.

Entire code:

// filename relative to files directory
// e.g. 'masthead.jpg'
$filename = $node->field_image['und'][0]['filename'];

// relative path to raw image in 'scheme' format
// e.g. 'public://masthead.jpg'
$image_uri = file_build_uri($filename);

// relative path to 'styled' image (using an arbitrary 'banner' style) in 'scheme' format
// e.g. 'public://styles/banner/public/masthead.jpg'
image_style_path('banner', $filename);

// html for a styled image
// e.g. '<img typeof="foaf:Image" src="http://mysite.com/sites/default/files/styles/banner/public/masthead.jpg" alt="" />'
print  theme('image_style', array('style_name' => 'banner', 'path' => $image_uri));


Drupal 7 Orphaned fields, how should they be deleted? Currently I uninstalled ubercart and there are still fields that exists in my database. I have the following fields that I want to delete:

uc_catalog_image
uc_product_image

http://prntscr.com/1hj1rt

How should one go about deleting these tables from the database? What would it affect if I just dropped those tables complete? And where else would I have to update if I did that manually?

I recommend using drush for this type of thing and let the field crud api do the heavy lifting.
drush eval field_delete_field("YOUR_FIELD_GOES_HERE")


Display only taxonomy parents from an entity reference field Is there a taxonomy entity reference field formatter to display only taxonomy parents from hierarcherical taxonomy elements ?
Else what could be the way to display, from an entity reference field, only the taxonomy terms parents?

Create a custom view mode for taxonomy terms and display the taxonomy term as "rendered entity", using your customized view mode.

Then create a Twig template for that special view mode: Assuming your newly created view mode is onlyparents, create a template taxonomy-term--onlyparents.html.twig

There is no field like "parents", so there also is no pre-built field formatter for this. To get the parents, you will need to do some manual preprocessing like

function mymodule_preprocess_taxonomy_term(&$variables) {
  $term = $variables['elements'];
  $parents = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadAllParents($term->id());
  $variables['parents'] = $parents;
}

In Twig you can do something like

{% for parent in parents %}
  {{ parent.label }}
{% endfor %}


Add hidden field to checkbox and submit unchecked value I want to submit a value if a checkbox is unchecked (on a node edit form).

Using theme_form_element I can add the hidden field as follows:

$variables['element']['#children'] = '$variables['element']['#name'] . '" value="0" />' . $variables['element']['#children'];

But on submit, because value 0 is not in the allowed values list, I get the 'An illegal choice has been detected. Please contact the site administrator.' error message.

How can I bypass this validation and/or submit the value 0 for each unchecked checkbox?

Take a look at the answer to Custom validation for a form? This tells you how to add your own validation handler to the form. You will need to implement the form_alter like they show to add your custom validation, but also remove the validation that is throwing the error when the value is 0. (You can do this by unsetting that index in the array.) Then, for your custom validation method, my recommendation is to have a validation handler something like:

function my_custom_validation(&$form, &$form_state) {
  if ($form_state['values']['my_checkbox_field'] !== 0) {
    // Call the validation handler you removed in your form_alter
    // I might set the name of the method to a variable in form_state
    the_validation_handler_you_removed($form, $form_state);
  }
}

where you call the original validation handler from your method if the checkbox value is not the specific value you're looking for, in your case 0.


Passing info into an entityform? I am displaying a 'Contact Us' entityform in a lightbox (fancybox, specifically).  I need the entityform to send the admin the page that the user was browsing when they decided to contact us.

However, because I am displaying the form in fancybox via an iframe (in order to use drupal's ajax capabilities), my entityform is always loading from its own node - not the one I need to email the admins about.

Ultimately, I need to know how to get arbitrary info into an entityform.  Any thoughts?

Did you try the Prepopulate module? Entityforms just use Drupal Fields so I imagine it should work. You would then just define the values per field in the URL from your email.

  The Prepopulate module allows fields in most forms to be pre-populated
  from the $_REQUEST variable.

  For example, the following URL,

  http://www.example.com/node/add/blog?edit[title]=this is the title

  will automatically fill the Title field on a new blog post with the
  words "this is the title". Any field can be prepopulated this way,
  including taxonomy and CCK fields. You can prepopulate more than one
  field at a time as well. Prepopulate is excellent for creating
  bookmarklets. For examples on usage for all of these cases, please
  read the USAGE.txt file that comes with the module or you can read the
  online handbook page.


Getting node user view permissions (Nodeaccess) Is it possible to get node permissions through PHP. Like I load node id by ID and test it thru user ID. Is this user has permission to view this node or not.

I'm using nodeaccess module and I want to archive this through grants (assigning some users have rights to see and some not depending content). Calling something like if node page is ID = 12 (to get all project certain page). Then if it is I load some project nodes there (created new content type). I have to be sure, that viewer (account) has permission to see this data.

I am not sure if I fully understand your question but this is what I make out of it: you want to check if a certain user has access to a certain node, am I right?

If this is the case, this can easily be achieved with the following code:

// Use this if you want to load the current user.
global $user;
// Use this if you want to load a user by UID.
$user = user_load($uid);
// Load the node object.
$node = node_load($nid);
// Perform the access check.
if (node_access('view', $node, $user)) {
  // The user has permission.
}

You can read more about node_access in the Drupal docs.


How do I add custom validations to Webform? I have created the country and state fields with the Webform module, and I want to add a field validation for the state field when user select US as country.

How can I achieve this?

Make use of the validate function in hook_form_alter:

 if ($form_id == 'webform_client_form_14') {
    $form['#validate'][] = 'cork_creation_validate_custom';
 }

function cork_creation_validate_custom($form, &$form_state) {
  if (!preg_match('/^[A-Za-z]+$/', $form_state['values']['submitted']['name'])) {
            // $form['submitted'][$key]['#attributes']['class'] = 'error';
            form_set_error('name', t('Please enter alphabets only for Name.'));
 }

  }


How to Change block.tpl.php I created my own bootstrap sub theme and wondering how can I edit the following line:

<h2<?php print $title_attributes; ?>><?php print $title; ?>

to

<h3<?php print $title_attributes; ?>><?php print $title; ?>

As you can see, I want to change the h2 tag to h3 tag.

The code above can be found under bootstrap/theme/block. But I believe that it's not a good idea to edit it directly on this location, unless I'm mistaken.

I know that html.tpl.php or page.tpl.php can be copied from bootstrap/theme/system folder to mytheme/templates but wondering how can I do the same with block.tpl.php.

Any ideas?

Note: I'm using bootstrap 3.0.

Copying the template file from the bootstrap theme to your subtheme, and making the changes in the subtheme should work just fine.
Just note to clear the caches.


Get Post Data from drupal_http_request I have two websites use Drupal.

In Websites ONE:  I have code

$data = array(
  'key1' => 'value1',
  'key2' => 'value2',
);
$request = array(
  'headers' => array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
  ),
  'data' => drupal_json_encode($data),
  'method' => 'POST',
  'max_redirects' => 3,
  // We set a lower timeout since we don't want the user waiting for the page too long
  'timeout' => 30,
);

$url = 'http://examplesitetwo.com/return-data';
$response = drupal_http_request($url, $request);

In Website TWO: i have code

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

  $items['return-data'] = array(
    'page callback' => 'return_data_pcb',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function return_data_pcb() {
  // How to get post data form drupal_http_request in website one;
}

How to get post data form drupal_http_request() in website one? Thank you!

Sorry. It's not answer. But i try debug in function

function return_data_pcb() {
  watchdog("debug", '<pre>' . print_r( $_POST, true) . '</pre>');
  // But $_POST is empty array. It's show in admin/reports/dblog, when in website one // call function drupal_http_request.
}

I don't know my problem by when call drupl_http_request data post doesn't not send. Or problem with hook_menu in website two. Please help!


Remove inline JS from specific page type? This is an answer how to unset js from specific page types:
https://stackoverflow.com/questions/10138660/how-to-remove-css-and-js-from-a-certain-content-type-in-drupal-7
And I've made it for Syntax Highlighter module's js:

function tlito_theme_js_alter(&$js) {
  if (arg(0) != 'node') {
    unset($js['sites/all/libraries/syntaxhighlighter/scripts/shCore.js']);
    unset($js['sites/all/libraries/syntaxhighlighter/scripts/shAutoloader.js']);
    unset($js['sites/all/modules/syntaxhighlighter/syntaxhighlighter.min.js']);
    unset($js['images/syntaxhighlighter.autoloader.js']);
  }
}

And everything is ok but also module adds inline JS that gives error on pages where js ar removed. Inline js is this:

<script type="text/javascript">
<!--//--><![CDATA[//><!--
SyntaxHighlighter.defaults.toolbar = false;
//--><!]]>
</script>

How can I remove inline js from $scripts in my template.php ?

Put this inside tlito_theme_js_alter().

foreach ($js as $key => $value) {
  // Skip if data is not a string or is not inline.
  if (!is_string($value['data']) || $value['type'] !== 'inline') {
    continue;
  }
  // Remove SyntaxHighlighter.defaults.toolbar inline js.
  if (strpos($value['data'], 'SyntaxHighlighter.defaults.toolbar') !== FALSE) {
    // Remove from the js array & exit loop.
    unset($js[$key]);
    break;
  }
}


How to pass information by reference from a hook to Feeds? I need to have the ability to tell Feeds to skip a node from hook_feeds_before_update. But since there is no variable sent by reference I don't know if it's possible without having to modify the code in Feeds.

Anyone know how to do this?

The hook hook_feeds_before_update() doesn't support skip items. You could use the hook hook_feeds_presave() instead. Set $entity->feeds_item->skip to TRUE if you want to skip saving the entity. See feeds.api.php for an example.

You could also use the hook hook_feeds_after_parse() to remove items from the list to be imported. The items are in $result->items. This hook is invoked before processing happens, so at this point it is still unknown to which entities the items will be imported (you have no entity ids). Feeds Tamper uses this hook to modify the data to be imported.


Having my own theme for creating and editing Nodes: No WYSIWYG Editor I disabled the option "Use the administration theme when editing or creating content" so I see everything in the default theme.
But now I got a problem: The JS Drupal object is on the bottom of the page (like in a usual page all JS files should be on the bottom).
But CKEditor (which I'm using) needs that object in head.

//update: I checked the scripts and found out, that ckeditor is executed on the very top of all scripts. The Drupal object on the other hand is on the bottom.
I tried to reverse the array, but still the same result. Even jQuery is loaded after CKEditor.

//update2: Okay I changed the order by putting weight on the CKEditor script files and set the scope of every script file to footer, but still the Drupal object is under all files, no matter what weight I give $js['settings']. Maybe that's the wrong item?

Thanks

Since the weight did not work as expected I tried to set the scope for every script to 'header' except for ckeditor files. > Did not work

Because I had no clue I tried the opposite way:

  // Set scope for every script to footer.
  foreach ($js as $index => $value) {
    $js[$index]['scope'] = 'footer';
  }

  // Except for ckeditor files.
  $js_ckeditor_utils = &$js['sites/all/modules/ckeditor/includes/ckeditor.utils.js'];
  $js_ckeditor_utils['scope'] = 'header';
  $js_ckeditor = &$js['sites/all/libraries/ckeditor/ckeditor.js'];
  $js_ckeditor['scope'] = 'header';

This works - I don't know why, but it works.


jQuery gallery with imageFUpload here's the code of kartinkin.php file:

<?php

  $node = node_load(707);
  node_view($node);
  //$index = $_GET['index'];
  //dpm($node);

?>

<?php $index = $_GET['index']; dpm($index); ?>

  #
  #

    <?php if ($index == 0): ?>
      <?php print theme_imagecache('imba', $node->field_pics[0]['filepath']); ?>
    <?php else: ?>
      <?php print theme_imagecache('imba', $node->field_pics[$index]['filepath']); ?>
    <?php endif; ?>

    <?php for ($i = 0; $i <= count($node->field_pics); $i++) { ?>
      <a href="?index=<?php print $i; ?>"><?php print theme_imagecache('230x130', $node->field_pics[$i]['filepath']); ?>
    <?php } ?>

I have included that file with include_once() inside a node.

PROBLEM. When i click on small-image it reloads the page and after reload my big image changes. With a code above i've tried to do it without a page reload, i even write e.preventDefault(); But still after clicking on a preview image it reloads the page. How can i make big image changing without reload?

You've got several issues here:

PHP runs on the server, JavaScript runs on the client's browser so they don't know about eachothers variables.
You're not doing anything with your $.get(..) results, you need to do something with the results of the ajax get request in a success or complete callback.
You're calling a URL to a full page, i'm assuming you want just the image.

If your image names follow the naming convention I see where the thumbnails use /230x130/ in the path and the larger image uses /imba/ instead, then use the code below instead of your current click event:

slideShowIndex = 0;

$('#big-image-slider img.imagecache-imba').load(function(){
  hideSlideLoader();
});

$('.small-images a').click(function(sender){
  sender.preventDefault();
  showSlideLoader();
  var lnk = $(this);
  slideShowIndex = $('.small-images a').index(lnk);
  var imgUrl = lnk.find('img').attr('src').replace('/230x130/','/imba/');
  $('#big-image-slider img.imagecache-imba').attr('src', imgUrl);
  return false;
});

function showSlideLoader() {
  //$('#big-image-slider').html('')
  var loader = $('#big-image-slider .loader');
  if(!loader.length) {
    console.log('creating loader');
    loader = $('')
    $('#big-image-slider').append(loader);
  }
  $('#big-image-slider .imagecache-imba').hide();
  loader.show();
}

function hideSlideLoader() {
  $('#big-image-slider .loader').hide();
  $('#big-image-slider .imagecache-imba').show();

}

$('.left-arrow').click(function(){
  if(slideShowIndex > 0) {
    moveSlideIndex(slideShowIndex--);
  }
});

$('.right-arrow').click(function(){
  if(slideShowIndex < ($('.small-images a').length - 1)) {
    moveSlideIndex(slideShowIndex++);
  }
});

function moveSlideIndex(index) {
  $('.small-images a:eq(' + slideShowIndex + ')').click();
}


How do i give other users permissions for modules? I have the following question: How do I give other users permissions for modules?
Example: FAQ module.

Any and all help greatly appreciated.

To adminster the permissions for a module navigate to  Administration » People » Permissions.  There you will find a panel where you can assign permissions for the various modules.  The section for the FAQ (Frequently Asked Questions) module is shown below:

As you can see, this module have three separate permissions:

Administer FAQ module
Administer FAQ order
View FAQ pages

To grant as specific role a permission, you tick the mark to the right of the permission and below the role.

In the screen shot above, all roles are granted the right to "View FAQ pages", but only the administrator is granted the other two permissions.


Ajax errors on upload fields I have an image field that allows a single image to be uploaded. The selection works, but if I click upload, I get an AJAX error. If I just submit without uploading first, the image is uploaded properly. If I go in to edit that image field and click remove, I again get an ajax error.

An error occurred while attempting to process /file/ajax/field_front_image/und/0/form-XprUtXJvTcMRlmsz3CmBs6uDFpuJcev4SO_I_PvsM-E: Array.prototype.reverse called on null or undefined

I get this error locally and on the production server. It happens for all image fields and it's the same error when clicking upload or remove.

How can I fix the ajax on these form fields?

Please check your theme's jQuery and Drupal jQuery conflicts. Check 'View source' and check the jQuery version the page using.

I had similar issue when used latest jQuery in my theme.


how to make radio buttons be one under the other on drupal contact form by default the radio buttons on my drupal contact form come out next to each other and the title is very far from the actual button.

with CSS alone it doesnt work.  I seem to need to be able to edit the html which I cant do since its a drupal form. https://stackoverflow.com/questions/26432418/how-to-line-up-radio-buttons-and-text/26432623#26432623

Thanks

add this to each of the select button wrapper display: block; also it's not a drupal issue, you should ask these kind of question on stackoverflow


How to use a set of global and per subsite permissions in a multisite installation? Use case:
I have a multisite installation in which I want to define a global configuration to be available to all subsites. I define this configuration in the default site. For this example let's say that is:

a role editor
a content type Article
a content type Page

Now..

In all subsites that role editor need to have the permission "Use the toolbar". A global permission.
In subsite-a, I want to allow the editor to only add nodes of type Article
In subsite-b, I want to allow the editor to only add nodes of type Page

To add to that, let's say in the future I need to add a permission to the global set, I want to be able to import that set of permissions to all subsites without overriding any individual subsite permissions.

Currently I am using config_split and added user.role.editor.yml to the conditional section but I can't seem to make it work with the scenario described above.

Question:
How to maintain a global set of permissions and per site set of permissions without the global config overriding the config of the subsite? They need to rather extend each other so to say.

Any suggestions/help?

For now I solved this by creating a seperate global role which stays in the default shared config. I added the editor role to the conditional (graylist) section (configured per subsite) using config_split. So that way I am able to have seperate permissions for that role.

That global role can be automatically assigned to a subsite user during a new subsite install via a bash script/drush command for example.


Changing form field requirement via ajax I have a selectbox field, that should change the disabled and required states of another field based on the value selected in the selectbox field. The change must be done via ajax.

In my modules form_alter function I have the following code:

$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change'
);
if ($form['field_type_app_details']['widget']["#default_value"][0] === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

And the corresponding ajax_type_callback function looks like this:

function ajax_type_callback($form, $form_state) {
  return $form['field_type_app_details'];
}

What I would expect is, that when I change the value in the selectbox, to i.e. "Second", that the required and disabled states of field_version change accordingly.

What actually happens is, that when I change the value in the selectbox, the ajax request fires correctly, but doesn't change anything of field_version. Additionally, not even the changed value of field_version is saved, when the form gets submitted.

Where is the mistake?

Thanks to @Clive for pointing me in the right direction.

I've managed to accomplish what I want with the following changes to the form_alter function:

$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change',
  'wrapper' => 'version-release'
);
$form['field_version']['#prefix'] = '
';
$form['field_version']['#suffix'] = '
';
$typeValueChangedByUser = $form_state->getValue(['field_type_app_details', 0, 'value']);
$typeToCheck = $typeValueChangedByUser ? $typeValueChangedByUser : $form['field_type_app_details']['widget']['#default_value'][0];
if ($typeToCheck  === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

And the following change to the ajax_callback function:

function ajax_type_callback($form, $form_state) {
  return $form['field_version'];
}


How do I filter down on multiple taxonomies? I'm trying to create a simple classifieds area e.g. think of Craiglist.

I have 2 taxonomies; Region and (Ad) Category.

Everything is fairly easy when using just the Category in the following way:

Marketplace (views page)

Cars (5)
Clothes (10)
Electronics (14)
etc.

Category (views taxonomy page)

Cars
Listing of 5 nodes belonging to this category

Now, I want to bring along the Region but I am stuck on how to make it work with the listings I have. The user should be able to choose the Region before coming into the Marketplace or when on the Marketplace page. The number of items in each category would reflect on the chosen Region and consequently the Category pages would list only nodes that are in that Region.

What I've tried is to use the Views exposed filters and it works fine on some parts. The real problem is how to make it all flow from the beginning so that the Region information carries across the steps?

For this case, exposed filters are the wrong approach.

You can do this by making a contextual filter that operates on your region vocabulary.

Assuming your view is set to display taxonomy terms, I would do the basic configuration like this:

Add a contextual filter of type Taxonomy term: Term ID.
Set When the filter value is not available to Display a summary.

When you do this, you should get a page that list the regions if you have not selected one yet but lists data if you have selected a region.


Complicated Drush setup with MAMP Since two weeks I have replaced my optical hard drive with an SSD for my OS and all my applications while I kept my hard drive for data. So I've installed MAMP on my SSD and my Drupal directory (workspace within Eclipse) is on the Macintosh HD.

So,
Path to MAMP: /SSD/Applications/MAMP
Path to Drupal: /Macintosh\ HD/Users/me/Documents/workspace/drupal

I've put the drush folder /Macintosh\ HD/Users/me/Documents/workspace/drush and drush is working just fine, but for some reason, whenever I download a module by using drush, the module ends up in my homefolder while it should be using my Drupal folder I think, right?

How can I fix this and make drush work with my Drupal directory?

Try using a aliases.drushrc.php file to specify project details.

Create an aliases.drushrc.php file in one of the following places:

/etc/drush
$HOME/.drush

If you don't have /etc for /etc/drush perhaps it would work in: /Macintosh\ HD/Users/me/Documents/workspace/drush

aliases.drushrc.php contents

<?php
$aliases['dev'] = array(
  'uri' => 'dev.example.com',
  'root' => '/Macintosh HD/Users/me/Documents/workspace/drupal',
);

// or perhaps root with the escaped space char '/Macintosh\ HD/Users/me/Documents/workspace/drupal'

then from anywhere in the filesystem, you should be able to go

drush @dev dl views
drush @dev sqlc
drush @dev updb

etc..

Fully commented example drush aliases file here


Views all data export included image name/path I have a View. In my view Image, Product Id, etc are shown. I want to export all the data of that View in the form of doc file or CSV or excel sheet, in the tabular form if it store the data in the form of doc or csv.

My condition is that : For image field atleast image name/image path stored.

Is there any module?

You can achieve that using the Views data export  module.

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft
  XLS
  Microsoft DOC
  Basic TXT
  XML.


hook_theme_suggestions_page() provide default template file inside module folder I am using hook_theme_suggestions_HOOK() to implement a custom template file in my drupal 8 website like below.

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function mymodule_theme_suggestions_page(array $variables) {
  $template_suggestions = array();
  // This is used to display only $content.
  if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $template_suggestions[] = 'page__ajax';
  }
  return $template_suggestions;
}

Above code is working fine and I can add template page--ajax.html.twig inside my current active theme and changes in template is reflecting in page.

But when I put that file inside my module itself file is not detecting and changes not reflecting in page and taking default page.html.twg template file.

How can I provide default template file within my module itself?

This issue got resolved by adding hook_theme(). Normally theme suggestion templates are only picked up when they are in themes. So We need explicitly define theme suggestions using hook_theme() inside a module. Then only it takes templeate from your modules templates folder.

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'page__ajax' => array(
      'render element' => 'elements',
      'base hook' => 'page',
    ),
  );
}


How can I add background music to an existing Drupal 7 website? I have a nice little website built with Drupal 7. It's very basic, nothing crazy going on.

The client is demanding there be background music playing on the site. I have pleaded with them not to do this, but they are insistent and they are also signing the checks. :)

What is the best way to add background music to an existing Drupal 7 site that won't stop playing between pages? For any given solution what are the consequences to search engine friendliness and impact in general to the structure of Drupal?

Looking only for solutions to the music problem as not having music on the site isn't an option here.

I'm looking at doing the same thing for a band's website where the music can keep playing even when switching pages. AJAX is definitely the way to go here.

Check out the pjax for Drupal module.

  pjax is a jQuery plugin that loads new content into the current page without a full page load. This is usually quicker and smoother than a full page reload, because Drupal only has to deliver the main page content and not the full page – and the browser only has to redraw a smaller amount of markup.

  In addition to this, pjax updates the page URL with the proper page path using HTML5 pushState – not with #url-fragments that are commonly used with ajax-loaded content. It also updates the page title with the title of the loaded page. In other words, it has all of the benefits of standard page loads (permalinks, SEO), while taking advantage of partial page loads in the browser.


Preprocess Node function not being called I'm attempting to perform an action in a preprocess node hook inside my .theme file, but I can't seem to get it to fire.

Here's the content of my customtheme.theme file

<?php

function mytheme_preprocess_page(&$variables){

    $menu = \Drupal\block\Entity\Block::load('custom_main_menu');

    $variables['main_menu'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($menu);
}

function mytheme_preprocess_node(&$variables){
    die('Test');
}

Everytime I load a node, even though I have a die() statement in my mytheme_preprocess_node function it never fires, and the page loads just fine. I'm making sure that I'm loading pages that are nodes. Such as basic pages, and other custom content types. What's odd is that the mytheme_preprocess_page function does fire. It's able to load the main_menu variable inside the page.html.twig template just fine. I also made sure I was clearing the cache.

Why would a preprocess_page hook function fire but not a preprocess_node function.

You need check your page url. Hook_preprocess_node only run with page is node (example node/1...) or page have content is node (example page views have entity is node). If you done, you need clear cache.


Using a panel for the homepage? I am building a site in Drupal and I'm using the Panels module to create my page layouts. I have created the layout that I would like for my homepage and created the content that I'd like in there.

I have set it to 'promoted to homepage' yet, when I visit the homepage, I just get the title and submitted date, and a read more link. The layout isn't being seen, you have to click through in order to see the page.

How can I turn off the 'read more' link and use the panel as the homepage?

Visit admin/config/system/site-information, and set the panel's path as the default home page.


hook_form_alter function does not call the validate function? i'm creating a unique field module which restrict a user with specific role to create one node per year. it works first but after installing some modules Automatic Nodetitles, Cancel Button, Field Permissions, View profiles permissions, More Buttons Content my custom module does not work. its hook_form_alter function works but hook_form_validate function does not work.

function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['#validate'][]  = 'uniquefield_form_validate';
  }
}
function uniquefield_form_validate($form, &$form_state) {
  $user = user_load_by_name($form_state['values']['name']);
  if ($user) {
    if($form_state['values']['type'] == 'target_achieved' &&  in_array('vidyakjatha', $user->roles)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'target_achieved')
     ->propertyCondition('status', 1)
     ->propertyCondition('uid', $user->uid , '=');
     if ($form_state['values']['nid'] != '')
       $query->propertyCondition('nid', $form_state['values']['nid'] , '<>');
       $query->fieldCondition('field_achieved_year', 'value', $form_state['values']['field_achieved_year'][LANGUAGE_NONE][0]['value'], '=');
       $result = $query->execute();
     if (isset($result['node'])) {
       form_set_error('field_achieved_year', t('You have already added target achived status for year !year.', array('!year' => date('Y', strtotime($form_state['values']['field_achieved_year'][LANGUAGE_NONE][0]['value'])))));
     }
   }
  }
}

as your validating just one field - at least, it seems like it; consider using:

function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['your_desired_field']['#element_validate']  = array('uniquefield_validate');
  }
}

on the fileds in your alter hook


How to make a hierarchical categories of a view's nodes? I want to have hierarchical categories of a view's nodes,where categories will be taxonomy terms of the nodes.How to do that?

If you want to display your taxonomy as tree, and insert nodes having given term, into that tree, you'd need Views Tree. This adds a display plugin for Views. You just need to create a node listing view which accepts a term argument.

If you mean to format the term attached to a node, as a hierarchical tree, try Term Reference Tree.


How to alter the state of a radio button in an exposed filter to "checked" based on the view URL? I have a D7 site where I have several main topics, each containing subtopics.  I've made a views block which is shown on each of the pages of the main topics where you have two filter options:

Filter on main topic
Filter on subtopic

The idea is that when the user enters a URL like www.mysite.com/topics/maintopic, the main topic filter radio button is set automatically to the main topic the user entered and the first sub-topic for that main topic.

So how can I do that?  I tried with a contextual filter, but unless I missed something I don't see an option to preselect a radio button in an exposed filter (nor in fact to filter basing on the last part of a URL, unless it's an argument). I also tried the following code.

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // ...
}

I didn't see any option to alter which radio button is selected.

You will need to use 2 contextual filters as each one takes a different argument, for example www.mysite.com/filter1/filter2.

You're confusing the difference between exposed filters and contextual filters, and their behaviour. An exposed filter is form based. As you want a radio button,  that's perfect. However, an exposed filter passes its values either via POST or GET; the only way to get these values through the URL is via the query string.


Redirect after a new node is added but not edited I have a custom redirect on node submit.

function mymodule_form_alter(&$form, $form_state, $form_id) {
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
}

function custom_node_submit($form, &$form_state) {
    $form_state['redirect'] = 'request-sent';
}

However, I would like to redirect only when a new node is created but not updated.
How do I check the action being executed on the node ?

function mymodule_form_alter(&$form, $form_state, $form_id) {
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
}

function custom_node_submit($form, &$form_state) {
    if (arg(2) != "edit") {
      $form_state['redirect'] = 'request-sent';
    }
}


Help Understanding Aegir So I've been struggling with installing Aegir for about a week now, and trying to understand how it should work, and hopefully get it resolved. (BTW, here is a related issue if you're curious:  http://drupal.org/node/1202568 )

First, lay of the land:

RedHat 5.5
MySQL 5.5.13
Apache 2.x
PHP: 5.3.2

I am installing using this command

drush hostmaster-install --aegir_host=hostname --aegir_db_user=myadmin --aegir_db_pass=adminpasswd --aegir_root=/pathto/aegir

So my guesses of what needs to happen to get Aegir up and running:

Upon a successful install, there should be a sites/hostname directory where Aegir lives
This directory should contain a settings.php files
This settings.php file grabs the database credentials that are set in a file inside the vhost.d directory using SetEvn, right? The vhost.d directory is empty. But an entry is needed to get Aegir up and running, right?

Does this make sense? What am I missing?

KM

(2nd Attempt!)
It almost looks like the symbolic link they have you create in step 3.1.1, is not working correctly and may be causing this issue.

I don't know anything about the differences between Debian and RH 5.5, but maybe RE doesn't have a /etc/apache2/conf.d directory, in which case you would have to manually add an include line into httpd.conf

Cheers.


Custom target URL for Views content pane exposed filter (block) Here is the situation:

There are 2 pages in Page manager

Overridden page of the Taxonomy term (i.e. Path: /%term )
Page with Taxonomy term filters (i.e. Path: /%term/filter )

And a View with 2 displays (content panes) :

Show all from term
Show filtered (with exposed filters in block).

How to place the exposed filter block on /%term page but when the filter is submitted,  redirect and apply it to the /%term/filter path ?

Thank you

Use form redirection in hook_form_alter.


How we can define constant in template.php for our theme I want to define some constant for my theme like theme path etc. How i can achieve that.

For module we can define like this

define(THEME_PATH, drupal_get_path('theme', 'xyz'));

But it is undefined in theme. Any suggestion would be appreciated.

In the preprocess function (hook_preprocess_THEME), you can use this:

$variables['theme_path'] = drupal_get_path('theme', 'xyz');

Which you can then use as $theme_path in your template.


Where is $page['sidebar_second'] rendered? I want to edit the style of the  listing of the recent comments The comments in the block recent comments is styled with an unordered list. I want the points of the list beginn exactly under the N of New Comments.

Google Chrome tells me that there is a padding-left: 40px; attribute:

I do not know from where i get this attribute. I looked in my themes css files but there is no attribut padding-left: 40px;

Here is the element lookup in Firefox:

I need to set the padding-left attribute to exactly 15px. This is how it should look like:

I'm using the mas Theme in markapot.

Can I define the style of the ul in the function $page['sidebar_second']? If so, where is the sidebar built?
Thanks for any help!

I think you have to look in how theme works in Drupal. However, as per your question, $page['sidebar_second'] is the variable that stores the region "sidebar_second".
This region doesn't have any specific styles and this goes for all the other regions as well. If a block is created in your system it needs a region to be displayed. So The blocks are always assigned to the desired regions.

If you want to style the block then you have to find the candidate files via devel & devel_themer module and then in the theme directory have to create the file and style. Also if you are not wiling to do that then write a overriding css for your theme that will override the styles like,

.class-name {
   padding: 15px !important;
}

But I would recommend not to use !important unless its really needed.