title: Clear cache of node

text:
# Question
Title: Clear cache of node
I am implementing hook\_entity\_view() in my module. In the hook I am adding a link to the node by rendering a array. The links need to be added only when a certain configuration condition becomes `TRUE`. The code which I have written is something like this:

```
function module_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode, $langcode) {
  $condition = \Drupal::service('config.factory')->get('module.settings')->get('variable');
  if ($condition is TRUE) {
    return render array which adds links;
  }
}

```

The problem with above code is that even when I have updated my configuration setting and then refresh node page there is no effect of change in configuration in rendering of node's content. But when I have cleared cache the effect immediately shows.When should I do so that I need not to clear cache? Thanks.

# Answer
> 1 votes
The answer is exactly the same as an existing question you asked, even though the question was quite different.

The answer is: cache tags or more generic, cache metadata.

Quoting myself from https://drupal.stackexchange.com/a/160982/31:

> Blocks are cached by default.
>
> You don't need to manually clear those caches when you change your configuration, but you need to flag/tag your blocks output to tell Drupal that your block output depends on your configuration.
>
> Read the Cacheability documentation. What you need is something like this:
>
> ```
> $output['#cache']['tags'] = $config->getCacheTags();
>
> ```

Just replace block with entity in the description and you have your answer. Note that when doing something conditional, you must always add the cache tags/context, meaning, outside of the if condition, not inside.

I just realized my code sample there is problematic when you alter existing render arrays, because you risk overwriting existing cache tags. So you should use what the referenced documentation does, that ensures that existing cache tags are kept:

```
\Drupal::service('renderer')->->addCacheableDependency($build, $config);

```

That basically reads "$build depends on $config".

Memorize that link and the steps there. Always check them you add or change render arrays:

> **The thought process**
>
> Please try to adopt the following thought process.
>
> Whenever you are generating a render array, use the following 5 steps:
>
> 1. I'm rendering something. That means I must think of cacheability.
> 2. Is this something that's expensive to render, and therefore is worth caching? If the answer is "yes", then what identifies this particular representation of the thing I'm rendering? Those are the **cache keys**.
> 3. Does the representation of the thing I'm rendering vary per combination of permissions, per URL, per interface language, per … something? Those are the **cache contexts**. *Note: cache contexts are completely analogous to HTTP's `Vary` header.*
> 4. What causes the representation of the thing I'm rendering become outdated? I.e. which things does it depend upon, so that when those things change, so should my representation? Those are the **cache tags**.
> 5. When does the representation of the thing I'm rendering become outdated? I.e. is the data valid for a limited period of time only? That is the **max-age** (maximum age). It defaults to "permanently (forever) cacheable" (`Cache::PERMANENT`). When the representation is only valid for a limited time, set a max-age, expressed in seconds. Zero means that it's not cacheable at all.
>
> Cache contexts, tags and max-age **must always be set**, because they affect the cacheability of the entire response. Therefore they "bubble": parents automatically receive them.
>
> Cache keys must only be set if the render array should be cached.

---
Tags: nodes, caching, 8
---


# Question
Title: why doesnt Drupal recognize my route name?
I have a module I am upgrading from 7 to 8. I am working on the mymodule.routing.yml file

```
mymodule.admin:
  path: '/admin/structure/mymodule'
  route_name:mymodule
defaults:
  _controller: '\Drupal\mymodule\Controller\QuicktabsController::adminOverview'
  _title: 'mymodule'
requirements:
 _permission: 'administer mymodule'

```

Now when I try to enable my module the log shows this error

```
Uncaught PHP Exception Drupal\\Component\\Plugin\\Exception\\PluginException: "Plugin (mymodule.admin) definition must include "route_name"" at /srv/www/appdocroot/releases/20150428151557/core/lib/Drupal/Core/Menu/LocalTaskManager.php line 161

```

I assume this error means that the snippet of code from my routing.yml file is the offending piece.

I have gone through the upgrade tutorial on the drupal site and it does not include the "route\_name" field in the section. I originally tried it without and later put it in when I discovered the error.

Am I correct in my assumption of where the error is coming from? If thats true what is wrong with my route\_name field?

# Answer
> 3 votes
That code snippet looks very strange, is it really like that in your yml file or is it just wrong in the question here?

There is no route\_name key inside the definition, and everything needs to be inside the first key, which is the route name. There are plenty of examples in system.routing.yml. Always try to find actual examples in Drupal core and not some online tutorials when you're not sure, as they might be outdated.

Make sure that you always use two spaces for indentation.

Your example should look like this:

```
mymodule.admin:
  path: '/admin/structure/mymodule'
  defaults:
    _controller: '\Drupal\mymodule\Controller\QuicktabsController::adminOverview'
    _title: 'mymodule'
  requirements:
    _permission: 'administer mymodule'

```

---
Tags: 8, routes
---


# Question
Title: Application form and fee for Drupal Commerce
I am taking application fees for application processing for a real estate broker. When the user fills out an application, they need to submit payment immediately.

The issue is this isn't really a product. It's a processing fee. Am I stuck with using a product? Can I create an order without the product and just use the fee? I feel like I should create a line item for an order and do it that way, so the pricing rules flow normally.

When the user is ready to submit their application, I'm going to use the Drupal NoCart module to take the customer straight to payment.

I haven't been able to find a business case like this online anywhere.

For the new line item type, it looks like I should create a new one:

```
function mymodule_commerce_line_item_type_info() {
    $line_item_types = array();

    $line_item_types['appfee_type'] = array(
        'name' => t('Application Fee'),
        'description' => t('Line item type for app fee.'),
        'product' => FALSE,
        'base' => 'appfee_type'
    );
    return $line_item_types;
}

```

# Answer
> 0 votes
The new line item type and adding it to the order was the way to go it seems. My code is posted in this post.

That code worked, however, I kept getting an access denied when trying to check out. DC runs a hook called `hook_commerce_checkout_order_can_checkout()`. The order is passed to this hook, and you can determine if you want to allow access. I did on all instances and didn't need to write any logic, so I just returned TRUE, and everything worked.

---
Tags: 7, commerce
---


# Question
Title: Is it possible to show taxonomy terms in a views filter sorted alphabetically?
I have some content that is classified using a two-level taxonomy: Accommodation -\> B&B Accommodation -\> Hotels Accommodation -\> Self Catering Things to Do -\> Arts & Crafts Things to Do -\> Family attractions Eating out -\> Cafes Eating out -\> Restaurants

In some situations, I need to display all these categories together in views as a taxonomy filter.

When I do that, they are displayed grouped by the parent term, so they look weirdly random. Is it possible to break them out from their parent term and show them in the filter sorted alphabetically, or alternatively, show the parent term as well as the child term, so that it's clear why the terms are sorted like that?

I am on Drupal 7, Views 3.11.

# Answer
> 1 votes
Upgrade taxonomy and views to the latest version and select the following options.

And when the filters terms are being listed, they will be listed in alphabetic order.

You can confirm that there is hierarchy in terms and they are not alphabtic in order.

---
Tags: taxonomy-terms, views
---


# Question
Title: Can I set "$conf["image_allow_insecure_derivatives"] = TRUE" in settings.php file?
Hi my multisite site structure is, I have followed sub directory multisite mechanism

So in hosting server the url will be

http://123abc.hostring.com/mysitename1 http://123abc.hostring.com/mysitename2

I have pointed and configured with production url as,

www.mysitename1.com (http://123abc.hostring.com/mysitename1) www.mysitename2.com (http://123abc.hostring.com/mysitename2)

Everything working fine. But the private (Amazon S3) image styles cannot be created.

private file link http://www.mysitename1.com/system/files/styles/stylename/s3/myimage.jpg

It shows "Access Denied" error.

When I added below line in settings.php file the images styles has been created perfectly.

$conf\["image\_allow\_insecure\_derivatives"\] = TRUE;

But I believe there are some security issues in that. Do I need to follow any other configuration instead of this?

Please advice.

# Answer
It is not a critical security issue perse. But it can expose your site to DDOS attacks. So you can fairly enable this setting and you can disable it if you face any DDOS attacks that targets your site.

You can find more about this issue on https://www.drupal.org/SA-CORE-2013-002

> Drupal core's Image module allows for the on-demand generation of image derivatives. This capability can be abused by requesting a large number of new derivatives which can fill up the server disk space, and which can cause a very high CPU load. Either of these effects may lead to the site becoming unavailable or unresponsive.
> 1 votes

---
Tags: multi-sites
---


# Question
Title: Hierarchical select ajax conflict in custom bootstrap theme
I have created a custom theme from scratch using twitter Bootstrap. In my content type there is Taxonomy term Hierarchical Select (HS) list.

**Problem:** When authenticated user try to select any term from first level, HS keeps on loading...for ever.

**Note:** Hierarchical select is working fine for admin with core Seven theme enabled and with jQuery update version 7.

Please help.

# Answer
> 1 votes
It was Colorbox which was conflicting with HS. I disabled the colorbox module and it worked perfectly. I don't know why this happens, but this should be raised as an issue since both are contrib modules.

---
Tags: 7, forms, ajax, taxonomy-terms
---


# Question
Title: When altering the submit button, the form does not work
We need a `<button>` instead of an input in our search-form. So I changed the markup accordingly using `theme_form_alter`:

```
function giga_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit'] = array(
      '#type'   => 'markup',
      '#prefix' => '<button type="submit" class="btn btn-primary">',
      '#suffix' => '</button>',
      '#markup' => '<i class="icon-search icon-white"></i>'
    );
    $form['actions']['submit']['#executes_submit_callback'] = true;
    $form['actions']['#type'] = 'none';
    $form['#attributes']['class'][] = 'search-quick';

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
  }
}

```

However, I can submit the form, but the search won't be processed. The page reloads and I'm not redirect to the search results. However when I remove `$form['actions']['submit'] = array([…]);` it all works fine.

I'm not quite sure what's going on here.

# Answer
> 0 votes
Try to use this:

Drupal 6:

```
 $form['actions']['submit']['#type'] = "Submit";

```

Drupal 7:

```
$form['actions']['submit'] = array(
  '#type'  => 'submit',
);

```

# Answer
> 0 votes
I just had the same problem. All the needed was adding this.

```
$form['actions']['submit'] = array(
  '#type'  => 'submit',
);

```

---
Tags: forms, search
---


# Question
Title: Disable Rule which is causing a redirect loop
I have created a rule for logged in members that if they go to the home page it redirects them to a different page. The home page needs to be different for anonymous and authenticated users.

One problem is that my rule is not working. I have created a redirect loop by mistake. This means I can not get to the rules interface to disable the module. I know I could disable the rules module via drush however I will have the same problem when I turn it back on.

I had a quick look in db and see the rules\_rules table. However the data is stored as a blob so I can not edit it. Except for deleting my rules what could I do to disable it?

# Answer
> 2 votes
You got a few options.

* You can try to edit the data by deserializing it with PHP and try to get some meaning out of it. Most likely there is a status which is either 1 or 0.
* You could delete the rule from the database entirely.
* You can temporarily modify the `rules_invoke_event` (`rules.module` line 249 for 1.4), if you comment out the `call_user_func_array` call, no rule should be invoked on the site.

Either of these should work, personally I would go for the last one if I had write access to the rules files.

# Answer
> 1 votes
In Rules 7.x-2.6:

* In the rules\_config table set the active column to 0 for the problematic rule
* Empty/Truncate the cache\_rules table

# Answer
> 0 votes
They way i did to revert reload in one of my drupal 6 project.

1. logged in using ssh to the terminal.
2. logged in to database.
3. selected database.
4. goto rules\_rules table.
5. written sql quary to delete affcting rule.

# Answer
> 0 votes
Devel Module module has a nifty setting for this. Install devel module and visit `devel/settings`, enable the option `Display redirection page`.

As the description says

> When a module executes drupal\_goto(), the query log and other developer information is lost. Enabling this setting presents an intermediate page to developers so that the log can be examined before continuing to the destination page.

you can visit the intermediate page in-spite of the redirection.

---
Tags: 7, rules
---


# Question
Title: Limit the menu level on node add/edit page
On node add/edit page we have a menu settings option. This option by default show all the nodes in the main menu under Parent Item tab. Is there a way we can limit the nodes in the menu(under parent item) to only first two levels.

# Answer
Menu Performance Module does exactly that.

Drupal is already aware of this issue and has a variable `menu_override_parent_selector` which can be leveraged by other modules to come up with their own implementation of the menu handlers on node edit page.

As the project page reads

> Menuperformance takes advantage of this, and sets the variable when installed. It then proceeds to add its own AJAX based parent menu item selector widgets for the node edit, node type edit and vocabulary edit pages.

How to Use from README.txt

> * Enable the module.
> * Go to /admin/config/user-interface/menuperformance , and activate the module. Checking the checkbox sets Drupal variable menu\_override\_parent\_selector.
> * After the module is activated, the menu item selectors on the above mentioned pages should have been replaced with a multiple dropdown AJAX-powered selector instead of the standard single dropdown.
> 0 votes

---
Tags: routes
---


# Question
Title: Skip user edit page on first login using fboauth
I am using the latest dev version on FBOAuth module on my site. I am using Popup for facebook login.

When the user logs in for the first time using facebook currently the user is being redirected to the account edit page. Is there a way I can skip this test, so that user will be back to the page where he came from. Later on he can go to account edit page and set the password if he wants to. Else he continue using the facebook login only.

Once the account is already connected, I am not facing this issue as the user is rightly directed to the page he came from. The issue is only with the first login using facebook.

Please let me know if there is some setting that I can enable.

# Answer
You can redirect the page using `rules` modules and drupal\_goto function
> 0 votes

# Answer
Looks like the module doesn't have an option for that currently. I have submitted a patch for the same which will add an option on the admin screen to skip the profile edit page on the first login.

You can try the patch here https://www.drupal.org/node/2508838#comment-10041388
> 0 votes

---
Tags: social-network
---


title: how to validate file upload in drupal

text:
# Question
Title: how to validate file upload in drupal
how to validate file upload in drupal means,

in my form allowed only txt file, but now user also can upload image file also after change the extention .jpg -\> .txt

```
function oz_workbench_moderation_buttons_form_alter(&$form, $form_state, $form_id) {
  dpm($form);
  if ($form_id == 'catalog_node_form'  )
    {
    $form['#validate'][] = 'upload_validate_function';
       return $form;
    }
}

function upload_validate_function(&$form, $form_state){
$extensions = array('txt' => 'text/plain; charset=us-ascii','doc' => 'application/msword; charset=binary','pdf' => 'application/pdf; charset=binary','xls' => 'application/octet-stream; charset=binary','docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=binary');
$uploadedfile=count($form_state['values']['field_application_document']['und']);
        for($i=0;$i<$uploadedfile-1;$i++){
                $file_name=$form_state['values']['field_application_document']['und'][$i]['fid'];
                $file_handler = file_load($file_name);
                $file = $file_handler->uri;
                $filename = $file_handler->filename;
                //echo $file;
                $finfo = new finfo(FILEINFO_MIME);
                $type = $finfo->file($file);
                //echo $type;
                    if (!in_array($type, $extensions) )
                    {
                    drupal_set_message(t($filename.' is not valid file'), 'error');
                    }
         }
}

```

# Answer
> 2 votes
If your are writing your own validation u can use finfo\_file from php

http://www.php.net/manual/en/function.finfo-file.php

**Example #1 A finfo\_file() example**

```
<?php
  $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
  }
  finfo_close($finfo);
?>

```

The above example will output something similar to:

* text/html
* image/gif
* application/vnd.ms-excel

# Answer
> 0 votes
You can validate file type by checking MIME type or by checking the extension. So there are two methods:

1. Check if the file uploaded is actually an image no matter what extension it has.
2. The uploaded files must have a specific image extension

Here is the reference: http://www.bitrepository.com/how-to-validate-an-image-upload.htmlenter link description here

---
Tags: files, media, forms
---


# Question
Title: I am trying to use AJAX with Drupal 6. How do I determine the URL I am trying to contact?
I looked at the documentation here and it left me a bit confused. I don't need to access any files, I am just returning the date that is on the server to my Javascript code. (I don't want the date/time from the user's perspective)

The example gives this in the javascript portion of the example. This example seems to already know where get should call to get the response back. I am not sure what the URL would be on my server to just talk to my php code.

```
$.get('/photos/get/photos/' + parseInt(this.id, 10), null, imageDetails);
        return false;

```

# Answer
> I am not sure what the URL would be on my server to just talk to my php code.

It's the path implemented from your module. In the example, they use /photos/get/photos because in `mymodule_menu()` they define that as path handled by the module.

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['photos/get/photos'] = array(
    'page callback' => 'mymodule_get_photos_ajax',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

```

It's you who defines the path, so you know it.
> 1 votes

# Answer
The URL you use is the one that delivers you the data you want. If you want to grab the server time you can create a short PHP script that gets the info and then make that info available to JS using Drupal.settings.

For example:

```
// Create the array that is required by drupal_add_js()
$server_time = array(
  'serverTime' => date("h:i:sa"),
);

// This is what makes the variable available to JS
drupal_add_js(array('time' => $server_time), 'setting');

```

Then, in your.js:

```
var time = Drupal.settings.time.serverTime;

```
> 1 votes

---
Tags: 6, ajax, javascript
---


title: Site works in locale but not in remote

text:
# Question
Title: Site works in locale but not in remote
I uploaded my site and the database on the remote server; the site is working in locale, but on the remote I get the following error.

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'queryfdu\_drupal7.watchdog' doesn't exist: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> domain \[:db\_insert\_placeholder\_2\] =\> Domain access failed to load during phase: bootstrap include. Please check your settings.php file and site configuration. \[:db\_insert\_placeholder\_3\] =\> N; \[:db\_insert\_placeholder\_4\] =\> 3 \[:db\_insert\_placeholder\_5\] =\> \[:db\_insert\_placeholder\_6\] =\> \[:db\_insert\_placeholder\_7\] =\> \[:db\_insert\_placeholder\_8\] =\> 122.175.149.244 \[:db\_insert\_placeholder\_9\] =\> 1434778958 ) в функции dblog\_watchdog() (строка 160 в файле /home/queryfdu/public\_html/drupal/modules/dblog/dblog.module).

The watchdog table exists in the database.

How can I fix this problem? What could be causing it?

# Answer
That is fairly straight forward. The watchdog table - the system log for Drupal - is missing from your production environment. The real question is really how are you deploying your site. Whatever method you are using doesn't seem to be working properly. If this is a brand new site it would be better to deploy as an install and add all of your customizations as Features.
> 0 votes

# Answer
Looks like your `settings.php` you have added a table\_prefix but the database doesn't seem to have it.

Remove the table prefix option in your `settings.php` and everything should work fine.

Look for

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',  // <-- remove your prefix here
);

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to sort autocomplete results by post date?
I have a content type named "News" which contains a node reference field named "Related News" in autocomplete mode. Does anyone knows how to sort the results when i write something? I need to get the most recent nodes.

Thank you!

# Answer
You should use views entity reference widget.you can custom you result like want you want.

this link is good tutorial for you achieve your job.I hope learn it and use it in future project and issues.
> 1 votes

---
Tags: nodes, ajax
---


# Question
Title: Let user pick background Image/Color on node form
I would like to allow my users to choose a background image or color for a node. I created a content type with two fields: 'background image' of type image, and 'background color' of type color field.

I can retrieve the values of the fields on my module but how can I pass them to my stylesheet? Should I use the `style` attribute of my HTML elements?

The background color can be any color so I can't precreate css classes, or files.

Any idea on how to do this? Thank you!

# Answer
> 0 votes
I suggest you do it in your node.tpl.php. You can add the style attribute directly to the attributes array in a node preprocess.

in your `template.php` , load(add css file ) or insert in-line css style

```
function THEMENAME_preprocess_node(&$variables) {
  $type = $variables['type'];
   // dpm($$variables['node']);
  // as example
 if($color=$variables['node']->field_color['und'][0]['value']){
 $css = "p {background-color: $color }";
 drupal_add_css($css, 'inline');
   }
 }

```

you can do something like this .I hope this solution get you some good clue .

---
Tags: 7, nodes, theming
---


title: Search box for views and tags

text:
# Question
Title: Search box for views and tags
I want to be able to have a search box so that when you search, the result is displayed in a view. I want to search for tags in nodes.

The reason I want to display this in views is because I only want to display 3 fields and I want to display it in a 3x3 grid with a pager.

I don't want to be using Apache Solr because the output of the search is quite ugly and I can't customise the fields I want to display etc... Also I want to keep the layout consistent with the rest of my views.

I found this http://drupal.org/project/apachesolr\_views but it requires views 3, and I don't feel comfortable upgrading.

Is there any way to have some sort of search box for views that would search for tags? and what module would you recommend me for tagging my content?

I'm using Drupal 6.

Thanks.

# Answer
> 1 votes
You create a search box for Views by adding a filter and then setting it to be "exposed". This creates a form by which the user can set filter values such as tags.

You don't need any special module for tagging under normal circumstances as the core Taxonomy module works perfectly well.

# Answer
> 0 votes
Create view and use **better exposed filter** module to have a search box for the view.

> The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively.

---
Tags: views, search, taxonomy-terms
---


title: Problem Sending data send to a block

text:
# Question
Title: Problem Sending data send to a block
after form submit in a page its return some value,I want to prnt this value in a block .how can I do this? and I want the form and the block are in the same page.

# Answer
> 0 votes
Use hook\_block\_info and hook\_block\_view. Something like this:

```
function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'my_block':

      $blockContent = '<p>Nothing to show</p>';

      // assuming we're getting it from POST but the source can be whatever you want
      if (isset($_POST['key']) && null != $_POST['key']) {
          $blockContent = '<p>' . $_POST['key'] . '</p>';
      }

      $block['subject'] = t('My Block Title');
      $block['content'] = array(
          '#markup' => $blockContent
      );
      break;
  }

  return $block;
}

```

---
Tags: forms
---


# Question
Title: How to get Views Total number of records in Page.tpl.php file. (Before Views rendered)
See this image for more understanding.

I want to fetch Views total number of records in page.tpl.php before views.tpl called. Is it possible to fetch that row total before views rendered? I am also using contextual filter for this view. Views have page type display.

I have also used module views\_record\_count. but this will print total number of records on Views header or footer. (Not outside of views)

# Answer
You could use this code to print the count.

```
<?php

$view = views_get_view( 'test' );
$view->set_display('block');
$view->set_arguments( array( 1, 2, 3 ) );
$view->execute();
$count = count( $view->result );
print $count;

?>

```
> 1 votes

---
Tags: blocks, views
---


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

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

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

# Answer
> 0 votes
Flushing all caches solved it for me, thanks :)

---
Tags: 7, path-aliases, version-control
---


# Question
Title: How to get rid of auto generated classes in secondary menu links and add my own classes
I have taken the standard code for secondary menu from a Drupal 7 theme:

```
 <?php if ($secondary_menu): ?>
            <?php print $search_form; ?>
          <?php endif; ?>
    <?php if ($search_form): ?>
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('menu', 'nav', 'navbar-nav'),
              ),
              'heading' => array(
                'text' => t('secondary'),
                'level' => 'h2',
                'class' => array('element-invisible'),
                  ),
                    )); ?>
                  <?php endif; ?>

```

Now the ht,l output generates some autogen css witch i whant to get rit of and replace with my own classes?

```
<h2 class="element-invisible">secondary</h2>

<ul id="secondary-menu-links" class="menu nav navbar-nav">
<li class="menu-3 first"><a href="/user">My account</a></li>
<li class="menu-15 last"><a href="/user/logout">Log out</a></li>
</ul>
</div>

```

How to delete menu-3 and menu-15 as well as all classes following when we add more links and add some custom links to work with stuff like font awesome?

# Answer
> 0 votes
You can use this preprocess hook to modify the menu classes.

For example, modify the output of the secondary menu links like this.

```
function YOURTHEME_links__system_secondary_menu(&$variables)
{
   $output = "";

   foreach ($variables['links'] as $item => $link) {
      $classes = array('class1', 'class2');
      $output .= sprintf('<li class="%s">%s</li>', implode(' ', $classes), l($link['title'], $link['href']));
   }

   return $output;
}

```

---
Tags: routes
---


title: Disqus Comment for one role type

text:
# Question
Title: Disqus Comment for one role type
I have installed Disqus on localhost and want users of a particular role type only to be able to comment. Basically, there are free and premium users but I wish to allow only the premium users to be able to comment using Disqus. The comments should be visible to every role type but the ability to comment should be given to only the premium users and the administrator. It would be great if someone could help me out with this !

# Answer
in admin/config/services/disqus set the location to block

then in admin/structure/block put the "Disqus comment" block below the "Main page content"

Now, edit the Disqus comment block, scroll all the way down, under Visibility Settings, click on roles and check mark premium and administrator.

**Edit:**

Unfortunately, you can't remove the comment box. Disqus used to offer a way to do it, but now they don't.

The only workaround, would be to create a block that is displayed for anonymous users and non premium authenticated users only.

Then inside that block put css to hide the comment box behind/underneath the article body.

For Example:

```
<style>
 #disqus_thread { z-index: 1; position: relative; top: -180px;}
 .article-body { z-index: 2; position: relative; background: white;}
</style>

```

Unfortunately, with this tactic you would lose the comment count and the sort option. Although, you could display the comment count using the views module.
> 0 votes

---
Tags: users, comments
---


# Question
Title: How to create a form on settings o settings page
In template.php file I am using the following code.

```
function MYTHEME_preprocess(&$variables, $hook) {
  $variables['socialmaintenaceurl'] = "https://twitter.com/test";
  $variables['maintenaceurltext'] = "Get the latest news on Twitter";
}

```

This is just for the maintenance page. I like to have two form elements on my settings page to manipulate these two values from the administrative area.

Could anyone show me what I can put in theme-settings.php?

# Answer
> 1 votes
My solution is for Drupal 7.

To add two textfields to the settings you have to implement the following hook:

```
function themename_form_system_theme_settings_alter(&$form, &$form_state) {

  $form['theme_settings']['socialmaintenaceurl'] = array(
    '#type' => 'textfield',
    '#title' => t('Social maintenance URL'),
    '#default_value' => theme_get_setting('socialmaintenaceurl'),
  );
  $form['theme_settings']['maintenaceurltext'] = array(
    '#type' => 'textfield',
    '#title' => t('Maintenance URL text'),
    '#default_value' => theme_get_setting('maintenaceurltext'),
  );
}

```

You have to replace themename in the function name with the name of the theme. The declaration of the input elements is based on the Drupal 7 Form API (https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7).

It is an array, which will be rendered according to the information you provide. Normally, keys starting with # are information to control the render process. For example: If you choose a different #type it gets a different widget/appearance in the form.

The $form\['theme\_settings'\] should place the two new fields into the existing theme settings group.

If you want, you could ship default values for your two fields. You only need to add a few lines in you themes .info file:

```
settings[socialmaintenaceurl] = https://twitter.com/test
settings[maintenaceurltext] = Get the latest news on Twitter

```

I am not sure, if you need quotation marks around them, but I think in the .info file you dont need them.

To get these values in another file, you would need to use

```
theme_get_setting('maintenaceurltext')
theme_get_setting('socialmaintenaceurl').

```

---
Tags: forms
---


# Question
Title: How to change default value of taxonomy term in View exposed filter drupal 7?
I have created view page to find events from Start date - End date and category(taxonomy terms). I have enabled expose filter on fields. How do I show '-select-' instead of '-any-'

or else is there any other method to show no result until user does not add filter value?

# Answer
> 2 votes
**To display Results Only when Criteria is selected :**

* In your view, change `Advanced Settings -> Exposed form style` **to** `Input required`

* In **Exposed Form style settings** you could define the text to be displayed on no results

**OR**

**To Alter Exposed form options:**

* You need to implement `hook_form_alter()`
* Here is a sample code of it:

> ```
> function mymodule_form_alter(&$form, &$form_state, $form_id) {
>     case 'views_exposed_form_id':
>     $name = 'Vocabulary_name';
>     $myvoc = taxonomy_vocabulary_machine_name_load($name);
>   $tree = taxonomy_get_tree($myvoc->vid);
>     foreach ($tree as $term) {
>      $tax[$term->tid] = $term->name;
>     }
>     $form['field_taxonomy']['#options'] = $tax;
> }
>
> ```

# Answer
> 0 votes
You can use Better Expose Filter Module and within Views -\> Exposed Form Style -\>Choose (Better Exposed Filter) now in BEF settings -\> Display "tid" exposed filter as -\> Select (Default Select List) -\> Show More options for "tid\_1" -\> see (Override "Any" option label ) -\> write (-Select- ) then save the view . This will change the to -Select- .

---
Tags: views
---


title: How to execute php script using drush?

text:
# Question
Title: How to execute php script using drush?
I am new to Drush. How can I execute this script to remove comments of a specific user?

```
$uid = xx // the spam users id;
$query = db_query("SELECT cid FROM {comments} WHERE uid = %d", $uid);
while($cid = db_result($query)) {
  comment_delete($cid);
}

```

Also, that would be great if you could tell me how to complete the script so that it takes username instead of $uid.

Thanks

# Answer
> 31 votes
You can convert the script in a Drush shell script.

> A drush shell script is any Unix shell script file that has its "execute" bit set (i.e., via `chmod +x myscript.drush`) and that begins with a specific line:
>
> ```
>     #!/usr/bin/env drush
>
> ```
>
> or
>
> ```
>     #!/full/path/to/drush
>
> ```

Drush scripts are better than Bash scripts for the following reasons:

* They are written in PHP
* Drush can bootstrap the site before running the script

The following is the example you can find on helloword.script.

```
#!/usr/bin/env drush

//
// This example demonstrates how to write a drush
// "shebang" script.  These scripts start with the
// line "#!/usr/bin/env drush" or "#!/full/path/to/drush".
//
// See `drush topic docs-scripts` for more information.
//
drush_print("Hello world!");
drush_print();
drush_print("The arguments to this command were:");

//
// If called with --everything, use drush_get_arguments
// to print the commandline arguments.  Note that this
// call will include 'php-script' (the drush command)
// and the path to this script.
//
if (drush_get_option('everything')) {
  drush_print("  " . implode("\n  ", drush_get_arguments()));
}
//
// If --everything is not included, then use
// drush_shift to pull off the arguments one at
// a time.  drush_shift only returns the user
// commandline arguments, and does not include
// the drush command or the path to this script.
//
else {
  while ($arg = drush_shift()) {
    drush_print('  ' . $arg);
  }
}

drush_print();

```

You can made the script executable, so you can execute it with `<script file> <parameters>` where `<script name>` is the script name, and `<parameters>` are the parameters passed to the script; if the script is not executable, you call it with `drush <script name> <parameters>`.

# Answer
> 30 votes
With `drush php-eval`, you can run your script *without* having to save it to a file first:

```
drush php-eval '
  $uid = 1234;
  $query = db_query("SELECT cid FROM {comments} WHERE uid = %d", $uid);
  while($cid = db_result($query)) {
    comment_delete($cid);
  }
'

```

This uses nested quotation marks, so to prevent a mess I recommend to use only double quotes `"` within the PHP code.

# Answer
> 16 votes
I think you're looking at `drush -d scr --uri=example.org sample_script.php` to execute sample\_script.php.

# Answer
> 11 votes
We can use `drush php-script script_name` to excute php file in Drush.

For help related to Drush for executing php files Type `Drush php-script --help` will list you the commands

Note: I have placed php scirpt in root folder of Drupal

# Answer
> 6 votes
It is simple you can run a php script by `drush scr ~/sample.php`.

# Answer
> 4 votes
On your command line, from anywhere, run:

```
$ drush --root=/path/to/drupal-installation --uri=youdomain.com scr /path/to/your/script.php

```

In case you are already at /path/to/drupal-installation just run:

```
$ drush --uri=youdomain.com scr /path/to/your/script.php

```

In case you are even further ahead at /path/to/drupal-installation/sites/youdomain.com than just run:

```
$ drush scr /path/to/your/script.php

```

your script.php file:

```
<?php
// Not always needed but sometimes you might have to first login as an administrator.
$admin_uid = 1;
$form_state = array('uid' => $admin_uid);
user_login_submit(array(), $form_state);

// Now the logged in user global $user object become available.
global $user;
print_r($user);

// Do whatever you want here.

```

# Answer
> 0 votes
Please note that the `db_result` has been removed in Drupal 7. The above code can be changed to:

```
$result = db_query($query);
foreach($result as $cid) {
  comment_delete($cid);
}

```

If you want to use username instead of the uid then you can get the username using this:

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

```

---
Tags: drush
---


title: Forcefully logout user from website

text:
# Question
Title: Forcefully logout user from website
I have a site which contains many links on the pages. Now I want to achieve the following:-

* User logs in website with credential and visit one of the page in the site.
* User right click on link and open the link in new tab.Now there are two pages of website opens in user's browser in two tabs.
* Currently Log Out option is visible on every page of the website. Authenticated user click on log out option in the page opened in one of the tab.
* Log out redirects user to login page.
* So as per these scenario ,there is one more page remains open in another tab.
* Now if the same user click on any of the link in the page then it should redirect to login page

Please provide your valuable input to achieve this functionality.

# Answer
> 0 votes
Sounds as if you need the Redirect 403 to User Login module:

> Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:
>
> "Access denied! You must login to view this page."
>
> Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.

---
Tags: 7, users
---


# Question
Title: How to run a Drush command with the full site path?
Im trying to get Drush working. When I type 'drush' into terminal I get a list of commands so I know its installed.

I dont have any path aliases set up yet so im trying to use the full path. When I type the following into terminal:

```
cd path-to-my-site drush dl views

```

I get this message:

```
unknown:omegav3 my-user-name$

```

Should the path-to-my-site be the base path? Im working locally with MAMP. I have different sites that arnt in the root folder so my local url for this site im trying to target is:

```
http://localhost:8888/omega/omegav3/

```

# Answer
> 3 votes
```
cd path-to-my-site drush dl views

```

Means you're trying to change directory into "path-to-my-site drush dl views" folder. You need to separately type the commands

```
cd path-to-my-site
drush dl views

```

Or you can use double ampersand or semi-colon to separate the commands. Double ampersand means previous command must succeed before the second executes, whereas semi-colon just means execute next command regardless of success or error on previous command:

```
cd path-to-my-site && drush dl views

cd path-to-my-site; drush dl views

```

# Answer
> 11 votes
Your command should be like:

```
drush dl views

```

or:

```
drush dl views -r /path/to/site/root

```

To get help manual for commands run:

```
drush help

```

Please find better explanation for drush commands at GitHub.

# Answer
> 9 votes
* On your command line, from anywhere, run:

> $ drush --root=/path/to/drupal-installation --uri=youdomain.com dl views

* In case you are already at /path/to/drupal-installation just run:

> $ drush --uri=youdomain.com dl views

* In case you are even further ahead at /path/to/drupal-installation/sites/youdomain.com than just run:

> $ drush dl views

See also how to run a script at How to execute php script using drush?

---
Tags: drush
---


title: Ajax form in block

text:
# Question
Title: Ajax form in block
From my experience, I believe Drupal8 treat Form API in BlockBase differently from FormBase Class, the below block doesn't seem to work. Do I have to do anything else to make Ajax Form work in Block? Please suggest. Maybe I need to #attach something? or do I have to do it non Drupal way by directly injecting jQuery into the code?

```
    class SearchBlock extends BlockBase
    {

        /**
         * {@inheritdoc}
         */
        public function build()
        {

            $build = array();
            $build['form'] = array(
                '#e' => 'form',
                '#method' => 'get'
            );

            $build['form']['q'] = array(
                '#e' => 'textfield',
                '#size' => 50,
                '#name' => 'q',
                '#ajax' => array(
                    'callback' => '::ajaxSearchSuggest',
                    'wrapper' => 'search-suggest',
                    'event' => 'keypress'
                ),
                '#default_value' => $_GET['q'],
                '#suffix' => format_string('<div style="search-suggest"></div>'),
            );
            $build['form']['submit'] = array(
                '#e' => 'button',
                '#attributes' => array('onclick' => 'return false;'),
                '#ajax' => array(
                    'callback' => '::ajaxSearchSuggest',
                    'wrapper' => 'search-suggest',
                    'event' => 'click'
                )
            );

            return $build;
        }

        public function ajaxSearchSuggest($form, FormStateInterface $form_state)
        {
            return array('#markup' => 'TEST');
        }
    }

```

# Answer
You can only use the `::something` shortcut for callbacks if your class is the form class, otherwise the form system doesn't know on which object that method should be called.

Instead, you need to use something like `[$this, 'someMethod']` or make it a static method with `['full\classname', 'someMethod']`.

Another thing that you need to be aware of is that the form structure and form values there will be in a different structure. Your form is inside a settings form element, but you shouldn't hardcode it and instead find our element through the submitted form element and the parents of it.
> 0 votes

---
Tags: forms, blocks, ajax, 8
---


# Question
Title: How to convert user menu tabs to menu links?
I have on user account 5-6 tabs created by some modules.My wish is to covert these tabs to menu items so as to insert to 2 separate menu links. I have read that something like that could be possible with hook\_menu\_alter. Is this correct?If so,how can I use it in my case? thanks a lot

# Answer
By creating an extremely simple custom module, you can Remove tabs using hook\_menu\_alter. Make sure to also clear the cache when you experiment with this.

Note: Consider refining your question to specify the path of each of those tabs you want to replaced.
> 2 votes

---
Tags: users, routes
---


# Question
Title: Further optimizing CSS delivery with AdvAgg?
It seems to me that my main **Drupal UI based task** to leverage my site's optimization is **further** optimizing it's CSS delivery...

Given the following facts, It's wired for me that Google's PSI advices me to do so:

1. Aggregation is on for CSS.
2. AdvAgg is installed and (as can seen from the picture) Both CSS minification & compression are on.
3. If it relates in any way in this case --- HTML is minified (if CSS served via HTML it would be served better, I guess).

Besides that, the site is very light in graphic details (both images and CSS).

---

I've tried to do the following AdvAgg conf's, but when I ran PSI again the advice still appeared:

1. Putting more css bundles per page (5 instead of 4) while I admit I am not familiar with the term at all.
2. compressing the (small amount) of inline CSS via YUI method.
3. Enable preprocess on all CSS and Checking all checkboxes at "Optimize CSS rendering", at the Modifications tab (via Modifications sub-module).

**Further details:**

Full PSI score results

---

It seem I don't have much options left... Would appreciate your help, Ben.

# Answer
This is the issue you'll want to follow: https://www.drupal.org/node/2396609 Inline critical css.

You can get rid of this message by using "Deferred CSS Execution: Use JS to load CSS". It's under the Experimental Settings of the CSS section. When you enable this, the page will no longer wait for the CSS to download before it starts to render. The bad part is you'll get what's known as a flash of unstyled content (FOUC). The issue I linked to above has to do with inlining the CSS that's needed to display the above the fold content so the FOUC doesn't happen.

Another way to get rid of the message is to inline all the CSS. This can be done by going to the Inline CSS/JS on specific pages section; just use the CSS section. Pick the pages you want to be optimized; `node/*` works for all nodes as an example.

The bundler comes into play when you look at the connection view from http://www.webpagetest.org/. If you're opening a connection in order to download a single css and/or js file then you should lower the number of bundles and see if that prevents a new connection from being used; this is super helpful with HTTPS connections which take up a lot of time to open. If there are a lot of files being transferred (image heavy site) then using more bundles will help with getting a better cache hit ratio in the browser. I found that 4 for both works pretty well in most sites but going higher or lower really depends on the site. Higher is usually better if the visitor is going to hit multiple pages. It's sorta an art form in order to get it optimal. Here's the issue for Drupal.org in regards to using AdvAgg for front end optimization: https://www.drupal.org/node/2493801
> 3 votes

---
Tags: performance, css-js-aggregation
---


# Question
Title: My slider's images have larger file-size than their originals
I have a slider in my homepage and this slider has 3 photos named a.jpg, b.jpg, and c.jpg.

The original file's sizes are (respectively), 42kb's, 20kb's, 52kb's. And yet when I download them from my slider (Flexslider) they whey much larger (c for example is 191 kb's).

# Answer
> 0 votes
Replace image style from the Slider's View (At Views module). I kept it without any style so the image won't be scaled to a larger style (You could scale it yourself with CSS in the relevant Div at the slider and it won't affect size).

---
Tags: media, javascript, performance
---


title: Clean URL's Test Failed in D 7

text:
# Question
Title: Clean URL's Test Failed in D 7
I am tired of finding solution for this issue..

I have tried allmost allthings. But It doesn't work for me. What I have tried is given below:

1. uncommenting RewriteBase /
2. Changing the syntax of REWRITE URL
3. No .txt extension in .htaccess file (EDITED)
4. mod\_rewrite Enabled.
5. Directly removing the query string and giving enter also doens't work.
6. If I include ALLOWOVERRIDES ALL in httpd.conf file it is showing Authentication Required Error.
7. Tried disabling the overlay module - Doesn't work.

Here is the .htaccess file for your refernce.

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

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

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
  # RewriteCond %{HTTP_HOST} !^mysite\.com$ [NC]
  # RewriteRule ^(.*)$ http://mysite.com/$1 [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
   RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  # RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

```

Any help will be really appreciated....

# Answer
> 6 votes
A good way to debug is to first see if your `.htaccess` is being picked up by Apache. My guess is that it is not, as the Drupal `.htaccess` should make clean URLs work out of the box with the rules that it ships with, supposing the `mod_rewrite` module is enabled.

To confirm this, however, make a blatant error in the `.htaccess` file and go to your Drupal home page, if the serving of the request failed (HTTP 500), it means that you are good to go and the problem is somewhere else.

If not, check if the directory from which your site is being served (i.e. your `DocumentRoot`) or one of its parents has `AllowOverride All` set. Basically, this is where you let the web server know that it should respect `.htaccess` overrides from the directories that it is serving from.

This might sound obvious but if you are running off a different web server (eg. nginx or IIS), you should know that you may have to configure it differently to get clean URLs to work.

# Answer
> 1 votes
The reason is because you have not uncommented the mod\_rewrite line inside your httpd.conf. This is the most common setup error in apache. Navigate to your httpd.conf file (it is an apache file) and do a (ctrl+f) search for mod\_rewrite. there should only be one instance. remove the # from the beginning and save. Restart apache and the check box should be there.

# Answer
> 0 votes
Best way is to check whether .htaccess is available in root folder or not normally when you install it goes in drupal folder so move all file to root by seeing hidden files.

---
Tags: 7, uri
---


# Question
Title: How to view blocks with Text Overlay on hover?
I'm working on a Drupal 7 site and I want to achieve similar thing (view blocks with Text Overlay on hover) shown here. http://ibakatv.com/ under the following blocks (sub sections): Basically I would like to show text upon mouse hover just like what is shown on the above website.

* MOVIE TRAILERS
* TRENDING MOVIES ..
* LATEST MOVIES etc etc

Also, can someone help how to achieve those view blocks with the navigation as listed above? Do you know this was done? I looked at BX Slider, but I'm unable to achieve it.

# Answer
Your question appears to be a variation of Create a simple Text over Image Overlay on Hover with Drupal 7 and Views. If you also install/enable the Link module, the node title shown over the image can be a hyperlink to the node also.

Especially this part in it seems to be what you're looking for (be it with some minor variations):

> Create a view 'Overlay'. Create a page which shows content of type 'overlay-image'. It shows an unformatted list of fields. Save and edit. On the edit page, add the fields 'Content: Image' and 'Content: Link' to the fields and exclude them from display. For the last field add 'Global: custom text'. In the text field, write: `<ul class="img-list"><li>[field_image]<span class="text-content"><span>[field_link]</span></span></li></ul>`

Curious to hear if this somehow will help ...
> 1 votes

---
Tags: 7, views, blocks, modal-dialogs
---


# Question
Title: Importing Custom (Trumba ) RSS Feeds into Node
I'm working on a Drupal 7 college project that involve in importing the college calendar feeds into a calendar content type in Drupal. The RSS feed is coming Trumba - 25livepub-collegenet-com in the following format.

```
    <item>
        <title>Worship</title>
        <description>Christ Chapel <br/>Sunday, Januar</description>
        <link>http://www.gettysburg.edu/events/inde.....</link>
        <x-trumba:ealink>http://25livepub......</x-trumba:ealink>
        <category>2015/01/25 (Sun)</category>
        <pubDate>25 Jan 2015 16:00:00 GMT</pubDate>
        <guid isPermaLink="false">http://uid....8</guid>
    </item>
</channel>

```

I went to Feed Importers under Admin/Structure/Feeds and set up the Node processor as well as the Mapping for the Node processor using the following:

Source --------\> Target

* Title - - \> Title
* Published date - - \> Published date
* Categories --- ---\> Event Category
* Item GUID - - - - \> Item GUID
* Item URL (link) - - \> URL
* Description - - - \> Description

The nodes are imported into the calendar content type. The problem is everything except the **Title** is imported into the **description** field - making it difficult to differentiate them especially when the description is combine with the publish date, category etc etc. Can somebody please point me in right direction how to go about this. Thanks alot.

# Answer
> 0 votes
Consider using the Feeds XPath Parser. Here is a quote from its project page:

> Feeds XPath Parser is a Feeds plugin for parsing XML and HTML documents. It enables site builders to leverage the power of Feeds to easily import data from complex, external data sources. Each element you wish to extract is setup using configurable mapping queries, saving time for developers who would otherwise have to code complex, specific-use modules. It also enables end-users to build web scrapers and other useful tools within Drupal.

---
Tags: feeds
---


# Question
Title: Extending Entityreference Field Class to contain additional input fields
I am currently trying to build a custom field consisting of an EntityReference Input Field (Autocomplete Widget) and two textfields to add additional information in Drupal 8beta11.

I used the code from the example module and the EntityReference field type. I copied it into my custom module. Everything worked.

But then I remembered the 'new' OOP approach of Drupal 8. Why copy, when I can extend? Extending the EntityReferenceItem Class worked without any problems. The table was correctly created.

Then I tried to extend the autocomplete widget class EntityReferenceAutocompleteWidget to show my additional two textfields. Here it somehow doesn't work. The Error I get:

```
Fatal error: Call to undefined method Drupal\Core\Field\FieldItemList::referencedEntities() in ...\core\lib\Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget.php on line 95

```

I know it means more or less, that somehow the $items, which are put into the parent::formElement method doesn't have the function referencedEntities implemented. But how can I fix this?

I tried to look into other modules and even found Drupal\Core\Field\Plugin\Field\FieldWidget\AutocompleteTagsWidget to extend the EntityReferenceAutocompleteWidget, but I don't find the difference.

This is my CompoundReferenceWidget. I am grateful for any advice or hint to get it working. Or to get the information, that it can't be done the way I tried it.

```
/**
 * @file
 * Contains \Drupal\compound_reference\Plugin\field\widget\CompoundReferenceWidget.
 */

namespace Drupal\compound_reference\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
/**
 * Plugin implementation of the 'compound_reference_widget' widget.
 *
 * @FieldWidget(
 *   id = "compound_reference_widget",
 *   module = "compound_reference",
 *   label = @Translation("Modeling a reference with additional fields."),
 *   field_types = {
 *     "compound_reference"
 *   }
 * )
 */
class CompoundReferenceWidget extends EntityReferenceAutocompleteWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['description'] = array(
    //$element += array(
      '#type' => 'textfield',
      '#title' => t('Description of the reference.'),
      '#default_value' => isset($items[$delta]->description) ? $items[$delta]->description : NULL,
      //'#min' => 1,
      //'#required' => TRUE,
    );
    $element['start'] = array(
      '#type' => 'textfield',
      '#title' => t('Start Date'),
      '#default_value' => isset($items[$delta]->start) ? $items[$delta]->start : NULL,
      '#description' => t('Start'),
    );

    return $element;
  }
}

```

# Answer
> 3 votes
The error is on the field item list class.

What you are missing is the list\_class definition in the annotation of your field type, for anything that's an entity reference, you need to explicitly specify it, since annotations aren't inherited. See EntityReferenceItem:

```
*   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",

```

---
Tags: entities, 8
---


# Question
Title: hook_entity_bundle_field_info_alter() only validates article bundle
I used hook\_entity\_bundle\_field\_info\_alter to validate fields in node as below:

```
function my_module_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && !empty($fields['title'])) {
    $fields['title']->addConstraint('UniqueField', []);
  }
}

```

The validation I wrote in `UniqueFieldConstraintValidator` Plugin works for "article" bundle but not for any other bundles. What am I doing wrong?

# Answer
> 2 votes
You're using the bundle alter hook, which is only called on by-bundle fields.

Title is a base field but it can be overridden by a per-bundle through field override.. this is what happens if you chose a different title through the node type settings form. I guess that's why it's only available sometimes.

Try to use `my_module_entity_base_field_info_alter()`. Due to the override, which completely replaces the base field, you actually might need both hooks.. I don't know if the constraint is transported to the field override correctly and certainly not if the field override already exists when you add the alter hook. Not much that can be done about that I fear.

---
Tags: 8, nodes
---


# Question
Title: All instances of block are not getting removed
This question is a continuation of this Block in Drupal 8, The second problem I am facing is that suppose I select block made for comment section and place it under Sidebar second section and afterwards deselect comment from configuration setting then after clearing cache the label for comment from block section is removed but block placed under Sidebar section still remains with default message for broken blocks "This block is broken or missing. You may be missing content or you might need to enable the original module.".What changes should I make so that this message is removed ? Thanks.

# Answer
> 0 votes
As mentioned in the other question, what you need to do is query for the blocks that no longer exist and delete them.

`BlockContent::delete()/getInstances()` is an example for that. You can do a similar query, either by using entity\_load\_by\_properties() for the plugin ID that those blocks would have. Or you can run an entity query, which has more options.

You don't have an entity, so in your submit, you need to build a list of all unchecked options and then query for those. The advantage of doing an entity query is that you can do an IN condition, so you probably want to use that.

A more complicated example, that looks at settings and either updates or deletes the affected blocks can be found in simplenews.module's `Newsletter::postDelete()`:

```
if (\Drupal::moduleHandler()->moduleExists('block')) {
  // Make sure there are no active blocks for these newsletters.
  $ids = \Drupal::entityQuery('block')
    ->condition('plugin', 'simplenews_subscription_block')
    ->condition('settings.newsletters.*', array_keys($entities), 'IN')
    ->execute();
  if ($ids) {
    $blocks = Block::loadMultiple($ids);
    foreach ($blocks as $block) {
      $settings = $block->get('settings');
      foreach ($entities as $newsletter) {
        if (in_array($newsletter->id(), $settings['newsletters'])) {
          unset($settings['newsletters'][array_search($newsletter->id(), $settings['newsletters'])]);
        }
      }
      // If there are no enabled newsletters left, delete the block.
      if (empty($settings['newsletters'])) {
        $block->delete();
      }
      else {
        // otherwise, update the settings and save.
        $block->set('settings', $settings);
        $block->save();
      }
    }
  }
}

```

---
Tags: blocks, 8, configuration
---


# Question
Title: Display Image logo along with site slogan and site name
I am using Impact theme for my site. It either displays text logo(site name, site slogan) or image logo. I want both image logo and text logo for my site.

Any help is welcome.

# Answer
> 0 votes
I assume you have created a sub-theme, in that case, copy the page.tpl.php from the parent Impact Theme to your sub-theme if you haven't already, and delete the `else` statement (line 73):

```
<?php if (theme_get_setting('image_logo','impact_theme')): ?>
  <?php if ($logo): ?><div id="site-logo"><a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a></div><?php endif; ?>

<?php else: ?> <!-- delete this line -->

  <hgroup id="site-name-wrap">
    <h1 id="site-name">
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <span><?php print $site_name; ?></span>
      </a>
    </h1>
    <?php if ($site_slogan): ?><h2 id="site-slogan"><?php print $site_slogan; ?></h2><?php endif; ?>
  </hgroup>
<?php endif; ?>

```

Be aware that the setting for deciding whether to use the logo or the text will no longer work in a either/or scenario, it would force all or nothing. You can get rid of the IF statement entirely, and the setting becomes useless

# Answer
> 0 votes
I would recommend to use the "Panels" module to do that. Create a "mini-panel" and while editing one of it's panes (boxes of content) choose on the edit menu "Page elements" and then add "Logo, "Site name", and "Site slogan" respectively. Make sure you arrange them as your liking.

The second part of your work is to do some CSS for this. The Panels css system takes some time to learn --- You should use DOM tags carefully to isolate the Id's and classes of the right div's and manipulate them in relation to their upper div's, but it's worth the shot.

If your site is responsive you should add some responsiveness with a Media query, i.e:

```
@media screen and (max-width:519px) {#panel-col-first {width:100%;} #panel-col-last {width: 100%;}}

```

In Panels, make sure that after you choose basic details and layout you navigate in "content" tab. Then, Add the aforementioned details - Here is a screen that'll show you how:

---
Tags: theming
---


# Question
Title: Private website with Rules - Inherit custom fields
I want to create a website where all the content is only visible to logged in users.

*(I don't want to solve it by using other access modules or by configuring the permissions of the roles, for specific other reasons.)*

What I basically try to do with Rules is the following:

```
Given the value of "custom field X" (boolean) of "content type A" is true,
When a user  views a node of "content type B"
Then I want to redirect the user to [site:login-url]

```

But it seems that there is not a straightforward way to do this. Couple of methods that could be possible are:

1. Using entity reference: inheriting the value and firing the condition on the node view
2. Views looping: creating a view and firing the condition on all node views
3. Checking the value somehow when Drupal is initializing

I could do this also within a template tpl preprocess, by simply adding the logic. But it feels not right to solve it that way. Possibly because then there are other security issues that I'm afraid of neglecting.

**Is there a better / easier way to do this? What would you recommend?**

# Answer
> 0 votes
This is very straight forward in Rules without the need for extra modules:

* Event: Content is viewed of type \[content-type\]

You can add one event for each content type, or as the description in the Rule itself states: `If you need to filter for multiple values, either add multiple events or use the "Entity is of bundle" condition instead.`

* set a boolean field in the content type to determine if it should be public or not
* Condition: Data Comparison: Parameter: Data to compare: \[node:field-to-determine-if-viewable\], Data value
* Action: Page Redirect: Parameter: URL: user/login

This will check every page load of a content type (or all if you so desire) and redirect if the boolean is set (or not set) depending on how you want it set up

---
Tags: rules, users
---


# Question
Title: 7 - Display translated content using Flexslider Views Slideshow
I have a Views block which uses FlexSlider Views Slideshow as the format. The fields which supply the captions have translations but only the default (English) versions are displayed with the FlexSlider Views Slideshow format. Example of the Views block using FlexSlider Views Slideshow can be seen here.

I have a Views page as part of the same view which uses unformatted list as the format. This handles the translated as expected. Example of the Views page is here.

The captions are from the title field of the content type which use the Titles module so they can be translated.

Other modules in the mix are i18n, i18n\_block, i18n\_field, i18n\_views which enable the content to be translated in the first place.

**So, my question is**: How to get the FlexSlider Views Slideshow to display translated content?

I've checked the *Field Language* setting is Current User's Language in the View.

I've checked the *Make this block translatable* option is checked in the block's configuration.

I've checked the *Language Detection Settings* are ordered; *URL, User, Default*

I've cleared all the caches.

I appreciate your suggestions.

# Answer
> 0 votes
Your problem might be because of the "language detection" configuration.

So check this configuration via *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.

---
Tags: views, i18n-l10n, javascript
---


# Question
Title: PHPUnit with custom/contrib and submodules structure
I am starting to write our tests with PHPUnit on Drupal 8, and I am not sure about the best practices with the phpunit.xml.dist file. We separates the custom and the contrib modules using two directories in the /modules directory - /modules/custom and modules/contrib. The original phpunit.xml.dist file contains the following line `<directory>../modules/*/tests/src/Unit</directory>` so I had to add the `<directory>../modules/*/*/tests/src/Unit</directory>` directory.

I have another issue with sub-modules, our current structure is /modules/custom/main\_custom\_module/modules/sub\_module, so I had to add another directory to the file (`<directory>../modules/*/*/modules/*/tests/src/Unit</directory>`).

What is the best practice when it comes to overriding the phpunit.xml.dist file? should I remove the file from VC (e.g. git,svn..)?

# Answer
The right thing to do is to not add it to the core phpunit.xml.dist file. You have your own code, so you want to test that. The idea that core also tests contrib / custom code is not the right thing to do, IMHO
> 1 votes

---
Tags: 8, testing
---


title: All Contents related to a content list

text:
# Question
Title: All Contents related to a content list
Say a user has a list of 2 favorite books , one with taxonomy term "adventure" and one with taxonomy term "art". (n favorite books, related with m taxonomy terms)

How to automatically display a list of all books with taxonomy term "adventure" or "art" (or m taxonomy terms)

The steps could be :

* step 1 : build the list of the user's favorites books (views, flag, filter : this is OK)
* step 2 : get the list of all taxonomy terms referenced by theses nodes,
* step 3 : get the list of all books referencing one or several of the taxonomy terms listed at step 2

My question is how to build a view which do these 3 steps.

Thanks

# Answer
> 0 votes
You can use views , build a view of content type book , then filter them based on taxonomy term , you even can expose the filter and let it to user to decide which genres want to view .

# Answer
> 0 votes
I found this solution with a chain of relationships :

In Views

Advanced : add a relationship "Flags" : favorites(by current user, include only flagged content) . set identifier to "favorite books" add a relationship "Content: Book\_category", relationship : "favorite books", check "Require this relationship). set identifier to "book category" add a relationship : "Taxonomy term: Content using Book\_category", relationship : "book category", check "Require this relationship. set identifier to "recommended books"

in Fields :

title, id,book, category etc with relationship : "recommended books"

# Answer
> 0 votes
I know your solution is working but I think it might be a time consuming query , too many relationships . I suggest you another solution :

1. add a new field to users account (type : term reference and link it to your taxonomy vocabulary , I named it Favorite Genre)
2. Hide it from users using Field Permissions module
3. Install Rules module
4. Enable flag actions sub-module
5. go to Rules and add new rule , event = A node has been flagged, under "your content type"
6. add an action , add an item to a list (we want to add the books genre to user's favorite)
7. item to be added is the flaged-node-\>book\_catagory and that must be added to user-flagged-favorite\_genre

by now when a user bookmark a book the book genre will be added to his/her favorite genre. the benefit is that there is no need for more querying to find this out.

now go to views add a relation based on user , and you can filter books based on user's favorite genre.

be careful : maybe you do a trick on unbookmark , and remove the book genre from his list , this would be make mistake cause maybe user have other books with this genre . in this case you need to make a loop based on user's bookmarked books and check their genres , if there were no book with that genre then you can remove that genre from user's favorite .

more details about Rules module here.

---
Tags: taxonomy-terms, views, entities
---


# Question
Title: Clean up test payment transaction from drupal commerce site
I am trying to find an admin page where I can delete all test payment transactions happened on drupal commerce, but could not find it.Need to no if my following plan will create any referential integrity issue after cleanup.

1. From orders page clean all test orders.
2. Manually clean the database tables 'commerce\_payment\_transaction' and 'commerce\_payment\_transaction\_revision' and then using db API clean payment transaction table using

db\_truncate('commerce\_payment\_transaction'); db\_truncate('commerce\_payment\_transaction\_revision');
3. Clean up all tested customer profiles from admin page for the same using bulk operation.
4. Clean up test users created with the checkout process.
5. Truncate orders table to start with order id , using again following code.

db\_truncate('commerce\_order');

db\_truncate('commerce\_order\_revision');

# Answer
> 3 votes
The short answer is there is no such page. What you're attempting to build with VBO should work well, but currently there is no automatic deletion of payment transactions when orders are deleted. It's questionable whether or not we actually want that to be the default behavior. However, if you're just using VBO driven by custom rules components, you should be able to load any payment transaction referencing the order to be deleted and delete them from within the same rule. Using commerce\_order\_delete() will not delete payment transactions; for that you'd need commerce\_payment\_transaction\_delete().

# Answer
> 0 votes
So using just views and listing commerce\_payment\_transaction and deleting them will not work? I tried that and cant delete them. What also happened is that I deleted all orders first and then transactions remained in system, so only way I see is to delete them directly in DB.

---
Tags: commerce
---


title: Not able to install a module via drush

text:
# Question
Title: Not able to install a module via drush
I am trying to install Vote Up/Down module via drush. But even if it is not already installed and it has been downloaded, it is not being installed.

```
[root@localhost custom]# drush dl vote_up_down
Install location /var/www/html/d7/sites/all/modules/contrib/vote_up_down already exists. Do you want to overwrite it? (y/n): y
Project vote_up_down (7.x-1.0-alpha1) downloaded to /var/www/html/d7/sites/all/modules/contrib/vote_up_down.                [success]
Project vote_up_down contains 5 modules: vud_term, vud_field, vud_node, vud_comment, vud.
[root@localhost custom]# drush en vote_up_down
vote_up_down was not found and will not be enabled.                                                                         [warning]
There were no extensions that could be enabled.                                                                             [ok]
[root@localhost custom]#

```

Can anybody help me with this?

# Answer
Project contains 5 modules. Neither of them is named exactly like the project. See the names you were given in first message.

You probably meant

```
drush en vud

```
> 2 votes

---
Tags: 7, drush
---


# Question
Title: What is the best way to achieve this result?
I've hit a bit of a stumbling block with how to tackle this design I'm working on in Drupal. The end result needs to be a block that sits on the home page and it updated weekly by anyone with the 'staff' user flag.

This is what it needs to be in the end: https://i.stack.imgur.com/9pU60.png (Data being the focus of this question, design is irrelevant):

* Whoever generated the list has their name and picture on the block.
* There will always be 3 products.
* The person who picked this week can include a personal comment on the picks.

I've been able to get it working so far by making a block that uses inline PHP to grab a view that contains 3 products that have the taxonomy term "Promote to Front Page", and then manually filling in the user information myself... But I'd like for this to be something a staff member can fill out themselves without needing any code knowledge.

Is this something achievable with a content type or something else i'm not thinking of?

An awesome bonus is if there's a way to do it so that each week a new pick is generated but the old ones are still stored for reference.

Thanks muchly!

# Answer
I would do it with content type using entity reference to products. Entity reference allows you to reference other nodes in your "deal of the week" node and use this relationship in your view. No PHP should be needed. With this setup, you can do almost anything:

* only Staff is allowed to create new content of this type
* view can show author name (and picture)
* custom comment? no problem, just a text field in content
* old content is still available
> 0 votes

---
Tags: views, commerce, nodes
---


# Question
Title: Drupal Commerce - Reference Product in another product
I am building a Drupal Commerce based site and now I am facing the following issue.

I have created some T-Shirt Products like,

* T-Shirt (White)
* T-Shirt (Black)
* T-Shirt (Blue)

And also created a product display called "Shirts". In that product display I created a new node "T-Shirt". Since The "size" is an attribute to the product type so I am having a select box to select the color while viewing the "T-Shirt" content.

But the problem comes here. As per my need, if the user selects "Color - White" while viewing the product display, we need to add another product "Blue-Jeans" to it. So that means, White Shirt and Blue Jeans will go together in cart if selected.

I am using inline\_entity\_form to reference products in a Product display (Same as Commerce Kickstart Demo "Tops" product display). How can I achieve this functionality?

# Answer
> 0 votes
What you are looking for is bundling of products.

Take a look at Commerce Product Bundle Module

The project page says

> You can define products that consists of other products. They are all combined in one add to cart form. The form works like the core add to cart form with all the fancy selection and ajax magic. So the customers can make their selections as usual. The difference is, that the products from mulitple reference fields were presented on one add to cart form.

---
Tags: commerce, entities
---


title: Different user registration

text:
# Question
Title: Different user registration
small question

I've created a content type 'Player' with the necessary fields. With the 'Inline Entity Form' module i've added this tot the default user registration form.

Now when a user register, he immediately creates a node for the content type 'Player'. And when he edit his user profile, he also edit the node.

Now I want to have the option, that a user can choose to register as a player or a coach. When a coach register, he should fill in other fields, and so create a node for the content type 'Coach' .

With which modules can I realize this?

# Answer
> 0 votes
You can achieve this using Profile 2 and Profile2 Registration Path

As the project page of Profile2 Registration Path mentions

> Profile2 Registration Path enables you to set a unique registration path for each Profile2 profile type. Users who register via that unique path will be presented with fields from the chosen profile type(s).

# Answer
> 0 votes
You can use profile2 and Profile2 Registration Path module.

---
Tags: 7, rules, users, entities
---


# Question
Title: Empty field collection in hook_node_presave with entity_metadata_wrapper
I have a node with a field type field\_collection which has 2 items:

```
$node->field_field_collection['und'] = array(
  0 => array('value' => 1),
  1 => array('value' => 2),
);

```

on the save node drupal fire hook\_node\_presave:

```
/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  $ewrapper = entity_metadata_wrapper('node', $node);
  $wrapper_counter = 0;
  $node_counter = 0;
  foreach ($ewrapper->field_field_collection->getIterator() as $delta => $fc_wrapper) {
    $wrapper_counter++;
  }
  foreach ($node->field_field_collection['und'] as $key => $value) {
    $node_counter++;
  }
}

```

after runing code

```
$wrapper_counter = 0;
$node_counter = 2;

```

what am I doing wrong?
I want to walk the field collection using entity\_metadata\_wrapper.

Drupal: 7.34
Entity API: 7.x-1.5
Field collection: 7.x-1.0-beta8

# Answer
> 1 votes
By this way as per this post:

```
/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  if ($node -> type == 'my_type') {
    $field_field_collection = field_get_items('node', $node, 'field_field_collection');
    foreach ($field_field_collection as $key => $value) {
      $fc_wrapper = entity_metadata_wrapper('field_collection_item', $value['entity']);
      $fc_name = $fc_wrapper -> field_field_collection_name -> value();
      dsm($fc_name);
    }
  }
}

```

See: Understanding Field Collection Values and Entity metadata wrappers pages.

---
Tags: entities, nodes
---


title: Insert task to Queue only if unique

text:
# Question
Title: Insert task to Queue only if unique
I wanted a way to only insert items into the Queue when it was not already added. I want to have a large queue and work my way through it, simply adding as required. Previously I was deleting the queue and recreating on a set time table.

I couldn't find any way of doing this, or any discussion other than 'it's not possible.

I created the method below. I have not used it for huge queues yet, but I post it here in the hope that better options if available might get posted too.

# Answer
> 1 votes
Create a class to extend the systemqueue. I called mine Unique. This will serialise the data use db\_merge to insert only if it doesn't exist.

```
class Unique extends SystemQueue {

  public function createItem($data) {

    // save doing this twice
    $serial_data = serialize($data);

    // ignoring expire
    $query = db_merge('queue')
    ->key(array('name' => $this->name, 'data' => $serial_data))
    ->fields(array(
        'name' => $this->name,
        'data' => $serial_data,
        'created' => time(),
    ));
    return (bool) $query->execute();
  }
}

```

You then add the variables to hook\_install() or hook\_enable().

```
variable_set('queue_class_[your queue name]', 'Unique');

```

matching \[your queue name\] to the queue name, e.g if you used this:

```
DrupalQueue::get('update_profile_tasks')->createQueue();

```

the variable would be:

```
variable_set('queue_class_update_profile_tasks', 'Unique');

```

Thanks to this for getting me on track. Updated answer to be cleaner thanks to comment suggestions.

---
Tags: 7, cron, queue
---


# Question
Title: How to add some configuration option to vertical tab on content type edit page
Is it possible without touching Dupal core's code, add some configuration option to content type edit page? preferably to vertical tabs of bottom? such as a checkbox.

I mean this page: /admin/structure/types/manage/article

# Answer
Yes, you can add a fieldset to the content type edit form with hook\_form\_FORM\_ID\_alter.

e.g:

```
function MYMODULE_form_node_type_form_alter(&$form, &$form_state) {
    // Define field set in additional settings group
    $form['advanced'] = array(
      '#type' => 'fieldset',
      '#title' => t('Advanced settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => 10,
      '#group' => 'additional_settings',
    );
    // Add checkbox option
    $form['advanced']['special_option'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use special option'),
    );
    // Set default value from automatically saved config variable
    $form['advanced']['special_option']['#default_value'] = variable_get('special_option_' . $form['#node']->type, 1);

}

```
> 3 votes

# Answer
Ok I found the answer: seems to be needed to add a submit function to your $form, to set the variable to store.

In the MYMODULE\_form\_node\_form\_alter() function, add:

```
$form['#submit'][] = 'MYMODULE_node_form_submit';

```

then the submit function:

```
function userprog_node_form_submit ($form, &$form_state) {
  $special = $form_state['values']['special_option'];

  variable_set('MYMODULE_' . $form_state['values']['type'] . '_special_option', $special);
}

```

NB: the variable\_get() in the hook\_form\_alter() function, becomes:

```
// Set default value from automatically saved config variable
$form['advanced']['special_option']['#default_value'] = variable_get('MYMODULE_' . $form['#node_type']->type . '_special_option', 1);

```
> 1 votes

# Answer
You could also have a look at the nodeapi\_example module. (From the Drupal Example modules).

It gives a quite legible example on adding a setting to the *content type edit page* AND an extra 'setting'/option to every node for which it is enabled.
> 0 votes

---
Tags: nodes, entities
---


title: Add more and remove fieldset

text:
# Question
Title: Add more and remove fieldset
I created one content typa and I put one fieldset group through Field\_group module, but I can't see settings to add more fieldset. I've 6 fields per fieldset. But I'm not able to do the same with fieldset. It can be done with particular field only.

# Answer
> 0 votes
You can add more fieldset by Add new group option available in Manage field page, please find the below screenshot..

**And you can drag and drop the filed inside the fieldset as you required**

---
Tags: 7
---


title: Domain based on alias

text:
# Question
Title: Domain based on alias
Currently we use the Domain Access module to make a couple of domains. Our current domains are for example:

```
www.domainemployer.com
www.domainclient.com

```

But our client now wants it to be like this:

```
www.domain.com/employer (<--- previously domainemployer)
www.domain.com/client (<--- previously domainclient)

```

I don't see if this is possible with the domain access module. Can anybody point me in the right direction?

Should we do this with rewrite rules (but is this going to clash with the current existing rules)?

# Answer
> 0 votes
I think Domain Path module can solve your issues.

> The Domain Path module allows the creation of separate path aliases per domain for nodes created using the Domain Access module.

---
Tags: 7, domain-access
---


title: Drupal 6 views and duplicates

text:
# Question
Title: Drupal 6 views and duplicates
I have view that shows articles. It works fine if user selects one image but if she selects multiple images to article, it will duplicate the article on my view X amount time (x = number of images that article has). I have tried using distinct but that doesn't do any difference. Why would this image amount effect on this?

I'm using Drupal 6, with Views Version 3.

Here is the query if it helps:

```
 SELECT DISTINCT(node.nid) AS nid_1, users.uid AS users_uid,
 node_data_field_article_image.field_article_image_fid AS
 node_data_field_article_image_field_article_image_fid,
 node_data_field_article_image.field_article_image_list AS
 node_data_field_article_image_field_article_image_list,
 node_data_field_article_image.field_article_image_data AS
 node_data_field_article_image_field_article_image_data,
 node_data_field_article_image.delta AS node_data_field_article_image_delta,
 node.type AS node_type, node.nid AS nid, node.vid AS node_vid,
 node_data_field_article_color.field_article_color_value AS
 node_data_field_article_color_field_article_color_value,
 node_data_field_article_numbers.field_article_numbers_value AS
 node_data_field_article_numbers_field_article_numbers_value, node.created AS
 node_created, users.name AS users_name, node.title AS node_title,
 node_revisions.body AS node_revisions_body, node_revisions.format AS
 node_revisions_format, feeds_node_item.url AS feeds_node_item_url FROM node node
 INNER JOIN users users ON node.uid = users.uid LEFT JOIN
 content_field_article_image node_data_field_article_image ON node.vid =
 node_data_field_article_image.vid LEFT JOIN content_type_blog
 node_data_field_article_color ON node.vid = node_data_field_article_color.vid LEFT
 JOIN content_field_article_numbers node_data_field_article_numbers ON
 node.vid =
 node_data_field_blog_font.vid LEFT JOIN node_revisions node_revisions ON
 node.vid = node_revisions.vid LEFT JOIN feeds_node_item feeds_node_item ON
 node.nid = feeds_node_item.nid WHERE (node.type in ('blog', 'feed_item')) AND
 (node.status = 1) ORDER BY node_created DESC

```

# Answer
> 0 votes
The version you have should provide an option for the image field `Group multiple values` and also underneath this you can choose just to show 1 image. Either or a combination should stop these duplicates happening

---
Tags: views, 6
---


# Question
Title: Appears the same orders in the admin/commerce/orders and in the admin/commerce/orders/carts
In admin/commerce/orders appears the orders that order status is: Checkout:Payment,Checkout:Checkout,Shopping cart (these orders that appear in admin/commerce/orders/carts).Ι would like to appear only orders tha order status is:pending. How could I do it?

Thank you very much.

# Answer
In views list, there is one view named "Orders". In this view two pages are available:

1. "Orders"
2. "Shopping carts"

In "Shopping carts" page, click on `Commerce Order: Order state` from filter criteria and select states for which you want to display records.

Let me know if you face any future query with this.

Thanks!
> 0 votes

---
Tags: commerce
---


# Question
Title: Webform : A partially-completed form was found. Please complete the remaining portions
Yesterday I have updated webform module from **7.x-4.0-beta3** to **7.x-4.9**.

Post to that I am getting this notification message, throughout the site :

> *A partially-completed form was found. Please complete the remaining portions*

I have also checked some threads :

https://www.drupal.org/node/2483859

https://www.drupal.org/node/2278177

When I check log entries I got this error :

> *Notice: Undefined property: stdClass::$is\_draft in webform\_client\_form()*

Which suggest that some alteration leading this issue but unable to get any solution.

# Answer
> 3 votes
Try this:

Delete the form submission that is having problem(that is the submission id that is partially filled) in the following tables:

> webform\_submitted\_data
>
> webform\_submission

---
Tags: webforms
---


# Question
Title: Deleted files for node are being included in view for services
We are using the services module to provide a JSON feed for our internal portal to pick up our articles. The page view that provides all files for each node uses the File Usage: Content relationship. We just noticed that even files that have been deleted from the node are still being listed.

The query that views shows (when I take that same view and set as a block)

SELECT file\_managed.uri AS file\_managed\_uri, file\_managed.fid AS fid, file\_managed.filemime AS file\_managed\_filemime, users\_file\_managed.mail AS users\_file\_managed\_mail, 'file' AS field\_data\_field\_caption\_file\_entity\_type, 'file' AS field\_data\_field\_file\_image\_alt\_text\_file\_entity\_type, 'file' AS field\_data\_field\_file\_image\_title\_text\_file\_entity\_type FROM {file\_managed} file\_managed LEFT JOIN {file\_usage} file\_usage ON file\_managed.fid = file\_usage.fid INNER JOIN {node} node\_file\_usage ON file\_usage.id = node\_file\_usage.nid AND file\_usage.type = 'node' LEFT JOIN {users} users\_file\_managed ON file\_managed.uid = users\_file\_managed.uid WHERE (( (node\_file\_usage.nid = '') ))

The nid is provided as a parameter.

How can I get it to not include files that were removed from the node?

# Answer
> 0 votes
You should use file\_usage\_delete to remove file usage records to nodes that files was having relations so you stop that problem for future deleting files on nodes.

And you still have to fix it for the existing nodes I suggest two ways

First : write a script to loop on file\_usage records and check if the not currently used in the node (via node load and check fid exist) if so delete that record (if u have small number of rows in that table)

Second : Implement hook\_views\_pre\_render and do the same check.

The first is preferred however it may take long time but it will stop the problem reason.

---
Tags: views, services
---