title: how do I build a dynamic URL in views?

text:
# Question
Title: how do I build a dynamic URL in views?
I am using drupal 7, have a content type and two taxonomy categories, size and shape.

Im trying to build a dynamic url such as mysite.com/node/nid/tid/tid, which would get rewrote as e.g mysite.com/page-1/large/square.

I want the content of the url to just show the node, so in this case node/1. But I am also going to make 2 blocks one for category size and another block for category shape which will get the relevant IDs from the url and show the relevant content, in this case block 1 will show large and block 2 will show square.

I thought I could generate the page in views by setting the URL to node/%/%/% or node/%/*/* and setting arg 1 to nid, but this comes back as page not found.

So I am wondering is this possible in views if not how can I create a url such /arg1/arg2/arg3 which represents /a nid/a category 1 tid/a category 2 tid, and then populate the page dynamically?

Thanks for any help

edit/

So I have got the arguments working. mysite.com/%/%/% by setting the last argument as the target page rather than the first argument. But how can I rewrite the url. So arg1 becomes node title, arg2 becomes term id 1 and arg3 becomes term id 2 title?

# Answer
You'll need to set your pathauto pattern settings to rewrite your URL. Goto **Configurations \> Search and metadata \> URL aliases \> Patterns**. Set the pattern for your content type to:

```
[node:title]/[node:field_...]/[node:field_...]

```

Where the "node:field\_..." is replaced with the respective tokens for your taxonomy fields.
> 0 votes

---
Tags: 7, views
---


title: UberCart product image won't scale

text:
# Question
Title: UberCart product image won't scale
The image in a product (full view not teaser) is coming in full size (and too big) and I can't figure out how to change it. Looking at the Product content type I see the 'Preview image style' is 'Thumbnail (100x)'. I read in some doc the Preview image style should be 'uc\_product' so I'm a bit surprised by that. In an attempt to figure it out I went to \>\>Media\>\>Image styles and changed every image style to Scale 50x50. Images in the teaser responded to the change but on the product page the image is still coming in large (full size probably). Also as a guess, I went to Configuration\>\>Media\>\>Colorbox and change Max width, Max height, Initial width & Initial height to very small values. This made no difference.

Any suggestions for solving this or tips for figuring it out?

Thanks

# Answer
May be the css property for the image in the full page was written as width:100% and height:auto , so it will always makes an image in large full size. you can check by inspect element to see the correct path of image style is coming or not.

You can get the image path from there and paste that in new tab to see what size of image is coming without applying any css rules.

Hope this will help you.
> 0 votes

# Answer
This turned out to indirectly be a CSS problem. I could not find a style in the css that controlled the the image size for any images. The fix was to go to the Product content type \> Manage Display and for the Image field change Format to one of the following:

> Colorbox - which then present you with options to choose styles such as uc\_product OR 'Ubercart product' - I noticed the teaser was already set to this which explained why the teaser image was sizing but not product detail image.
> 0 votes

---
Tags: ubercart
---


# Question
Title: Can you make a block appear only in a specific content-type
The natural option is to filter blocks by node ID's. I am looking for a way to filter it by content-types (i.e the block "roses in special prices!" will appear only at the content type "Flowers").

Google search didn't help me very much in this subject. Thank you for your help.

# Answer
> 1 votes
In the block configuration page, select the content type like this picture:

---
Tags: blocks, nodes
---


title: Limiting User Permissions

text:
# Question
Title: Limiting User Permissions
I have 3 sets types of users admins, writers & paid writers. Drupal has a built in administer role but not a limited administer role. I want the paid writer role to control some permissions but not all permissions of writers (like the types of content they can create). Is there a place to do this in Drupal?

# Answer
> 1 votes
In the `admin/people/permissions` set `Administer permissions` for the `paid writer` role:

---
Tags: users
---


title: path aliases in drupal 7

text:
# Question
Title: path aliases in drupal 7
I want to calculate the path aliases for array of nids. But it always give me the path for latest content. Actually I can not get all the nids. My array structure is like below. When I used the command `product_childnid = array_pop(array_keys($result['node']));` I always get the `100` nid but I want all of them for path aliases.

```
Array
(
[node] => Array
    (
        [78] => stdClass Object
            (
                [nid] => 78
                [vid] => 78
                [type] => product
            )

        [80] => stdClass Object
            (
                [nid] => 80
                [vid] => 80
                [type] => product
            )

        [82] => stdClass Object
            (
                [nid] => 82
                [vid] => 82
                [type] => product
            )

        [84] => stdClass Object
            (
                [nid] => 84
                [vid] => 84
                [type] => product
            )

        [86] => stdClass Object
            (
                [nid] => 86
                [vid] => 86
                [type] => product
            )

        [88] => stdClass Object
            (
                [nid] => 88
                [vid] => 88
                [type] => product
            )

        [90] => stdClass Object
            (
                [nid] => 90
                [vid] => 90
                [type] => product
            )

        [92] => stdClass Object
            (
                [nid] => 92
                [vid] => 92
                [type] => product
            )

        [94] => stdClass Object
            (
                [nid] => 94
                [vid] => 94
                [type] => product
            )

        [100] => stdClass Object
            (
                [nid] => 100
                [vid] => 100
                [type] => product
              )
          )
  )

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'product');
$query->propertyCondition('status', 1);
$query->fieldCondition('field_product_sub_cat', 'tid',array($leaf_nodes));
$result = $query->execute();
if (isset($result['node']))
{
  $product_childnid = array_pop(array_keys($result['node']));
}
$path = 'node/'.$product_childnid;
$product_alias = drupal_get_path_alias($path);

```

# Answer
> 0 votes
You have to ***iterate*** over all nodes in `$result` to do that. array\_pop() only returns the last item in $result. So you'll have to do something like this:

```
$paths = array();
if (isset($result['node']))
{
  foreach($result['node'] as $key => $node) {
    $paths[$node->nid] = drupal_get_path_alias("node/$node->nid");
  }
}

```

After this `$paths` will contain an array of keys that map to each node id with a value that corresponds to its alias path.

---
Tags: 7, path-aliases
---


# Question
Title: How to clear ALL cache, including field and filter caching of nodes and fields?
I'm working on a text format filter module. Now, somehow Drupal keeps the node content in some cache that is not refreshed with `drush cc all`, which I would have hoped to "clear all cache". This is with *Cache pages for anonymous users* and *Cache blocks* disabled.

I wrote a little script that adds `" "` at the end of the node body, but even running that between two `drush cc all`s doesn't cut it, still with cache disabled. It's really strange. If I go to a page I haven't accessed yet, it will show me an old version what was filtered. So I'm tempted to now also let the script access the specific node over HTTP...

Is there an easy way to really clear all cache? I guess dropping and recreating all `cache_*` tables could cut it but that seems a bit convoluted.

# Answer
> 1 votes
"All" cache doesn't include the filter cache and if you are working with filters then that's the one you most likely want to clear.

You can clear the filter cache by truncating the `cache_filter` database table.

If you have drush at your disposal, you can run `drush sqlq "truncate table cache_filter;"` to get the intended result.

Please note, if you are using database prefixing you will need to add the prefix yourself, as the `drush sql-query` command executes the query exactly as provided.

---
Tags: 7, caching
---


# Question
Title: how to make an existing listbox autocomplete
I have made a content type which has a list box field. now I need to change its widget to autocomplete but as you know list box fields does not have autocomplete widget. now I have added 650 contents of that type and changing the field type would be my last solution because I can't spend time in editing 650 contents! so is there any way to add an autocomplete widget to the current list box field?

# Answer
> 2 votes
The list box field does not have `autocomplete` widget unless you use the `taxonomy` terms, and there are already 650 contents and you do not want to edit the content then you should use the Chosen module, the chosen module will allow you to search within the list. here is the examples page http://harvesthq.github.io/chosen/

following is the module page. https://www.drupal.org/project/chosen

---
Tags: ajax, entities
---


# Question
Title: Images Not Uploading to sites/default/files/*
I transferred my website to a live hosting from my local computer. Now the image files don't seem to upload to the correct folders. The images that I added while the site was local appear fine, but if I try to add new ones the preview is broken. However, if I click the link next to the preview I get the image. It seems like the images are not going into the sites/default/files/style/... sub directories. All of directories have permissions of 0755 or 0775.

# Answer
Please check `admin/config/media/file-system` page on your site to see if the file directories are set correctly and accessible by Drupal. It's possible the server is configured differently from your local installation or the relative directories are set incorrectly in the configuration fields.

As for the comments about permissions and ownership - it seems you can run `chmod` on the directory, so the intention was that you would run `chown` on the directory to set the owner to the Apache group (on Ubuntu it `www-data`).
> 0 votes

---
Tags: media, files
---


# Question
Title: Drupal in subfolder, clean urls and images (htaccess not quite right)
I have my Drupal installation in a subfolder and it's working ok, but there's one problem. New images can't be generated from image styles unless clean urls are turned off.

This is my .htaccess in the root:

```
Options -Indexes
RewriteEngine on
Options +FollowSymLinks
RewriteBase /
# Redirect all user to without WWW
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

#files
RewriteCond %{REQUEST_URI} ^.*\.(jpg|jpeg|gif|png|css|js|pl|txt)$
RewriteCond %{REQUEST_URI} !^/drupal/
RewriteRule ^(.*)$ /drupal/$1 [L,QSA]

#url 's
RewriteCond %{REQUEST_URI} !^/drupal
RewriteRule ^(.*)$ /drupal/index.php?q=$1 [L,QSA]

```

The htaccess in drupals folder is just as normal, just uncommented RewriteBase /drupal.

I understand what the problem is, the files are redirected directly to where they are, not going through Drupals system, which becomes the case when clean urls are turned off. But this is the only version of a htaccess file that works, and I've tried several. If I rewrite the files to /drupal/index.php?q=$1 images in the stylesheet and the logo and other images like that aren't displayed.

Would appreciate any help!

# Answer
> 0 votes
The ultimate goal here is to get any request to the base domain (http://www.example.com) redirected the drupal subdir (http://www.example.com/drupal), correct? Why not just remap everything to the subdir and let Drupal handle the www. prefix and clean-url mapping?

```
RewriteCond %{REQUEST_URI} !^/drupal
RewriteRule ^(.*)$ /drupal/$1 [L,R=301]

```

---
Tags: media, .htaccess, uri
---


# Question
Title: How to let users choose one role from 2 offered on their account page?
I have Drupal 7 installed on my local WAMP server.

I need some simple solution to let users choose one role from 2 offered on their account page AFTER registration.

Is it possible to do it with the Rules module? - when a user follows one of the 2 links he is assigned the corresponding role. The problem is I cannot find the proper Rules Event that could initiate this process.

As the last resort I would probably have to use the Auto Assign Role module.

# Answer
Using Rules, I would do it this way (untested):

* Create a user field, select list (or radio button, whichever you prefer) - we will call this field\_user\_role\_choice with the options (Role1Name, Role2Name)

First Rule:

* Create a new Rule, React on Event: After updating an existing user account

If you don't assign a default value,

* Condition: Data value is empty - selector: account:field\_user\_role\_choice, Negate (this is to ensure it doesn't trigger on a registration or if the user doesn't select a role)
* Condition: Data comparison - selector: account:field\_user\_role\_choice, value: Role1Name key
* Actions: Add User Role - whichever role is associated with Role1Name
* Actions: Remove a User Role - whichever role is associated with Role2Name (this is to prevent both roles being assigned to one person)

Second Rule:

* Create a new Rule, React on Event: After updating an existing user account

If you don't assign a default value,

* Condition: Data value is empty - selector: account:field\_user\_role\_choice, Negate (this is to ensure it doesn't trigger on a registration or if the user doesn't select a role)
* Condition: Data comparison - selector: account:field\_user\_role\_choice, value: Role2Name key
* Actions: Add User Role - whichever role is associated with Role2Name
* Actions: Remove a User Role - whichever role is associated with Role1Name (this is to prevent both roles being assigned to one person)
> 1 votes

# Answer
This is what you need Auto Assign Role

> The second is to allow the end user the option of choosing their own role or roles when they create their account
> 0 votes

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


# Question
Title: Implement hook_node_access based on field value
I need to implement hook\_node\_access based on field value, which I can get only via $form variable. At the moment I cannot do this because I only have variables ($node, $op, $account) available in hook\_node\_access. Could you please help me to find the way how to implement something like:

if ($form\['...'\]\['...'\] == 'TRUE') {return NODE\_ACCESS\_ALLOW;}

# Answer
> 0 votes
You don't need the node form to access its fields to check for conditional access. Use the field data in your node object.

```
if($node->my_field_name[LANGUAGE_NONE][0]['value'] == 'TESTED_VALUE') {
  return NODE_ACCESS_ALLOW;
}

```

---
Tags: users
---


title: form attached JS attributes

text:
# Question
Title: form attached JS attributes
I'm trying to convert this:

```
<script type="text/javascript" data-main="/Scripts/submenu/main" src="/Scripts/require.js"></script>

```

into something like this:

```
$form['#attached']['js'] = array(
        libraries_get_path('lib').'/Scripts/require.js' => array(
            '#attributes' => array('data-main' => 'main'),
        ),
);

```

but I can't seem to find the way to add an attribute :( Any Ideas?

# Answer
From what I remember, `drupal_add_js`, which ultimately is called, doesn't support attributes in the script element. You can use `drupal_add_html_head` to add js with other attributes; the docs page has some examples on how to do this.
> 3 votes

---
Tags: 7, forms, javascript
---


# Question
Title: how to display fetched record from database in a table
I am fetching records from a custom table and want to display it in a table. Here is my custom table structure:

```
nid | sku    | orderIn | orderOut
1   | prod-1 | 200     | 20
2   | prod-1 | 230     | 10
3   | prod-1 | 250     | 20
4   | prod-1 | 200     | 20

```

Here is the function where I am using my query to fetch the records from the database. The problem is that `drupal_set_message()` doesn't print the array.

```
     function formModule_menu() {
      $items = array();

      $items['form/formModule/reviewOrder'] = array(
        'title' => 'Review Order',
        'page callback' => 'formModule_page',
        'access arguments' => array('access simple page'),
        'access callback' => TRUE,

        'type' => MENU_NORMAL_ITEM,
        'weight' => 3,
      );

      return $items;
    }

function formModule_page() {
  return array('#markup' => '<p>' . t('Review Order: The table below shows the TOTAL STOCK and TOTAL QUANTITY of product purchased.') . '</p>');
  // We are going to output the results in a table with a nice header.
  $header = array(
    // The header gives the table the information it needs in order to make
    // the query calls for ordering. TableSort uses the field information
    // to know what database column to sort by.
    array('data' => t('S.No.'), 'field' => 't.S.No.'),
    array('data' => t('Product Name'), 'field' => 't.Product Name'),
    array('data' => t('Total Stock'), 'field' => 't.Total Stock'),
    array('data' => t('Total Purchasing'), 'field' => 't.Total Purchasing'),

  );

  $query = db_select('formmodule_order', 't'); // Using the TableSort Extender is what tells the
                           // the query object that we are sorting.
  $query->fields('t');

  $result = $query
    ->orderByHeader($header) // Don't forget to tell the query object how to
                             // find the header information.
    ->execute();

  $rows = array();
  foreach ($result as $row) {
    // normally we would add some nice formatting to our rows
    // but for our purpose we are simply going to add our row
    // to the array.
    $rows[] = array('data' => (array) $row);
  }

  // build the table for the nice output.
  $build['formmodule_order'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  );

  return $build;
}

```

# Answer
You miss a **fetching function** after your query is executed. You can use `while($row = $result->fetchAssoc()) {` instead of `foreach ($result as $row) {`
> 1 votes

# Answer
As Gregory mentioned, you would need to use fetch statement after calling `execute()`.

Check all available fetch functions in the documentation.

Or use db\_query() instead. The `db_query` is still valid in D7, but db\_select() is recommended.
> 0 votes

# Answer
The main error in your code is the first line of `formModule_page()`.

```
return array('#markup' => '<p>' . t('Review Order: The table below shows the TOTAL STOCK and TOTAL QUANTITY of product purchased.') . '</p>');

```

Since that line is a `return`, the rest of the code will never be executed.

The other error is in the following code.

```
$query = db_select('formmodule_order', 't'); // Using the TableSort Extender is what tells the
                       // the query object that we are sorting.
$query->fields('t');

$result = $query
  ->orderByHeader($header) // Don't forget to tell the query object how to
                         // find the header information.
  ->execute();

```

That code is not using the TableSort extender, since the `$query` object is not extended. As consequence of this, the method `orderByHeader` is not recognized: SelectQueryInterface doesn't define it.
The correct way is invoking SelectQuery::extend(), as in the following code.

```
$query = db_select('formmodule_order', 't')
  ->fields('t');

$query = $query->extend('TableSort');

$result = $query
  ->orderByHeader($header)
  ->execute();

```
> 0 votes

# Answer
### `hook_menu()` implementation

```
function formModule_menu() {
  $items = array();

  $items['form/formModule/reviewOrder'] = array(
    'title' => 'View Order',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_display'),
    'access callback' => TRUE,
    'file' => 'formModule_display.inc',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 3,
  );
  return $items;
}

```

### yourmodule.inc file

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

  // The form we are building
  $form = array();

    $query = db_select('formmodule_order', 'h')
   ->fields('h',array('nid','sku','orderIn','orderOut','created'));

    $result = $query->execute();
   //print_r($row->sku);

   $form['requests'] = array('#prefix' => '<div id="interview-request">',
                            '#suffix' => '</div>',
                            '#tree' => TRUE,
                            '#theme' => 'table',
                            '#header' => array(t('Product ID'), t('Product Code'), t('Product Stock'), t('Product Purchased'), t('Created')),
                            '#rows' => array(),
                            );

 while($row = $result->fetchAssoc()) {

     //   print_r($row);
    //$debug .= '<br/>Header Record #'.' <pre>' . print_r($row, true) . '</pre>';
  $nid = array('#id' => 'id',
                 '#type' => 'markup',
                 '#markup' => '<b>' . $row['nid']. '</b>',
                 );
    //drupal_set_message('<pre>' . print_r($nid, true) . '</pre>');
    $sku = array('#id' => 'sku',
                     '#type' => 'markup',
                    '#markup' => '<b>' . $row['sku'] . '</b>',
                 );
    //drupal_set_message('<pre>' . print_r($sku, true) . '</pre>');
   $orderin = array('#id' => 'orderin',
                 '#type' => 'markup',
                 '#markup' => '<b>' . $row['orderin']. '</b>',
                 );
            //   print_r($orderin);
    //drupal_set_message('<pre>' . print_r($nid, true) . '</pre>');
    $orderout = array('#id' => 'orderout',
                     '#type' => 'markup',
                    '#markup' => '<b>' . $row['orderout'] . '</b>',
                 );
    //drupal_set_message('<pre>' . print_r($orderOut, true) . '</pre>');
    $created = array('#id' => 'created',
                     '#type' => 'markup',
                    '#markup' => '<b>' . $row['created'] . '</b>',
                 );
    $form['requests'][] = array('nid' => &$nid,
                                'sku' => &$sku,
                                'orderIn' => &$orderin,
                                'orderOut' => &$orderout,
                                'created' => &$created,
                                );
    $form['requests']['#rows'][] = array(array('data' => &$nid),
                                         array('data' => &$sku),
                                         array('data' => &$orderin),
                                        array('data' => &$orderout),
                                         array('data' => &$created),
                                         );
    unset($nid);
    unset($sku);
    unset($orderin);
    unset($orderout);
     unset($created);

  }

  return $form;

}

```
> 0 votes

# Answer
Maybe consider another approach, using the Forena module. It is built of the idea of using SQL to get data out of a database (which can be the Drupal database or an external one such as My SQL, Oracle, MS SQL, ...) and use XHTML and CSS to format it into web reports. There are quite some reasons for considering Forena. Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links. Refer to its community documentation for a lot more details.

To answer this specific answer I'd use its typical report writing features to build the report (the content of the custom table to be displayed), and then use the most appropriate site building feature(s) to actually visualize these reports. As a variation, use the available hooks provided by Forena in your custom module. The forena documentation that gets installed with the module also includes a chapter about (a) these site building features and (b) the available hooks, as shown also in the demo site (via the various links near the bottom of that link).

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

---
Tags: forms
---


title: How to unpublished a node from a view?

text:
# Question
Title: How to unpublished a node from a view?
I have a list of all nodes (in my specific case Product Display, generated in Commerce kickstart) using a view. Is there a quick way I can have an unpublish/publish option right there in the view results list? I'd like to avoid the following everytime I need to perform this operation.

1. browsing to **Node/Edit**
2. selecting the **publish options** tab
3. (un)ticking **Published**
4. hitting Save

Does anyone know of a simple way?

# Answer
I suppose you could use Views Bulk Operations (VBO) to achieve this. VBO lets you select various nodes in a list and then perform an action to all of them. VBO is highly customizable and extendible. VBO can be combined with other modules like mighty Rules and others. Bulk publishing and unpublishing would (of course) also be possible.

ps: actually this could also be achived through the 'regular' content handling (/admin/content). Just set the content type filter to your content type and you can already bulk publish/unpublish. But I suppose you tried this already and would prefer to have the same nodes as you have in the view?
> 3 votes

---
Tags: views, nodes
---


# Question
Title: output same form buttone on same page - drupal_render($form
I try to duplicate form button on the same page. The button is printed like this

```
drupal_render($form['continue_shopping']);

```

The problem is that once I render the button, the second one is not rendered again later in DOM. How to overcome this? Thank you

# Answer
From the top of my head, I would just duplicate the button in `hook_form_alter()` and render it as two separate buttons.

Some code examples here: https://www.drupal.org/node/1415334

And here: How to add extra save buttons
> 1 votes

---
Tags: 6, forms
---


# Question
Title: How to search and replace content type (system)name in database for product types
Using Commerce kickstart, I wanted to replace the existing example content type names with other names. I downloaded the database, applied a search and replace, and after uploading the database and clearing caches, the website now shows new content types plus the old ones. It appears that the website has recreated the old content types..but I have no idea what does that and how to prevent that. Any ideas?

# Answer
> 0 votes
It appears that commerce kickstart uses features in order to create the demo store, and that the content types cannot be deleted. Apparently they are recreated by features when the machine name of the content type is not present any more.

See https://www.drupal.org/node/1796468

---
Tags: commerce, nodes, database
---


title: Some errors when I save my content

text:
# Question
Title: Some errors when I save my content
I have some errors when I try to validate my content, I add a lot a modules at the same time, and I don't know witch module causes this error. I uninstalled some of them without success, Is it some explanation in the following errors for the specialists you are?

```
Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1108 dans /var/www/V1/modules/node/node.module).

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1134 dans /var/www/V1/modules/node/node.module).

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1140 dans /var/www/V1/modules/node/node.module).

PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nid' cannot be null: INSERT INTO {location_instance} (nid, vid, uid, genid, lid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => cck:field_endroit: [:db_insert_placeholder_4] => 9 ) dans location_save_locations() (ligne 1132 dans /var/www/V1/modules/location/location.module).

```

# Answer
The error is related to the location module. Uninstalling that module will remove the errors.
> 0 votes

---
Tags: database
---


# Question
Title: Creating menu items for views during installation of a custom install profile fails
I have created a custom installation profile in which I enable some default features and modules. In the profile I added an extra task at the end in witch I enable a custom deployment module.

That deployment module I then use to enable all project specific stuff. I do this using update\_N functions and a script that runs through all the updates on installation of the deployment module.

One of the last updates contains the activation of some features that have a view with a page in code, each with a path but no menu item. I need those menu items but I don't put them in the view to prevent that the view is marked overridden when a user decides to change the menu title of a menu item.

That's why I run another script in a following step that creates default menu items for each view using the menu\_link\_save function.

The problem is that I can trace the creation of a menu item during installation (I get an mlid back) but when installation is done there are no menu items for the views.

As I understood from another Drupal Question (Drupal installation profile: menu\_link\_save() doesn't work for "import" path) the problem is that the path's of the views are not defined yet at that moment.

Any suggestions on how to create menu items on installation within an update of that deployment module or is this never going to work?

Thanks in advance! Hatznie.

# Answer
I've found it! Adding "'customized' =\> 1" to the options of each menu item did the trick.
> 1 votes

---
Tags: views, routes, deployment, updating, installation-profiles
---


# Question
Title: How to exclude certain variable from the Feature code?
In my Feature I wanted to add the multilingual `path_breadcrumbs_home_link_title` for `en` and `de`, but when generating the feature by including the `realm_variables` there is the `site_name` and `site_slogan` in the `en` array included too.

The `site_name` is a mandatory field, so I can not just leave it empty.

The generate file looks like this:

```
<?php

/**
 * Implements hook_variable_realm_default_variables().
 */
function foo_variable_realm_default_variables() {
  $realm_variables = array();
  $realm_variables['language']['de'] = array(
    'path_breadcrumbs_delimiter' => '»',
    'path_breadcrumbs_home_link_title' => 'Startseite',
  );
  $realm_variables['language']['en'] = array(
    'path_breadcrumbs_delimiter' => '»',
    'path_breadcrumbs_home_link_title' => 'Home',
    'site_name' => 'Demo Site',
    'site_slogan' => '',
  );
  return $realm_variables;
}

```

The site name would overwrite all the site names of any already deployed Drupal site.

I don't understand why it doesn't appear in the `de` array even while site name is set there too.

How can I get rid of this?

Any workarounds?

# Answer
> 1 votes
The `hook_features_export_alter` would allow you to alter the final array of Component names to be exported, just prior to the rendering of defaults.

This allows feature modules a final say in whether or not certain Components are exported.

However the Components' actual data cannot be altered by this hook, so I'm not sure if that actually helps.

Example:

```
function hook_features_export_alter(&$export, $module_name) {
  // Example: do not allow the page content type to be exported, ever.
  if (!empty($export['features']['node']['page'])) {
    unset($export['features']['node']['page']);
  }
}

```

---
Tags: i18n-l10n, features
---


# Question
Title: I got duplicated modules after updating an installation. How to remove them?
I have a site built using the Commerce Kickstart profile. Then there are enabled modules provided by the distribution at:

> profiles/commerce\_kickstart/modules/contrit

and also there are modules which I added at:

> sites/all/modules

The distribution added some modules: colorbox, entity, etc. in its last version.

The problem is that I already had these modules at sites/all/modules.

The I got those modules duplicated at:

> profiles/commerce\_kickstart/modules/contrit/colorbox

and

> site/all/modules/colorbox

I guess this is wrong. My question is which folder do I have to delete?

# Answer
> 2 votes
Here are the steps I would perform to address this question, in the specified order:

1. Download and unpack a fresh copy of the new Commerce Kickstart release.
2. Create a list of all your modules in your sites/all/modules folder, and identify all modules in there with the same name (module namespace) as in the new Kickstart release. The result should be a list of the duplicate modules that need to be resolved.
3. Use the Hacked! module to identify any hacks, patches, customizations, etc that might have been applied to any of these duplicate modules in the sites/all/modules folder.
4. Disable and uninstall the duplicate modules.
5. Backup and then delete the entire folder of each of the duplicate modules in the sites/all/modules (or move them to a folder outside your Drupal root directory).
6. Enable the fresh copy of the new Kickstart release. That inherently will also re-enable the vanilla version of the duplicate modules, as contained in the new Kickstart release.
7. Reply any hacks, patches, customizations, etc that are appropriate to be re-applied (e.g. because upgrading to the new Kickstart release does not make them obsolete).
8. Should you run into weird problems because of some of the duplicate modules being moved to another directory, then download and enable the Registry Rebuild module (and/or related `Drush RR` command). That will probably resolve those problems.

---
Tags: 7, distributions
---


# Question
Title: Is it possible to change the path of modules/themes installed using an installation profile?
I have a site which has a profile which downloads a number of modules using `drush make`. It adds the modules in the path /profiles/*profile\_name*/modules.

Is it possible in the make file of the profile to change the path to where the modules and themes are put, so that they are then installed in sites/all/modules and sites/all/themes?

# Answer
> 1 votes
If you have already installed the profile — no, you can't move modules by modifying make file. Profile's `.make` file is used only during installation process.

If you want to replace modules from `profiles/%PROFILE_NAME%/modules/` to `sites/all/modules` on already installed copy of Drupal, you can just replace files (with `mv` or something) and then run `system_rebuild_module_data()` function to ask Drupal to update modules destination. With Drush:

```
drush eval "system_rebuild_module_data();"

```

For profile installation process — I really don't know why and don't know how to modify `.make` file. Maybe you can specify `'contrib_destination'` property for every project?

# Answer
> 0 votes
Isn't that what the `[destination]` is for? Take a look into the openatrium.make file

# Answer
> 0 votes
As an alternative to using `system_rebuild_module_data` (mentioned in another answer here), you can use contributed module "Registry Rebuild". That module integrates with Drush via the `Drush RR` command.

Basically what you do is to (1) just move your modules to another directory, and (2) Registry Rebuild will then rebuild the system table to get the modules in the right place.

I first learned/discovered it via DrupalEasy Podcast #133, which further explains how this module / drush cmd can be used.

---
Tags: 7, distributions, drush
---


# Question
Title: How to enforce role selection on the user's create, so they can edit other certain users?
I have three roles.

* registry
* teachers
* students

How do I enforce role selection on user's creation?

2. I want the registry role to create and edit users (**ONLY** teachers or students role).

# Answer
> 1 votes
Look at Auto Assign Role module. This documentation will help you.

# Answer
> 0 votes
1. Look at Profile2 & Profile2 Registration Path for having multiple role signup forms.
2. For limited role assignment checkout RoleAssign.

---
Tags: users
---


title: Drupal Restful API

text:
# Question
Title: Drupal Restful API
I have quick question about Drupal Restful API modules.

There is a restful web services module https://www.drupal.org/project/restws and there is another restful module https://www.drupal.org/project/restful

I cannot figure what's the exact difference between the two. As, both supports CRUD operations, json format. So, what's the exact difference between two.

Thanks!

# Answer
> 2 votes
One of the maintainers of the module gave a good explanation on this issue:

> Here are the differences between RESTful and other modules, such as RestWs and Services Entity:
>
> * RESTful requires explicitly declaring the exposed API. When enabling the module, nothing happens until a plugin declares it.
> * Resources are exposed by bundle, rather than by entity. This would allow a developer to expose only nodes of a certain type, for example.
> * The exposed properties need to be explicitly declared. This allows a clean output without Drupal's internal implementation leaking out. This means the consuming client doesn't need to know if an entity is a node or a term, nor will they be presented with the field\_ prefix.
> * Resource versioning is built-in, so that resources can be reused with multiple consumers. The versions are at the resource level, for more flexibility and control.
> * It has configurable output formats. It ships with JSON (the default one), JSON+HAL and as an example also XML.
> * Audience is developers and not site builders.
> * Provide a key tool for a headless Drupal. See the AngularJs form example module.

---
Tags: 7
---


# Question
Title: How do I insert multi image with restFul service?
I have a little issue I try to add to my node with RESTful service on Drupal 7 multiple `fid`s for a image gallery and I can't finish the process, I try

```
'field_gallery[und][0][]' => array(
  'fid:2381',
  'fid:2375',
),

```

and I don't know where I do it wrong. This is a request with php curl.

```
<div class="image-widget-data"><input type="file" class="form-file" size="22" name="files[field_gallery_und_0][]" id="edit-field-gallery-und-0-upload" multiple="multiple">
  <input type="submit" class="form-submit ajax-processed" value="Upload" name="field_gallery_und_0_upload_button" id="edit-field-gallery-und-0-upload-button">
  <input type="hidden" value="0" name="field_gallery[und][0][_weight]">
  <input type="hidden" value="0" name="field_gallery[und][0][fid]">
  <input type="hidden" value="1" name="field_gallery[und][0][display]">
</div>

```

# Answer
I think what you really want is to end up with something more like:

```
'field_gallery[und][0]' => 2381,
'field_gallery[und][1]' => 2375,

```

The second level of array indexing is the field position. So the first file id goes into `[0]` and the second into `[1]`.
> 1 votes

---
Tags: hooks, media
---


# Question
Title: how to open a link field in new window in view
In views,for image field, I have selected "output this field as link" and in link path, I wrote "node/\[nid\]". Link works and open in same window. How to open the link in a new window? I dont see any option in view.

Thanks

# Answer
1) Click your image field at your views 2) Click Rewrite results. Check Output this field as a link. Key in your URL in the Link Path

) 3) At Target text field, key in this "\_blank"
> 3 votes

# Answer
To do so programmatically, you need to define `ThemeName_preprocess_views_view_fields` function. Then in this function you should theme the views output. If the image field name is `field_image` then write:

```
function ThemeName_preprocess_views_view_fields(&$variables)
{
      $view = $variables['view'];
      if($view->name == "TheViewName")
      {
           $variables['image'] = $variables['fields']['field_image']->FIND THE IMAGE PATH BY DEVEL MODULE;
           $variables['link'] =  $variables['fields']['field_image']->FIND THE IMAGE LINK ADDRESS BY DEVEL MODULE;
      }
}

```

Then create `views-view-fields--TheViewName--DisplayNameOfView.tpl` file and in this file write

```
$image = strip_tags($image) ;
<a href="<?php print $link?>" target="_blank"><img src="<?php print $image;?>"</a>

```

Notice that you should install devel module to get required information about the image, its link and etc.

Clearly in this method you will have more choices of displaying the link and you can also use this method to open the image in a popup window.

This is the main idea of doing this and I always use this. I didn't test this code but a few modification might be needed. for example in `views-view-fields--TheViewName--DisplayNameOfView.tpl` you can use `<?php print $fields['field_image']->content; ?>` to output the entire linked image.
> 1 votes

---
Tags: views
---


# Question
Title: How to display the alt below images in Panels?
I have a drupal site which sells variety of products. I set a content type for my product and use panel for the layout. Basically, the text is on left, and images on right Is there anyway So I can Display the alt text below images because they are very valuable keywords for SEO and customer. I can't find the any tokens of node field to import into panel.

Can anyone help me with this? Thank you very much.

# Answer
If you add your images by using content and content type, this might help.

Content type -\> one of the list -\> manage field

click on image hyperlink follow by edit tab

Check Enable Alt field and it wil appear in edit content.

Hope this help.
> 1 votes

---
Tags: media
---


# Question
Title: Show full content of related entity using Entity Reference in node view
Basically I've created a relationship between two content types: Testimonials and Case Study as follow: in Case Study I've created a field *Testimonial* using the Entity Reference widget.

When I create a *case study* type of content I can choose a *Testimonial* to link with this case study. So far so good.

My question is this: When I view the newly created Case Study content, I can only see the title of testimonial but none of the additional field available in the testimonial content type.

In order to view the full content, do I need to create a View for it or is there a way to display the full content as it is?

Thanks

# Answer
> 1 votes
You don't need a view for this. Instead, you can set the display settings for your entity reference field to *Full display*.

On *Structure \> Content types \> My content type \> Manage display*, for the entity reference field choose *Rendered entity* as format. You can then have *Full content* as a view mode.

>

---
Tags: views, entities
---


# Question
Title: How to hide a form element having a certain class in ajax callback in form?
How can I hide the product using ajax callback . I am trying to implement that using ajax\_commands\_invoke but it does not work using below code

```
  $form['field_product_type_select']['und']['#ajax']= array('callback' => '_change_table_product_type','wrapper' => 'display-table-ajaxify');
 $header = array(
   'field_name' => t('Field Name'),
   'field_type' => t('Field Type'),
   'field_no_of_values' => t('Single/Multi Value'),
 );
 $options = array();

 foreach(commerce_product_types() as $product_type => $product_type_array){
   $field_info_instances = field_info_instances('commerce_product',$product_type);

   foreach($field_info_instances as $key => $value){
   $field_info_types = field_info_field_types($value['type']);
   $options[$key] = array(
     'field_name' => $value['label'],
     'field_type' => $field_info_types['label'],
     'field_no_of_values' => $value['cardinality'],
   );
  }

 $form['display_table'][$product_type] = array(
   '#type' => 'tableselect',
   '#options' => $options,
   '#header' => $header,
   '#multiple' => TRUE,
   '#prefix' => '<div class="display-'.$product_type.'" id="display-table-ajaxify" style="display:none;"><b>'.\
$product_type_array['name'].'</b>',
   '#suffix' => '</div>',
 );
 }

function _change_table_product_type(&$form,&$form_state){
  $commands = array();
  $product_type = $form_state['values']['field_product_type_select']['und'][0]['value'];
  drupal_set_message($product_type);
  $commands[] = ajax_command_invoke('display-'.$product_type,'show');

  /* $product_type = $form_state['values']['field_product_type_select']['und'][0]['value']; */
  /* foreach ($form['display_table'] as $key => $value){ */
  /*   if ($key != $product_type) { */
  /*     unset($form['display_table'][$key]); */
  /*   } */

  /* } */
  //  return $form['display_table'][$product_type];
  //  return array('#type' => 'ajax', '#commands' => $commands);
  print ajax_render($commands);
}

```

# Answer
AJAX Commands are supposed to be returned in the callback function, not printed. Also, you have to give a CSS valid selector.

Try this:

```
function _change_table_product_type(&$form,&$form_state){
  $commands = array();
  $product_type = $form_state['values']['field_product_type_select']['und'][0]['value'];
  drupal_set_message($product_type);
  $commands[] = ajax_command_invoke('.display-' . $product_type, 'show');

  return array('#type' => 'ajax', '#commands' => $commands);

}

```

You can show the actual selector that code generates and test it in the JavaScript console. Just type:

```
 jQuery('CSS_SELECTOR').show();

```

If element is shown your CSS selector code is right.
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Repeat the alt text and title text for a series of image field values
I have created a content type for an image gallery, and added an image field with alt text and title tags and gave unlimited upload feature.

If I upload 10 images I want to give the title and alt tags 10 times. Can I bypass each individual image by giving these details one time and applying for all subsequent images?

Is this possible to do via the Drupal admin UI?

# Answer
> 0 votes
You could just implement a custom template for your field and implement whatever logic you require there.

So, in admin, you could enter the alt and title just for the first image, and then with the template you could apply the alt and title to all the images.

Does that make sense to you ?

# Answer
> 0 votes
I not sure will this help you. You can use node clone module. What you need to do is clone the node and change the picture. https://www.drupal.org/project/node\_clone

---
Tags: media
---


# Question
Title: Image re-sizing while uploading via drupal 7 dashboard
I am looking for an option to re-size the images while uploading from a content type.

I can set the max upload size to 8 mb and while user uploads the images it should be resized to a lesser size automatically.

How can i do it?

# Answer
Follow the steps.

1) Add new image style from Configuration-\>image style

2) Go to your content type and Edit the image field

3) Select your newly created image style from the "preview image style" dropdown list and then save settings.

Now the images will be resized according to your created style.
> 1 votes

# Answer
You should check these modules:

1. Image Resize Filter :

* Automatically resizes both local and (optionally) remote images.
    * Optionally create a link to full size images from the resized inline versions.
    * Prevents inline "hot linking" of images from other sites by storing them locally.
    * Adds height and width attributes to inline images when your users are too lazy to add them.
2. Image API optimize :

> Despite the name, this module does not depend on ImageAPI. It depends only on the core image.module. Please read the documentation page for more information.
> 1 votes

# Answer
You can define the maximum size for the image field. That means you could have individual settings for every content type and for every image field you use. Just check the settings on `structure > content types > my content type > fields > image field`. The images will then be resized to a maximum size according to your settings.
> 0 votes

---
Tags: media
---


# Question
Title: Changing product price depending on node field in commerce node checkout
i am using `comerce_node_checkout` with `drupal_commerce`

I want to change product price depending on node field .

eg,

I have a field as `field_gender` if we select `male` then price will be `1000.00` or if we select `female` then it will be `500`.

Any help is most appriciable.

Thanks in advance .

# Answer
Ohhh!!!!!!!!

**Power Of Rules**

```
 { "rules_update_amount_female" : {
    "LABEL" : "Update amount Female",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Update amount" ],
    "REQUIRES" : [
      "rules",
      "commerce_line_item",
      "commerce_product_reference",
      "commerce_cart"
    ],
    "ON" : {
      "commerce_product_calculate_sell_price" : [],
      "commerce_cart_product_prepare" : []
    },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item" ],
          "field" : "commerce_node_checkout_node"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-node-checkout-node" ],
          "field" : "field_ap_gender"
        }
      },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-node-checkout-node:field-ap-gender" ],
          "value" : "Female"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "500",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Display a Quicktab content in Colorbox pop-up Drupal 6
I have a quick tab (*Drupal 6*) which contains three tabs. One of it has a table which is larger in size. Hence, when the third tab was clicked I need to show the third table as a **Popup** using **Colorbox**.

I have that table as a node Page and I want to display that node as a Popup.

# Answer
If the Quicktab content is a node or any other internal entity, you can do this by using the colorbox-load class and appropriate href. If you aren't able to alter the links in any of the preprocess functions, you can use JS to accomplish this and use Drupal.attachBehaviors() to add the colorbox functionality.
> 1 votes

---
Tags: 6, javascript, blocks
---


title: Get content page field value

text:
# Question
Title: Get content page field value
I have a content page contain three field. Number A: Number B and Total Number. During add content page, I fill up Number A: 20 and Number B: 30. How to let Total Number auto display 20 + 30 = 50?

# Answer
> 1 votes
What do you mean by content page? if it is the node page and the fields name are `field_number_a` and `field_number_b` then install entity module and in the `template.php` and in `hook_preprocess_node` function and write this:

```
function YourTheme_preprocess_node(&$var){
    if($var['node']->type == "YOUR_CONTENT_TYPE"){
          $wrapper = entity_metadata_wrapper('node',$var['node']);
          $a = $wrapper->field_number_a->value();
          $b = $wrapper->field_number_b->value();
          $var['total'] = $a + $b;
    }
}

```

Then in the node page you can use `$total` variable as the sum of the `a` and `b`

# Answer
> 0 votes
If you want to save the data also in field(Total Number) then you can use hook\_node\_presave for save the data in fields. example :-

```
function yourmodule_node_presave($node){
    //check your content type
    if($node->type == 'page'){
          // check fields are having values
         if(isset($node->field_a['und'][0]['value']) && isset($node->field_b['und'][0]['value']))
         $node->field_total_number['und'][0]['value'] = $node->field_a['und'][0]['value'] + $node->field_b['und'][0]['value'];
    }
}

```

or if you want to display on create page auto upate the field(total number value) after enter the values in field\_a and field\_b, you can use hook\_form\_alter and update value using ajax.

also you can check example module for form alter and how to update fields automatically

# Answer
> 0 votes
Computed Field module can be used for this purpose. It provides an option to define custom fields in the content type and derive their values based on other fields. It also gives you an option to either store the computed value to the database or calculate them on the fly.

The method suggested by @Drupalist computes it on the fly and is invoked before displaying the node page only. This method is not helpful if you intend to use the computed field(total\_number) in a view for example.

---
Tags: 7, nodes, tokens
---


title: Ways to sync outlook calendar?

text:
# Question
Title: Ways to sync outlook calendar?
I need to display the outlook calendar in the same calendar format in a page. I need to add events to the calendar and synchronize it with Outlook.

What module should I prefer to both synchronize with Outlook and display as calendar?

# Answer
Try to use Add to Cal module. I hope this module solve your query.

> A field formatter providing a widget for exporting events to:
>
> * Google Calendar
> * Yahoo! Calendar
> * iCal
> * Outlook
>
> The field formatter provides a button next to the field that shows a drop-down menu. This menu contains links to the supported formats, and includes basic styling that can be easily modified through CSS.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to create image gallery and integrate it to lightbox2
I have a content type *Product* with a field *Images*. There are 4 photos. When i go to the product-node page i want to click on one of the photos (1 of 4) and open a popup/modal window where i would like to see all 4 photos (not only 1, as Lightbox does). How can i do that?

# Answer
> 1 votes
You can do this by using Colorbox module.

> Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal. Images, iframed or inline content etc. can be displayed in a overlay above the current page.

How to use ?

---
Tags: media, javascript
---


# Question
Title: Countdown timer for schedule unpublish date
I am using Scheduler module in order to enable unpublish date for a content type.

Now I want to create countdown timer for the nodes that unpublish date is set for them.

I checked jQuery Countdown and Countdown Timer Field modules but it seems they can't help in this issue.

What is your suggestion? Is there any way to create a relation between node unpublish date and countdown\_timer modules or I must edit source of themes?

Thanks a lot for your help

# Answer
> 1 votes
You could add the snippet below as a new module `scheduler_unpublish_countdown`. It defines a block which you can shown on the node page of any content type you choose and allow it to countdown to the scheduled unpublish time for that node. As the block that comes with the `jquery_countdown` module counts down to a global event; this might be better for your use case.

```
<?php

/**
 * Implements hook_block_info().
 */
function scheduler_unpublish_countdown_block_info() {
  return array(
    'unpublish_countdown' => array(
      'info' => t('Scheduler Unpublish Countdown'),
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

/**
 * Implements hook_block_view().
 */
function scheduler_unpublish_countdown_block_view($delta) {
  if ($delta == 'unpublish_countdown') {
    $node = menu_get_object();
    // Ignore non-node pages, already unpublished nodes, nodes that don't have a
    // date/time set for unpublishing and nodes whose unpublishing date-time is in the past.
    if (!$node ||
      empty($node->status) ||
      empty($node->scheduler['unpublish_on']) ||
      ($node->scheduler['unpublish_on'] <= REQUEST_TIME)) {
      return;
    }
    $variables = array(
      'id' => drupal_html_id('jquery_countdown-' . $delta),
      'options' => array(
        'until' => date("F d, Y g:i a", $node->scheduler['unpublish_on']),
        'description' => ' ', // So that the CSS doesn't get screwed
        // Reload the page when the countdown is done
        'onExpiry' => '(function() { location.reload(); })',
      )
    );
    return array(
      'subject' => t('Scheduled unpublish in..'),
      'content' => theme('jquery_countdown', $variables)
    );
  }
}

```

Once the countdown is complete, the page will simply reload (see `onExpiry` option above). As unpublishing happens only either during the normal Drupal cron run or through the Scheduler's own light-weight variant, it may not happen *exactly* at the time of unpublishing meaning the page would reload and nothing would happen (except for the timer not showing up anymore) which might be slightly awkward.

I'd recommend, therefore, to redirect to a custom page once the countdown expires where you explicitly call `_scheduler_unpublish()` and then redirect back to the node page. You might want to send a one-time-only token along for security.

Remember to add `scheduler` and `jquery_countdown` as dependencies for your new module.

# Answer
> 0 votes
Is the provided solution still operational? I've enabled it as submodule, but I don't seem to see any difference (config / display) after enabling it. Am I overlooking something that should be done before it should work?

---
Tags: nodes
---


title: Templating JSON

text:
# Question
Title: Templating JSON
Is there a way to template the results of a AJAX query that returns JSON data? The JSON is returned to a module.

# Answer
> 0 votes
I would use the hook\_theme and use a custom .tpl file to theme the results of an ajax output by sending the variables to the template(tpl) file using the theme function.

---
Tags: theming
---


# Question
Title: Setup a Tabular View to Include Total Count of Nodes
Need to create a Views page displaying tabular data.

Fields I need are:

1) Total count of nodes created from Content Type A, filtered by US State, and the 2) second field is the total count of nodes created from Content Type B, filtered by US state.

# Answer
Create two block display of a view. The view should contain All content types. displays are `block_1` and `block_2`. set `content type:Content Type A` as filter criteria for `block_1` and `content type:Content Type B` as filter criteria for `block_2`. so `block_1` and `block_2` shows all of the nodes of `A` and `B`. This link shows how to count number of results. Now the following code

```
<?php print views_embed_view('YourView','block_1');?>
<?php print views_embed_view('YourView','block_2');?>

```

outputs the number of results and you can format them in any way you want.
> 0 votes

---
Tags: views
---


title: Drush is pointing to the wrong web site

text:
# Question
Title: Drush is pointing to the wrong web site
Currently drush points it commands to /domains/steve\_public/sites/default. I actually want drush to point its commands to /public\_html/sites/default.

Can anybody advise me to how achieve this? Do I need to do this?

# Answer
You need to specify your Drupal root to Drush in one of several ways:

1. Pass --root=/public\_html --uri=http://example.com as an option on the commandline.
2. Set $options\['root'\] = '/public\_html'; and $options\['uri'\] 'http://example.com' in a drushrc.php (not a good option if you have multiple sites on the system)
3. Use an alias, and set 'root' =\> '/public\_html', 'uri' =\> 'http://example.com' (per the article you quoted)
4. Change your current working directory to '/public\_html/sites/default' before running Drush commands (only works if you don't do any of 1 - 3).
> 2 votes

---
Tags: 7, drush
---


title: Translate page.tpl.php strings

text:
# Question
Title: Translate page.tpl.php strings
I have a custom slideshow and the phrases are all in page.tpl.php (please see figure attached) But they are not dynamic, so they are in PT.

Now I have a multilingual site (I installed all the necessary modules) and everything in my site is working great.

My question is: How can I translate those strings in page.tpl.php to English everytime I switch to EN in my site? Does it require much coding?

Thanks!

# Answer
> 4 votes
Just edit the `page.tpl.php` file and wrap all text in `t()` function.

For example:

```
<p>This is a sample string.</p>

```

Turns into:

```
<p><?php print t('This is a sample string.'); ?></p>

```

EDIT: this will make those strings translatable. After that, use the translation interface to find those strings and translate them in other languages.
If your original question was about where you can translate those strings in the admin, let me know and I'll update the answer.

---
Tags: 7
---


# Question
Title: Commerce- How to add a product image on a product display to the shopping cart summary view
I have two products on my site that are named similarly but easily distinguished by their images. Users sometimes buy the wrong one by mistake, so I want to put the product image on the **Shopping cart summary view**. By default, this view can be used to add fields of products.

My product images, however, are on the **Product display** content type. Though the **Product display** has a product reference to **Products**, there seems to be no way to get the reverse of that relationship (in other words, to get the **Product Display** from the **Product**).

There aren't too many products, so I thought about just adding an image field to **Product** as well and duplicating all the data, but that is definitely a maintenance problem down the line. Is there a way to get the image on the **Product Display** with just the **Product** in Views without duplicating data?

# Answer
You should be able to do it by adding two relationships. First add *Commerce Line item: Referenced products*

and then that allows you to add *Commerce Product: Referencing Node*.

From there you should be able to add and reference fields from your display node.
> 1 votes

---
Tags: commerce
---


# Question
Title: The Drupal way of adding HTML syntax within hook_redirect_alter
I'm trying to setup client-side redirects instead of server-side redirects. Since Varnish is being used for caching, I would like that to remain; so the request should not get to Drupal, Varnish should handle the redirect. Ultimately, using session cookies, I'm trying to have the value for source/referrer path available at the landing page (because redirects clear the original referrer headers).

In Drupal 7, within a custom module, I'm using hook\_redirect\_alter() to stop the redirect process, then print out javascript to the page to do the redirect. My question is, what is the Drupal way of adding the below print statement to the page within this hook?

```
/**
 * Implements hook_redirect_alter().
 */
function mymodule_redirect_alter($redirect) {
  print('
    <html>
    <head>
    <script src="sites/all/modules/contrib/jquery_update/replace/jquery/1.10/jquery.min.js?v=1.10.2"></script>
    <script src="sites/all/modules/contrib/jquery_update/replace/ui/external/jquery.cookie.js"></script>
    <script>
      $(function() {
        var source = $(location).attr("pathname");
        var source = source.slice(1);
        $.cookie("source", source);
        window.location.replace("' . $redirect->redirect .'");
      });
    </script>
    <noscript>
      <a href="/' . $redirect->redirect . '">Javascript is disabled. Click here to continue</a>
    </noscript>
    </head>
    </html>
  ');

  // This kills sever-side redirect
  exit();
}

```

# Answer
Since you cannot specify a 301 redirect in javascript, here is what I did all within hook\_redirect\_alter() :

```
function mymodule_redirect_alter($redirect) {
  // If checkbox is set then use URL parameter for redirect, otherwise ignore everything
  if (variable_get('my_checkbox', '') == '1') {
    $params = drupal_get_query_parameters();
    $my_parameter = variable_get('my_parameter', '');

    // Append redirect values seperated by commas if the specified parameter exists
    if (!empty($params[$my_parameter])) {
      $refs = $params[$my_parameter] . ',' . $redirect->source;
    }
    // Otherwise add souce as the value of the parameter
    else {
      $refs = $redirect->source;
    }

    // Create parameters to append to URL
    $params = array('query' => array($my_parameter => $refs));

    // Do the actual redirect with this new parameter
    drupal_goto($redirect->redirect, $params);

    // This kills sever-side redirect
    exit();
  }
}

```

So the URL mysite.com/original\_page will be redirected to a page with URL mysite.com/mypage?redirect=original\_page
> 0 votes

---
Tags: redirection
---


title: Link field with Browse Server button

text:
# Question
Title: Link field with Browse Server button
Is it possible to add the Browse Server button on Link Field? So user can link to and see internal file or image? I have tried the Linkit module, but that is not really what I want.

# Answer
You can use the IMCE module.

> IMCE is an image/file uploader and browser that supports personal directories and quota.
>
> Features
>
> * Basic file operations: upload, delete
> * Image(jpg, png, gif) operations: resize, create thumbnails, preview
> * Support for private file system
> * Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
> * Personal or shared folders for users
> * Permissions per directory
> * Ftp-like directory navigation
> * File sorting by name, size, dimensions, date
> * Tabbed interface for file operations
> * Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
> * Built-in support for inline image/file insertion into textareas
> * Multiple file selection(using ctrl or shift)
> * Ajax file operations
> * Themable layout using tpl files
> 0 votes

---
Tags: 7, navigation
---


title: Drupal security ACL

text:
# Question
Title: Drupal security ACL
I have a client having website in Drupal . He need to create user and want to assign rights for edit and delete on every column displayed in webpage. I have tried ACL but that didn't work, so Iam planing to have my own code and tables in DB to save table and column permission for each user. But my senior told me that this is security compromise and advise me to use ACL.

What is security risk and what issues can be raised in future if I use my own code and tables to do the job? Plz help me understand this .

Also recommend me how to use ACL or some other work for this scenario....

# Answer
You should use a specific ACL module for Drupal, such as Content Access.

The ACL module does nothing on its own:

> The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.

Here are basic instructions for setting up the permissions, content types and content access:

1. Install Content Access module. *Note:* you will be asked to rebuild the content access permissions. If you have a lot of content on your site, this action may take a while.
2. Create necessary user roles at `Admin -> People -> Permissions -> Roles`
3. Create necessary content types.
4. Go to: Admin -\> Structure -\> Content types -\> Edit \[Your content type\] -\> Access Control tab
5. You can there setup specific permissions for viewing, editing or deleting nodes according to the group a user belongs to.

---

To elaborate more the security risks in handling permissions manually: your senior is right - it is always better to have a centralized system which will manage access control on a website. This way maintenance is easier and you do not need to predict all possible outcomes in order to prevent access to sensitive data at all places.
At some points in custom implementation you might reinvent the wheel, which is completely unnecessary, especially if you can already use an existing framework for setting up those rules.

Imagine the following situations: you blocked direct access to particular nodes using a custom module. What happens if a user goes to /node page and your node is listed there? RSS feed page? What happens on category pages? What happens if you use a contributed module which shows nodes and might possibly expose your sensitive data? What if the modules are updated with a security bugfix and you need to update all your code?
If you are writing those rules manually, you would need to write a solution for all possibilities and still you/someone else be able to maintain that.
Not all problems will be solved by using centralized system, but the risk is significantly reduced; all third party modules are made according to that system. You can call it a convention.

---

By saying that you want them to be able to edit a *column* I guess that you are speaking about nodes. If this is not what you mean, elaborate your question a bit more.
> 1 votes

# Answer
Not totally sure what you mean by columns either, but if you are referring to fields on an entity, you can use Field Permissions (https://www.drupal.org/project/field\_permissions).
> 0 votes

---
Tags: security
---


# Question
Title: Running Drupal 6 with PHP 5.3 and Maintaining Security
I have a number of Drupal 6 sites that I can't upgrade at this time due to sheer lack of time to do so (it would be a major overhaul). Therefore, I am required to continue running PHP 5.3 on my server, but it is already EOL, and there are security fixes that have not been applied to it.

Are there other people here that are using Drupal 6 and PHP 5.3, while keeping their PHP secure? If so, how are they doing it? Is there a source for PHP 5.3 with backported security fixes, like an LTS version? I've seen Zend's version of that, but can't afford it. I saw Red Hat has RPMs with some security fixes backported into PHP 5.3, but not the most recent ones, at least as far as I can tell.

# Answer
> 4 votes
Here are the patches I'm using for D6. Some of these issues will have been committed, thus they don't need a patch anymore.

**Views**
http://drupal.org/node/853864#comment-6465560 \- views\_get\_default\_view() - race conditions and memory usage
http://drupal.org/node/402944#comment-4650020 \- Persistent caching for unpack\_options() calls from building displays
http://drupal.org/node/1372388#comment-5370432 \- Inline/Remove recursion in views\_object-\>unpack\_options to improve performance
http://drupal.org/node/465332#comment-4756670 \- Strict warning: non-static method should not be called statically
http://drupal.org/node/893128#comment-4894754 \- Strict warning: Declaration of * should be compatible with that of views\_handler::\*
http://drupal.org/node/1265138#comment-4928988 \- Notice: Undefined variable: teaser in views\_plugin\_row\_node\_rss-\>render()
http://drupal.org/node/1432242#comment-5807802 \- Notice: Undefined index: size in views\_db\_object-\>export\_row()

**Views Bonus Pack**
http://drupal.org/node/1223910#comment-4756506 \- Strict warning: is\_a(): Deprecated

**Views Bulk Operations**
http://drupal.org/node/1782662#comment-6469236 \- Notice: Undefined index: HTTP\_USER\_AGENT in views\_bulk\_operations\_form()

**Views Datasource**
http://drupal.org/node/1265190#comment-4929150 \- Notice: Undefined property: stdClass::$name in views\_plugin\_style\_xml-\>option\_definition()

**Views Slideshow JCarousel**
http://drupal.org/node/1885586#comment-6926004 \- php notices

---

Here are some of the more popular modules as well

**Calendar**
http://drupal.org/node/999514#comment-4761150 \- Strict warning errors for views plugins

**CCK**
http://drupal.org/node/1118792#comment-4358322 \- array\_keys() expects parameter 1 to be array, null given in content\_multigroup.node\_form.inc
http://drupal.org/node/1244534#comment-4845816 \- Notice: Undefined index
http://drupal.org/node/1247732#comment-4857954 \- Undefined index: \_remove
http://drupal.org/node/1156096#comment-4868230 \- Notice: Undefined index: title/description in content\_storage()
http://drupal.org/node/1251146#comment-4871780 \- Notice: Undefined index: #children in template\_preprocess\_content\_field()
http://drupal.org/node/1251160#comment-4871816 \- Notice: Undefined index: #field\_info in fieldgroup\_form\_alter()
http://drupal.org/node/1265080#comment-4928778 \- Notice: Undefined property: stdClass::$broken in content\_handler\_field-\>render()
http://drupal.org/node/1316510 \- fix undefined index '#id' notice in form\_alter hooks
http://drupal.org/node/533610#comment-5157454 \- Notice: Undefined index: safe in theme\_text\_formatter\_default()
http://drupal.org/node/1762506#comment-6411880 \- Notice: Undefined property: stdClass::$field\_\* in content\_rules\_field\_has\_value()

**CTools**
http://drupal.org/node/1226098#comment-4765262 \- Strict warning: Only variables should be passed by reference
http://drupal.org/node/1334894#comment-5215962 \- Warning: Invalid argument supplied for foreach() in views\_content\_views\_content\_type\_render()
http://drupal.org/node/1510118#comment-5807950 \- Strict warning: Creating default object from empty value in views\_content\_views\_content\_type\_admin\_info()

**Context**
http://drupal.org/node/866208#comment-4845268 \- Notice: Undefined property: stdClass::$taxonomy in context\_node\_condition() on line 352

**Date**
http://drupal.org/node/802722 \- Extra comma in output when using "display from and to dates" on Display fields configuration
http://drupal.org/node/1223956#comment-4756746 \- Strict warning: Creating default object from empty value in date\_handler\_fields
http://drupal.org/node/1948238#comment-7200236 \- Strict warning: Declaration of date\_handler\_field\_multiple::pre\_render()

**Features**
http://drupal.org/node/1516900#comment-5833834 \- Notice: Undefined index: group in views\_handler\_dependencies()
http://drupal.org/node/1515878#comment-5833794 \- Strict warning: Only variables should be passed by reference in content\_features\_rebuild()

**FileField**
http://drupal.org/node/1180508#comment-4872304 \- Warning: array\_merge() Argument #2 is not an array in filefield\_widget()
http://drupal.org/node/1164892#comment-4500360 \- Warning: Trying to get property of non-object in filefield\_field\_sanitize()
http://drupal.org/node/1317424#comment-5146998 \- Notice: Undefined index: fid in filefield\_widget\_process
http://drupal.org/node/1415840#comment-5514392 \- Fatal error: Cannot unset string offsets
http://drupal.org/node/1677208#comment-6213652 \- Notice: Undefined index: data in theme\_filefield\_widget\_preview
http://drupal.org/node/1775708#comment-6440138 \- Notice: unserialize(): Error at offset 0 of 1 bytes in filefield\_get\_node\_files()

**ImageAPI**
http://drupal.org/node/1189884#comment-4608576 \- Allow for custom code to be inserted into the convert command before it is ran
http://drupal.org/node/1201914#comment-4663120 \- Add in the ability to "nice" the convert process
http://drupal.org/node/1250348#comment-4868656 \- Fix divide by zero errors.
http://drupal.org/node/1766064#comment-6434498 \- User error: ImageMagick reported error code 1. Message: convert: no encode delegate for this image format

**Imagecache**
http://drupal.org/node/1243258#comment-4841244 \- use lock.inc instead of a file lock
http://drupal.org/node/1761108#comment-6407780 \- Notice: Undefined index: filepath in theme\_imagecache\_formatter\_default()

**jQuery Update**
http://drupal.org/node/1067290#comment-6516884 \- Fix jQuery 1.7 for Drupal 6

**Rules**
http://drupal.org/node/1250384#comment-4868884 \- Strict warning: Only variables should be passed by reference in rules\_core\_action\_execute()

---

**Core patches**
http://drupal.org/node/496184#comment-5787602 \- db\_set\_active errors out if db\_connect fails. Add in the ability to handle this gracefully (don't always call \_db\_error\_page)
http://drupal.org/node/764726#comment-5787642 \- (Shared taxonomy patch) hook\_taxonomy\_term\_presave() is missing
http://drupal.org/node/905156#comment-5791724 \- PHP notice in form\_builder function
http://drupal.org/node/1006938#comment-4661790 \- Remove PHP warnings from legacy PHP4 XML parser for new update status release history XML
http://drupal.org/node/352180#comment-2562140 \- Better, multi-site friendly "www." addition/removal in .htaccess
http://drupal.org/node/939810#comment-5791876 \- Notice: Undefined index: key in format\_xml\_elements()
http://drupal.org/node/985814#comment-5791916 \- Undefined index: configurable in actions\_synchronize()
http://drupal.org/node/557542#comment-4989990 \- Cache module\_implements()
http://drupal.org/node/1317236#comment-5146174 \- Race condition in file\_delete: Warning: unlink() No such file or directory in file\_delete()
http://drupal.org/node/1004820#comment-5171678 \- Notice: Undefined index: type in dblog\_build\_filter\_query()
http://drupal.org/node/1345204#comment-5259212 \- Optimize element\_children()
http://drupal.org/node/753064#comment-5274348 \- \_menu\_link\_translate() might avoid calling \_menu\_load\_objects()
http://drupal.org/node/261148#comment-5798704 \- menu\_masks variable is empty (race condition)
http://drupal.org/node/1688282#comment-6240944 \- Unknown error: Function split() is deprecated in \_filter\_autop()
http://drupal.org/node/521838#comment-6375266 \- Clean up drupal\_get\_schema\_versions()
http://drupal.org/node/1710656#comment-6474030 \- If item is hidden in \_menu\_tree\_check\_access() skip it right away.
http://drupal.org/node/1882556#comment-6913038 \- Notice: Undefined index: REMOTE\_ADDR in includes/bootstrap.inc on line 2835
https://www.drupal.org/node/2292125#comment-8912499 \- PHP 5.5 - preg\_replace(): The /e modifier is deprecated, use preg\_replace\_callback instead in decode\_entities() (line 349 of includes/unicode.inc)

---

Most of the issues I'm following that have the word notice in it
https://www.drupal.org/project/issues/search?text=notice&projects=&project\_issue\_followers=mikeytown2&status\[0\]=Open&categories\[0\]=1&issue\_tags\_op=%3D&assigned=&submitted=&issue\_tags=&&order=field\_issue\_version&sort=asc

And the ones that contain the word warning
https://www.drupal.org/project/issues/search?text=warning&projects=&project\_issue\_followers=mikeytown2&status\[0\]=Open&categories\[0\]=1&issue\_tags\_op=%3D&assigned=&submitted=&issue\_tags=&&order=field\_issue\_version&sort=asc

---

Query used to find the worst offenders for php issues: http://groups.drupal.org/node/170339

---
Tags: security
---


# Question
Title: Resizing the Height of 2 blocks to always be the same depending on block with most content
I have two blocks based off views on the home page of my site:

```
block-views-featured-resource-block
block-views-featured-resource2-block

```

I want them to be the same height as each other on the home page ALWAYS. They are both drawing from nodes. The nodes for each has a description field. And it varies depending on which node is set for the home page, so the length of the description for each changes regularly.

I want each block to expand in size to fit whatever contents are in the description field (might be one sentence or multiple paragraphs) for the node, and I want them both to resize based on whichever of the two has the most characters of content to the same size (one might end up having a bunch of white space below it, but that's ok.

Right now I have them set like so:

```
block-views-featured-resource-block,
block-views-featured-resource2-block {
    min-height: 350px;
    position: relative;
}

```

But of course this only resizes each to fill whatever contents are in each block separately...so if the content takes up more than 350px of space one might be larger than the other. I also tried adding clear: both to the above and overflow: auto but neither of those seemed to help.

Anyone know of a way to do what I want with css?

# Answer
> 1 votes
There's plenty of equal height jquery plugins out there.

jquery-match-height and jQuery.equalHeights are two plugins that you can use, but there's others just google it up and you'll see for yourself.

Beyond that it's just a matter of integrating the plugin to your theme.

# Answer
> 0 votes
We should know how you implement the parent of blocks, are these blocks sibling? If yes then I recommend you to use flex display for blocks and set the `align-items` to `stretch`. for more information visit A Complete Guide to Flexbox

# Answer
> 0 votes
Assuming your layout wraps around the two blocks, one next to the other, floated or inline: Flexbox is a solid solution for the future. Right now, if you're targeting visitors using IE9 and below, there's another CSS feature you can use: display: table and table-cell.

```
.wrapper-name {
    display: table;
    width: 100%;
}

block-views-featured-resource-block,
block-views-featured-resource2-block {
    float: left;
    display: table-cell;
}

```

# Answer
> -1 votes
Javavascript has an equal heights library.

---
Tags: theming
---


title: Redirect user to dynamic url

text:
# Question
Title: Redirect user to dynamic url
I am writing a custom rule, I do not know how to approach getting the correct URL for the redirect.

I have a page - website.com/content/newsletter-activity-001 that needs to redirect an anonymous user to website.com/content/activity-001 until they are logged in.

I have a reference field in 'newsletter-activity-001' that holds the title to 'activity-001'. I want to write a rule that will apply this for newsletter-activity-002 and so on as the site content grows.

How do I dynamically pull that url out and place it into the redirect path? Would tokens do it?

# Answer
The tokens `[site:current-page:path]` & `[site:current-page:url]` will retrieve the current Drupal path & the full URL, respectively.
> 0 votes

---
Tags: rules, tokens
---


# Question
Title: Why is my theme table row array not being displayed?
I have the below code and I know both the $headers and the $html have values stored in them as i can echo them out. I can also set the *'header' =\>* in the theme function to be either $header or $html and it will display the data.

However when I add in *'rows' =\>*, no data is displayed.

Can anyone see why?

```
function emnies_ad_hoc_query_exporter_get_html_formatted_ad_hoc_query_responses($obj_response) {
  $str_current_country = '';

  foreach ($obj_response as $response) {
    if ($str_current_country != $response->country) {
      $str_current_country = $response->country;
      $html = emnies_ad_hoc_query_exporter_get_country_row($str_current_country, $obj_response);
    }
  }
  $header = array('Country', 'Wider Dissemination', 'Responses');
  $output = theme('table', array(
    'header' => $header,
    'rows' => $html
  ));
  return $output;
}

function emnies_ad_hoc_query_exporter_get_country_row($str_current_country, $obj_response) {
  $rows = array();
  $i = 0;
  foreach ($obj_response as $response) {
    if ($str_current_country == $response->country) {
      if ($i == 0) {
        $rows[] = $str_current_country;
        $rows[] = $response->wider_dissemination;
      }
      $i = $i + 1;
      $rows[] = $response->response;
    }
  }
  return $rows;
}

```

# Answer
Try looking at it this way. From looking at your $header, you are looking for 3 columns?

```
foreach ($obj_response as $response) {
if ($str_current_country == $response->country) {
  $rows[] = array($str_current_country, $response->wider_dissemination, $response->response);
}

```

**EDIT**

```
// Test Output
$header = array(t('Country'), t('Wider Dissemination'), t('Responses'));
$rows = array();
$rows[] = array('US', 'Extremely Wide', 'Response');
print theme('table', array('header' => $header, 'rows' => $rows));

```

The test works for me. Maybe something in your response value is messing with it?
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to remove unused files from directories
I want to remove/delete files from site directories (e.g. `/sites/default/files/*`) that are not used in site. There are thousands of files that causing fillup size. Any suggestions for this?

# Answer
I found this post https://drupal.org/node/733258... may help...

The main purpose talked in this issue is about removing the images which doesn't have any use directly from database via SQL queries.

Audit files module is suggested as a good start (because doesn't delete files) to find files which are unused.

This code snippet is one of the suggested solution from the issue :

```
<?php
//db_query to find all files not attached to a node:
$result = db_query("SELECT fid FROM file_managed WHERE NOT EXISTS (SELECT * FROM file_usage WHERE file_managed.fid = file_usage.fid) ");

//Delete file & database entry
for ($i = 1; $i <= $result->rowCount(); $i++) {
  $record = $result->fetchObject();
  $file = file_load($record->fid);
  if ($file != NULL) {
    file_delete($file);
  } }
?>

```
> 8 votes

# Answer
A simple way of searching the unused files is running the following query:

```
SELECT fm.*
FROM file_managed AS fm
LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
WHERE fu.type = 'node' AND n.nid IS NULL

```

This query would return all the files that are not associated with any node.

Also, in order to avoid landing up in such situations its better to add a file\_usage\_add() to every file. This will enable the system to know that the file is being used. Appending a file\_usage\_delete() does a cron type job of removing unused files from the system.
> 1 votes

# Answer
There is a sandbox project called File Delete, which provides the drush command `drush file-delete-unused --all` to delete all files reported in file\_managed which aren't in file\_usage. It deletes the file itself and the database-entry.
> 1 votes

# Answer
You could either remove it manually or could go through https://drupal.org/node/733258 which would help you remove unwanted images.
> 0 votes

# Answer
Here is my example of removing unused gmap\_markers files using drush:

```
drush sqlq "SELECT fid FROM file_managed WHERE status = 1 AND filename LIKE 'gmap_markers%'" | xargs -L1 -I% drush -v eval "file_delete(file_load(%));"

```

You can see all the Drupal files by:

```
drush sqlq "SELECT fid, filename, uri FROM file_managed WHERE status = 1"

```

To see if any specific file is not used, I'd suggest to scan for each of these files in the filesystem and database by the following example commands:

```
grep -R "my_file.jpg" /Drupal/webroot
drush --ordered-dump sql-dump | grep "my_file.jpg"

```

Once the file doesn't exists anywhere else apart of standard file\_managed, etc. then I think it can be removed safely.
> 0 votes

---
Tags: 6
---


title: Adding HTML just to a block

text:
# Question
Title: Adding HTML just to a block
I've added a node as a block to my home page (using nodesinblock module). I've got it looking basically like I want it to look with the teaser appearing in the block, but I'd like to add a 'read more' link (or button) to the bottom of the block.

Note: I do NOT want this 'read more' link to appear on the full content node, just the block.

Anyone know how to add some html specifically to a block on the home page?

# Answer
> 1 votes
I just tried this module today when I saw your post, if you don't want the 'read more' to appear on a full content node display you could create a new display template and add the php path/read more html link on the template you created then choose it from the render mode of node in block settings.

But I'm a little curious, why did you not use views block instead? it's a lot easier, you could just put the read more link on the footer.

---
Tags: blocks
---


title: file as field node block

text:
# Question
Title: file as field node block
I am building a site in which authenticated users may upload files. When such a user is viewing URLs of a certain content type, I would like the left sidebar to contain, among other things, a file control. The right column of an unauthenticated user holds the login controls, and that column must hold something else for authenticated users who have not accepted the required condition. My goal is to have the user perform the upload while also reading the content. Hopefully, this improves retention.

At any rate, I need a block which contains a file field. I have been trying to do this with Node Fields Block. So far no success.

I added a hidden file field to my content type, installed and enabled node\_fields\_block, and added a Node Fields Block which is enabled for pages of my content type and which contains the File. I've created a 'Node Fields Block' display mode for the content type in which the file is supposed to appear, but nothing shows up. I've looked at the generated HTML and the block isn't being generated.

I'm at a loss. Any help greatly appreciated.

# Answer
The last time I tried node fields block, some of the fields doesn't really show. So I just switched to using the views blocks. it's just the same. Just insert the fields you wanted to show. If you want users to upload files on the current page you could try Block upload \- it's a simple module, which allow users to upload images/files into field without node edit page.

Did I understand your case correctly?
> 0 votes

---
Tags: nodes, entities, blocks
---


# Question
Title: How to assign a user to administer one content type only?
I have created a content type "TestContent". I created view using the content type. I can add content using the TestContent and I can see the content just fine in view. And I am the admin. Now, I have created a role "David" and I have created a user "xpress". I also have assigned the user to the role.

Then in Admin \> People \> Permission: I have selected check box for 'David' for the below items:

```
David: TestContent: Create new content
David: TestContent: Edit own content
David: TestContent: Edit any content
David: TestContent: Delete own content
David: TestContent: Delete any content

```

I logged out as admin and logged back in as xpress but I did not see the add content, find content for the content type that he has permission. Note that this user only have the permission to add content, edit content, update content, delete content for the content type.

Can you please help?

Thanks.

# Answer
The xpress is not an admin, right? So the xpress won't be able to see the admin toolbar. Have you tried accessing the link of node/add/testcontent, node/node-id/edit? was xpress able to access it? if yes then you need to provide a link/button for the xpress to see when he/she logs in. Then I think you need to use views to show the lists of TestContent where xpress can search/filter.
> 0 votes

---
Tags: users
---


title: Access denied after installation

text:
# Question
Title: Access denied after installation
I've completed installation without error messages, but when I visit the site and attempt to log in, I can't, and I don't receive e-mails sent to reset the password.

Here are the details:

Using XAMPP 5.6.3 under Windows 7. Installing Drupal 7.36.

* Site URL: localhost/Drupal7 (entered for "Site name" on "Installing Drupal" page of installation script)
* Database user name: d7db\_010\_drupal7
* Database name: (same as database user name)
* Site user name: D7\_010\_Drupal7 (entered for "Site maintenance account Username" on "Installing Drupal" page of installation script)
* Site e-mail address: D7LocAdmin@mydomain.com (not the actual domain) Passwords for two above user names: 10-char pws generated by www.passwordsgenerator.net

Database d7db\_010\_drupal7:

```
- Table users has two records:
    * User ID 0: All other fields either empty, null, or 0
    * User ID 1: name = D7_010_Drupal7, pw = hash, mail and init both = D7LocAdmin@mydomain.com, created = 1428953185, login = 1428953512 (See note on timestamps below.)
- Table users_roles has one record: User ID = 1, Role ID = 3
- Table watchdog has 55 records, mostly about installing and enabling modules, and:
    * Event ID 52: uid = 1, type = user, msg = Session opened for %name., location = http://localhost/Drupal7/user, timestamp = 1428953513
    * Event ID 53: uid = 0, type = access denied, msg = user/1, location = http://localhost/Drupal7/user/1, timestamp = 1428953513
    * Event ID 54: uid = 0, type = user, msg = Password reset instructions mailed to %name at %email., location = http://localhost/Drupal7/user/password, timestamp = 1428953546
    * Event ID 55: uid = 0, type = user, msg = Password reset instructions mailed to %name at %email., location = http://localhost/Drupal7/user/password, timestamp = 1428953571

```

Note that value of "login" for user 1 in the table "users" is one second before the timestamp of events 52 and 53.

Actions I took when installation completed:

* Went to localhost/Drupal7. Prototype page came up.
* Entered site user name and its password. Nothing happened. No event for this in table "watchdog".
* Clicked on link for "Request new password". In form that came up, clicked on "Log in" tab. Entered site user name and its password. Result: "Access denied". This is event 53
* Clicked on "Request new password" tab. Entered "D7\_010\_Drupal7" and clicked button. Result: "Further instructions have been sent to your e-mail address." This is event 54. No e-mail received.
* Clicked on "Request new password" tab. Entered "D7LocAdmin@mydomain.com" and clicked button. Result: "Further instructions have been sent to your e-mail address." This is event 55. No e-mail received.

I sent myself an e-mail at the site e-mail address to test that it's working and I received it.

Can someone see:

(a) Why I can't log in

(b) Why I'm not receiving the e-mails

or tell me what to inspect or test further to find out?

Thank you.

===============================

Update

In order to check that the problem is not with characters in the user name or with using the wrong password, I reset the name and password to "hello" and "there". I did the following:

* Ran php on "scripts\password-hash.sh there"

The response was

password: there hash: $S$DK0K/McRjrM9f7D/OwExsr8Fk.8uaU1U4CC030GbqjAArbEMIFg/

* Ran the following two queries on table "d7db\_010\_drupal7":

UPDATE users SET name = 'hello' WHERE uid = 1;

UPDATE users SET pass = '$S$DK0K/McRjrM9f7D/OwExsr8Fk.8uaU1U4CC030GbqjAArbEMIFg/' WHERE uid = 1;

* Entered "hello" and "there" on the login on the main page. Again, nothing happened.
* Went to "localhost/Drupal7/user" and entered "hello" and "there". Result: Access denied.
* Repeated the last step above in case of mistyping. Result again: Access denied.

Grrr!

# Answer
Thank you to Alyssa Gono for solving this. She did it in a comment, so I can't formally credit her with the correct answer. But I'll lay out here what happened.

I thought at first that couldn't be it. How could a cookie be interfering with the analysis of the login credentials? But I was so frustrated by this problem that I decided to give it a try. I work in Firefox, so first I loaded IE, and logged in there, and it worked! Then I went back to Firefox and looked at my cookies. Rather than deleting them all, I looked for cookies from localhost. There were about 20 of them. I deleted those and bam! I was able to log in!

This was with the credentials "hello" and "there" set in the update above. So next I undid the changes described in that update by resetting the credentials back to the intended ones. Went back to the site, logged out and logged back in with those credentials and Wow! Problem solved.

Now I can finally get to work on developing my sites.

I'm going to submit a bug report at Drupal because it would be helpful if the sw could let the user know that a cookie is blocking the login. If it can't detect that, at least it would be helpful to suggest clearing cookies if one believes the login should be working and isn't.

Can someone explain how it is that a cookie interferes with the analysis of the login credentials?

Thank you again to Alyssa.
> 1 votes

---
Tags: users, installation
---


title: Views: CSS Style

text:
# Question
Title: Views: CSS Style
Normally when I create views, I will change the style at style.css. Example: #block-views-example{ margin: 0px auto; }. In the views, I see some styles setting. Am I able to just set the style setting there? Example: style.css .margin0px {margin: 0px auto} and just place class="margin0px" in the views style setting. Is it possible?

# Answer
The views style setting will allow you to assign classes on the style settings ( .margin0px), choose wrapper whether div, span or something else. So yes, if you're going to put your class on the views style setting that is possible.
> 1 votes

# Answer
I just add a style sheet to my theme. Every page/node can be accessed and filtered with a class in front of the class you want to edit.

There is also the possibility to edit styles with the help of Emmet Livestyle extension in Chrome. In combination with Sublime text editor you can edit your css live in chrome and the result is directly saved in one the theme files. So changing your style.css can be still a good method.

If you new to css i suggest to take a look at http://sass-lang.com/
> 1 votes

---
Tags: 7, views, theming
---