# Question
Title: Can I downgrade to drush 5.x using homebrew?
I used `brew install drush` which installed the latest stable version (6.1), when I need the 5.x branch.

This GitHub issue indicates a drush 5.x package was made available for homebrew, but I'm unsure how to install it.

# Answer
Homebrew install specific version of formula? \- this answer on drupal.stackexchange might help you to get the overview of how specific formulas can be installed via homebrew.

Short version related to your specific question:

1. Update homebrew with `brew update`.
2. Get all the versions available for drush formula with `brew versions drush`
3. You will see a list of commits that point to specific drush versions, e.g.,

```
6.1.0    git checkout a188056 Library/Formula/drush.rb
6.0.0    git checkout 1264aaf Library/Formula/drush.rb
6.0-rc4  git checkout 39b2450 Library/Formula/drush.rb
6.0-rc2  git checkout 2a61472 Library/Formula/drush.rb
6.0-beta1 git checkout 54ba68d Library/Formula/drush.rb
5.9      git checkout 81108ad Library/Formula/drush.rb
5.8      git checkout 91cb127 Library/Formula/drush.rb

```
4. Go to the base brew directory by typing `cd $( brew --prefix )`
5. Uninstall your current drush installation with `brew uninstall drush` (this won't affect your settings in ~/.drush directory).
6. Checkout the drush formula for specific commit that you are interested in. If you want to have drush version 5.9, type `git checkout 81108ad Library/Formula/drush.rb` and you will have a brew formula available for this particular version.
7. Install drush (version 5.9) with `brew install drush`
8. Type `drush --version` to make sure you have the correct version installed.
> 3 votes

# Answer
The standard way to install drush is via pear.

You can install a specific version using the following command:

```
pear channel-discover pear.drush.org
pear install drush/drush-5.9.0

```

Available versions can be found on the Drush pear page: http://pear.drush.org/
> 2 votes

# Answer
If you have the most up-to-date version of Homebrew, you can use the `brew switch` command. For example in my terminal I switched to 5.9, then back to 6.2:

```
KTaylor$ brew switch drush 5.9
Cleaning /usr/local/Cellar/drush/5.8
Cleaning /usr/local/Cellar/drush/5.9
Cleaning /usr/local/Cellar/drush/6.0-beta1
Cleaning /usr/local/Cellar/drush/6.0-rc2
Cleaning /usr/local/Cellar/drush/6.1.0
Cleaning /usr/local/Cellar/drush/6.2.0
2 links created for /usr/local/Cellar/drush/5.9

KTaylor$ brew switch drush 6.2.0
Cleaning /usr/local/Cellar/drush/5.8
Cleaning /usr/local/Cellar/drush/5.9
Cleaning /usr/local/Cellar/drush/6.0-beta1
Cleaning /usr/local/Cellar/drush/6.0-rc2
Cleaning /usr/local/Cellar/drush/6.1.0
Cleaning /usr/local/Cellar/drush/6.2.0
2 links created for /usr/local/Cellar/drush/6.2.0

```
> 2 votes

---
Tags: drush
---


# Question
Title: How to add a custom link to login form block with hook_form_alter
How to add a link with custom path to my login block with hook\_form\_alter. I 've created a custom module but i dont know what to add to my hook\_form\_alter function.

# Answer
In Drupal 7 you can use **#markup attribute**, as suggested by MOLOT

```

/**
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      $form['link'] = array('#markup' => l(t('Link text'),'node'));
      break;
  }
}
```

Note:
> 4 votes

---
Tags: forms, users, navigation
---


title: How can I activate a horizontal tab?

text:
# Question
Title: How can I activate a horizontal tab?
Drupal 7 has the field group module which contains a `horizontal_tab.js` file.

Inside this file i found this written

```
// If the current URL has a fragment and one of the tabs contains an
// element that matches the URL fragment, activate that tab.
if (window.location.hash && $(window.location.hash, this).length) {
   tab_focus = $(window.location.hash, this).closest('.horizontal-tabs-pane');
}

```

Can someone explain how this would work and what exact url i should call so that a particular tab is activated.

# Answer
`window.location.hash` returns the part of the URL after the *#*, including the *#*.
Passing to `$()` a string like, for example, "#tab1" selects any element that uses "tab1" as ID. (Differently, ".tab" selects any elements that uses "tab" as CSS class.)

$(window.location.hash, this) select all the elements that has `window.location.hash` as CSS selector, using `this` as context; `this` is the element on which an handler is triggered.
$().closest() returns then the first ancestor element that matches the selector passed ad argument.
> 2 votes

# Answer
horizontal-tabs.js file have line 42 which is "this.id". so all your tab have a particular id so just print "this.id" and you can easily find out id of your tab. after finding this id you just have to pass in your url after # ex : alert(this.id); its print all id one by one choose id of tab which you want to set activate
> 0 votes

---
Tags: 7, javascript
---


title: Cannot setup Drupal anymore

text:
# Question
Title: Cannot setup Drupal anymore
Ever since I switched to a brand new retina MacBook Pro, I'm not able to setup a new Drupal installation anymore...

I use MAMP and I configure my `vhosts.conf` so I can work on virtual hosts (like `dev.newproject.com`). But whenever I try to install a new Drupal installation, it looks like the setup is confused...

Normally, you have

```
 1. Choose profile
 2. Choose language
 3. Verify requirements
 4. Set up database
 5. Install profile
 6. Configure site
 7. Finished

```

But for some reason, after step 5, het installation goes back to step 1 or 3 or whatever step... When I look in my database, it looks like Drupal has been installed and also a `settings.php` file was created, but I'm in an infinite set-up loop...

Has anyone ever experienced such weird behaviour? And how can I fix this?

# Answer
> 1 votes
It appears more people suffer from this issue. It has nothing to do with the brand new retina structure.

This question on SE describes the same issue. Solution is waiting a few seconds WITOUT filling in the database credentials again and refresh the page. You'll see, the installation profile completes.

# Answer
> 1 votes
It could be write permissions of the files - try `chmod -R a+rw .` command in Terminal in the root of your drupal folder. It could be a time out meaning that the database is not been written correctly (don't have a remedy for that, except for not using a native setup, but rather a Virtual Machine, VM-based setup...)

You might want to consider a VM-based setup (which would more closely resemble your production environment), see a guide I wrote to using Vagrant to automate generation of a setup here: https://stackoverflow.com/a/15067918/227926

# Answer
> 0 votes
Check your MAMP error logs. It is very probably, than in a default MAMP installation (with no modifications), either your MySQL or PHP ran out of memory while in the midst of installing the default profile.

Also, did you take a look at this answer? It has some excellent links.

---
Tags: installation, 7
---


# Question
Title: Drupal 7: Using Views to display articles with a taxonomy that is also selected for the current user
I'm trying to make a View that displays all articles having the same value in an taxonomy field as the current user has in its taxonomy field (taxonomy is "Work Location" and I want to display the work location news)

For that I created the taxonomy and added several locations. Then I added a field based on this taxonomy to the user and to the article content type.

Now I'm trying to create the View but I just can't figure it out.

# Answer
> 1 votes
Found my own solution: See this link: http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-a-user-profile-field/

---
Tags: views, entities
---


# Question
Title: Field:REWRITE , Contextual filters Views 3
i am pretty new to drupal 7 , and i have managed to create a view (conferences\_details) with a contextual filter Content:Nid, the link to the view is now conference\_details/% How then do i include node id to the title field in the page that links to the respective conference\_details/% view page.? I have tried to REWRITE output field:Title as link using: conference\_details/%nid conference\_details/%Nid conference\_details/\[%nid\] conference\_details/\[Nid\] conference\_details/\[nid\] with no luck. Can you please help. on how to do this . what i m trying to do

# Answer
You should call **Content: Nid (Nid)** field above the conference\_details field, as showing below Than only \[nid\] will be available for **REPLACEMENT PATTERNS** for `Rewrite the output of this field` as `Output this field as a link`

edit the **Content: Nid (Nid)** configuration
> 1 votes

---
Tags: views
---


# Question
Title: Is there an optimal method to grant permissions for a newly added permission defined by hook_permission?
I'm attempting to deploy a new permission and granting in a single update.

I have **custom.module** which defines a new permission with `hook_permission`:

```
function custom_booking_permission() {
  return array(
    'custom allow registration' => array(
      'title' => t('Fill out Registration Form'),
      'description' => t('Allows a user to register their online account.'),
    ),
  );
}

```

And then in the **custom.install** in `hook_update_n`:

```
function custom_booking_update_7002() {
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('custom allow registration'));
}

```

The problem is that when I deploy this code and run `drush updb -y` in my script, I get this error:

> SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'module' cannot be null \[error\]

Which as I understand it is because Drupal has yet to recognise the new permission in `hook_permission`.

I have other aspects to the update script such as enabling modules and reverting features, and then running `drush updb` later in the script works fine. However I've always believed that `drush updb` should be as early as possible. Maybe I just need to be more flexible.

Alternatively I was thinking about either an SQL insert to avoid the grant permission validation, or running a `drush php-eval` later in the deployment script separate from `drush updb`. Both strike me as undesirable.

# Answer
> 1 votes
The only reason Drupal would not know of the new permission is because it hasn't yet registered your hook. This would only happens after a cache clear.

I would not advise to run a full cache clear before an update (as that might well invoke code that will expect the update to have been run already). Maybe you could get away with clearing the cache of hooks in module\_implements. You could call this in your hook\_update\_N before setting the role:

```
module_implements('permission', FALSE, TRUE);

```

But even that feels a bit risky ; it is best not to interfere with the way things run, you might end up with debugging headaches.

Otherwise I don't think there is a perfect solution. Drupal just doesn't have a 'post-update' style hook. You could implement such a hook yourself (maybe using a variable\_get/set and hook\_init ; or as a drush script as you suggest), however this feels like a complicated way to do what could otherwise be done with a simple SQL query.

If you know your target uses an SQL database, then I think that, while not entirely satisfying, the SQL insert statement is the simplest solution.

---
Tags: users, deployment, updating
---


title: Get views exposed filter values

text:
# Question
Title: Get views exposed filter values
I have a view in which I want to have a link that passes the current exposed filters values through to another custom page (not a view).

For example if the "Day One" checkbox is checked I want my link to be able to reflect this checkboxes value.

```
<a href="page?checked=day+one">Link</a>

```

Is there some form of array where all exposed values are stored when a view is shown? I can't seem to find one

# Answer
I got what I needed after reading a couple of views docs.

```
 $view = views_get_current_view();
 $view->exposed_input['filter_name']

```
> 2 votes

---
Tags: views
---


title: Views entity reference field

text:
# Question
Title: Views entity reference field
I am trying to create a news content type which can display related content.

In the news content type I have an Entity Reference field with unlimited values, which is used to select the nodes which should be "Related" to the current node.

I have created a view and managed to get it to display all content which is "related" to ANY node with a content type of news using the relationship setting, but i can't manage to get it to display content related to a specific node.

What am I doing wrong? I can provide more info if I have missed anything.

# Answer
I recommend you to use eva module. visit this link (comment 3), I tested this solution and it works.
> 1 votes

---
Tags: entities, views
---


# Question
Title: Drupal doesn't send email to reset password
While having difficulty logging, I reset my password but the page stays and does no form action.

After I changed my password in the mysql database, I went to log in and the page does nothing even when I hit submit. Is there something wrong with my installation?

# Answer
Taking a quick peek at your code (at http://cie.austin.utexas.edu/uex-cm/user/password) it looks like something is overriding the default HTML output for your forms. You're missing the `<form>` tags and the associated `action` and `method` attributes.

If you're looking for a quick fix (just to login one time) you can use Chrome Inspector or Firebug or similar to add the `form` tags around your form elements:

```
<form action="/uex-cm/user/login" method="post" id="user-login" accept-charset="UTF-8">
  // Your existing form elements
</form>

```

But ultimately, you'll need to figure out what is stripping the `<form>` tags from your HTML.
> 1 votes

# Answer
Use the Chrome DevTools to see if there is any kind of errors related to this, and use the "Network" tab to see if the request is triggered when you hit submit button.

Another thing to check is the logs, check the Apache error log.

You can also check the drupal log:

* If you have enabled the dblog module, check the watchog table to see if you can find an error related to this problem.
* If you have enabled the syslog module, check the syslog to see if you can find the problem.

If you have drush installed on the server, run:

```
drush core-requirements

```

to see if there is something that may be wrong in your Drupal installation.
> 0 votes

---
Tags: users
---


# Question
Title: How to access Machine name fields in PHP?
If I go to `admin/config/people/accounts/fields` I can see a lot of fields being mapped for LDAP on my server.

For example - for first name there is a machine name "field\_fname".

How can I access this on my webform using PHP?

Like I want to display something like this on my webform through PHP:

> "Hello first\_name last\_name, how are you ?"

# Answer
Here is a little code snippet that should load the value of field\_fname into a variable called $first\_name.

```
global $user;
// Load the user object
$user = user_load($user->uid);

$first_name = $user->field_fname[LANGUAGE_NONE][0]['value'];

```
> 1 votes

# Answer
You can reference fields in PHP like this Reference Custom Field on User Profile

I'm not sure about Webforms and PHP but you can retrieve fields with PHP fairly easily.
> 0 votes

---
Tags: 7, webforms, authentication-authorization
---


# Question
Title: Drupal core tries to update to current version
Many sites on my server are running Drupal 7.23, I usually use Drush to update them without any issue. Eveything works fine with modules and themes but Core keeps installing 7.23 on itself.

The *admin/reports/updates* page display this :

```
Drupal Core 7.23
  Recommended version: 7.23
  Security update: 7.24
  Last version: 7.25

```

It obviously tries to update to the recommended version, which is in this case the current one (7.23).

I use the permissions guidelines given in the script on the bottom of this page. I tried to change the file owner, it is not working. We recently installed Nginx as a reverse proxy on our server but the problem still the same calling directly Apache.

I also have some sites running Drupal 7.24 and no issue when updating to 7.25.

Any clue on the origin of this issue ?

# Answer
I found the solution, with the following command line.

```
drush pm-update drupal-7.25

```

I still do not understand why the regular update fails but this last command works fine.
> 2 votes

# Answer
I don't have any installation with 7.23, but would you try to do first a security-only update:

```
drush pm-update --security-only

```

Maybe that would do the trick that it updates to 7.24, which is a security update. Then you can update it again to 7.25 in a regular way.

As I said, I didn't test it, but it worths to try.
> 1 votes

# Answer
This is likely a drupal.org updatexml bug. A regression in https://drupal.org/node/2167845#comment-8370565. Also reported at https://drupal.org/node/2167845#comment-8370565
> 1 votes

---
Tags: updating
---


# Question
Title: How can I setup a site with Acquia Dev Desktop 2 beta?
I'm using the new version of Acquia's Dev Desktop beta 2 (https://docs.acquia.com/dev-desktop2) and I want to use it to test and develop on Drupal 8, but it seems tied to a specific set of distributions (ex. commons, COD, Acquia Drupal) and doesn't have the option to install a separate installation. How can I use this for another version of Drupal, besides the versions they are offering?

# Answer
To do this, I used dev desktop to create the site instance (instantiating the database and vhost files within Apache) than overwrote that with the install I wanted. Specifically,

I created my site instance normally, selecting "Acquia Drupal" or any of the installations when it asked me to choose a distribution.

For my site settings, I changed it from the long name to 'drupal8' for simplicity

then I went to my local sites directory through terminal and removed the Drupal 8 installation it created (these commands assume OS X environment)

```
cd ~/Sites/Dev\ Desktop/
rm -rf ./drupal8

```

Now I can add whatever I like back into this directory, making sure I create it with the same name:

```
git clone --branch 8.x http://git.drupal.org/project/drupal.git ./drupal8

```

Now we should be able to install this normally with a couple changes at the install stage. For the database settings, you can use

```
username: drupaluser
password: <blank>

```

as Dev Desktop uses these credentials for all the databases.

Under advanced configuration there were two other settings you need to get this to work:

```
port: 33067
localhost: 127.0.0.1

```
> 5 votes

# Answer
There is an even easier way to do this via drush:

```
$ mkdir path/to/your/new/docroot
$ cd path/to/your/new/docroot
$ drush dl drupal-8.x

```

You then simply open acquia dev desktop 2 and select "import local site" and tell it to create you a new database.

Acquia basically handles the rest for you and creates you a fresh database. It will pre populate most of the details for you, including tagging the acquia specific details onto your settings.php file.

The only setting I had to change was the database port (change to 33067) and complete the install.

This will keep your code living outside of the dev desktop docroot but it works just fine. This is the same process I used to import sites I had already developed using a slightly different local workflow prior to using Acquia.
> 1 votes

---
Tags: 8, acquia-dev-desktop
---


# Question
Title: Rules: how to create variable with PHP and $_SERVER['HTTP_REFERRER']
I want to parse the query string off the HTTP\_REFERRER and make that available as a variable for actions to use.

I feel like one of these options should let me do that, but I can't be sure...

The concept is simple

```
<?php
  $parts = parse_url( $_SERVER['HTTP_REFERRER'] );
  parse_str( $parts['query'], $q );
  // now set $q (or its elements) as the variable
?>

```

# Answer
Turns out I just had to look harder and change my expectations a little.

1. Click `Add a Variable`
2. Select `text` (for my scenario)
3. In the `Value` field, you can then use php to echo out a value for a single variable

I was hoping to be able to create a variable with a type of 'object' (or similar) so that I could use the url values like `[url:param1]` or `[url:param2]`.

I have not found a way to do that - I just created a different variable for each of the two parameters I needed off the query string.
> 1 votes

---
Tags: 7, rules, actions
---


# Question
Title: How to restrict access to private files to members of an organic group?
I have an organic group with a file field that stores its files in a private directory (sites/default/files/private/). These files are visible only to members of that group. But, as is commonly known, if someone guesses the Drupal path even if he is not a member of that group or not even logged in, he can access that file by using the correct file link directly.

How can I restrict file access to group members?

# Answer
OG provides no access control on attached files. I ran into the same situation and came up with two options.

The file depot module integrates nicely with OG and does prevent users who are not members of a group from accessing files that are attached to a group.

> The filedepot module is full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.

Another option is writing a custom module that implements `hook_file_download()`. In that module you would have to get the node id of the file attachment then use that to determine what group the node belongs too then from there determine if the logged in user is a member of the group. If they are not a member of the group the module would return -1 which would give them access denied if they try to directly download the file via url.
> 5 votes

# Answer
What John said is correct. In open scholar there is an option for private files and groups. We then using hook\_file\_download and verifying if the user has the privilege for that(in the group level and also site wide level)
> 0 votes

---
Tags: organic-groups, files
---


# Question
Title: How do you apply timezone formatting to a date?
I'm trying to build my own output for a date field \*see Group multiple times by day (multi-value date field) \*, but the problem I'm having is how to apply the timezone?

This article -\> Date value to different date format and nearly every other reference out there tells me that it should be applied by default. But it isn't.

What I'm doing is theming the field with:

```
function theme_field__field_times($vars){
    $dates = $vars["element"]["#values"];
    foreach($dates as $item){ // there are many dates, so we'll cycle through each one
        $date = ('U', strtotime($item['value'])); // convert to unix time
        print('This date renders as: '.format_date('$date', 'custom', 'D d/m/Y - g:ia', '', date_default_timezone_get());
    }
}

```

Which outputs, for example, **27/07/2011 -1:10pm**. The value should be **27/07/2011 - 11:10pm**, or the date that my function spat out +10hours - the timezone ('Australia/NSW') that should have been applied...

date\_default\_timezone\_get() is returning the correct timezone.

If I let Drupal render the dates using it's default field theming, the dates are right.

So why isn't the timezone being applied? How do I fix it?

# Answer
> 2 votes
I did something along the lines of this for a date field coming in as UTC that I wanted output using my site's timezone.

```
print format_date(strtotime($row->field_data_field_event_field_event_value.' '.$row->_field_data['nid']['entity']->field_event['und'][0]['timezone_db']));

```

# Answer
> 1 votes
The arguments you pass to the function are wrong; in particular, what you pass as last argument should be the one before it.
The arguments the function accepts are `format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)`, but your fourth argument is an empty string, and then you pass the timezone identifier as last argument, which should be the language identifier.
You are also using `'$date'` as first argument.

Try with the following call:

```
format_date($date, 'custom', 'D d/m/Y - g:ia', date_default_timezone_get()).

```

# Answer
> 1 votes
When you convert the time-string to a timestamp using the strtotime function, it already applies the default timezone. Later, when calling format\_date, the timezone is applied again - which breaks the calculation.

The solution is to add "UTC" to your time-string, which sets the "neutral" timezone. So you get a timestamp in UTC, which is then formatted and converted to the default timezone by format\_date().

---
Tags: 7, datetime
---


# Question
Title: Custom Line Item Loses commerce_unit_price and commerce_total
I'm working on commerce\_layaway and running into an issue with my custom line\_items. I've been using the commerce\_shipping module as a base to work from.

I've added a new checkout page and pane. The current sequence of events is - Review cart, Shipping/Billing Information, **Select Layaway option**, Select Shipping option, Credit card information, Review, submit transaction.

When I select the layaway option I want to use, the commerce\_line\_item of type 'layaway' is created and has the commerce\_unit\_price and commerce\_total price. At this point the line\_item has been saved (which is why we have the commerce\_total price on the line item). Moving on to the next step.

During the submission of the shipping pane form the following error occurs.

```
EntityMetadataWrapperException: Unable to get the data property currency_code
as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue()
(line 442 of /var/aegir/platforms/commerce-7.x-1.3/profiles/worxco/modules/
secondary/entity/includes/entity.wrapper.inc).

```

This occurs because when the commerce\_order\_calculate\_total($order) function is called it loads up the order\_wrapper and loops through each line item. It gets the pricing of the commerce\_total and for some reason when it gets to my custom commerce\_line\_item of type 'layaway' the commerce\_total and commerce\_unit\_price and no longer there. So the error from above is thrown because the currency\_code can not be retrieved from the non-existing commerce\_total.

Is there something special I'm supposed to do in order to retrieve my commerce\_unit\_price and commerce\_total for my line\_item? I've debugged the code and don't see where the shipping is loading extra data and yet it still has it's commerce\_unit\_price and commerce\_total.

# Answer
The implementation of hook\_commerce\_line\_item\_type\_info() fixes this issue. Each custom line\_item needs to be created via this hook. This will add the two fields commerce\_unit\_price and commerce\_total to the line\_item.
> 0 votes

---
Tags: commerce
---


# Question
Title: How do I get $view->the actual row number?
How do I get the actual rows number in views-view-field--title.tpl.php in Drupal7 and views3?

I know how to get the total by

```
$view = views_get_current_view();
$view->total_rows;

```

But how do I get the actual row number? To print 1/4 2/4 3/4 4/4

# Answer
user1090003 has the right answer.

> in views-view-fields.tpl.php or... you can have the row index like this $view-\>row\_index

Further explanation:

In views-view-field--title.tpl.php (suggestion of views-view-fields.tpl.php), you already have the $view object available. That view object has a property "row\_index" that equals the current row number starting at zero.

Example of use:

```
    <?php print $view->row_index; ?>
    <?php print $output; ?>

```

Example results:

```
    0
    Node Title 1
    --
    1
    Node Title 2

```
> 13 votes

# Answer
I usually accomplish this by adding a "count" field and making it excluded from display. In the title field I add the token for the "count" field in "rewrite output." Make sure the count field is BEFORE the title field.
> 3 votes

# Answer
in views-view-fields.tpl.php or... you can have the row index like this $view-\>row\_index
> 2 votes

# Answer
Setting the $static var to 0 in the VALUE CODE area allows to do $static++ in de OUTPUT CODE area
> 0 votes

---
Tags: views, theming
---


title: Override default register form

text:
# Question
Title: Override default register form
```
<?php
/*
** Implements hook_menu().
*/
function custom_register_menu() {
    $items = array();
    $items['custom-register'] = array(
    'title' => 'Custom register',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_register_form'),
    'access arguments' => array('access content'),
  );
    return $items;
}
/*
** Implements hook_form().
*/
function custom_register_form($form, &$form_state) {
  // Display page 2 if $form_state['page_num'] == 2
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
    return custom_register_page_two($form, $form_state);
  }
  // Otherwise we build page 1.
  $form_state['page_num'] = 1;
  $form['egn'] = array(
    '#type' => 'textfield',
    '#title' => t('EGN'),
    '#size' => 20,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['last_digits'] = array(
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 4,
    '#title' => t('Last digits from the card '),
    '#required' => TRUE,
  );
  $form['authorization_code'] = array(
       '#type' => 'textfield',
     '#size' => 20,
     '#maxlength' => 6,
     '#title' => t('Authorization code'),
     '#required' => TRUE,
  );
  $form['transcation_date'] = array(
       '#type' => 'textfield',
     '#size' => 20,
     '#title' => t('Transaction date'),
     '#required' => TRUE,
  );
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Forward>'),
    '#submit' => array('custom_register_next_submit'),
    '#validate' => array('custom_register_next_validate'),
  );
  //dsm($form_state);
  return $form;
}
/**
* Validate handler for the next button on first page.
*/
function custom_register_next_validate($form, &$form_state) {
    if(!is_numeric($form_state['values']['egn'])) {
        form_set_error('egn', t('Please enter only numbers!'));
    }
    $egn_length = strlen($form_state['values']['egn']);
    if($egn_length == 10) {
    }  else {
        form_set_error('egn', t('Please insert proper ЕГН'));
    }
    if(!is_numeric($form_state['values']['last_digits'])) {
        form_set_error('last_digits', t('Please enter only digits!'));
    }
    $last_digits_length = strlen($form_state['values']['last_digits']);
    if($last_digits_length == 4) {
    }  else {
        form_set_error('last_digits', t('Please enter 4 digits!'));
    }
    $authorization_code_length = strlen($form_state['values']['authorization_code']);
    if($authorization_code_length == 6) {
    }  else {
        form_set_error('authorization_code', t('Please enter 6 digits!'));
    }

```

I'm building a multistep form for custom registration on Drupal 7. The reason that I don't use hook\_form\_alter is because later I have to create a submit handler to a webservice and other database, but I'll open a new thread later for that.

This is a part of my code (sorry about putting text the down bellow, but drupal.stackexhange is not so friendly for putting text and codes) and you can see that I've created a menu page (custom-register). On that page there are four fields with custom validators and next button. On the next step it should be displayed the Drupal four fields (username, password, password repeat and email) and after that it should redirect to some register successful message page.

My questions are:

1. How can I redirect /custom-register to user/register page? I've read about hook\_form\_alter, but I didn't find a way how to override user/register page.
2. For the second step of the form after submitting how can I create a new user like on the core user module?

EDIT:

I've managed to alter the default register form with my new form created. :) This is the code:

```
<?php

    function custom_register_menu_alter(&$items) {
        $items['user/register']['page arguments'] = array('custom_register_form');
        return $items;

    }

```

Now the next thing is to create the 4 fields (username, password, password repeat and email) and to find a right submit handler to save the user.

# Answer
> 0 votes
I've finally done it! :) This thread https://drupal.org/node/999420 has a great examples how to achieve the multistep form with hook\_form\_alter.

# Answer
> 1 votes
You can still use hook\_form\_alter and have a special variable (in the $\_SESSION for example) to define which part of the form do you need to show. Code sample below:

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
  if ($form_id === 'user_register_form') {
     switch ($_SESSION['register_step']) {
         case 1:
              // confirm smth
         break;
         case 2:
              // establish the connections to other services, etc.
         break;
         default:
              // show initial form
         break;
     }
  }
}

```

Hope this is helpful.

**EDIT**

Some links:

---
Tags: forms, hooks, users
---


# Question
Title: How to abort a module if some condition not met?
I have a module that creates a couple of menu items hook\_menu, displays custom forms, has a couple of form validate and submit functions etc.

But I only want any of this to happen if a specific persistent variable has been set. I check for this using variable\_get(). If the variable isn't set, I just want to display a 'configuration not set!' message and go no further.

What's the proper way to achieve this? I thought about wrapping all my hook functions in an IF statement, but that can't be right. Ideally I'd want a function at the top of the .module that does the check and aborts there and then. But I have a feeling it's not that simple...

# Answer
> 5 votes
One solution would be to set a custom `access callback` for each menu item.

In the function you can then do a check to see wether the variable is set or not. If it isn't then you can either return FALSE to provide an access denied page or use drupal\_goto to forward to a custom config form.

---
Tags: 7
---


# Question
Title: How do I enable a features module in the setup of a simpletest testcase
I'm trying to test some permissions that are related to custom node types and Organic Groups that I've built and packaged as a feature using the features module.

I'm trying to enable the feature (and create all the content types and taxonomies that are part of the feature) in the setUp method of my simpletest test case class like this:

```
class PermissionsTestCase extends DrupalWebTestCase {
  public function setUp() {
    parent::setUp(array(
      'addressfield',
      'ctools',
      'date',
      'entityreference',
      'features',
      'file',
      'list',
      'node',
      'og',
      'og_field_access',
      'og_ui',
      'options',
      'strongarm',
      'taxonomy',
      'text',
      'my_custom_feature',
    ));
    debug(module_list(TRUE));
    debug(features_get_features());

    // More setup stuff that depends on content types and taxonomies in my feature
    // ...
  }
}

```

However, when I look at the output of `module_list` it doesn't include my feature or the dependencies and subsequent setup tasks that rely on a taxonomy that's part of my feature don't find the taxonomy vocabulary.

Can I enable a module created with features in the setUp method? What's the best way to do this?

Do I have to explicitly specify the dependencies of my feature in the call to parent::setUp? What about the dependencies of my dependencies? Does the order matter?

# Answer
> 0 votes
As of Drupal 7 you don't have to explicitly specify module dependencies, they are resolved automatically. The order doesn't matter either for that same reason.

As far as actually enabling the feature, it *should* be fine... I was going to suggest calling `drupal_static_reset('system_list')` before `module_list()` but it already does that itself when you pass `TRUE` as the first param like you did.

I've had some issues when testing features modules and, in certain situations, I've found that it's actually better (and much slower) to force SimpleTest to use the live database.

Granted, that's very specific to certain types of client projects, but still, might help! :)

---
Tags: features, testing
---


# Question
Title: How do I act after quantity change in cart?
I am writing a Commerce submodule that needs to run some code on the line items in an order when the Update Cart or Checkout buttons are clicked in the shopping cart form, but I'm not sure where to put it. More specifically, I need to see if the user updated the quantity of a line item in their cart and then write code that acts on the quantity change (without using Rules).

I am already using `hook_form_FORM_ID_alter()` to alter the Remove buttons in the shopping cart, I figured I could just add a submit handler in this hook but that doesn't seem to work.

```
function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
  $form['#submit'][] = 'MYMODULE_cart_submit';
}

function MYMODULE_cart_submit($form, &$form_state) {
  dsm($form);
}

```

When I hit either Update Cart or Checkout, dsm doesn't load on the next page. Am I in the right spot?

Thanks! :)

# Answer
You could use the Entity API type hooks (load, presave, update etc..) to act when the `commerce_line_item` is updated

e.g:

```
/**
 * Implements hook_entity_update
 */
function MYMODULE_entity_update($entity, $type){

  if($type == 'commerce_line_item'){
    // Do stuff with line item in $entity;
  }

}

```

You might have access to `$entity->unchanged` or similar in `$entity` which stores the entity content prior to the save. Useful for comparing quantity to see if it's changed!

```
dpm($entity); // for details.

```

You can also use `hook_ENTITY_TYPE_update`

```
/**
 * Implements hook_ENTITY_TYPE_update
 */
function MYMODULE_commerce_line_item_update($entity){

  dpm($entity);

}

```

The hooks for load, presave, insert, update and delete are available for all Commerce entity types.
> 1 votes

# Answer
Welcome to the Drupal StackExchange !

If you are looking to detect changes in cart orders or line items i believe you can use below hooks which are exposed by cart module.

```
/**
 * Rules event hook: allows modules to react to the addition of a product to a
 * shopping cart order.
 *
 * @param $order
 *   The cart order object the product was added to.
 * @param $product
 *   The product that was added to the cart.
 * @param $quantity
 *   The quantity of the product added to the cart.
 * @param $line_item
 *   The new or updated line item representing that product on the given order.
 */
function hook_commerce_cart_product_add($order, $product, $quantity, $line_item) {
  // No example.
}

/**
 * Rules event hook: allows modules to react to the removal of a product from a
 * shopping cart order.
 *
 * @param $order
 *   The cart order object the product was removed from.
 * @param $product
 *   The product that was removed from the cart.
 * @param $quantity
 *   The quantity of the product line item removed from the cart.
 * @param $line_item
 *   The product line item that was deleted to remove the product from the cart.
 */
function hook_commerce_cart_product_remove($order, $product, $quantity, $line_item) {
  // No example.
}

```

Cheers, Anil Sagar
> 0 votes

# Answer
Thanks for all your answers, but I answered this myself. I think! :)

Should be:

```
function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
  $form['#validate'][] = 'MYMODULE_cart_validate';
  $form['actions']['submit']['#submit'][] = 'MYMODULE_cart_update';
  $form['actions']['checkout']['#submit'][] = 'MYMODULE_cart_checkout';
}

function MYMODULE_cart_validate($form, &$form_state) {
  dsm('Form validated');
}
function MYMODULE_cart_update($form, &$form_state) {
  dsm('Update Cart button pressed');
}

function MYMODULE_cart_checkout($form, &$form_state) {
  dsm('Checkout button pressed');
}

```

So I guess my question now is why doesn't the regular submit handler work?

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

```
> 0 votes

---
Tags: commerce, forms
---


title: tinymce and colorbox and inline images

text:
# Question
Title: tinymce and colorbox and inline images
I have a blog, I am developing and using the following plugins, but I am not committed to them and will change to get the behavior I want.

1. TinyMCE
2. Wysiwyg
3. Colorbox
4. Media

In many blogs I see inline images that are small and when they clicked on then expanded in a colorbox.

I am curious how to achieve this using drupal 7 and uploading images using the media module?

# Answer
There are two approaches I know to make inline images in WYSIWYG editors open in Colorbox. The one which I used in my last project was inserting images with Insert module. Which requires you to add an image field to your content type and upload your images to that field and than insert them with any image settings (instead of uploading them via the Media button on the editor).

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

This approach allows you also to get the images with Views etc, since they are actually stand-alone fields.

The second approach is adding a CSS class to the inline image uploaded via the media button. I'm not quite sure about how and which class but I did use this approach a few years ago and back then the mentioned modules had their 7.x-1.x versions, still. I was looking for the current state of using this approach but didn't find anything new. I'll experiment it a bit and write here.

Edit: After investigating about an hour, couldn't find any better way than the approach with the Insert module. It's the best user experience among all other approaches, if not still perfect.
> 1 votes

# Answer
I prefer using IMCE and Lightbox with CKEditor. With this combo there is no need to add an image field to your content type and the text can wrap around any image(s) that are added. You can set the image size when adding -- no need for pre-defined sizes. Lightbox works similar to colorbox, but includes an option to view a full-size image.

I haven't tried IMCE with colorbox, but I have tried colorbox and Insert and did not like the results or the UX.
> 0 votes

---
Tags: media, javascript, wysiwyg
---


title: How to see all changes made by an admin

text:
# Question
Title: How to see all changes made by an admin
Is it possible to somehow pull a report on an admins activity on a Drupal 7 site? I'd like to know for example any development changes, and settings changes, and database changes that an admin on a site has performed.

I've found some modules that help with that, but its too late to install them now.

# Answer
Administration Notifications this is a simple module that can be used for communication of site changes/updates between the site designer/developer, and the site owners.

> if you maintain a drupal installation for another company, you can use this module to inform them when you have updated versions of the site (ex drupal 7.1 -\> 7.2), updated modules on the site (i.e. Administration Notifications 7.x-1.0 -\> 7.x-1.1), added new modules, or changed the site design in some manner.

or you can try Activity module.

> The Activity module keeps track of the things people do on your site and provides mini-feeds of these activities in blocks, in a specialized table, and via RSS. The module is extensible so that any other module can integrate with it. The messages that are produced are customizable via the admin interface and are context sensitive.
> 1 votes

---
Tags: 7, users, log-messages
---


title: How do autocomplete text fields work?

text:
# Question
Title: How do autocomplete text fields work?
I am asking this question because I have an autocomplete text field with `#autocomplete_path` set to a valid working path but key events are not handled by the misc/autocomplete.js file. When the form is being created, it apparently assigns all the functions to the respective variables, but none of those functions are executed. For example following function in the misc/autocomplete.js isn't executed.

```
Drupal.jsAC = function ($input, db) {
  var ac = this;
  this.input = $input[0];
  this.ariaLive = $('#' + this.input.id + '-autocomplete-aria-live');
  this.db = db;

  $input
    .keydown(function (event) { return ac.onkeydown(this, event); })
    .keyup(function (event) { ac.onkeyup(this, event); })
    .blur(function () { ac.hidePopup(); ac.db.cancel(); });

};

```

Hence, when a user types a letter, *key up* or *key down* handlers aren't invoked and nothing happens. So to debug, I want to know how autocomplete works.

Could someone please explain how this works?

# Answer
> 6 votes
Working with Drupal autocomplete form is good, instead of using the jQuery autocomplete.

Here we have a solution that how to create a custom autocomplete form and to get the user names or whatever.

I am giving the simple example of using it.

Take a menu item in hook\_menu to get the autocomplete form. This will call the function called `test_autocomplete_form`.

```
$items['autocomplete_form'] = array(
        'title' => 'Test autocomplete form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('test_autocomplete_form'),
        'access arguments' => array('access test autocomplete'),
        'type' => MENU_NORMAL_ITEM
);

// Which will get the autocomplete form
function test_autocomplete_form(){
    $form = array();
    $form['testauto'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'test/autocomplete',
        '#description' => t('Please type any letter.'),
    );
    return $form;
}

```

We have to mention our custom path in for the `#autocomplete_path` attribute. Here I have given a path like `test/autocomplete` which will have to get the autocomplete result for that need to have one more menu item with the same path which we have given for the `#autocomplete_path`:

```
// menu item to get the autocomplete result,Which will call the function called 'test_autocomplete'
$items['test/autocomplete'] = array(
        'title' => 'Test autocomplete',
        'page callback' => 'test_autocomplete',
        'access arguments' => array('access test autocomplete'),
        'type' => MENU_CALLBACK
);

// function to get the autocomplete result, I am taking the user table to get the users names in the autocomplete field
    function test_autocomplete($string = '') {
      $matches = array();
      if ($string) {
        $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10); // only 10 results will show
        while ($user = db_fetch_object($result)) {
          $matches[$user->name] = check_plain($user->name);
        }
      }
      drupal_json_output($matches); // Returns the data in JSON format
    }

```

---
Tags: ajax
---


# Question
Title: How do I block google analytics from my development sites?
Is there a way (in code or configuration) that I could prevent google analytics from collecting visits on any of my development websites?

# Answer
just add the following line in in hosts file in computers which you want to exclude analytics tracking:

```
127.0.0.1 www.google-analytics.com

```
> 2 votes

# Answer
I am assuming that you are referring to Bots or Crawlers. If that is true you can add a robots.txt file. Visit http://www.robotstxt.org/faq/prevent.html to know more about it.

If you are in fact referring to the Google Analytics, you can just disable the module or remove the tracking code if you have added it manually.
> 0 votes

---
Tags: google-analytics
---


title: Accessing field inside a block

text:
# Question
Title: Accessing field inside a block
I have created a block to display flash content. All it needs a a variable to be assigned dynamically from the content to flashVar. I created a field called myfile path in the custom content type. Which is just a text pointing to the path of file. I also created a block and below is the code inside the block.

```
<?php
$myFilePath = field_get_items('node', $node, 'field_myfilepath');
?>

<script src="/player/swfobject.js"></script>
<script>
        function swfDimensions(width,height)
        {
           document.getElementById('altContent').style.width=width+'px';
           document.getElementById("altContent").style.height=height+'px';
        }
        var flashvars = {
                    filepath:"<?php echo $myFilePath;?>" // this where I use the filed value which my flash app uses internally

        };
        var params = {
            menu: "false",
            scale: "noScale",
            allowFullscreen: "true",
            allowScriptAccess: "always",
            bgcolor: "",
            wmode: "direct" // can cause issues with FP settings & webcam
        };
        var attributes = {
            id:"altContent"
        };
        swfobject.embedSWF(
            "/player/contentviewer.swf",
            "altContent", "640px", "390px", "11.3.0",
            "/player/expressInstall.swf",
            flashvars, params, attributes);
    </script>
        <h4>Floorplan Basic</h1>

    <div id="altContent">
                To view this content you need Adobe flash player (v11+) plug-in installed on your browser
        <p><a href="http://www.adobe.com/go/getflashplayer">Get Adobe Flash player</a></p>
    </div>

```

I am getting this error

```
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7663 of C:\...\www\includes\common.inc).

```

Can any on tell me how to get the value of the field in this block? I am totally new to drupal.

# Answer
I guess `$node` is not defined. You should know when a node page is shown. Then get the `node id` using `arg(1)`. Load the node object and then use.
> 1 votes

# Answer
Try variable\_set() and variable\_get()

Set the variable like that:

```
// I have assumed the variable name to be "the_name_of_the_variable"
variable_set("the_name_of_the_variable", "the value of the variable");

```

And then retrieve the value like that:

```
$my_variable = variable_get("the_name_of_the_variable", "a default value in case the variable has never been set before");

```
> 0 votes

---
Tags: blocks, entities, database
---


title: Update field value without edit page

text:
# Question
Title: Update field value without edit page
I need to create a button that will allow a user to update a field value on a node without accessing the edit page. I'm using access control to limit access to the node, and roles which could define which user sees the button. The field I need to update is a custom pick list.

Is there a module to do this? I can't find one. THANKS!

(More info on my specific implementation)

My site allows users to list resources for other users to book. When a user wishes to book an item, he creates a new node (Booking). The owner of the resource is also given access to this node. Here, they can comment and exchange files (attachments) to work out the details. This node has a field called "Stage", which starts as "Pending". Once the owner has confirmed the details of the booking, I want him to be able to click "Approve" on the booking node, changing the status to "Approved". When the resource has been returned, the owner should hit a "Completed" button, changing the status to "Complete". I'd also like both users to see a "Cancel" button at all times.

# Answer
See editablefields module.

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).
> 2 votes

---
Tags: entities, nodes
---


# Question
Title: Port of Ubercart "Dependant Atributes" or "Chained Attributes" modules
Do you know of a Drupal 7 version of either of these modules?

1. Ubercart dependant atributes
2. Chained Attributes and Options

I've spent a couple of days trying to find an appropriate solution.

# Answer
> 0 votes
This answer may be slightly late judging by your ask date but I figured I would post it anyway.

This module performs similar to the above.

https://drupal.org/node/1192892

---
Tags: 7, ubercart
---


title: How to GET REST resources for Views

text:
# Question
Title: How to GET REST resources for Views
Getting a node via Drupal 8's RESTful web service can be done by doing a GET with this url:

```
/entity/node/1

```

How then, do you access a View? I've tried the following, with no luck:

```
entity/view/myviewid

```

Where 'myviewid' is id specified in views.view.myview.yml

My rest settings for views are exacty the same for nodes, which return JSON successfully. The view GET attempt however, returns a 500 Internal Server Error.

# Answer
> 5 votes
If you have the rest module enabled you have a new display type called "REST export". There you can configure to either return just the normal REST output for all entities, or you can even configure which fields you want to include.

Much like you enable REST support for entity types you also don't want to deal with unwanted REST access by default.

---
Tags: views, entities, 8
---


# Question
Title: Getting the inverse of drupal_realpath (Drupal 7)
I know drupal\_realpath is depreciated but as far as I can tell I cannot avoid using it.

I have a little module that will unzip a file and search the contents of the unzipped file and create content with the images it finds. In order to search the unzipped directory tree I need to rely on standard php methods will not work with paths like 'public://..." so I need to use drupal\_realpath to massage my paths into something drupal can handle.

When I actually create the image file I do not want to use the drupal realpath because this would obviously be problematic if I migrated to a different server.

Is there a way I can turn the realpath which will look something like this:

```
/Applications/MAMP/htdocs/drupal/sites/default/files/my_file.png

```

back into something like:

```
public://my_file.png

```

If not is there some way I can search a directory structure without using drupal\_realpath?

EDIT: So it seems that my problem may really only be with certain PHP lirbaries for example simpleXML.

```
$shape_xml = 'public://Arcade Projects/ender2012/AgentCubes/Open Arcade/Moonsweeper/version8/Moonsweeper/agents/Tutorial/shapes/Tutorial/shape.xml';

watchdog("file exists normal",file_exists($shape_xml));
watchdog("file exists real path",file_exists(drupal_realpath($shape_xml)));

```

In the above example, both watchdogs print 1, so it seems that file\_exists works fine with the drupal path or the realpath.

But, if I call simplexml\_load\_file with the drupal\_realpath like this:

```
$xml = simplexml_load_file(drupal_realpath($shape_xml));

```

everything works fine.

But If I call it like this:

```
$xml = simplexml_load_file($shape_xml);

```

I get the following error:

```
Notice: Trying to get property of non-object in harvest_icons() (line 775 of /Applications/MAMP/htdocs/drupal/sites/all/modules/custom/unzip/unzip.module).

```

# Answer
It's not pretty but this will reverse engineer such a path quite reliably:

```
$old_path = '/Applications/MAMP/htdocs/drupal/sites/default/files/my_file.png';

$doc_root = $_SERVER['DOCUMENT_ROOT'] . '/';

$public_file_path = variable_get('file_public_path', 'sites/default/files') . '/';

$replace = array($doc_root, $public_file_path);

$new_path = 'public://' . str_replace($replace, '', $old_path);

```
> 3 votes

# Answer
Stream wrappers are a PHP feature. You can use a path like public:// with normal PHP functions like fopen().
> 2 votes

# Answer
Here's my code

```
$purl= drupal_realpath('public://');
$filepath = file_build_uri(str_replace($purl, '', drupal_realpath($image_relative_path . '/' . $file['filename'])));

```

where $image\_relative\_path is something like sites/default/files/mydirectory
> 1 votes

---
Tags: 7, files
---


title: Comment body field is missing

text:
# Question
Title: Comment body field is missing
I enabled the forum module, and when I add a comment on a forum post, there is no body field. I disabled both the Comment and the Forum modules, and re-installed them, but I still have the same problem.

If I manually create a body field (field\_comment\_body), I get the following error message:

> Notice: Undefined property: stdClass::$comment\_body in comment\_admin\_overview() (line 107 of /var/www/lms/modules/comment/comment.admin.inc).

Is there any solution to make the comment body appear as it happens with other content types?

# Answer
> 1 votes
1. disable comment module
2. uninstall comment module
3. enable comment module

---
Tags: nodes
---


# Question
Title: Access webform select list key from within rules
I have a webform that needs to be sent via rules. That's all fine but I don't seem to be able to access the data key for a select list in my webform.

I can get the value like this:

```
[data:location-value]

```

But I need to key not tha value.

I tried (as a guess)

```
[data:location-key]

```

But that doesn't work.

Any ideas?

# Answer
> 0 votes
I used a work-a-round for this by using the translate option in Drupal.

I've set up the key as a value and translated the key to the value that I wanted.

This was used for a custom field, but it worked fine for me.

---
Tags: 7, rules, webforms
---


# Question
Title: Drupal Module for arranging Nodes of special type into a table||chart
I'm trying to map Nodes of special Types on the basis of their field datas in a table or a chart.

The table should look like this:Table Example

Explanation: Table Header and first row are the datas of two specified fields. The node titles (rest of table) are mapped on the free table rows/columns according to their field values. Since i got no solution for this i tried to look for an approach with graphs. But it doesn't turn out as an easier way.

Maybe i've overlooked something. I would be really glad if anybody have a solution for this problem.

# Answer
> 1 votes
I'm really glad that I found a good and comfortable solution for my problem.

There are two modules available: Views Table Group, Views Merge Rows

At the beginning, I had some problems with the settings. After a few tryings I got along with these: check "Use values of this field as a filter" instead of "Use the first value of this field"

Note: I've just seen the merged rows logged out! So you had to change the visibility/accessibility settings or just log out to check the table.

My result:

---
Tags: 7, nodes, entities
---


title: Remove Commerce Payment Method Pane?

text:
# Question
Title: Remove Commerce Payment Method Pane?
So for my project there will only ever be one payment method with is Credit Card by Sage Pay.

Essentially I want to remove the pane where you select a payment method and set the payment method always as Sage Pay. I want to hide payment selection from the user.

This way after entering user details the user can go straight to the payment gateway redirection. How would I go about this?

# Answer
> 1 votes
You'll need a custom module with the following function:

```
function yourmodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
 // Do something here
}

```

You'll probably want to add a `dpm($form);` (assuming you have Devel installed) to get the exact item, but the array you'll probably want to target is: `$form['commerce_payment']['payment_method']` by perhaps setting the `#access` to `FALSE` if you only have one choice. In other words, add the following: `$form['commerce_payment']['payment_method']['#access'] = FALSE;`

Be sure to clear the cache after adding this function.

# Answer
> 1 votes
Go to Administration \>\> Checkout settings (`admin/commerce/config/checkout`). Move the payment method pane to `Disabled` region and save setting.

---
Tags: 7, commerce
---


# Question
Title: From managed file ID to end-user link - neat and clean way?
I have a structure in database, and I want it printed. So in hook menu I have entry with

```
'page callback' => 'mymodule_mystructure_display',

```

And in inc file I have

```
function mymodule_mystructure_display($id_structure) {
  $mystructure= something(); // Data preparation
  return $mystructure;
}

```

And I have all helpers set up so in mystructure.tpl.php I can simply use:

```
kpr($mystructure);

```

and it all works, so let me omit details for now, they are covered in Examples for Developers anyway.

## The real struggle is with files.

In `$mystructure['files']` I have a nested array like this:

```
array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(26) "Display name of first file"
    ["fid"]=>
    int(34)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(27) "Display name of second file"
    ["fid"]=>
    int(62)
  }
}

```

where `["fid"]` corresponds to `{file_managed}.fid` field in Drupal's database.

**What's the cleanest way to output links to files, with `["name"]` used as link text?**

What I'm doing now is pretty dirty:

1. In `function mymodule_mystructure_display` I `foreach` or `array_walk` over files.
2. For each element, I take file id, and use this helper function on it:

```
_uri_by_id($id) {
  $file = file_load($id);
  return $file->uri;
}

```
3. Result is fed to `file_create_url` function, and it's result is saved under `["url"]` index, to give me this array in `$mystructure['files']`:

```
array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(26) "Display name of first file"
    ["fid"]=>
    int(34)
    ["url"]=>
    string(50) "http://example.com/sites/default/files/example.pdf"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(27) "Display name of second file"
    ["fid"]=>
    int(62)
    ["url"]=>
    string(50) "http://example.com/sites/default/files/example.txt"
  }
}

```
4. In mystructure.tpl.php I use l() to print actual link:

```
echo l($item["name"], $item["url"]);

```

This all works. But it feels bad. I was always a backend guy, my frontend knowledge is somehow lacking. But I'm sure there should be a shorter way from managed file ID to a link. So what would it be?

**Note:** value under `["name"]` is derived from `$mystructure`, it is not something taken directly from file object. This pretty much stopped me from using `theme_file_link()`. But even if it wouldn't be the problem, I still need to load file object manually to use `theme_file_link()`.

# Answer
> 2 votes
I'd personally prefer something like this:

```
// Extract file IDs so we only run one file_load().
$fids = array_map($mystructure['files'], function($x) { return $x['fid']; });
$files = file_load_multiple($fids);

$build = array();
foreach ($mystructure['files'] as $file) {
  // Update the description
  $files[$file['fid']]->description = $file['name'];

  // Add to the build
  $build[] = array(
    '#theme' => 'file_link',
    '#file' => $files[$file['fid']],
  );
}

return $build;

```

A bit cleaner/more performant, and using as much core API as possible.

---
Tags: theming, navigation, files
---


# Question
Title: Where is the CCK autocomplete widget field php configuration code stored?
I have run myself into a serious problem. I have a custom CCK datatype in Drupal6 in combination with an autocomplete widget on a text field. I have defined php code in the web configuration for the "allowed values list", but the code I wrote is faulty and uses up all memory (three nested foreach loops, returned array gets way too large, 2G mem limit reached).

Unfortunately, I cannot access the Drupal6 instance at all, as it seems the faulty php code is executed on all pages (not sure about this, but did reboot the server and still could not log in).

I guess it would be best just to delete the faulty PHP code for the Autocomplete widget from the backend, but I am unable to find it in the Postgres database. Can anyone give me a hint as to where in the database this code is stored?

Any other hint as to how to resolve this problem will be highly appreciated.

# Answer
> 2 votes
Try looking in the content\_node\_field table, under the global settings value:

```
mysql> desc content_node_field;
+-----------------+--------------+------+-----+---------+-------+
| Field           | Type         | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| field_name      | varchar(32)  | NO   | PRI |         |       |
| type            | varchar(127) | NO   |     |         |       |
| global_settings | mediumtext   | NO   |     | NULL    |       |
| required        | tinyint(4)   | NO   |     | 0       |       |
| multiple        | tinyint(4)   | NO   |     | 0       |       |
| db_storage      | tinyint(4)   | NO   |     | 1       |       |
| module          | varchar(127) | NO   |     |         |       |
| db_columns      | mediumtext   | NO   |     | NULL    |       |
| active          | tinyint(4)   | NO   |     | 0       |       |
| locked          | tinyint(4)   | NO   |     | 0       |       |
+-----------------+--------------+------+-----+---------+-------+

```

I just did a test, defining an arbitrary PHP string (print "Hello Stack Exchange";) under allowed values for a field (field\_test2) and found the following:

```
mysql> select global_settings from content_node_field where field_name = "field_test2";

+----------------------------------------------------------------------------------------------------------------------------------------------------+
| global_settings                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------+
| a:4:{s:15:"text_processing";s:1:"0";s:10:"max_length";s:0:"";s:14:"allowed_values";s:0:"";s:18:"allowed_values_php";s:31:"print "Hello Stack Exchange";";} |
+----------------------------------------------------------------------------------------------------------------------------------------------------+

```

The string you are looking for is at the end (s:31:"print "Hello Stack Exchange";";) and it's serialized with the character count at the front. If you want to zero this out, it would look like:

```
a:4:{s:15:"text_processing";s:1:"0";s:10:"max_length";s:0:"";s:14:"allowed_values";s:0:"";s:18:"allowed_values_php";s:0:"";}

```

---
Tags: nodes, 6, entities, ajax
---


# Question
Title: How do I add a Site Information variable and make it multilingual?
So I've used form alter to add in a site information variable (which auto-saves because it's a system\_settings\_form), but I can't seem to get it to show up as multilingual.

Here is my form alter to add the field:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function omm_form_system_site_information_settings_alter ( &$form, &$form_state ) {
    // Add field in Site Information area of admin configuration.
    $form['site_information']['site_pretitle'] = array(
        '#type' => 'textfield',
        '#title' => t('Site Pre-Title'),
        '#description' => t('This will appear above the website name on all pages.'),
        '#default_value' => variable_get('site_pretitle', ''),
        '#weight' => '0',
    );
}

```

Edit: I've solved this already, but need 8 hours to post the solution because I'm new.

# Answer
> 10 votes
So I managed to solve this after searching through Drupal's code and the Variable module. Turns out if you add a call to `hook_variable_info`, it will add it into the multilingual variables list, and then if you check that off, it makes it translatable like the rest of the Site Information.

```
/**
 * Implements hook_variable_info().
 */
function omm_variable_info($options) {
  // Site configuration, site information
  $variables['site_pretitle'] = array(
    'type' => 'text',
    'title' => t('Site Pre-Title', array(), $options),
    'default' => '',
    'description' => t("This will appear above the website name on all pages.", array(), $options),
    'group' => 'site_information',
  );

  return $variables;
}

```

After adding this, go to `admin/config/regional/i18n/variable` and click on the `Site information` group. Click the checkmark beside your variable (site\_pretitle for mine), and hit `Save configuration`. Once that's done, return to the Site Information area (`admin/config/system/site-information`) and you should see it appear and say `This is a multilingual variable.` in bold.

---
Tags: i18n-l10n, forms
---


# Question
Title: Any kind of sorting gives duplicate results in Views (Search API)
**Problem**

My view based on Search API is giving me duplicate results. I get duplicate results if I use the following things in combination:

* A pager
* A sort of any kind. e.g. Sort by ascending integers, sort by descending select field etc.

Sometimes I get a couple duplicate results, other times entire pages are identical.

According to the module page I should be able to use view sorts on single valued indexed fields, but I can't seem to get this to work at all.

Has anyone else run into this? How did you solve it?

**Common solutions for duplicate results**

Most of the solutions I've spotted for this involve options which don't appear for Search API. They usually involve adding aggregation or distinct filters in the Views options.

The possible solution here fails. The problem is it searches for duplicate results only amongst the current page of the view.

i.e. if I get 60 nodes on a search with a pager of 15, this splits into 4 pages. If the duplicates are on pages 1 & 3 then they're not spotted.

# Answer
Bleh what a horrible bug.

I solved it by re-creating the search index (and therefore the view as well).

**Why did it happen?**

I think it's possible to have certain things saved into the Search Index (possibly when it's created?) and then it's impossible to remove them without just starting afresh.

I discovered this bug while trying to debug this.

After re-creating the new index the only difference I can find between it and the original is that I can now sort by an un-related taxonomy field (see the bug). Presumably this is an indicator of something as it doesn't seem relevant, but I have no idea what.

**Second EDIT:**

Actually just re-creating the index wasn't enough to solve this problem, I then continued to find duplicates after.

Deleting and re-creating the field with a new ID however did work. I never worked out why, but I'm presuming something was corrupted.
> 0 votes

---
Tags: 7, views, search
---


# Question
Title: Unable to upload large files (>50mb) to Amazon S3 from D7 on EC2
I'm trying to configure Drupal to upload large videos (eventually goal is ~300mb, but currently testing with ~50mb files) to S3 through my Drupal site running on an EC2 instance.

I have configured and tried both the Amazon S3 and Storage API modules. When trying to upload a small file around 5mb, everything is fine and works perfectly. However, when I try with a large file, I receive the following error:

> Warning: filesize(): stat failed for storage-field-storage-test://\[FILE NAME\].mp4 in file\_save() (line 601 of /var/www/includes/file.inc).

This error is the same for both the Amazon S3 and Storage API modules.

It turns out that the large videos are not being uploaded to S3, which explains the error message.

I am able to upload files directly to S3 okay and I am able to upload large files to local storage just fine as well (the PHP upload limit is set well above what I'm trying). What I don't understand is what could be causing the failure with the large file sizes between Drupal and S3. Any suggestions?

# Answer
> 2 votes
As pointed out in the comments, this ended up being a PHP config issue.

While I had set the `post_max_size` and `memory_limit` arguments to 1GB, the `upload_max_filesize` was not set at all. Setting this to 1GB in the `php.ini` file as well resolved the problem.

---
Tags: 7, files
---


# Question
Title: Why is "drush cc all" failing with "undefined function user_load()"
After updating my Drupal test server to have a fresh copy of the database and code from the production system, "drush cc all" would fail with a message saying

> PHP Fatal error: Call to undefined function user\_load() in /usr/share/pear/drush/includes/drupal.inc on line 138

I'm running drush version 6.2.0 with a drupal 7.25 system. I'm using memcache as `cache_default_class`.

# Answer
> 2 votes
The problem went away after I restarted memcached.

I discovered that by running drush with `-d` and seeing a PHP error about a `$theme` value not being a valid index. Tracing the code showed that access to `cache_bootstrap` was getting empty arrays for the module and theme data.

From now on I plan to restart memcached or flush its cache on my test server after rebuilding its database. (I've done this kind of rebuilding dozens of times before with no issues.)

---
Tags: drush, caching
---


# Question
Title: How to grant a role permission to edit terms in a specific vocabulary
Is there a way/module to grant a role permission to list and edit terms in a specific vocabulary?

# Answer
> 10 votes
The only module I can think of is the Taxonomy access fix module, which has only a version for Drupal 7.

> This module
>
> * adds 1 permission per vocabulary: "add terms in X"
> * changes the way vocabulary specific permissions are handled
> * changes the Taxonomy admin pages' access checks
> * alters the vocabularies overview table to show only what you have access to edit or delete
>
> The module does what native Taxonomy lacks: more specific Taxonomy permissions (and checking them correctly).

# Answer
> 2 votes
Both answers didn't work for me. "Taxonomy access fix" didn't work at all and the drupal permissions didn't work as expected. The only thing which is still having a chance to work is http://drupal.org/project/vppr \- you may download a D7 version on the issues.

# Answer
> 1 votes
I can confirm Vocabulary Permissions per Role https://drupal.org/project/vppr works. It adds these permissions so you can give access to users per Vocabulary: https://drupal.org/project/vppr

They can not change or delete the vocabulary itself, which is important. So they can not really administer the vocabulary but its terms.

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


# Question
Title: node_view not picking up view mode, always printing full
I have the following code:

```
$form['commerce_fieldgroup_pane__group_event_information']['field_event_information']['und'][0]['#markup'] = drupal_render(node_view($eventInfo['event']), 'teaser');
```

and for some reason, its printing out the node fine, but not printing the correct view mode, its always using full.

# Answer
> 4 votes
I think you have a misplace parenthesis. You have

```
$form[...] = drupal_render(node_view($eventInfo['event']), 'teaser');

```

The view mode should be a parameter to `node_view()` and not `drupal_render()`:

```
$form[...] = drupal_render(node_view($eventInfo['event'], 'teaser'));

```

As a side note, I don't think you need to explicity render the node and stuff it into a `#markup`. `node_view()` returns a render array with a `#theme` already defined, so you should be able to do:

```
$form['commerce_fieldgroup_pane__group_event_information']['field_event_information'][LANGUAGE_NONE][0] = node_view($eventInfo['event'], 'teaser');

```

---
Tags: nodes
---


title: Accessing external data in a field

text:
# Question
Title: Accessing external data in a field
When creating a content type I would like to have a field type that could be used to call a rest service or make a db call to an external database. Does this exist?

# Answer
> 0 votes
To the best of my knowledge, no, there isn't a module out there to do this. I have seen something similar done in the past though, where a node would have an id of some sort provided, and a module would connect to an external service to load in information for the node.

I suspect you might want to think about writing a custom module to do this. If you haven't taken a look at https://drupal.org/developing/modules yet you might want to. Just remember when modifying functionality of Drupal you should never hack the core, but create/use a module instead.

I think what your gonna want to do is architect a way to know what you need to pull and from where, then use hook\_node\_view to change/add the data you pull from your DB/external service (https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_view/7)

---
Tags: entities
---


title: How to configure Facet Advanced Range?

text:
# Question
Title: How to configure Facet Advanced Range?
I'm lost on how to configure advanced ranges in Facet API displays. I see this page, which supposedly quotes from the README

> For example \[100 200\] will produce a range between 100 and 200.
> For example \[100 \*\] will produce a range of "100 and above"

I've configured my ranges like this:

But the drop down menu appears like this:

# Answer
> 2 votes
It turns out the documentation is just a lie...

https://drupal.org/node/2126017

These values worked:

```
0-800
800-1000
1000-1200
...
1800-2000
2000-

```

---
Tags: search
---


title: Two Site Themes

text:
# Question
Title: Two Site Themes
PROBLEM: Drupal 6 website developed with customized theme. Blog module does not play well with customized theme.

POSSIBLE SOLUTION: Would it be possible to set up a directory called /blog and load the Drupal BlogBuzz II theme? It needs to use the existing main website DB so searches on the main website will also return blog content.

Is this possible and if so are there any resources online that describe the process?

P.S. Thought about using WordPress as a sub-site but then Search queries on the main website will not return content in the WordPress Blog website.

Thanks-in-Advance,

John

# Answer
You can use ThemeKey to achieve this (https://drupal.org/project/themekey). It will allow you to use a second, tailored theme, in specific places, like for a specific content type.
> 3 votes

# Answer
If you don't want to install another module (or don't need something super fancy), you can do something like this in your `sites/default/settings.php` file:

```
if (strpos($_SERVER['REQUEST_URI'], '/blog')===0) {
  $conf['theme_default'] = 'blogbuzzii'; // or whatever it's called
}

```

and every page path that starts with `/blog` should now be themed with the `blogbuzzii` theme.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: couldn't load site name in html template
```
<?php print $site_name; ?>

```

Why I couldn't perform the above code in 'html.tpl.php'. This works find in page template. Please suggest how to load this in html template

# Answer
> 0 votes
There's no `$site_name` variable added to html.tpl.php, but you can add it yourself quite easily with a preprocess hook:

```
function MYTHEME_preprocess_html(&$vars) {
  $vars['site_name'] = variable_get('site_name', 'Default');
}

```

---
Tags: theming
---


title: Get values from a multi value field?

text:
# Question
Title: Get values from a multi value field?
I have a field that can accept unlimited values. I want to print those values in my template.

The array that I can see with the devel module looks like this....

```
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [value] => Dustin
                    [format] =>
                    [safe_value] => Dustin
                )

            [1] => Array
                (
                    [value] => Jen
                    [format] =>
                    [safe_value] => Jen
                )

            [2] => Array
                (
                    [value] => Mike
                    [format] =>
                    [safe_value] => Mike
                )

        )

)

```

What I'd like to do is have these values printed to a comma separated list like: `Dustin, Jen, Mike`

I've been using this code to print single value fields in my template but that of course isn't going to work well with a multi value field..

```
<?php echo $entityform->field_team_name['und'][0]['value']; ?>

```

# Answer
> 2 votes
`field_get_items()` will do the trick:

```
if ( ($items = field_get_items('entityform', $entityform, 'field_team_name')) ) {
  $values = array_map($items, function($x) { return $x['safe_value']; });
  $comma_separated = implode(', ', $values);
}

```

---
Tags: 7, entities
---


# Question
Title: Linking to front page with current selected language
`<?php print $base_path; ?>` Links to the front page with default language, So If site's default language is set to A and a user has selected language B, this code redirects user to the front page with language A.

Is there away to link to front page while keeping the current selected language?

# Answer
Use the following code:

```
<?php print url('<front>', array('absolute' => TRUE)); ?>

```
> 2 votes

# Answer
You can use a shorter version if you don't need your links to be absolute (usually needed for links displayed outside your website).

```
<?php echo url('<front>'); ?>

```

And also an even shorter version since the default value of the path is actually "front".

```
<?php echo url(); ?>

```

Documentation of the "url" function is here for Drupal 7 and Drupal 6 respectively. Note that what I previously stated is correct for both versions.

https://api.drupal.org/api/drupal/includes!common.inc/function/url/7

https://api.drupal.org/api/drupal/includes!common.inc/function/url/6

Cheers.
> 0 votes

---
Tags: 6, i18n-l10n
---


# Question
Title: hook_node_insert() and drupal_goto conflicts with each other?
I find some strange problem. I use hook\_node\_insert(). In order to create the other node after the user create the specific node! Then, I redirect the user to the other pages But there are some error messages that i can't figure out!

the below code is my hook\_node\_insert()

```
function campaign_node_insert($node)
{
    global $user;
    global $base_url;

    if($node->type=="my_content_type")
    {

            $userid=$user->uid;

        /**

                My code is right here !

               **/

               drupal_goto('/user/'.$userid);

          }
}

```

My error Message is as belowed :

# Answer
You can't use drupal\_goto() in hook\_node\_insert() and other node\_hooks too. The reason is that there is a queue of hooks that are executed on node insert and if you run drupal\_goto() in some hook - all other hooks which goes after will not execute!

If you need redirect user after node insert to some url - implement hook\_form\_alter for node\_form and add new submit callback $form\['actions'\]\['submit'\]\['#submit'\]\[\] = 'my\_module\_submit\_callback'. In this callback you will get $form\_state with all $node fields and you can perform you redirect by specifying $form\['#redirect'\] = 'some/url'.
> 3 votes

# Answer
Eugene is correct, although for D7 your submit handler should contain `$form_state['redirect'] = 'some/url'`.

You can look at the `node_form_submit()` function to see how Drupal core handles this.
> 0 votes

---
Tags: hooks
---


title: Link to exposed filter view?

text:
# Question
Title: Link to exposed filter view?
I'm building a block view that shows content related to whatever node is being viewed. It uses a contextual filter to pull the node author, and then displays content I've tagged as related. I also have a page view that has an exposed filter so the user can select an author and see all their work. I want to use the "more" link in views to take the user from the block to the filtered page of that author's work.

Since exposed filters doesn't change the URL, how can I link directly to a view with the correct filter already applied?

# Answer
> 2 votes
While exposed filters don't change the path, they do in fact change the url by adding the filters in there as variables. As an example, if you had a View with a page display at `your/path` and an exposed filter that filtered on content type, it would create this url after the exposed filter was selected:

```
www.example.com/your/path?type=NODETYPE

```

So, depending on what your exposed filter adds, you can create a link to

```
www.example.com/your/path/?filter=value

```

and go there directly. Just look in your browser afterwards and you should see it, assuming you aren't doing something fun with AJAX here anyway.

---
Tags: views
---


# Question
Title: How can I Display 'Items per page' in pager instead of the exposed form
I want to show 'Items per page' bellow the pager, I found viewsxtras, but it's just a placeholder and does not contain any code.

I'm using drupal 7 and views 3.x. How can I do this?

# Answer
> 2 votes
>

In Drupal 7 under PAGER click on "Paged, xx items", then look at the Pager options window

# Answer
> 0 votes
I think you can make use of the count in the aggrevation and then display it custom text in the footer region in the views. I have done it once, but not sure how.

# Answer
> 0 votes
This will only work with views exposed form

In .module file -\> hook\_form\_alter

```
$pager_options = array(5, 10, 15, 20, 25);
$form['your-views-form-id'] = array(
  ‘#type’ => ‘select’,
  ‘#options’ => $pager_options,
  ‘#default_value’ => 0,
  ‘#title’ => t(‘Items per page’),
);

$pages = $pager_options[$form_state['input']['your-views-form-id']];
$form_state['view']->set_items_per_page($pages);

```

It will provide you a select box with the options you have given and you will be able select no. of items to display on result.

---
Tags: 7, views
---


title: Profile2 Images

text:
# Question
Title: Profile2 Images
I have a image field in profile2, the images that are added to the profile are uploaded to /sites/default/files

This will be a mess with a lot of profiles and 5 images per profile. Also when the images are deleted from the profile they still remain in the folder.

Is there a way have each user's profile2 images goto their own location or at least one folder with all the pictures?

Also I would to know if there is a way so when the picture is removed from the profile or the account is deleted all the pictures are deleted to?

I am using the latest version of Drupal

# Answer
Hope this will help you.

In Drupal 7 you can use **TOKEN** module.

* Download and install **Token module**.
* By considering that you have add the new image field using the path `admin/config/people/accounts/fields`
* Go to your image field settings(admin/config/people/accounts/fields) and edit the image field
* Click ***Browse available tokens*** link to show the available tokens
* In my case I'm saving my **FILE DIRECTORY** path name as `profile-pictures/user-[current-user:uid]-[current-user:name]`
* When ever you upload files it will be stored in the **profile-pictures/user-UID-USERNAME**
* You can customize the **FILE DIRECTORY** path as per your requirement.
* You can use **file\_delete** and **file\_usage\_delete** to delete the file once removed.
* To delete the folder you can use USER API **hook\_user\_delete**

NOTE:

* You can also refer **IMCE** module.
> 1 votes

---
Tags: media, users
---


# Question
Title: Change texts according to other language in template.php
I have multilangual website ancak my site's footer is in template.php.

Like this:

```
function _site_footer(){
    global $language;

    $output = '<div class="footer_content container_12">
                <div class="item address grid_4">
                   this is a lorem ipsum
                </div>
            </div>
    return $output;
}

```

I want, when I turn my site to other language, get this footer:

```
function _site_footer(){
    global $language;

    $output = '<div class="footer_content container_12">
                <div class="item address grid_4">
                   TESTTESTTESTTEST
                </div>
            </div>
    return $output;
}

```

How can I change it in template.php? Thank you.

# Answer
> 1 votes
Global `$language` variable returns current language object, you can get current language code by `$language->language` property. Example:

```
global $language;
$output = '<div class="footer_content container_12">
                <div class="item address grid_4">
                   this is a lorem ipsum
                </div>
            </div>';
if($language->language == 'en') {
    $output = '<div class="footer_content container_12">
                <div class="item address grid_4">
                   this is a lorem ipsum in english
                </div>
            </div>';
}

return $output;

```

But better way would be using Render Arrays

**2-Solution:** is to wrap the text with t() function. And translate the text by `admin/config/regional/translate` link.

```
function _site_footer(){
    $output = '<div class="footer_content container_12">
                <div class="item address grid_4">
                   ' . t('this is a lorem ipsum') .
                '</div>
            </div>'
    return $output;
}

```

---
Tags: 7, theming
---


title: Admin login issues

text:
# Question
Title: Admin login issues
I have checked 'admin' user's status is currently 1 which means its active. I have tried to retrieve password via email also but I have not received any email may be because I am hosting in local.

I have reset the password from sql using below query

```
 update users set pass = md5('mynwepass') where uid = 1;

```

It seems like it updated the password but Drupal isn't recognizing my new password. I have repeatedly tried and my admin id got blocked temporarily and then I truncated the flood table to let me retry. But still it doesn't recognize my credentials.

Is there any other option left other than reinstall Drupal?

# Answer
> 2 votes
Drupal does not store passwords as md5. It is salted hash now, to prevent rainbow attacks.

If you need to be able to manually set password, without a need for working mail system, your best bet is to use Drush \- a command line shell and scripting interface for Drupal.

```
drush user-password someuser --password="correct horse battery staple"

```

# Answer
> 1 votes
You better change your password:

```
<?php
/**
* @file
* The PHP page that serves all page requests on a Drupal installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All Drupal code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once 'includes/password.inc';
echo user_hash_password('givenpassword');
die();
menu_execute_active_handler();
?>

```

after changing the pass delete that lines which are responsible to change password. You can see the solution by this link: Reset admin password

---
Tags: users
---


# Question
Title: How to add a 2nd submit button to a node form?
I need to have an extra Save button at the top of my node form.

Pressing the 2nd button should do the same action like the regular one.

The following code creates a 2nd save button:

```
function MYMODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {

  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );
}

```

But how do I put it at the top of the page (the form length is not fixed).

# Answer
The following code does create a 2nd submit button.

```
function MYMODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {

  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );
}

```

But since we want it on the top of the form, it's better to put it outside the 'actions' group. So the following code puts it just below the title, ready for styling:

```
function MYMODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {

  $form['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );

```
> 6 votes

---
Tags: 7, forms
---


# Question
Title: How to use entityform and ajax_form_entity in a modal window?
Just getting started with the entityforms module (and it looks sweet!). I want to create a 'contact us' link that displays the form in a modal window, submits and then closes the window.

There is a related module, ajax\_form\_entity, that looks like it would help make a clean submission. The demo site has a 'Views popup integration' section, but that doesn't look useful (or relevant, actually).

Anyone know how I can do an ajax submit of an entity form from a popup?

# Answer
There is a sandbox module called Modal Entity Forms https://drupal.org/sandbox/andreymaximov/2058521

It depends on the Modal Forms module and will work in the same way, but for entity forms. I have tested the module and it works fine for now, although I want to submit 1 or 2 patches to extend it's functionality.

**EDIT:** There is now a new module called Modal operations: https://www.drupal.org/project/modal It's currently dev only (still better than sandbox) and so far it seems to work fine.
> 3 votes

---
Tags: 7, ajax, javascript, entities
---


# Question
Title: Is it possible to set multiple permission in hook_permission()?
Let's say I have a custom module. Now I upgrade the module and add some new functionality which is bound to the old functionality. I already have a hook\_permission() set in the old version. But now need a second permission to keep unauthorised users away from accessing the new function. Is it possible to set a second permission in the same module? How would I do that?

That's how my hook\_permission looks for now:

```
function MYMODULE_permission() {
  return array(
    'name of permission' => array(
      'title' => t('Access Something'),
      'description' => t('Access Something to do something'),
    ),
  );
}

```

# Answer
> 4 votes
Of course:

```
function MYMODULE_permission() {
  return array(
    'name of permission' => array(
      'title' => t('Access Something'),
      'description' => t('Access Something to do something'),
    ),
    'name of another permission' => array(
      'title' => t('Access Something Else'),
      'description' => t('Access Something Else to do something'),
    ),
  );
}

```

---
Tags: 7, routes, users
---


# Question
Title: How to create page of multiple entity reference fields
I'm making a kickboxing archive. I would like to create a content type 'Fights'. But something isn't working.

A fight takes place between 2 fighters (content type 'Fighters'), at an event (content type 'Events'), in a venue (content type='Venues').

I need to select two fighters. I have added an entity reference of 'field\_fighters'. Now I want to add another entity reference of the same field for fighter 2, but I can only refer to this field once. How can I do this?

# Answer
> 3 votes
In the parameter of your entity reference field, you can set the number of values allowed. Just set it to 2 to answer your needs.

---
Tags: nodes
---


title: youtube video feed

text:
# Question
Title: youtube video feed
I'm new to Drupal and what I want to accomplish is a youtube video feed like the one on the Dalai Lama's website I know I can get an atom, rss, or json-c feed of my desired youtube playlist. What steps do I take next to create the page that has the list and hook it up to a page with the embedded youtube video?

# Answer
> 0 votes
You can use Feeds module and create Media files using that module with Media Youtube, there will be some configurations so you have to do them by your own.

# Answer
> 0 votes
HTML parser and can fetch data from existing URLs. Feeds is the way to go fetch rss feeds.

Modules required to fetch youtube feeds

1.Feeds it import's or aggregate's data as node, users, taxonomy terms or simple database records.

2.Youtube feeds, this module adds a new parser for Feeds module that makes it possible to parse and import YouTube video feeds

3.Youtube pull is a simple module to pull YouTube feed for latest video listing.This module is optional.

4.Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved.This module is used as per requirement.

Download and install the modules mentioned above. Configure the feeds module as per requirement. While configuring ,fields mapping plays a crucial role .Mapping helps to map current node field with the new nodes created from feeds. Use the YouTube API Tool to get the right URL! Once configuration is done you are all set to import feeds.

---
Tags: feeds, files
---


# Question
Title: How to hide language switcher block if node has no translation?
Having a bilingual site here. Some nodes are translated and language switcher works fine. But the switcher block also shows up on nodes which aren't translated. Then the untranslated language link has a different styling.

How can I hide the switcher when there's no (other) translation of the node? I looked up variables in all preprocess functions without finding any indicators. What do I have to look for? And how then can I hide the switcher?

# Answer
> 0 votes
In template.php add:

```
/**
 * hide language switcher if en-gb is not set
 */
function MYTHEME_links__locale_block(&$vars) {
  // made conditional if other languages are added later
  if(!isset($vars['links']['en-gb']['href'])) {
    unset($vars['links']['en-gb']);
  }
  // here is the condition
  if(count($vars['links']) <= 1) {
    return '';
  } else {
    return theme_links($vars);
  }
}

```

---
Tags: 7, i18n-l10n, blocks
---