# Question
Title: field_deleted_date_N and field_deleted_revision_N not removed on cron run or field_purge_batch()
I am running a site on D7. I noticed a no. of field\_deleted\_data\_N and field\_deleted\_revision\_N tables in my database. Through a lot of googling I found people saying that these tables will eventually be cleared on cron run. They also said you could run field\_purge\_batch().

However neither of there suggestions worked. Could somebody please help me solve this problem? Why are these fields never removed? Is there something wrong with my database? How can I remove them in a drupallish manner?

Thanks.

# Answer
> 2 votes
If drush doesn't help and running cron doesn't help, that might mean that the field data can't be purged because the module providing the field type has been disabled and / or uninstalled. In that case just drop the tables manually.

# Answer
> 0 votes
There is probably content in them. Drupal tries to play it safe and not remove fields that may result in lost data.

Use drush:

```
drush field-delete deleted_date_N --bundle=content_type

```

Other things to try that I have also found to be of varying success:

The status report sometimes gives you hints why. Reports -\> Status report. This report will let you 'run cron manually' and run the 'database update script'.

The database update script triggers *update* functions which you can try. I have found it is still far more 'safe' than drush.

Put it in a module .install file.

```
function hottopicsnotify_update_7002() {
  // Clear cache first?

  field_delete_field('field_effect');

  field_purge_batch();
}

```

This can also be run via drush:

```
drush updb

```

I have run 'drop table' in sql with varying success - I don't recommend it. Drush field-delete is the way to go.

# Answer
> 0 votes
This has become quiet a nuisance for me. I modified the renameTable function schema.inc in includes/database/mysql to return FALSE rather than throw exceptions for these conditions (which is more inline with the way the rest of the schema.inc code handles \[exists|!exists\] situations...

```
 public function renameTable($table, $new_name) {
if (!$this->tableExists($table)) {
  return FALSE;
//      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", array('@table' => $table, '@table_new' => $new_name)));
    }
    if ($this->tableExists($new_name)) {
      return FALSE;
//      throw new DatabaseSchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", array('@table' => $table, '@table_new' => $new_name)));
    }

```

---
Tags: 7, entities, cron
---


# Question
Title: Allow users to view others contents with autocomplete Entity Reference field
I'm trying to build a content type where any user can select an entity reference value through an **autocompleted Entity Reference field**.

Using this field works as an admin. I'm able to see the referenced contents. But when I try as a logged in lambda user, I **can't view the content created by other users**.

The field is in the content type "**Invoice**" and has to allow users to select a contact name (content type "**Contact**").

I think it's a matter of access rights on this specific content type. So far, I've tryed creating a module with a `hook_node_access` function :

```
function contact_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
    if ($op == 'view' && user_access('view ' . $type . ' content', $account)) {
      return NODE_ACCESS_ALLOW;
    }
  }

}

```

It still doesn't allow users to see and select other's people contacts.

# Answer
Generally if a user cannot see another user's content then it is either because there is a content access module installed that is restricting access or the content is unpublished.

By default in Drupal you cannot see unpublished content unless you created it or you are an administrator with access to all content.
> 0 votes

---
Tags: hooks, users, nodes, entities
---


title: Custom page with fixed content

text:
# Question
Title: Custom page with fixed content
Me again with the noob question.
I want to achieve this:
At the url `http://ROOT/something/{numeric_id_here}` to get a page that lists the header and the footer of the theme and my custom content. The content is not manage-able through the admin. It depends on the numeric id.
Here is what I got so far.
I use the `hook_menu` for this:

```
function something_menu() {
    $items['something/%id_here'] = array(
        'title' => 'Some title',
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

```

I have the function that parses the url and gets the numerical value:

```
function id_here_load($arg) {
    $data = get my custom data from an external xml feed based on $arg; //this works nicelly - I get an array with the data I need.
    //WHAT'S NEXT?
}

```

Now I'm stuck. how can I pass `$data` to a template and render that template in the content of the page?
My question is somehow similar to this one. Just that the answers provided there don't cut it for me.

# Answer
> 1 votes
Something like this. Do your hook menu with (optional) arguments. In the callback do an entityFieldQuery (or pull in your XML). Use hook\_theme to specify a custom template. this code isn't tested and will need some editing / adapting for your use context.

If you prefer to pull in a feed maybe https://www.drupal.org/project/feeds is what you are looking for.

//menu

```
/**
     * Implements hook_menu().
     */
    function example_menu() {
      $items = array();
      $items['example_object/something/%'] = array(
        'title' => t('callback'),
        'page callback' => '_example_mystuff',
        'page arguments' => array(
          0,
          1,
          2
        ),
        'access arguments' => array(
          ''
        ),
        'type' => MENU_CALLBACK
      );
      return $items;
    }

```

//callback

```
     function _example_mystuff($arg1, $arg2, $arg3) {
        $query = new EntityFieldQuery();
//or load in your xml
        //do an entity field query to look up your items
         $results = $query->execute();
        return $results;
        }

```

//theme function

```
 function example_theme($existing, $type, $theme, $path) {
      return array(
    '_example_mystuff' => array(
          'template' => 'example-theme',
          'path' => $path . '/templates',
          'variables' => array(
            'variables' => NULL
          )
        )
    }

```

# Answer
> 2 votes
You need more in your hook\_menu() like this:

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

  $items['something/%id_here'] = array(
    'title' => 'Some title',
    'type' => MENU_NORMAL_ITEM,
    // This is the function that will return your page content.
    'page callback' => 'something_custom_page',
    // This will pass the $data variable you returned from your loader function
    // into your page callback (not the ID in the URL).
    'page arguments' => array(1),
  );

  return $items;
}

```

Then your load function needs to actually return what it has loaded, like this:

```
function id_here_load($arg) {
  // Do some checks o make sure no one can pass in bad data via the url.
  // This is an example you need to check based on your data.
  if (is_numeric($arg)) {
    $data = get my custom data from an external xml feed based on $arg; //this works nicelly - I get an array with the data I need.
    // If you get back valid data.
    // Again you need to make this relevant to your data.
    if ($data) {
      // Return the data.
      return $data;
    }
  }
  // If for any reason you didn't end up getting data return FALSE.
  // This will cause access denied for this page because of an invalid ID or something.
  return FALSE;
}

```

Then you need to implement your page callback function like this:

```
function something_custom_page($data = array()) {
  // Do something with the $data to create the page and return
  // either a string of HTML or a drupal render array.
  // Returning a render array is the preferred option.
}

```

See Render Arrays in Drupal 7 form more info on render arrays.

---
Tags: 7
---


# Question
Title: Is it possible to done search indexing locally, then upload it?
I want to perform search items indexing on the local system . Due to high number of items and And slowing down the server

Can I do something like this , then I upload the result to the DB? Without completely erasing the previous database.just replacing drupal's index.

# Answer
The suggestions in the comments are good, specially using solr.

But in your case you can index the whole data locally, and dump these three tables: search\_dataset, search\_index, search\_total and then import it on the server.
> 0 votes

---
Tags: database
---


title: Can't update Drupal core to 7.34

text:
# Question
Title: Can't update Drupal core to 7.34
I am trying to update Drupal core from 7.32 to 7.34 using drush. It initially appears to be sucessful, however the status report and /modules/system/system.info still show the version number as 7.32. I have tried running update.php but it says that there are no updates.

I have another Drupal site on the same server that is very similar and had no issues updating it to 7.34.

The output of drush when updating is:

```
drush5.5-sp pm-update
 Name    Installed Version  Proposed version  Message
 Drupal  7.32               7.34              SECURITY UPDATE available

Update information last refreshed: Thu, 11/27/2014 - 22:43
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.34.
Backups were saved into the directory                                [ok]
/srv/users/site/drush-backups/u7i6t765rib76nb7tionytbyi_site/20141127154450/drupal.
No database updates required                                         [success]
'all' cache was cleared.                                             [success]
Finished performing updates.                                         [ok]

```

# Answer
> 0 votes
You don't need the `drush`. download the latest version, remove the `/sites` folder from the downloaded files and then simply copy and replace the files with the existing ones.

---
Tags: drush, updating
---


# Question
Title: How to hide roles from user_profil_form while keeping value?
After loading user\_profil\_form form, I tried to hide the roles fields. It worked fine, however after submitting the form, my user roles are removed and it's only linked to "authenticated user".

Is there a way hide this field but keeping the value ? I would not like to user the alter hook in order to keep the full form in the admin pages.

Thank you

# Answer
In my experience, unsetting the field works fine to disallow access to a field while keeping values on update. For example:

```
/**
 * Implements hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    unset($form['account']['roles']);
  }
}

```
> 1 votes

# Answer
You should use the '#access' = 0 for the roles field appropriately to hide it from users
> 0 votes

---
Tags: 7, users
---


# Question
Title: DRUPAL 7.33 - When i try to save a node with upload, i receive website encountered unexpected error...PDOException: SQLSTATE[25P02]
In my postgresql log i have error on this select:

```
SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp, base.type AS type
    FROM
    file_managed base
    WHERE  (base.fid IN  ('resultadopdf_1'))

```

The file is uploaded, but the node not... I want to understand why the select compare a field id (integer) with a string... Someone know where this select is made?

**After aplied patch:**

```
PDOException: SQLSTATE[25P02]: In failed sql transaction: 7 ERRO: current transaction has been halted , commands ignored until end of transaction block: SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = :schema AND table_name = :table AND (data_type = 'bytea' OR (numeric_precision IS NOT NULL AND column_default LIKE :default)); Array ( [:schema] => public [:table] => node [:default] => %nextval% ) em drupal_write_record() (linha 7239 de /var/www/portalunifei/includes/common.inc).

```

But in then postgrelog shows:

```
ERRO:  input syntax for integer is invalid: "notaspng" at character 256
COMANDO:  SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp, base.type AS type
    FROM
    file_managed base
    WHERE  (base.fid IN  ('notaspng'))
ERRO:  current transaction has been halted , commands ignored until end of transaction block
COMANDO:  SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'node' AND (data_type = 'bytea' OR (numeric_precision IS NOT NULL AND column_default::text LIKE '%nextval%'))
LOG:  duração: 0.025 ms  comando: ROLLBACK

```

# Answer
> 0 votes
sorry for the delay, but finally found the solution to my problem ... https://www.drupal.org/node/1003788

I would like to acknowledge the help of you gave me...

---
Tags: 7
---


# Question
Title: How to export content type with scheduler's settings using features
In my dev environnement, I've installed Features module for exporting the content types of my site. I've also installed Scheduler module to schedule for publishing my contents. On the admin page of my content type, I enabled scheduled publishing for my content type. Then I created the features of the content type. However after importing of features to the prod, I've found that the scheduler's settings to content type were not imported.

Does anybody know why? Is there any module supporting to resolve this problem? Thanks in advance.

# Answer
> 4 votes
In addition to exporting "Content types", "Field bases" and "Field instances" you should also export all variables named "scheduler\_\*_\[name of the content type\]".

To be able to export variables Strongarm module should be installed. Then on "Create Feature" page you will see section as on this screenshot.

BTW, lot of modules that extend content types save their configuration the same way, so you need include such variables in the the content type feature.

---
Tags: nodes, features
---


title: SOLR Snippet with link to PDF

text:
# Question
Title: SOLR Snippet with link to PDF
I'm using Apache SOLR as search engine. Everything works fine, indexing as I want, showing the data as I want. I only need to show the PDF which belongs to a certain snippet on a search result. Example:

```
Result 1: Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

Result 2: Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

Result : Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

```

The idea is, to have a list of snippets which can be either on the node itself or in a pdf (or any other file) which is attached to this node and link to it (in file case).

Tika extension and Apachesolr\_attachments are in place and working.

I get the $vars\['snippets'\] from `hook_apachesolr_search_snippets($vars)` and I can modify the output. But I don't see how I could add more information to it.

Any help appreciated.

# Answer
you can add extra field to solr. you need to implement hook\_apachesolr\_index\_document\_build\_node(ApacheSolrDocument $document, $node, $env\_id)

and there $document-\>addField('pdf\_field\_name', 'your\_url');

also you need to implement hook\_apachesolr\_query\_prepare(DrupalSolrQueryInterface $query)

and add there $query-\>addParam('fl', 'pdf\_field\_name');

then in your search-result.tpl.php $pdf\_field\_name should be available (after reindexing)
> 1 votes

---
Tags: 7, search
---


title: Display block on two different pages

text:
# Question
Title: Display block on two different pages
I'd like to view my block on pages where the `content type = booking` and where the address is `node/add/booking` (basically add, edit and view nodes), how can I accomplish this? So far my code only shows on pages where `content type = booking` (i.e. view and edit nodes).

```
<?php
// Change the type to the one you want to match on
$desired_type = 'booking';
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
   return $node->type == $desired_type;
}

return FALSE;
?>

```

# Answer
You can do it like this. It uses exactly the same principles as your existing if statement.

```
// Change the type to the one you want to match on
$desired_type = 'booking';
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  return $node->type == $desired_type;
}
elseif (arg(0) == 'node' && arg(1) == 'add' && arg(2) == $desired_type) {
  return TRUE;
}
return FALSE;

```
> 2 votes

# Answer
Here you go:

```
<?php
$desired_type = 'booking';

if ($_SERVER['REQUEST_URI'] == '/node/add/booking') {return TRUE;}

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

else {return FALSE;}
?>

```
> 2 votes

---
Tags: 7, views, blocks
---


# Question
Title: Change the the title on the `?q=user` page
I want to change the the title on the `?q=user` page to something generic e.g. "My Home", and not user name.

So far, I have tried using the string override module with little success. Is it possible to do this with a custom module that I can just drop into the page with some PHP code? If not, how can it be done?

# Answer
There are a number of ways you can do this:

1. Create a template file for user pages in your theme that renders the title differently
2. Create a custom module that alters the title using hook\_menu\_alter
3. Use Page Manager (part of ctools) and Panels to customise the layout of the user page
4. Likely other ways I don't know about

Number 1 is probably the most common, 2 is only really okay if you're already writing a custom module that changes user page behaviour, 3 is a more advanced method that basically lets you pull apart the page and put it back together how you want.

The simplest version of #3 would be to create a new variant of the user/%uid path with exactly the same content, and just set the title in the page manager UI using tokens.

Searching for keywords from the various options should provide you with plenty of tutorial material.
> 4 votes

---
Tags: 7
---


# Question
Title: hook_page_alter to change title on user profile page?
Right now I have the following function implemented in `template.php`:

```
function ccom_page_alter(&$page) {
  if (array_key_exists('#account',$page['content']['system_main'])) {
    $account = $page['content']['system_main']['#account'];

    if (isset($account)) {
      drupal_set_title($account->field_complete_name['und'][0]['safe_value']);
    }
  }
}

```

Is this the best way to set the title on a user page? Or should I be doing this through a different hook?

**EDIT**: I've updated my `template.php` to use `hook_preprocess_user_profile` instead, and I have this:

```
function ccom_preprocess_user_profile(&$variables) {
  drupal_set_title($variables['elements']['#account']->field_complete_name[LANGUAGE_NONE][0]['safe_value']);
}

```

The page title changes (like the one the browser shows you on a tab), but the user profile Drupal page title remains the username. Very annoying. Still working...

**EDIT 2**: I ran an experiment. I did the following:

```
function ccom_preprocess(&$variables, $hook) {
  dpm($hook);
}

```

Which gave the following output when viewing a user profile page:

* search\_block\_form
* block
* region
* block
* region
* user\_profile
* user\_profile\_item
* user\_profile\_category
* block
* region
* html
* region
* user\_picture
* page

So that's the order in which the preprocess hooks are called on that page. I then created two functions:

```
function ccom_preprocess_user_profile(&$variables) {
  dpm($variables);
  drupal_set_title('mytitle');
}

function ccom_preprocess_page(&$variables) {
  dpm($variables);
  drupal_set_title('mytitle');
}

```

I first loaded the page with the `ccom_preprocess_page` function commented out. The title in the browser tab changed to ***mytitle***, but the page title stayed as the username for the user profile page being viewed.

I then commented out `ccom_preprocess_user_profile` and uncommented `ccom_preprocess_page` and reloaded the page again. Both the browser tab title ***and*** the page title changed to ***mytitle***.

This tells me that somewhere after the user\_profile preprocess hook function and up to and including the page preprocess hook, the page title is reset. Where that is I'm not entirely sure.

So, my thinking at this point would be to create a global variable and set it equal to the user account object available in the user\_profile hook, and then in the page preprocess hook just set the title based on the complete name field available in the account object. Thoughts?

# Answer
> 9 votes
This finally worked for me; it's essentially what was posted at http://drupal.org/node/1262070#comment-5038516, but with some function renaming and generalizing:

```
function YOUR_MODULE_menu_alter(&$items) {
    // Change the title of user profile pages to the user's name.  Gak.
    $items['user/%user']['title callback'] = 'YOUR_MODULE_user_page_title';
}

```

and then

```
function YOUR_MODULE_user_page_title() {
    if (arg(0) == 'user') {
        // Load uid from url
        $user = user_load(arg(1));
        // Get the full user name somehow; here, I'm calling a function of my own.
        $output = get_user_full_name($user);
    }
    // Fallback to username if no fields are present
    if (empty($output)) {
        $output = $user->name;
    }
    return $output;
}

```

But, come on. It's nice that the hooks are there, but doing something like setting the title of a page REALLY shouldn't be this hard/obscure...

# Answer
> 1 votes
I know this has already been answered. However, assuming you wanted to change the title to an actual name it would have been easier to use the RealName module. You could have also done this, which I think is way easier than the accepted solution:

```
function hook_username_alter(&$name, $account) {
  if (arg(0) == 'user' && is_numeric(arg(1))) {
    if (isset($account->uid)) {
      $name = $account->your_field_name['und'][0]['safe_value'];
    }
  }
}

```

You could probably even wrap $account in entity\_metadata\_wrapper() and use value() instead of screwing around with the array.

# Answer
> 0 votes
it makes more sense to me to do it with this: http://api.drupal.org/api/drupal/includes%21theme.inc/function/template\_preprocess\_html/7

but really, whatever floats your boat ;)

# Answer
> 0 votes
This is untested but it seems like hook\_user\_view is the right way to go, the caveat being you cant put this in your theme, but in a custom module.

```
function mymodule_user_view($account, $view_mode, $langcode) {
  if ($account->uid == 1 && $view_mode == 'full') {
     drupal_set_title('my custom title');
  }
}

```

---
Tags: 7, hooks, theming
---


title: Callback on Bean save?

text:
# Question
Title: Callback on Bean save?
Is there any callback hook like hook\_node\_insert / hook\_node\_update when saving a bean block?

# Answer
Beans use the entity system, so you have a couple options here:

As AyeshK stated, hook\_entity\_insert and hook\_entity\_update are the obvious options.

If you need to do something before creating OR updating you can use hook\_entity\_presave.

Finally, Drupal doesn't have any native hooks that runs *after* an entity is created/updated, but the Hook Post Action module offers a nice set of additional functions to solve this problem. If you don't want yet another module dependency, read the module's codebase and figure out how it implements the post-save functionality, then add similar custom code in your own module.
> 0 votes

---
Tags: blocks
---


# Question
Title: Use Rules to Change Field Value By Clicking URL
I am creating a simple internal ticketing system which emails customers when the status of their ticket changes (Open -\> Waiting on parts). I have set up rules to do this and I haven't had any issues with it. However, I would like to create a way for customers to "unsubscribe" from the emails. I have created a checkbox field named "allow emails" which determines if customers will or will not get an email as a condition for the rule.

I would also like to include a link at the end that if clicked the customer would set the field to "no" or "off".

Note:Customers aren't actual users on the site but are nodes within a "customer" content type. The users are our internal staff that would log in to use the website.

Can rules do this by itself or do I need a separate module?

Thanks

# Answer
I'm not sure I understand exactly what you need, but the great module Rules Link (https://www.drupal.org/project/rules\_link) provides a link that can be attached to any content type or entity, and can also be accessed in Views as a special Rules Link field. When you click the link a preset Rule is triggered. The link passes the node or entity as a parameter to the Rule. There is also the option of using a "Javascript" link that invokes the Rule via AJAX (without reloading the whole node) - I've never used that option, but I suspect that it may help your needs.
> 1 votes

# Answer
You can definitely set the field value of a node with a Rules action assuming the referenced node is passed into the Rule.

Also, remember that in order to set a field value in a Rule, you have to first check to see that the field exists using a Rules condition (there is a specific condition for this).

Related question: How to change a field value with a Rules Action?
> 0 votes

# Answer
Perhaps try Rules Argument. https://www.drupal.org/project/rules\_url\_argument

Compose your URL using token field values and then check for these values in the path when the user clicks through (you may need the Path Rules module). IMO the path handling would be better done with a menu callback in a custom module, but if you want to use Rules, you should be able to use the above mods.

As a security measure, you may want to create a custom token so that a malicious 'user' can't unsubscribe another 'user' by guessing path vars.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Generate consecutive number as title using auto_nodetitle?
I need that new submissions for an specific content type have a consecutive number as title. Found auto\_nodetitle, but I don't know how to make it a consecutive number, they don't give clear instruccions as how to program it. I'm fairly new to Drupal.

# Answer
> 0 votes
If you haven't installed Token module, do so.

From there, you can insert the token \[node:nid\] into the auto title field. If you don't want to use the nid, you can install the Serial field module, add a field to the content type, and insert that into the title via \[node:field\_machine\_name\]. For most purposes, nid should suffice.

You can browse & insert token values via the supplied token browser ui.

---
Tags: nodes
---


# Question
Title: Blocks display in the wrong place and can't be turned off
I'm experiencing problems: Some of my blocks are appearing in two blocks at the same time. Some blocks appear when disabled, even if I disable the block is still appears in one of the locations. It's happening with several blocks but not all.

This is what the footer looks like:

Drupal 7.34 running locally Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3

The theme is BigWig

* Block caching is switched off. I've used the "Flush all caches" button and deleted everything in the cache DB table.
* I only have 4 blocks displaying, the "business info" (currently duplicated), "copyright info" (appearing correctly) and "main page content" and "System help".
* I've checked the theme code and the "Powered by Drupal" block is a block and not hard coded. But the block is disabled.

# Answer
After nearly going insane I noticed that the module, "Context", was overriding my blocks.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: Image cache present in which config file
I am new to drupal and was learning about image cache.So far its going good but I want to know where exactly the image cache config is getting saved.I mean to ask which file I have to browse to see image cache setting?If my doubt is silly then please forgive me.Thanks

# Answer
> 2 votes
Image cache is core in Drupal 7 IIRC. So you can access its config and settings via /admin/config/media/image-styles. The cached images themselves are saved in your theme/files dir as defined in /admin/config/media/file-system.

---
Tags: media
---


# Question
Title: Is there any way in drupal to get all primary links through views?
My objective is to get the primary links or any kind of menus items, to be shown as JSON, so that an app could consume it and show it.

I tried it using views and I have services module and views\_datasource as well, but no success.

If there is no easy way then I am open to build a custom module as well. Any suggestions?

# Answer
Can you create a hook\_menu() and then in the callback do a https://api.drupal.org/api/drupal/includes!menu.inc/function/menu\_tree\_all\_data/7 to get the menu tree and then expose that to services or return json.
> 1 votes

---
Tags: views, 7, routes, services
---


# Question
Title: Drush installation - setting symlink to /usr/local/bin/drush is a must?
Refering to https://www.drupal.org/node/2132447, I would like to install Drush in `/usr/slocal/abc` directory, and I tried the following steps:

```
$ cd /usr/slocal/abc
$ wget --quiet -O - http://ftp.drupal.org/files/projects/drush-7.x-5.9.tar.gz
$ tar -zxf drush-7.x-5.9.tar.gz
$ ln -s /usr/slocal/abc/drush/drush /usr/local/bin/drush

```

Then, I got this error:

> ln: creating symbolic link '/usr/local/bin/drush': Permission denied

I asked my system admin who said that the company policy does not allow to install stuff into `/usr/local/bin`.

I've searched many installation guides, all of them requires to create a symbolic link '/usr/local/bin/drush' in order to run Drush. Is there any other way I can do it?

# Answer
This may not answer the question directly, but a preferred and much simpler way to install Drush, is to install it through the Composer.

# Installing Composer

See Composer's website for greater detail.

```
curl -sS https://getcomposer.org/installer | php
# If the above code fails, use this one.
# php -r "readfile('https://getcomposer.org/installer');" | php
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc source $HOME/.bashrc

```

# Installing Drush

See Drush instructions on GitHub for greater detail.

To install Drush 6:

```
composer global require drush/drush:6.*

```

Or to install Drush 7:

```
composer global require drush/drush:dev-master

```

# Update

Per @leekit, he was able to solve his original issue by substituting the symbolic link with `export PATH="$PATH:/path/to/drush:/usr/local/bin"`. For that and other alternatives, refer to step **3** of **Install - Manual**, on Drush instructions on GitHub.
> 2 votes

# Answer
Another option is to install Drush with Homebrew which is the route I usually go down. https://www.drupal.org/node/954766
> 1 votes

---
Tags: drush
---


# Question
Title: How to implement RSS feed in our website in drupal 7?
Can anyone help me out with steps as how to implement RSS Feed in a node in drupal 7?

# Answer
> 0 votes
You will need the Feeds module. It deals with all things feeds related. Or if you just want to set up an rss feed check out this tutorial which runs you through the process http://www.inmotionhosting.com/support/edu/drupal-7/configure-rss-feeds

---
Tags: nodes, feeds
---


title: Reading nested field collections

text:
# Question
Title: Reading nested field collections
I have a field collection called `field_sections` that has inside it it 2 fields:

`field_section_title` (just plain text field) `field_menu_item`(field collection with 4 fields)

`field_menu_item` has 4 fields

```
 - field_item_title
 - field_menu_image
 - field_item_price
 - field_item_description

```

> I would like to build an array sections, and those sections are objects that contain menu\_items, which are objects that contain menu\_items.

I have tried something so far, but unfortunately I can only get the sections and not the nested menu\_items and their values. For some reason in their place, only a number is contained instead of the actual field value.

How can I build those arrays?

ps:my apologies for the basic question, but I'm just now getting my hands dirty with PHP and this further complicates things for me.

This is what I did so far:

```
//prepare array
$sections;
$sectionsCounter = 0;

$node = node_load(8);
//Load sections field collection
$items = field_get_items('node', $node, 'field_section');
foreach ($items as $item) {

   $sectionItems;
   $sectionItemsCounter = 0;
   $fc = field_collection_field_get_entity($item);
   $sectionTitle = $fc->field_section_title["und"][0]["value"];
   //push item into array now
   $sections[$sectionsCounter]["sectionTitle"] = $sectionTitle;
   $sectionsCounter++;

}

```

*I have only managed to get the title of each section so far and push it into an array as an object with property title*

---

**UPDATE**:

Well ,it seems I somehow got it to work, but I'm worried this is not the best solution. Can someone please have a look and tell me if I'm doing this the correct way?

```
//Load sections field collection
  $sections;
  $sectionsCounter = 0;

  $node = node_load(8);
  $items = field_get_items('node', $node, 'field_section');
  foreach ($items as $item) {

     $sectionItems;
     $fc = field_collection_field_get_entity($item);
     $sectionTitle = $fc->field_section_title["und"][0]["value"];
     $sections[$sectionsCounter]["sectionTitle"] = $sectionTitle;
     $itemsField = $fc->field_menu_item["und"][0]["value"];

     $innerCounter = 0;
     for ($i=0; $i <sizeof($fc->field_menu_item["und"]); $i++) {

        $arr = $fc->field_menu_item["und"][$i]["value"];
        $innerArray = entity_load('field_collection_item', array($arr));
          foreach ($innerArray as $item) {
            $sections[$sectionsCounter]["sectionItem"+$i] = $item;
          }
        $innerCounter++;
     }

     $sectionsCounter++;
  }

```

I've managed to create 2 objects that each contain:

A section title An object that holds all the fields that the 'inner' field collection of the section contains

# Answer
You could make use of

```
entity_load('field_collection_item', array($item_id))

```

This how-do-i-load-a-field-collection-from-a-node post provides multiple solutions for your problem!!
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to make translated taxonomy terms correctly be shown in a view?
I wonder how to make a multilingual taxonomy term show up in view results.

I'm using Drupal 7. To get my terms translated, I'm using the setting `Translate. Different terms will be allowed for each language and they can be translated`. Next, I can edit the term, use the tab *Translation*, and add a translation for the name in Deutsch (and save it afterwards).

But when I then try to create a view to displays these terms(category), they get displayed for both the Deutsch and the English terms. How can I fix this?

# Answer
> 1 votes
Make use of i18nviews Modules

> Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet.

---
Tags: views, taxonomy-terms, i18n-l10n
---


# Question
Title: Filtering Views to make several users see the node
I have a content type which contains files. I have a node with that content type which i want several, but not all people to be able to see it from a Drupal View. I know the list of the people i want to see the files, and am willing to input the names of users into any type of field of that node.

How do i filter a View to only show that node to that certain people listed in that field of users?

For context, the nodes contain some private documentation or architect design files, that not everyone should see, but also should be seen by several people, not only administrator and owner of the node.

# Answer
> 1 votes
It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.

* use the Views module to create the list – actually a list of users (rather than nodes/content).
* use relationships settings to add in the interests, and finally
* add a contextual filter on "user: uid" with a default value fetched from the currently logged-in user.

# Answer
> 0 votes
You could just add your requisite users to a role / group and then assign access to that role via the access panel in your view.

---
Tags: nodes, views
---


# Question
Title: node_view does not show the comments box
*I am using* `node_view(node_load($nid), "full")` *and I* `print(render())` *the result in a template. But the content of the node is appearing but not the comments nor the comments form. How can I display them ?*

# Answer
You probably need to use the node\_show() function instead; it outputs the node as well as its accompany comment thread and comment form. node\_show() relies on node\_view() to print the node itself, but also calls comment module's code to build the rest.

One good rule of thumb for tracking down these scenarios is to visit the api.drupal.org site, look up the function that you're using to output a portion of the information you need, and look at the functions that *also* call it in Drupal core.
> 0 votes

# Answer
I have managed to get it work. With:

```
render( comment_node_page_additions(node_load($nid));

```

Incredible. Thanks for your help anyway, it headed me in the right direction.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to convert existing taxonomy terms (to ucwords) with Termcase module?
I'm using the Termcase module to make all the taxonomy terms ucwords in a specific vocabulary.

It also has the option: **Convert the existing terms in this vocabulary immediately**

It works for making the term UPPERCASE, lowercase but doesn't work for **ucwords** although it has the ucwords (propercase) option (first character of each word uppercase).

And if needed this is the related code part in termcase.module:

```
case TERMCASE_PROPERCASE;
  $words = explode(' ', $original_string);
  foreach ($words as $key => $word) {
    $words[$key] = drupal_ucfirst($word);
  }
  $converted_string = implode(' ', $words);
  break;

```

**What should I do to make all the existing terms ucwords?**

# Answer
> 1 votes
Not a perfect solution but this is the way I used to solve the problem while converting terms to ucwords:

If all the letters of terms are lowercase then applying ucwords is working correctly.

1. Go to the vocabulary page you wanted to convert terms (admin/structure/taxonomy/VOCABULARY\_NAME).
2. Select the "Convert all characters to lowercase" option.
3. Enable the "Convert the existing terms in this vocabulary immediately."
4. Save and then it will updates (converts) all the terms to **lowercase**.
5. Then select the "Convert the first character of each word to uppercase" option.
6. Save and then it will updates (converts) all the terms to **ucwords**.

**Done**.

## original -\> step 1-4 -\> step 5-6

* my first term -\> my first term -\> My First Term
* MY SECOND TERM -\> my second term -\> My Second Term
* My Third Term -\> my third term -\> My Third Term
* mY FourTH TErm -\> my fourth term -\> My Fourth Term

**It works correctly.**

---

(If you directly apply "Convert the first character of each word to uppercase" option to these terms above, the results would become:

## original -\> ucwords

* my first term -\> My First Term
* MY SECOND TERM -\> MY SECOND TERM
* My Third Term -\> My Third Term
* mY FourTH TErm -\> MY FourTH TErm

*Doesn't work correctly if the words has uppercase letters.* So do as I mentioned above (steps 1-6).

---
Tags: 7, taxonomy-terms
---


# Question
Title: How to import Image alt, titles or File description?
Hello Drupal Community,

In a Product display i have image and file fields, I was wondering if there is a bulk way to import image alt text and image title or File description?

I used feeds to import images and multiple Files into product display but i cant find a mapping options to link alt, title or file description. Also i was considering it is possible with VBO by executing arbitrary PHP script.

Any assistance would be appreciated. Thank you Darius

# Answer
> 0 votes
One way to deal with this issue is to use the ImageField Tokens module:

> The ImageField Tokens module extends the default functionality of Image fields adding the ability to specify default values and use node tokens in the Alt and Title text.

The module Token is required. After you install and enable the modules, you configure its settings in the field properties for each individual content type.

---
Tags: feeds
---


# Question
Title: User import from other DB with Batch API, user_save makes batch go into Lock wait timeout exceeded
I created module to import users from other DB to drupal. I used batch API, tried all kind of combinations but It is usually very slow in doing this and also constantly breaking with error

```
General error: 1205 Lock wait timeout exceeded; try restarting transaction: INSERT INTO {users}...

```

I also tried changing "batch config" with raising

```
if ($batch['progressive'] && timer_read('batch_processing') > 10000)

```

to 10 seconds or so (found this advice somewhere) but it didnt help. What I realised is the user\_save(null, $newUser) makes this happen. For some reason saving new users data makes this problem, when I remove it batch goes without the problem to the end.

Here is the full module code, with comments and lots of testing code and different variables that can be set, but whatever I changed the same situation happens.

```
<?php

/**
 * Implementation of hook_menu()
 */
function import_user_migration_menu() {
  $items['admin/config/import_user_migration_form'] = array(
    'title' => t('Migrate users from old site.'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_user_migration_form'),
    'access arguments' => array('administer site configuration'),
    );

  return $items;
}

function import_user_migration_form($form, &$form_state) {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Start processing...'),
    );

  return $form;
}

function import_user_migration_form_submit($form, &$form_state) {
  //switch to old user db
  _import_user_migration_switch_to_old();

$start = 0;
$end_count = 50;
  $query = db_select('lelo_customer_temp', 't');
  $query->fields('t', array('customerId', 'email_address', 'password', 'cust_name'));
  $query->condition('t.password', '', '<>');
  $query->range($start, $end_count);
  //$query->condition('t.Cust_Bill_Email', '', '<>');

  $results = $query->execute()->fetchCol();
  $user_count = count($results);
  //$user_count = 450;
  $batch_size = 50;

  //Break up all of our data so each process does not time out.
  $chunks = array_chunk($results, $batch_size);
  $operations = array();
  $count_chunks = count($chunks);
  //switch to new db
  db_set_active('default');

  //for every chunk, assign some method to run on that chunk of data
  $i = 0;
  foreach ($chunks as $chunk) {
    $i++;
    $operations[] = array("import_user_migration_batch_process", array( $chunk ,'details'=> t('(Importing chunk @chunk  of @count)', array('@chunk '=>$i, '@count'=>$count_chunks)), $batch_size));
  }
  $batch = array(
    'operations' => $operations,
    'init_message' => t('Batch is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Batch has encountered an error.'),
    'finished' => 'import_user_migration_batch_finished',
    );
  batch_set($batch);
}

function import_user_migration_batch_process($uids, $operation_details, $batch_size,  &$context) {

//set defaults for the first time
  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_user'] = 0;
    $context['sandbox']['max'] =  $batch_size ;
  }

  $context['message'] = $operation_details; //Will show what chunk we're on.

  //dpm($context);

  foreach ($uids as $uid) {

    _import_user_migration_switch_to_old();
    $old_user = _import_user_migration_user_load($uid);
    db_set_active('default');
    $user_info = array(
      'uid' => $uid,
      'name' => $old_user['cust_name'],
      'pass' => $old_user['password'],
      'mail' => check_plain($old_user['email_address']),
      );

      // Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_user'] = $uid;

  $context['message'] = "Working on " . $old_user['cust_name'] . ' : ' . check_plain( $old_user['email_address']);
  $context['results'][] = $old_user['cust_name'] . ' : ' . check_plain( $old_user['email_address']);

    //Notice: Trying to get property of non-object in import_user_migration_batch_process() (line 94 of /Applications/MAMP/htdocs/lelo-pht/sites/all/modules/custom/import_user_migration/import_user_migration.module).
    if (user_load_by_mail(check_plain($old_user['email_address']))) {
    //user found
    } else {
    //user NOT found
      _import_user_migration_create_user($user_info);
    }
  }

   // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }
    _import_user_migration_update_http_requests();
}

function import_user_migration_batch_finished($success, $results, $operations) {
  if ($success) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _import_user_migration_get_http_requests())));
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array(
      '@operation' => $error_operation[0],
      '@args' => print_r($error_operation[0], TRUE),
    )));
  }
}

/**
 * Switch to database import_user
 */
function _import_user_migration_switch_to_old() {
  $other_database = array(
    'database' => 'users',
    'username' => 'root',
    'password' => 'root',
    'host' => 'localhost',
    'driver' => 'mysql',
    );
  Database::addConnectionInfo('old', 'default', $other_database);
  db_set_active('old');
}

/**
 * Create a user in new site
 *
 * @param array $user_info
 *   array('uid', 'name', 'pass', 'mail')
 */
function _import_user_migration_create_user($user_info) {
  $newUser = array(
    'name' => $user_info['name'],
    'pass' => $user_info['pass'],
    'mail' => $user_info['mail'],
    'status' => 1,
    'init' => $user_info['mail'],
    'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'),
    );
    user_save(null, $newUser);
}

/**
 * Load old user data
 *
 * @return array
 *   array('uid', 'name', 'pass', 'mail')
 */
function _import_user_migration_user_load($uid) {
  $query = db_select('lelo_customer_temp', 't');
  $query->fields('t', array('customerId', 'cust_name', 'password', 'email_address'));
  $query->condition('t.customerId', $uid);

  $results = $query->execute()->fetchObject();

  return (array) $results;
}

function _import_user_migration_update_http_requests() {
  $_SESSION['http_request_count']++;
}

function _import_user_migration_get_http_requests() {
  return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
}

```

# Answer
> 0 votes
Finally this is the answer to my problems.

User\_save is very slow for no apparent reason

so that problem (cURL slow response) made the above.

---
Tags: 7, users, importing-exporting
---


# Question
Title: Drupal and Require.js not playing nice - double load of jQuery
I’ve been given a design library from a large cooperate client built utilizing Bootstrap 3 and Require.js. It’s very robust and well-built with the various scripts using Require.js to load jQuery. Problem is, Drupal has already loaded jQuery and the double load is causing some items to fail. If I remove all the Require.js calls, Drupal jQuery stuff works great. If I remove the base Drupal jQuery file, all the stuff using the Require.js stuff works great. Here’ are options I have considered:

1. Stop jQuery from loading with Drupal, use require to load jQuery on every page - I haven’t tried this yet, but it just seems wrong. I think I can remove jQuery with hook\_library\_alter() in my theme? Wondering if anyone has tried this… My front end and admin screens
actually use 2 different themes, so I think I'd have to modify both.
2. Stop jQuery from loading with Require.js – I tried this and none of the other libraries that are loaded with require.js can find query if it’s not loaded with Require.js, so I don’t think this option works. This is my first time using require.js so maybe there is some fun fix for this I haven't figured out?
3. Add all libraries to the site with Drupal – This seems like a lot of messy work as I would have to remove all the require.js dependencies in the library, and there is an expectation that we not modify the library/framework so implementing new releases is easy.

Any other recommendations?

# Answer
I would try option 1. Require JS is pretty demanding in terms of getting all the dependencies right, so unless you want to debug that I'd load the Require JS version.

The place to look is: https://www.drupal.org/node/756722 where all this is explained.

Basically I think you should (for D7) define the Require JS stuff as a library using `hook_library` like so:

```
function hook_library() {
      $libraries['vertical-tabs'] = array(
        'title' => 'MY_STUFF',
        'version' => '1.0',
        'js' => array(
          'PATH/require_stuff.js' => array(),
        ),
        'css' => array(
          'PATH/bootstrap_stuff.js' => array(),
        ),
      );
      return $libraries;
    }

```

And on `hook_init` add it like so:

```
drupal_add_library('system', 'vertical-tabs');

```

And replace the core version of Jquery with `hook_js_alter`:

```
function hook_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/jquery.js'; // Swap out jQuery to use your version.
}

```

I wouldn't worry too much about sticking with the Drupal version of Jquery as it is very common to use the jquery\_update module to replace it anyway.
> 1 votes

# Answer
I recently had a similar issue while redesigning an existing codebase to use requireJS. It had several pages that had inline javascript calling jQuery functions so to keep things functional during the transaction I had to load jquery the old-fashioned way while migrating other parts to requireJS and this caused double loading issues as well. I've added the following under my requireJS config call.

```
define('jquery', [], function() {
    return jQuery;
});

```

Since I know jQuery will be loaded by the time require needs it, this should return the existing global jQuery variable.
> 0 votes

---
Tags: theming, javascript
---


title: Specific URL for each kind of content

text:
# Question
Title: Specific URL for each kind of content
I would like each kind of content to have its own base url, for example, example.com/international-news/friendly-url-of-node-id

How can I manage to get both a friendly url and a base url (friendly-url... and ../international-news/ respectively in the example) with the minimum possible modules (or only those from the core)?

# Answer
Use Path Auto and Token Module to achieve it. It also supports **multilingual** functionality!!

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123.

* Go to ***admin/config/search/path/patterns*** path :
> 8 votes

---
Tags: path-aliases
---


# Question
Title: How to add to index unpublished content by apachesolr?
I use apachesolr module for index content. As I understand, this module does not provide indexing unpublished content. Is it some trick to avoid that?

I try to use this hook and change status callback, but it does not work.

```
function hook_apachesolr_entity_info_alter(&$entity_info) {
  // Validate each entity if it can be indexed or not. Multiple callbacks are
  // allowed. If one of them returns false it won't be indexed
  $entity_info['node']['status callback'][] = 'apachesolr_index_node_status_callback';
}

```

p.s. it duplicate with this issue, but there no activity and it's very old.

# Answer
> 0 votes
You may want to follow this thread: Index unpublished nodes. There is no available patch right now but you'll find some hints to build your own custom module if you need to.

---
Tags: 7, search
---


# Question
Title: jQuery - 'once' won't apply a toggleclass after a click action
I want a click on #parent to toggleClass a 'newclass', on the parent's child element, 'child'. The page has an AJAX call, so I need the function to only apply on page load.

However, I can only get the 'newclass' to begin to toggle on the last AJAX call, I'm not sure why. Before the last AJAX call, clicking #parent has no effect.

Also, #parent is not unique, hence the $(this). (I only want it to toggle the class for the .child that had it's #parent clicked).

Any ideas why this won't work?

```
<div id="#parent">
  <div class="child">
  Content #1
  </div>
</div>
<div id="#parent">
  <div class="child">
  Content #2
  </div>
</div>

(function ($) {
Drupal.behaviors.arbitrarystring = {
attach:function(context, settings) {
$('#parent').once('arbitrarytitle', function() {
$('#parent').click(function() {
$(this).children('#child').toggleClass("newclass");

});
});
}
};

```

Tried setting up a JS fiddle, but was having problems to emulate the AJAX calls.

Thanks everyone!

EDIT: Here is the fiddle, without AJAX Request or the Drupal.behaviors wrapper; I was getting a syntax error when trying to close the brackets.

http://jsfiddle.net/fj6cedqf/

# Answer
You should have unique id's (#id-name) and as many elements as you would like sharing the same class (.class-name). I mean, you should not have multiple elements with same id inside HTML. Also, you cannot have \[#\] or \[.\] signs inside HTML. They should appear only inside CSS and jQuery code.

Here you can find the solution:

http://jsfiddle.net/6n02htLp/
> 2 votes

---
Tags: javascript
---


title: Show views page based on path

text:
# Question
Title: Show views page based on path
I have 3 node types:

* category
* subcategory
* product

These are all linked using Entity Reference module. All pages have a path (using autopath). What I want to do is show a view depending on the path.

So if I go to *categories/category-a/* I want to show all subcategories of that category Same for the products. I want to show all products referenced based on the path.

I'm trying to make a view with `path = categories/%`

I set a "**contextual-filter:** `content: nid`" - "provide default value" - "raw value from url". But when I visit "*categories/category-a/*" I see the node with this path. The view isn't shown.

Any idea what's wrong here?

# Answer
You could try out this Article..

The contextual filter should be "`content:nid`"

The options should be set as follows...

* The Relationship should be your "Entity Reference: Referenced Entity" relationship
* Under "When the filter value is NOT available" check "provide default value" and select "Content ID from URL"
* Apply changes and save view.
> 0 votes

---
Tags: views, path-aliases
---


# Question
Title: How to assign a CKEditor profile to a specific field?
I'm learning Drupal and right now CKEditor. I want my website to have a blog, with a complex editor for the articles, and a much simpler one for the comments. I have created two different profiles in CKEditor, but now I'm stuck and don't know what to do next...

Thanks for your help.

# Answer
> 2 votes
CKeditor profiles are assigned to text formats (admin/config/content/formats).

Ckeditor is available for "Long text" fields. When editing the field, you have to choose "Filtered text", so, if a Ckeditor profile is assigned to this format, when creating or editing the node, Ckeditor appears.

---
Tags: wysiwyg
---


# Question
Title: Show all events that are active between two dates chosen from exposed date filter
I have a problem in showing views results with an exposed date filter in D7 views 3.x.

**problem**

We have several events with a date field. It is required to fill in a start and end date. We want a visitor to choose a start date and an end date with an exposed filter in a view.

*wanted results*

The results should show every event that occurs:

* Events that occur between the two dates
* Events that are already started. So the start date is already in the past.
* Events that are in the future but the end date is not between the chosen dates.

We have already tried to configure a startdate with "equals or greater than" and an end date with "equals or less than".

Am I overlooking something?

# Answer
> 0 votes
If you have configured your view to display all events that has start date \>= x and end date \<= x then what you have done show do the job.

In order to make it easy for others to help you, I recommend that you give description of your content types date fields, update your question with export ***code*** of your view so that others look and spot mistakes if any.

In the meantime, I have created a content type called event, and give it one field called i.e. date (I have configured the date field to collect both start date and end date - only year/month/day). I then setup a view and setup two exposed filters on start\_date and end\_date of this content type with operators as greator than or equal to and less than or equal to, and they seem to work without any problem. Follow is the export code of my view

```
    $view = new view();
$view->name = 'events';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Events';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'eventsbydate' => 'eventsbydate',
);
/* Filter criterion: Content: date -  start date (field_date) */
$handler->display->display_options['filters']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value']['field'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['operator'] = '>=';
$handler->display->display_options['filters']['field_date_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value']['expose']['operator_id'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['expose']['operator'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_date_value']['group_info']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['group_info']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['group_info']['remember'] = FALSE;
$handler->display->display_options['filters']['field_date_value']['group_info']['group_items'] = array(
  1 => array(),
  2 => array(),
  3 => array(),
);
/* Filter criterion: Content: date - end date (field_date:value2) */
$handler->display->display_options['filters']['field_date_value2']['id'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value2']['field'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['operator'] = '<=';
$handler->display->display_options['filters']['field_date_value2']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value2']['expose']['operator_id'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['label'] = 'date - end date (field_date:value2)';
$handler->display->display_options['filters']['field_date_value2']['expose']['operator'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['identifier'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'events';

```

screenshot of the configuration page is as follow

If the above approach does not help you then have a look at this useful module https://www.drupal.org/project/views\_between\_dates\_filter

# Answer
> -1 votes
Do you want something like http://openwaterswimming.eu/eventslist ? You can find the complete code at http://openwaterswimming.eu/files/code\_eventlist.txt

---
Tags: 7, datetime, views
---


# Question
Title: Search form block only appear for administrarors
I have a site with three different languages on it. for a while we had a search bottom on the English site. I wanted to be on all three languages. after playing around with it, it now appears in all languages, but only for administrators. how can I make it appear for users as well?

# Answer
Most probably it's about the **permissions**. Give the users (anonymous user / authenticated user) the search permission (also), which you can do after navigating to `admin/people/permissions`.
> 1 votes

---
Tags: search
---


# Question
Title: Attempt to create an instance of field that already has an instance of that field
how can i check if an instance of a field has already been created so that the my\_module condition doesn't try to create it again? something like

```
if(!instance_exist){
//do abc
}

```

# Answer
> 0 votes
The function you are looking for is field\_info\_instance($entity\_type, $field\_name, $bundle);

for example:

```
field_info_instance('node', 'field_tags', 'article');

```

will return the field instance if a field 'field\_tags' exists on nodes of the content type 'article', NULL otherwise.

---
Tags: 7
---


title: Login block is missing from my theme

text:
# Question
Title: Login block is missing from my theme
The default login block is not listed in my theme's blocks, if I switch to Garland, it's there and if I type the direct path to the block I can access it, but I can't seem to save it to my block page... does anyone know how to resolve this issue?

# Answer
1. Go to /admin/structure/block
2. Go to your theme (top tabs)
3. Move your login Block
4. WIN!
> 3 votes

# Answer
If your login block is missing from your blocks then

* from the **Structure-\>Blocks** view click on a **tab** that has another theme, different from your custom theme, preferrably Bartik or some other default theme.
* Now locate the user login block there and click configure.
* Set it to whatever region you want it to appear in your custom theme.
* Navigate back to your theme using the tabs in **Structure-\>Blocks**
> 0 votes

---
Tags: 6, blocks, users
---


# Question
Title: Entity Reference - adding fields to reference?
I'm using taxonomy and nodes to create a tree structure. Inside the taxonomy term I created an Entity Reference (referencing to nodes). I know this looks like the world upside-down, but for this time this was the easiest way.

```
Term1 (reference to:) - Node A, Node B, Node C, Node D
Term2 (reference to:) - Node B, Node D, Node E

```

I want to add custom fields to the node, but with different values for each reference. Let's say I want to add a date field with different values for each reference. Adding a custom field to the content type won't work, because they will be the same for all references.

# Answer
> 1 votes
The Entity Reference module does not support this. You'll want to check out the Relation module. With this module the reference (relation) itself is a fieldable entity.

I do realize you'll have to write an update function to migrate your current references to relations, but aside from creating a custom table as @FriOne suggested, it's the only way to go as far as I know.

---
Tags: 7, entities, taxonomy-terms, nodes
---


title: variable api vs custom table

text:
# Question
Title: variable api vs custom table
I have a module Block No Results which displays the no results data when block has no results. **Variable Api** if I will use the variable api then I need the 4 variables for a single block to keep the no results data and displays the results. **Custom Table** If I'll go with custom table then I'll keep the 6 fields in the table.

id - primary key

module - varchar(64)

delta - varchar(32)

status - tinyint(4)

content - longblob

empty\_criteria - varchar

UNIQUE KEY `md` (`module`,`delta`)

KEY `list` (`status`,`module`)

**Overview** On every block view I need to check that whether the block no results criteria is enabled for this block.If it is then I need to check what is the empty criteria and on the basis of that I need to perform action.

**Problem** **Variable api** : If I'll use the variable api then on each block view I need to load the variables separately i.e. 5 variables load( ~5 database fetch queries)(if block no results is enabled) and 1 variable load(~1 query)(if block no results is disabled for that block). As the variable api is integrated with the cache api so on the development sites usually get the results from cache.This seems to me not good approach in the case if a site has 100's of blocks.

**Custom table** Load the whole row using the module & delta and take the appropriate action if needed.

Currently I have implemented this using the variable api. Which approach should I use ? Is there any other better approach then these ? how I can make it more better if you are going to suggest an approach ?

# Answer
> 3 votes
Not an answer per say; more of a critique of some of your assumptions with variables.

> If I'll use the variable api then on each block view I need to load the variables separately i.e. 5 variables load( ~5 database fetch queries)(if block no results is enabled) and 1 variable load(~1 query)(if block no results is disabled for that block)

In actuality all variables get loaded on EVERY pageload with a single query, including cache\_page hits (think anonymous users) unless your doing something special (`$conf['page_cache_without_database'] = TRUE;`, varnish, or boost). variable\_initialize() get's called very early; dig though drupal\_bootstrap() a little bit to see. So a variable get doesn't cost you a db query, but it's not a good idea to abuse the variables db table because the more data that's in there (KB), the slower Drupal gets.

Actual answer:
My personal preference is to use cache\_get\_multiple() if your looking at 100s of items to get; unfortunately it looks like \_block\_render\_blocks() makes this hard to do; the function that calls hook\_block\_view\_alter(). So in this case a cache\_get would be the easiest way to go. Another option is a cache loader; all in one cid (harder to manage writes) or get all cid's for the enabled blocks block\_page\_build() or `$blocks = drupal_static('block_list');` with drupal\_static(). What's ideal depends on many factors, biggest one being how large (KB) is the cached data; if its small a loader & drupal\_static() might be the fastest option. If you have a large amount of data then doing individual cache\_get() call might be better due to the lower memory usage and not loading unused data. See https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 for more details on caching.

Also be aware of cores built in block caching. Use it if at all possible. See https://www.drupal.org/project/blockcache\_alter for ideas and usage.

# Answer
> 0 votes
I would suggest using a custom table in combination with the CTools module. This has the additional benefit of making your configuration exportable with the Features module.

There is some pretty good documentation online, and if you install the Advanced Help module along with the CTools module, you'll get some pretty good documentation as well.

EDIT: CTools also caches your configuration objects for you, which means less code to write yourself.

---
Tags: 7, performance
---


title: How do I POST a new node?

text:
# Question
Title: How do I POST a new node?
I have referred many links including the following:

I tried several ways to POST a new node to a Drupal site, but I have failed. I have created a sample CCK for storing students data with name, age, gender, DOB, and added some list.

I have installed and configured the Services module (D7), and created a service end point at services.
As expected, GET is the easiest way to get details of a node in JSON. `http://localhost/drupal/services/node` simply listed all nodes.

I still can't figure out how to use the **POST** method.

1. I would like to search for the students whose name contains *john*. I tried `localhost/drupal/services/node&node[name]=john`. I used **POST Man** plugin for Chrome without success. I also tried some other ways.
2. I tried adding a new student to the site without success.

Can anyone guide me to make the above work fine?

UPDATE :

I tried adding new nodes of type **article** . It worked fine. but when i am trying to add nodes of type **Department CCK** It is showing "**s:22:"CSRF validation failed";**" Here are the screen shots

I have gone through the link https://drupal.org/node/2013781

I followed session = session\_name=session\_id but i still get an error.

# Answer
> 22 votes
Hope this will help you,

For Drupal 7

Tools used:

* Firefox Poster add-on to do tests and debugging. There may be other add-on as well. But for this example im using Firefox add-on.
* To help editing and validating the JSON data you can use
    + Edit the JSON data using this link
    + Validate the JSON data using this link

**HTTP requests**

* To make the HTTP requests, you need use the Firefox add-on POSTER.
* Two commonly used methods for a request-response between a client and server are:

+ GET
    + POST
* After the add-on is Downloaded. Open **Firefox -\> Tools -\> Poster**
* Make sure to enable the **Session authentication**. After the **Services** is configured properly, before creating the node you should **log-in**. Once logged-in you can create the nodes.
* For login use POST method, with the URL like - http://XXXXXXXX.com/demo/rulebook/rulebook\_endpoint/user/login
* If it is a **valid user** then it will return **user details** with **session ID and Name**. If not valid it will return **Access denied**
* By using Session name and ID in the POST HEADER, we can able to create new nodes
* Now after adding the HEADER, You need to make HTTP POST request and make sure user should have permissions to create node.
* If the node is created you will get the response with node link

NOTE : If you want the response in JSON then, you should always append .json at the end of the URL. eg., http://XXXXXXXX.com/test/endpoint/user.json OR http://XXXXXXXX.com/test/endpoint/node.json OR http://XXXXXXXX.com/test/endpoint/user/user\_id.json OR http://XXXXXXXX.com/test/endpoint/node/node\_id.json

# Answer
> 8 votes
**For Drupal 7 and Services 7.x-3.x**

**Step 1:** Issue a post request to `user.login` resource with your username and password.

If the login is successful, you will get a response object with 4 properties:

* session\_name
* sessid
* token
* user (object)

Screenshot from google chrome postman

**Step 2:** Issue a post request to `node` with 2 headers

* Cookie: \[session\_name\]=\[sessid\]
* X-CSRF-Token: \[token\]

Screenshot from google chrome postman

# Answer
> 0 votes
If you do *POST* to the *REST API* then you will have to put everything into *POST data*, not to *URL*. In *Postman* you can set the request to post, than type to `x-www-form-urlencoded` and below that you can add your data values. Don't forget to add *status, uid, language, type, title* and then the extra values. The resource URL should be only `HOST/REST_API_PATH/node`.

---
Tags: services
---


# Question
Title: How to create a form, using a function, located inside a class
Usually when we need to create a form we create a function inside module and call:

```
$form = drupal_get_form('function_name');
drupal_render($form);

```

Now I started using entities and created a subclass of `EntityDefaultUIController`. With a form generating function:

```
class transactionUIController extends EntityDefaultUIController {
  public function overviewForm($form, &$form_state) {
     //blah blah
     return $form;
  }
}

```

I need to get this from in an external module. What should I pass to `drupal_get_form` function?

# Answer
You can use the form callbacks provided by the entity module. So for your example (assuming your entity\_type is named 'transaction') you would call drupal\_get\_form like so:

```
drupal_get_form('entity_ui_overview_form', 'transaction');

```

You can find other Entity UI form related functions here.
> 0 votes

---
Tags: forms
---


# Question
Title: Is it possible to alter nodes on export with Node Export
I want to write my own module which changes a few things upon exporting of nodes with Node Export. I saw that there are some API's. But I haven't seen any working examples. Is there some documentation on the API of Node Export? And if not can someone provide me with some examples of changing data for export and changing it again upon import?

Thanks, Jaap

# Answer
> 1 votes
You can manipulate the nodes in hook\_node\_export\_node\_alter() and hook\_node\_export\_node\_import\_alter() See node\_export.api.php for more information.

---
Tags: importing-exporting
---


title: Cannot alter title on user profile page

text:
# Question
Title: Cannot alter title on user profile page
I've created a custom module called **renameprofile** to alter the title on my user page, but it doesn't seem to be working. Any idea what is causing this issue? Btw this is on the `?q=user` page.

**renameprofile.module**

```
<?php
function renameprofile_page_alter() {

  global $user;

  if(drupal_get_title() === isset($user->name)) {
    drupal_set_title('My Sharecab');
  }
}
?>

```

**renameprofile.info**

```
name = Rename user profile page title
description = This module renames the profile page title
core = 7.x

```

# Answer
Yeah, that's an odd approach with `=== isset()` basically checking if `drupal_get_title == TRUE;` whereas `drupal_get_title` returns a string title.

Something like this should work, in template.php or module (clear cache).

It will set the `$title` variable for `page.tpl.php`

```
/**
 * Implements hook_preprocess_page
 */
function MODULE_preprocess_page(&$variables){
  // Set title on user account pages.
  if ($account = menu_get_object('user')) {
    $variables['title'] = t('My Sharecab');
  }
}

```
> 2 votes

---
Tags: 7
---


title: how to debug drupal_http_request

text:
# Question
Title: how to debug drupal_http_request
I'm working on a module that takes a form submission and posts it to a rest api, using the webform validator module's hooks. I'm trying to debug what's going wrong, and I have the following code, which correctly displays $data and $url but nothing for $result (I'm assuming it's null?).

I'm new to drupal and I wonder what I'm doing wrong, with the http\_request that it comes back null, or what else I can do to debug.

```
      $options = array( data => $data,
                        method => 'POST');
      //verify $data
      $errors['item_2'] = $data;
      $errors['item_3'] = $url

      $result = drupal_http_request($url, $options);

      // display the returned JSON result as a form error
      $errors['item_1'] = json_decode($result);

```

# Answer
`drupal_http_request` doesn't just return the response data, it returns an object.

**Return value**

**object** An object that can have one or more of the following components:

**request**: A string containing the request body that was sent.
**code**: An integer containing the response status code, or the error code if an error occurred.
**protocol**: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
**status\_message**: The status message from the response, if a response was received.
**redirect\_code**: If redirected, an integer containing the initial response status code.
**redirect\_url**: If redirected, a string containing the URL of the redirect target.
**error**: If an error occurred, the error message. Otherwise not set.
**headers**: An array containing the response headers as name/value pairs. HTTP header names are case-insensitive (RFC 2616, section 4.2), so for easy access the array keys are returned in lower case.
**data**: A string containing the response body that was received.

For example, you can check

```
// This is the actual response data.
drupal_set_message($result->data);
// if there's an error, it'll  be in here
drupal_set_message($result->error);

```

or, if using the devel module

```
dpm($result);

```

In your case, you might just need:

```
if (empty($result->error) {
  $errors['item_1'] = json_decode($result->data);
}else{
  // An error occurred, log, show msg etc...
}

```
> 1 votes

---
Tags: webforms, 8
---


# Question
Title: How to prevent users editing their profile, but allow password change?
I have a Drupal 7 site that has additional fields added to the user profile page, to capture additional information (with these fields then displayed on the public-facing profile).

Only administrators should be able to edit non-admin profiles.

However, I am using !login\_url (one time login) functionality in email confirmations to allow new users to set their own password and I need to retain this feature.

I have installed the User Protect module, but unless I enable the 'Edit own user account' permission, the one time login link returns a 'You are not authorized to access this page' message and the password cannot be entered.

Is there a way via User Protect, another module, or via custom code for me to retain the Change Password option, but remove access to all other fields that have been added to build a more complete profile?

# Answer
> 0 votes
You might be able to use the module: Password Hustle

> Adds the password set form as an optional fields on the one click login. In other words, we encourage (hustle) the user into setting their password as they log into the site via a one click login.

---
Tags: 7, users
---


# Question
Title: How do I use Features to export a custom content type to a stand-alone module
This is a follow-up on, but not a duplicate of, Programmatically creating a content type with file field in a custom module.

As suggested by Tenken in a comment to the OP of that question, it is easy to do this by using the core **FieldUI** module to create the fields, and then then use **Features** to export the fields to a custom "Feature" module.

You can then install the "Feature" module as any other module that implements a custom content type, but you need to have **Features** installed for it to work.

I want to use the **FieldUI** and **Features** to create a custom content type module, but the module should be stand-alone (i.e. not depend on **Features** for (re)creation of the content type).

Is this doable? Or is **Features** a dead end in my use-case? I.e.: If I want a *stand-alone* module, I must create it from scratch.

And if it makes sense to use **Features**, what do I need to do in order to transform the "Features" module into a stand-alone one?

(I've searched for similar questions, but not found an answer that describes how you make the generated "Features" stand-alone.)

# Answer
> 2 votes
The features eco-system simply implements certain hook functions (like `hook_field_info` for example). It wraps these core api functions with import/export code.

When you export your content type using Features you can inspect what it creates -- besides a `mymodule.install` and `mymodule.module` files.

By examining the hooks the features implements for your exported content type -- there is nothing stopping you from copying/renaming these exported function definitions and migrating them to a new module's `hook_install()` function. Thus, creating a new content type which you used Features to create the building block(s).

---
Tags: features
---


title: Can't access my website

text:
# Question
Title: Can't access my website
I can't access my website. I guess it has been hacked. Some drupaldev user is already been created and is in admin list. I have blocked that user multiple times, but it reappears again and again in my admin panel list. My site has also faced spamming, which i stopped by disabling registration module. But i believe its too late now.

How can i prevent letting this user access my website? What have i missed in my security constraints? Please help.

Drupal Version : 7.17

# Answer
> What have i missed in my security constraints?

I looks like you're running an outdated version of Drupal (ver. 7.17) with many severe security issues including the one known as "Drupageddon" (fixed in ver. 7.32).

First, you must start reading up on the Drupal Security advisories, in particular SA-CORE-2014-005 - Drupal core - SQL injection, PSA-2014-003 and FAQ on SA-CORE-2014-005 \- they will tell you what you've missed regarding *Drupageddon*. This flowchart is a great resource.

To get back the control over your site, you should simply delete it, and start recreating it from scratch on a different server, since the attacker may have a root kit on your present server. Change the password of the db-user that Drupal uses, and the passwords of all privileged accounts. If you want to keep your content, roll it back from a backup created *before* Oct. 15 (you have backups, don't you?).

If you don't have backups, there are some tools (including a *Drush* command named Drupalgeddon) that may be use for forensics and part clean-up of an compromised site. I do *not* recommend that you use these tools, as there is no guarantee that they'll able to find all infected areas on your site and web server. But they're the last resort, if scrapping the site and starting over is *not* an option.

You should also start reading up an *all* Drupal SAs. Or even better, subscribe to them: Log in on Drupal.org, go to your user profile page and subscribe to the Drupal security newsletter on the *Edit » My newsletters* tab.

Contributed modules frequently have security flaws. These are eventually fixed, but the fix also tells all the bad guys how to exploit *unfixed* sites. That means that to keep your site secure, you must make sure you install security updates in a timely manner. That's why subscribing to the security newsletter is so important.

Custom modules made by inexperienced programmers is a huge risk. If you use custom modules, make sure you have their code reviewed by someone experienced in security.
> 3 votes

---
Tags: security
---


# Question
Title: How to change the HTML of the commerce shipping service form on checkout pages?
Right now, the HTML of the commerce shipping service consists by input buttons, where you select the desired method.
I'd like to is to have it in the form of a select, and - more importantly - have no default shipping method selcted.
How to do it?

# Answer
> 1 votes
As suggested by clive, You should try this:

```
function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

```

or

```
function MYMODULE_form_alter($form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}

```

---
Tags: commerce
---


title: Menu items with Userpoints total

text:
# Question
Title: Menu items with Userpoints total
Is it possible to show the current total userpoints a user have next to menu item?

example menu: Home | Downloads | **My Points (24)** | Logout

if it's possible, how would one do this (beginner)

# Answer
This snippet will return you user points :

```
<?php
print userpoints_get_current_points($user->uid);
?>

```

But to Place this PHP snippet in menu link, you may need Menu views and PHP Menu Modules
> 1 votes

---
Tags: routes, userpoints
---


# Question
Title: Site affected by PSA-2014-003, revoke all public keys?
I didn't patch my website right after PSA-2014-003, it run about one week unpatched.

Now, I'm moving my website to a new server, using an old database backup. In my old server, I used an passphrase protected authentication key to login to the server over ssh. The website in question doesn't use SSL (https).

In the chart on http://drupal.geek.nz/blog/your-drupal-website-has-backdoor, is says: "Revoke public keys for any of the server's private keys." I don't really understand what does it means. Does it refers to certificate-authenticated SSL (https://) or does it refers to the authentication keys used to login to the server over ssh? Do I have to generate a new pair of authentication keys for my new server?

Thanks!

# Answer
### Short answer

You don't need to replace your SSH-keys if only their *public* part was stored on the server. And that's usually the case if you've only used it for logging into the server.

### Long answer

Since the server may have been compromised all the data on the server might have been copied by any number of attackers. This includes everything used for authentication:

* *private* keys (SSH, SSL, GPG, …)
* passwords, if they were stored in an insecure manner
* API-keys for other web-services
* The mysql password

You should replace all of them.

For SSH's public-key authentication you usually copy your *public* key into the `~/.ssh/authorized_keys` file. Your private key remains safely on your computer. Therefore there is no need to replace your ssh-keys. That's the main benefit of asymmetric encryption: Everyone can have your public key without compromising the security.
> 1 votes

---
Tags: security
---


# Question
Title: View AJAX Refresh causing multiple refreshes
In attempting an AJAX refresh on several views contained in separate blocks on a single page, I seem to be coming across a problem. This is running on D7.34

The idea is for the page to contain 4 blocks, each with a view sorting by random - then using a simple click() on the block title to activate a refresh of any given view allowing the user to view a new random item. I am using the common:

```
var selector = '.view-dom-id-' + dom_id;
jQuery(selector).triggerHandler('RefreshView');

```

to achieve this, which works perfectly. The trouble I am having is in increasing multiples of refreshes:

clicking on one view refresh does refresh the view, but it seems to create a counter, when a different view is refreshed, that second view refreshes twice. Then going back to the first, the view would refresh 3 times, and so on. It doesn't happen if clicking on the same view multiple times - in this case it only refreshes once as expected, it only occurs when switching between refreshing different views, however it continues to "count" these refreshes which then effect the number of times a different view is refreshed when the other refresh is triggered.

* I have confirmed that the selector is correct and obtains the unique dom\_id for that view
* I have confirmed that the call jQuery(selector).triggerHandler('RefreshView'); only occurs once per click
* this occurs in Drupal.Behaviours, drupal\_add\_js, and straight JS added to a tpl file - they all "work" but with the same refresh issue
* I have used once() in the call as well with no perceived effect

It seems like when the triggerHandler triggers the refresh, the view itself is refreshing multiple times for reasons I can't seem to figure out. I have tried dozens of permutations now without any change in behaviour. I can't post of all the code from my attempts, but here is the last attempt which "works" but still refreshes multiple times - this is a straight JS addition to page.tpl, layed out for easier reading:

```
<script>
  jQuery(document).ready(function()
  {
    jQuery('#block-views-random-cat-block h2').click(function()
    {
      jQuery.each(Drupal.views.instances, function(i, view)
      {
        if (view.settings.view_name == "random_cat")
        {
          var selector = '.view-dom-id-' + view.settings.view_dom_id;
          jQuery(selector).triggerHandler('RefreshView');
        }
      });
    });

    jQuery('#block-views-random-dog-block h2').click(function()
    {
      jQuery.each(Drupal.views.instances, function(i, view)
      {
        if (view.settings.view_name == "random_dog")
        {
          var selector = '.view-dom-id-' + view.settings.view_dom_id;
          jQuery(selector).triggerHandler('RefreshView');
        }
      });
    });
  });
</script>

```

If I limit the page to one view only, it seems to work fine - it's only in the fact that there are multiple views that I see this effect.

# Answer
**EDITED ANSWER**

This seems to work now. Checked via the spinner and a console.log statement. Had to chain once() just before click binding. :

```
(function ($) {
    Drupal.behaviors.blockRefresh = {
        attach: function (context, settings) {
            jQuery('#block-views-block-1-block h2').once().click(function () {
                    jQuery.each(Drupal.views.instances, function (i, view) {
                        var selector = '.view-dom-id-' + view.settings.view_dom_id;
                        if (view.settings.view_display_id == "block") {
                            console.log('1');
                            jQuery(selector).triggerHandler('RefreshView');
                        }
                        jQuery(selector).unbind();
                    });
                });

            jQuery('#block-views-block-1-block-1 h2').once().click(function () {
                    jQuery.each(Drupal.views.instances, function (i, view) {
                        var selector = '.view-dom-id-' + view.settings.view_dom_id;
                        if (view.settings.view_display_id == "block_1") {
                            console.log('2');
                            jQuery(selector).triggerHandler('RefreshView');
                        }
                        jQuery(selector).unbind();

                    });
                });

            jQuery('#block-views-block-1-block-2 h2').once().click(function () {
                    jQuery.each(Drupal.views.instances, function (i, view) {
                        var selector = '.view-dom-id-' + view.settings.view_dom_id;
                        if (view.settings.view_display_id == "block_2") {
                            console.log('3');
                            jQuery(selector).triggerHandler('RefreshView');
                        }
                        jQuery(selector).unbind();
                    });
                });

        }
    }
}(jQuery));

```
> 1 votes

# Answer
This is not really an answer, but I put it here so I could format my code.

**This seems to me like it may be a bug.**

I have been playing around with this for about an hour and a half now and could not get it to work as expected when I had more than 1 view on a single page.

To test I made a view called 'testing' with 2 blocks with the names 'block\_1' and 'block\_2'. I placed both of these blocks on a single page and added the code below to refresh them via ajax when clicking the heading.

code:

```
(function ($) {
  Drupal.behaviors.myAjax = {
    attach: function (context, settings) {

      jQuery.each(Drupal.views.instances, function(domid, view){

        if(view.settings.view_name == 'testing' && view.settings.view_display_id == 'block_1' ||
           view.settings.view_name == 'testing' && view.settings.view_display_id == 'block_2') {

          jQuery('#block-views-'+view.settings.view_name+'-'+view.settings.view_display_id.replace('_', '-')+' h2', context).once().click(function(){
            jQuery(view.element_settings.selector).triggerHandler('RefreshView');
          });
        }
      });
    }
  };

})(jQuery);

```

This ended up with the same behavior as the OP.

I think you should file a issue report in the views module issue queue
> 2 votes

---
Tags: 7, views, ajax
---