# Question
Title: Apachesolr search results Facet Filter by date range
I am using apache solr search with my drupal 6 website and seek a modification in the facets being displayed.

Instead of the yearly facets like this:

to somewhat like this:

**last hour
last 24 hours
last week
last month
last year
**

I found http://searchhub.org/dev/2012/02/23/date-math-now-and-filter-queries/ saying that i can use fq=date:\[NOW/DAY-7DAYS TO NOW/DAY+1DAY\] in a custom module of my own to do this.

I tried this in my own module and figured out that its the $fq variable of apachesolr.module that should be overriden to achieve this.

I dont think I was able to use it successfully.

Can someone please tell me the exact function and variable to override.

# Answer
If i clearly understand you will have to use facets date.

And using Solr there's a issue where you cannot do multiple facets on the same field in the same query... This issue is now marked as fixed Solr backlog but the release is not ready yet i believe last time i checked. In my case since the fixed was not ready i created in the schema new field that are copyfields and i do the appropriate query.

Therefore you will have something like that :

**Last hour**

f.date1.facet.range.start=NOW-1HOUR&f.date1.facet.range.end=NOW&f.date1.facet.range.gap=+1HOUR&

**Last 24 hours**

f.date2.facet.range.start=NOW-24HOUR&f.date2.facet.range.end=NOW&f.date2.facet.range.gap=+24HOUR&

**Last 48 hours**

f.date3.facet.range.start=NOW-48HOUR&f.date3.facet.range.end=NOW&f.date3.facet.range.gap=+48HOUR&

**Last Week**

f.date4.facet.range.start=NOW-7DAY&f.date4.facet.range.end=NOW&f.date4.facet.range.gap=+7DAY&

facet.range=date&facet.range=date2&facet.range=date3&facet.range=date4

Hi hope that helps you!!! Cuz i've look so long to figured out myself ;)
> 2 votes

# Answer
I'm aware of the question actually has been asked over a year ago. However, I found it on Google and it pointed me in the wrong direction.

There is another way how you can achieve multiple date ranges without using copy fields in Solr. At first I thought this would be possible by specifing multiple facet.range.gap values. However, according to this issue, it is not possible (yet): https://issues.apache.org/jira/browse/SOLR-2366

So how am I doing it? By specifing multiple facet.query parameters this works:

```
facet.query=modified:[NOW-1DAY TO NOW]
facet.query=modified:[NOW-7DAY TO NOW]
facet.query=modified:[NOW-31DAY TO NOW]
facet.query=modified:[NOW-365DAY TO NOW]

```

The response will therefor look like this:

```
facet_counts: {
facet_queries: {
modified:[NOW-1DAY TO NOW]: 0,
modified:[NOW-7DAY TO NOW]: 27,
modified:[NOW-31DAY TO NOW]: 619,
modified:[NOW-365DAY TO NOW]: 9732
},
facet_fields: {} ...

```
> 1 votes

---
Tags: search
---


# Question
Title: How to get value from form field in rule?
I created a webform, and a rule. The rule works on the "form submit" event.

How do I get the value from a webform field in this rule event?

# Answer
> 0 votes
You have to use - `%value[key]` means - enter filed key name, for example: `%value['first_name']`. You will find this key name by following steps:

Go to `webform -> Form components -> edit` -\> you can find the entered "field key" value.

---
Tags: webforms, rules
---


# Question
Title: How can I run a query in the views in the context of the user access?
How can I run a query in the views in the context of the user? E.g. using `EntityFieldQuery` I can run

> $query-\>addMetaData('account', user\_load(1));

is there any equivalent for `$view->query`?

# Answer
> 2 votes
I've found possibility to do it in `hook_views_post_build`:

```
function MY_MODYLE_views_post_build($view) {
  if($view->name == 'MY_VIEW_NAME') {
    $query = $view->build_info['query'];
    $query->addMetaData('account', user_load(47));
  }
}

```

I've noticed that we have `SelectQuery` object only after query build (in views.inc `$this->query->build($this);`).

After it only one hook is executed `views_post_build`.

---
Tags: 7, views, database, users
---


title: Issue uploading Images

text:
# Question
Title: Issue uploading Images
I have a Drupal 7 site that runs on Windows 7 and SQLServer.

Recently, when users try to upload pictures or files they get an error message:

> File could not be saved. An unknown error has occurred. The file was unable to be uploaded.

I have a development and a test site. The site was on Drupal 7.20, then upgraded to 7.23 and it worked for the development and the test sites. However, it did not work in production.

In production I upgraded to 7.23 and verified the elfinder is using library files 1.2.

I am not sure why this is happening: No code was changed before the Drupal core update, and the error is sporadic.

# Answer
> 0 votes
The problem ended up being a server space issue. Increased space and the images were able to load.

---
Tags: media, files
---


# Question
Title: hide passwords in drupal module settings
we have a local community site for drupal and site is run by volunteer admins. my question is, is there any way I can 'hide' passwords in module settings? some modules ask for user password of the service they integrate. it's not safe to have them in plain text in their settings page.

and I don't want to restrict access to those module settings.

this is a common issue with drupal. you can create the permission using hook\_permission in your own module. then in your own module use hook\_form\_alter, find the form of the module andon those password fields use '#access' =\> user\_access('your\_permission'). but I have no idea how.

for example, Bot module has a password field. Mailchimp has API Secret field. etc

# Answer
> 1 votes
As you've already noted in the question, you can set `'#access' => FALSE` to any form element to remove it from display.

The correct place for this is in `hook_form_alter()`:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'relevant_form_id') {
    $form['some_element']['#access'] = FALSE;
  }
}

```

If you're asking for a way to do this generically, without having to target each element with a specific form ID/element key, then you're out of luck. Those fields are nothing special, just standard text fields, so there's nothing to distinguish them from any other text field.

Bottom line - you need to decide exactly what fields you want to disable, find the appropriate form IDs/element keys, and use the method above to apply the rule one-by-one.

# Answer
> 0 votes
The `settings.php` is a starter of drupal core, maybe you can put your password in another database(temp database) and fetch them in settings.php , but if another admin access settings.php, also can access you temp database.

I think restrict unix users by groups users in seperate groups and by `file permission` restrict them to access `settings.php` .

---
Tags: 7, security
---


# Question
Title: Is drupal safe against brute force login attacks?
A brute-force attack is an attempt to gain unauthorized access to a website by continually generating and inputting various combinations of a password. This task is usually done by automation software (a "bot") which looks for success or failure messages and keeps trying new passwords until it gets a success message.

Is Drupal 7 safe against it by default? what is more secure configuration for it ? Which module can help me for more secure sign in?

# Answer
> 12 votes
As you can see in the code, the function user\_login\_final\_validate register a flood event. That means if a same IP try to connect a user/login password many times we will be "banned" for a while.

This is one of the protections that Drupal offers. Another one, and I think if its happens to your web site you will notice it very fast, it's the CSRF token that Drupal generate for each form.

This means that the attacker bot should generate the form, then get the token and associate it with the submit form. That is very time consuming and will likely discourage the attacker. But first, you will see your server starting get hotter.

# Answer
> 3 votes
In addition to the good measures that Drupal 7 implements for stopping login attempts, I would suggest installing Spambot module, that deals specifically with new user registration attempts.

At every new user registration, that module will query Stop Forum Spam server to see if the user attempting registration is a known bot.

You can optionally contribute to Stop Forum Spam with your website's registration attempts.

# Answer
> 3 votes
There is Flood control

> This project is intended to add an administration interface for hidden flood control variables in Drupal 7, like the login attempt limiters and any future hidden variables.

**The functions to define and interact with core flood control system**

The flooding system provides us three functions:

```
flood_register_event($name, $window = 3600, $identifier = NULL)

```

Register an event for the current visitor to the flood control mechanism.

```
flood_clear_event($name, $identifier = NULL)

```

Make the flood control mechanism forget about an event for the current visitor.

```
flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL)

```

Checks whether user is allowed to proceed with the specified event. Basically, we check if a user has access by calling flood\_is\_allowed. If it returns FALSE, throw an ‘Access Denied”. Whenever a user performs the action we call flood\_register\_event.

By default it checks the user's ip adress. But we could pass some other unique identifier like the user id.

*Above copied from Playing with Drupal’s flooding system*

# Answer
> 0 votes
Thinking (and having) this problem, I wrote a module which allow you to prevent this kind of attacks: https://drupal.org/project/AntispammerBot

You can select which roles are safe, how many nodes the user can publish before considering it an spam attack, etc...

---
Tags: security
---


# Question
Title: I want to display one content type inside of another
I have a page called "Our Team" that will display all the members of our team. I have a content type called "Team Member" and have created many team members under this content type. How can I list all "Team Members" on one page?

# Answer
> 1 votes
What I would do is the combination of the comments above.

1. To your team 'Team member' content type add entity reference field with reference to 'Our Team' content type
2. Create a view that lists all of your team members (regardless the team for now).
3. In 'Contextual filters' under 'Advanced' settings of your view that you created in 2. add the field the you created in 1.
4. In the settings of that filter select 'Provide default value' and choose 'Content ID from URL'
5. Save your view.
6. Add view field to your 'Our Team' content type, in the settings of that field select 'Always display default value' and below select the view that you created in 2.

As long as I understood you correctly this should do the trick.

---
Tags: 7, nodes
---


title: Redirect Fisrt time login with LDAP

text:
# Question
Title: Redirect Fisrt time login with LDAP
The first time that the user login to the page, have to be redirected to the user edit profile to fill a field (Id) that is mandatory at the first login, I tryed using drupal\_goto at hook\_user\_insert and hook\_user\_presave and don't worked. How can I do that? In which hook I can do that?

EDIT: I am using LDAP Authentication, user don't have to fill a form registration.

# Answer
Thanks for your answers, I could do it, no with Rules module. I did it using hook\_user\_login(), and $\_GET\['destination'\].

```
    function webform_sub_user_login(&$edit, $account) {
    $currentuser = $edit['uid'];
    $_GET['destination']= "/user/".$currentuser."/edit";
    }

```

If it can cause problems, let me know. But for now it seems to work well.
> 1 votes

---
Tags: hooks, users, redirection
---


# Question
Title: Show total amount of results for an exposed filter
Found this answer, show amount of results for exposed filter and this answer.

However, my issue is that i'm trying find the total number of results after executing an exposed filter.

Views calc looks like it only returns the count of results from a single result not an exposed filter result. Or if i'm wrong please correct me.

Anyways, the question: How do you find the total number of results from an exposed filter?

**Desired result:**

* Complete an exposed result form
* return "x number of results found" as a block

# Answer
I'm using Views 3.7 in Drupal 7 right now and finally found out you simply can add a result summary `Global: Result summary` to the header/footer.
> 9 votes

# Answer
By using the below code, you can do that, It will display like this ***Showing 1-10 of 130 results***. on your result page.

Put this code in the **Header and set the input filter as PHP code** in your view.

> ```
> <?php
> global $pager_page_array, $pager_total_items, $pager_total;
> $my_view = views_get_current_view();
> $items_per_page = $my_view->pager['items_per_page'];
> if ($pager_total[0] == 1) {
>   echo t('Showing <b>!pager_total_items</b> results',
>     array('!pager_total_items' => $pager_total_items[0])
>   );
> } else {
>   $start = 1 + ($pager_page_array[0] * $items_per_page);
>   $end = (1 + $pager_page_array[0]) * $items_per_page;
>   if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
>   echo t('Showing !start-!end of <b>!pager_total_items</b> results',
>     array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0])
>   );
> }
> ?>
>
> ```
> -1 votes

---
Tags: views, search
---


# Question
Title: How can I add sort criteria for search api views?
I set up a view with search api data according to this, but the sort criteria available in each view are not complete. I'd like to sort on some fields (indexed) that are not showing in the list. I'm wondering if I need to use a hook to alter the query, or if there's a configuration option somewhere that I've not read about.

# Answer
I just discovered that if I re-index the fields (in this case, first name and last name) as strings, rather than the default fulltext, they are made available to sort on in views. This is great news.
> 4 votes

---
Tags: views, search
---


# Question
Title: Drupal Rules, create the SUM of a field decimal values
I m running a drupal 7 installation and I need to create a special routine for my site.

I have 2 content types -\> "Orders" and "Reports".

The "Order" content type has a field with decimal values called "final\_value". Any user can create an order with different "final\_value" each.

What I need is when a user creates a new report, a rule must trigger and calculate the SUM of all orders she created from the last time she logged in.

Any ideas??

# Answer
You could enable PHP filter module (in core package), what will expose a 'run PHP' rule. There you could run some queries. Have a look at db\_select and db\_query for how to construct them (there are good advices in the comments as well.).

Proceed with caution though as you are communicating directly against the database. Sanitize the in- and outputs.

If it is only for display purposes, you could achieve a similar effect with Views and aggregation enabled. Enable aggregation in the advanced section. Add the final\_value field, and select SUM. This is a much safer approach.

UPDATE

I suppose you are triggering the rule on the save event of the Order-node? In that case the Order is in the $node variable and you could go as follows;

```
$node->field_name = $calculated_value;
node_save($node);

```
> 2 votes

---
Tags: 7, rules
---


title: How to keep cache_form small

text:
# Question
Title: How to keep cache_form small
I have noticed in mysql that cache\_form.MYD table is 14GB. Why did it grow so big? Is it safe to empty it? and how can I avoid this happening in the future?

Thanks

# Answer
This is a known issue in Drupal 6 and 7 for that matter. It is not cleared when running cron. You can safely delete all rows that has expired.

```
DELETE FROM {cache_form} WHERE expire < now();

```

should do the trick.
> 8 votes

# Answer
https://drupal.org/project/optimizedb \- module that will solve your problem. He can clear the table cache\_form by Cron, also perform optimization and more. Versions available for Drupal 6.7.
> 8 votes

# Answer
I suspect that cron isn't running on your site. I am not 100% positive about that particular table, but other cache tables do get stale entries removed when cron runs.

If you need help setting up cron, peruse http://drupal.org/cron
> 3 votes

---
Tags: caching, database, theming, forms
---


title: Taxonomy Term for a sports team

text:
# Question
Title: Taxonomy Term for a sports team
I have taxonomy terms for teams ( say team one , team two , etc ) and content types of teams that have team pictures of your team.

Im trying to figure out how to create a view that will show a player that selects team one as their team, and then show them on team one.

I have the view created and its a table, I just can't figure out how to get each player on each team.

# Answer
> 0 votes
If I understood right, you want a view to display players of each team. For that, you could:

1) Create a taxonomy vocabulary for each team (which you have already done)

2) Add an image field to the taxonomy term, as you would do to a CCK (admin/structure/taxonomy/\[your\_vocabulary\]/fields

3) Create a CCK for "Player"

4) Add a field to the "Player" CCK of type "Term reference" (choose your Team vocabulary in the settings), so every time you create a new player you can select which team they belong to

5) Add the fields you need into your view, add a filter for the taxonomy term and expose it, so it will come out as a select list

I hope this helps a bit :)

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


# Question
Title: Store information from hook_form_alter to be used in later hook_user_update?
I have a hook\_form\_user\_profile\_form\_alter (hook\_form\_FORM\_ID\_alter) where I'm capturing user information that was changed when a user updates their profile.

I want *some* of that information available in hook\_user\_update, which is called after the form alter - maybe no more than 6 fields.

**Is there a way to hold some of the information from the hook\_form so it is available when I get to hook\_user\_update**? I'm looking for a server side solution. In Java I could use class variables or session storage. I see PHP has session storage. Is that the best practice or is there's a Drupal specific solution or a better PHP usage pattern?

Since someone will probably ask why I don't perform what I need done in hook\_form\_user\_profile\_form\_alter: That function gets called twice (which can be problematic) and I cannot be sure that the transaction is complete until I get to hook\_user\_update. So I feel that hook\_user\_update is a much better place to execute what I need to execute, because I'm synchronizing information with another application. I need to be sure the transaction went through before I perform the call to the other app.

# Answer
As far as I'm aware, all form element values entered by the user on the profile edit form are available in the hook\_user\_update()'s `$edit` argument. The only element that won't be there is the plain text password.

There is no "drupal way" to avoid this, as core handles this functionality and it's trying to stop you from accessing the plain text password.

REMOVING SUGGESTION PER @znerol. Will update later this evening
> 3 votes

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


title: Update core via Pantheon

text:
# Question
Title: Update core via Pantheon
I push all my local changes to the Pantheon git repository, then I update core via the pantheon dashboard. Now I pull from the Pantheon repository with `git pull git://github.com/pantheon-systems/drops-7.git master`. I am assuming that both versions are identical now. However, when I run `git status`, I get a message about my branch being ahead of origin/master.

Can somebody explain this to me? How can I get the local and remote repository in sync?

# Answer
Yes that makes perfect sense - you've merged changes from the core repo, so your working copy is one commit ahead of your site's dev repo on Pantheon. Note that `origin/master` refers to the remote representing *your* repo, not drops-7.git

```
git push

```

to send the changes up to your dev site when you're ready to test, then pull them through the dashboard as normal.
> 0 votes

---
Tags: version-control
---


title: Role Based Shared Control Panel

text:
# Question
Title: Role Based Shared Control Panel
I'm looking for a way to allow members of a specific role to share a control panel/settings page. These users do not have admin level access and I would like to use the field api to store data.

Currently I'm leaning towards the Profile2 module, but this doesn't feel very robust.

Is there a common way to accomplish this that I've missed, a module that is better suited for this use case or am I on the right track using the Profile2 module?

# Answer
> 1 votes
Yes, with the combination of `profile2` and `og` (organic group) you can achieve your job.

---
Tags: 7
---


title: Abnormal website database growth

text:
# Question
Title: Abnormal website database growth
I migrated my site to the production server about 3 months ago . 2 weeks ago , I noticed that the db was growing too fast(about 40Gb I could not account for) I backed the site , deleted WAMP and restored the site .

Result , slower until within the 2 weeks ,it has grown to a halt . Keeps on "connecting ". One other thing( could be related ) the site counter is showing a growth of about 1,000 users anonymous users very hour - this is not possible given the site is either too slow or not working at all outside the LAN

# Answer
I suggest `truncate` `watchdog` table, usually this table growth very quick.( maybe you can first get a backup of this table then truncate(empty) it)

( maybe trucnate cache tables be useful but If you see table size u will see the watchdog have biggest size )
> 0 votes

# Answer
You have to truncate the table cache\_form ..it's the main source of this problem and install the database optimizer module
> 0 votes

---
Tags: commerce
---


title: Styling Rewrite results in views

text:
# Question
Title: Styling Rewrite results in views
I have a field in my view and I have rewritten the result (  `p align="left" [field_about_us_read_more]` ) and also check the "Output the field as a link". in styling setting section, "*Customize field HTML*" is "*None*" and "*Customize field and label wrapper HTML*" is "*DIV*" the html code generated is like this:

```
<div>
    <a href="/www.com/test"></a>
    <p align="left">
        <a href="/www.com/test"> read more </a>
    </p>
</div>

```

How can I get rid of the first anchor link? and how to add extra html element in the " *styling setting* ".

TNX

# Answer
Remove check from "Output the field as a link" and then in rewritten the result put this

```
<p align="left">
        [field_about_us_read_more]
    </p>

```

or if not work try something like this (I mean in output use tag )

```
   <p align="left">
 <a href="/www.com/test">[field_about_us_read_more]  </a>

        </p>

```
> 0 votes

---
Tags: theming, views
---


title: Make the user avatar picture mandatory

text:
# Question
Title: Make the user avatar picture mandatory
In Drupal 7 is it please possible to enforce all new users to upload an avatar picture during the registration process? I.e. how to make the user picture field mandatory?

When I try to edit the registration form fields at `/admin/config/people/accounts/fields` there are no settings for the user picture, I only see it being an `account` widget:

# Answer
> 6 votes
Sounds like you need the register with picture module

# Answer
> 5 votes
Can you use hook\_form\_alter. **UPDATE** : this hook\_form\_alter must be put in a custom module, lets say mymodule the location of this module will be sites/all/modules/mymodule.

In order to use dpm(), you need to install the Devel module.

Here you can have a tutorial, explaining the basics for creating a custom module. In your case, this is going to be only .info file and a .module file. The hook\_form\_alter should look like

```
/**
* Implements hook_form_alter().
*/
 function mymodule_form_alter(&$form, $form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
  dpm($form,'form');
 }

```

A lot of nice snippets can be borrowed from here. drupal forum . After that you can use dpm ($form, 'form');

And see exactly the construction. Those forms use the Drupal 7 Form API construction mechanism. The idea would be to add `'#required' => TRUE` to the corresponding image field. I hope this helps in a way.

UPDATE: Do not forget to clear your caches(even twice) after enabling a module. Otherwise, some hooks (but not all) will not be recognized. This problem only caused a lot of frustartion when working with Drupal.

Best regards ! Oleg

# Answer
> 0 votes
I think you can add a new image field, called 'avatar' and mark it as required in the field's settings.

# Answer
> 0 votes
user picture field module allow you add an image field to user, and show it on user register form, after user register an account, this module will use the fid that upload by image field as user picture's fid. Usage:

1, Add a image field to user, for example "field\_user\_avatar"

2,config this field,and make it show on user register form.

3,install this module, navigate to "admin/config/people/user\_picture\_field", here you can config the "Machine name of source field that used as user picture"

> When user register an account, he/she upload an image through image field "field\_user\_avatar", this image will be used as user's picture(avatar).

---
Tags: 7, entities, users, media
---


# Question
Title: How do you keep the login block on the same page when validation fails?
On pages where the login block exists, I need to stay on that page (and preserve query string arguments) if the validation fails when submitting the form. Does anyone have any idea how this could be done?

# Answer
> 0 votes
You are looking for Ajax Login/Register module, it will not redirect on error, instead the login and register forms can validate using ajax and stay on same page.

> This module provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.

Features:

* This module provides a block with 2 links (Login, Register) for the anonymous user.
* When the user clicks on Login or register the requested form appears in a nice ajax popup.
* The login and register forms can validate using ajax and not redirect on error.
* On success the module redirects to the user page.
* When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
* This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.

---
Tags: 7, forms, blocks
---


title: Ajax Quiz or Ajaxify my site

text:
# Question
Title: Ajax Quiz or Ajaxify my site
im using Drupal 7 and the Quiz module for making some quick courses.

It works fine, but i would love to make them with ajax transitions instead of doing it by the old form way.

I have seen the ajax quiz module, but it doesnt seem to work. any other recommendation? there's any other module i could use in order to ajaxify my quizzes or my whole site? Thanks.

# Answer
> 1 votes
You can try Quiz Drag Drop module

> This module allow you to add drag drop type of question in quiz module.
>
> By using this module admin can upload images with their titles and later all the titles will become placeholder. User need to drag and drop images on the correct placeholder to get points.
>
> This module is an attempt to enhance Quiz module features by introducing another type of question.

---
Tags: 7, ajax, quiz
---


title: Using short URLs with AddThis

text:
# Question
Title: Using short URLs with AddThis
I am using the AddThis module on my site. Can this be configured to use short URLs instead of the native ones?

# Answer
> 2 votes
If you're not wedded to AddThis then the Service Links module integrates with the Shorten URLs module to provide this feature. It has the advantage of not being coupled with/crippled by the AddThis service.

---
Tags: 7
---


# Question
Title: How do I assign a view to a panel node in drupal
I have a panel that shows a teaser of a bunch of nodes of a certain content type. I am attempting to replicate this for a new content type.

I have created a similar content type with the exact same fields. I have cloned the view(**type = content pane**) and changed the filter to the correct content type. I have now created a page of content type panel.

**Question:** How do I assign the view to that page(node)? Does it have something to do with display suite and the layout?

I am using Drupal 6.

**EDIT:** To put the above in another way:

I have a panel and I don't know how to apply a view to it. So I have my view that basically aggregates a bunch of nodes based on content type. I'm not sure how to add panel content to the panel. But the panel content being the query the view execute

# Answer
> 2 votes
If you are display the panel on a node then you need to add a variant of the **node/%node** page. In Drupal 7 you would

1. Edit the **node\_view** (node/%node) page.
2. Press *Clone* to create a variant of your current page.
3. Under *Selection rules* add *Node:type* and select your new content type.
4. Ensure that the new variant is above your current variant, or add Selection rules to your current variant too.
5. In your new variant under *Content* replace the old View with the new View.

Note: If the only change to the View (and Page) is the Content type then you could have used the Content type of the node being viewed as a Contextual filter on the View. Then there would be no need for a Panel variant or another View.

---
Tags: views, entities, nodes, panels, display-suite
---


# Question
Title: How to use Drupal.behaviors in Drupal 7?
I have these codes in my druapl 7 theme js file (js/test.js):

```
 (function($) {
    alert("Hi");
    Drupal.behaviors.mythemename = {
      attach: function(context, settings) {
        alert("Bye");
      }
    };

 })(jQuery);

```

then I call this file using :

```
 drupal_add_js(drupal_get_path('theme', 'mythemename'). '/js/test.js');

```

in page--front.tpl.php file inside the theme folder.

But only the first alert is shown. Why is it so? where is my problem ?

# Answer
> 1 votes
Probably to late to load the js file in the .tpl try in template.php with

```
YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('theme', 'mythemename'). '/js/test.js');
  }
}

```

# Answer
> 0 votes
Here's what solved my problem. I have to use drupal\_add\_js in this way:

```
drupal_add_js(drupal_get_path('theme', 'bitcont') . '/js/s3.js', array(
  'scope' => 'footer',
  'weight' => '15'
));

```

---
Tags: 7, javascript
---


title: Error which i am incountering

text:
# Question
Title: Error which i am incountering
PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'dropjob.semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( \[:name\] =\> variable\_init ) in lock\_may\_be\_available() (line 167 of D:\drop\_job\includes\lock.inc).

Can anybody help me to solve it I will be greatful

# Answer
If the table doesn't exist (for some reason), you can create it manually by executing an sql query.

Here is the query to create the `semaphore` table:

```
CREATE TABLE `semaphore` (
  `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique name.',
  `value` varchar(255) NOT NULL DEFAULT '' COMMENT 'A value for the semaphore.',
  `expire` double NOT NULL COMMENT 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
  PRIMARY KEY (`name`),
  KEY `value` (`value`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Table for holding semaphores, locks, flags, etc. that...';

```
> 0 votes

---
Tags: database
---


# Question
Title: How get Drupal Alias from given node NID inside a module function?
I am trying to get the Alias from a given system path node NID (node/nid), inside of a node\_insert function in a custom module.

I already tryied:

```
drupal_get_path_alias('node/866'); // return node/866 in watchdog dblog

```

and

```
url('node/866'); // return node/866 in watchdog dblog

```

and

```
drupal_lookup_path('alias', 'node/866'); // return NOTHING in watchdog dblog

```

and

```
drupal_get_normal_path('node/866'); // return node/866 in watchdog dblog

```

It should return `seo/preparedUrl`, but I can´t find a way to do this.

I need this to change a path before the node is saved.

In URL alias (admin/config/search/path) the Alias(seo/preparedUrl) and System (node/866) are there!

**THE ANSWER**

First of all, Thanks to @arpitr with the help with devel/php path sugestion! Really fast debug this way!

The answer in my case is that is two languages. The path was in language, but my user was in another so, when I use dpm it continues to print the node/nid, but when I changed my user language to be equals to content language it began to work the way I want!

(I can´t answer my own question or vote up nothing here because I am a new user, so I putted here!)

# Answer
> 4 votes
It looks like you are debugging through watch dog table, you should better use devel module it provides you several debugging options few are

* dpm() example in your case : dpm(drupal\_get\_normal\_path('node/866'));
* devel/php path which allows you to test your php codes. example in your case : simply log in as admin visit sitename/devel/php and execute dpm(drupal\_get\_normal\_path('node/866')); and see what it shows

About the problem

* Make sure node/866 exists
* If node exists make sure when you are able to access the node-866 by node/866 and alias which you have configured.
* As as an option you can delete the existing alias and create the same alias again. And check again.

---
Tags: 7, hooks
---


title: Multisite with content sharing

text:
# Question
Title: Multisite with content sharing
The last couple of days I have been looking into Drupals multisite with content sharing. Got some great information like http://palantir.net/blog/multi-headed-drupal and http://munich2012.drupal.org/program/sessions/multi-headed-drupal

It gives me a good idea of the options I have building a multisite and content sharing setup. As I am quite new to Drupal I am trying to get input on my setup and the architecture that is required to build it. I will briefly explain the architecture and then the options I think will be suited for this.

**Basic setup** The basic setup is as follows. There will be 1 global website with an own admin/editor. Next to the global site there will be 10 regional websites with their own regional admins/editors. The regional websites will have content in their own language, but in the CMS there is an option to translate the content to English.

**Global website** The global website will be a 1 page website and it displays content (English) from the regional websites. Content that needs to be curated by the global content-editor.

**Regional websites** The regional websites are all the same (pages , nodes, content types) except for some different styling and logo's.

**Access levels** The global admin can access all the websites, this can be using other logins or preferably an own global account. The regional admins/editors can only access and edit their own site.

From the information I have so far, this will require a combination of Domain Access and Organic groups but I am not sure if this is going to work. My main concern is combining a global home with the regional websites and push content to the global home. Not only pushing but the the global editor will need to approve content before displaying it on the global home.

Does anyone know if we can build such a setup with Drupal?

Thanks in advance.

# Answer
I might think about using a login mechanism like OAuth (with its Connector module) or an LDAP instance so that your global admin can login to any site with the same login.

To distribute the content, I would try using a REST API from the regional sites via the Services module which supports login if content or views needs access control.

Good luck!!
> 1 votes

# Answer
Make views from reginonal site content that global can include in some admin page.

From that page global admin can pick url of the regional content and paste it in to list of "approved content".

Build stripped custom entity-view for the content available at regional url so the global site can parse the approved content list to list of entity-views.

This wouldnt necessarily need any cross site permission integration.
> 0 votes

---
Tags: organic-groups, multi-sites, domain-access
---


# Question
Title: Why does my front page only work in one language?
I have problem with language of Drupal. When I click in home page in English language, the front page contains all content, nodes and blocks. When I click on other language, the front page doesn't show any contents and shows this message:

> No front page content has been created yet

How can I make 1 front page that contains the same blocks and content and is also translated in different languages?

# Answer
This is the way I use it for a website with one single language in the front end (Spanish), and backend in english.

And..

All nodes are created using default language.
> 1 votes

# Answer
You could create a node with some static content to display as homepage, and then set this node as your default front page for default language in

> admin/config/system/variable/edit/site\_frontpage.

and then translate this node for other languages.

In order to display some views blocks especifically in your frontpage and in all languages, first make sure your block settings are

> Show block on specific pages : Only the listed pages : `<front>`

Then in view advanced settings, set *Field Language* as *Current user's language*

To complete, you can use Internationalization views to translate not dynamic content in your view, like views header, labels...
> 1 votes

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


title: How to create custom entity in Drupal 8

text:
# Question
Title: How to create custom entity in Drupal 8
I have a big personal project build on Drupal 7 that has many custom entities. I want to start upgrading the project into Drupal 8 but the completly rewritten Drupal 8 core is too big for me to get my head around without any documentation(+ Symfony is totally unknown to me, I'm just a simple Drupal-only guy).

I tried to create a custom entity just by looking at some of the core modules code but without any success.

Can you point me to some articles about custom entities in Drupal 8(I haven't been able to find single one) or give me some basic step-by-step guide?

Thanks.

# Answer
I'm working on Entity API documentation here: https://drupal.org/developing/api/entity.

The question is too big to answer in detail, and it depends on whether you need content or config entities. Assuming you want content entities (stored in database, can be fieldable/revisionable/..., details in the link above), you need to do something like this, the documentation linked above will eventually cover each step, including tutorials, right now, it only covers the first steps.

1. Provide an entity class and add the necessary annotations to expose it as an entity.
2. Provide the necessary table(s), you don't have to change much if you already have your 7.x schema, but you want to add a uuid and possibly langcode column if your entity can have a language/be translatable. See the node example linked in step if you want to make some base fields (properties) translatable or revisionable, you currently need to provide the necessary tables yourself.
3. Provide the base field definitions in your baseFieldDefinitions() method.. Note that the way this works will change in https://drupal.org/node/2047229 (from arrays to classes).
4. Implement the necessary pre/post Save/load/Delete methods if you have custom logic that needs to happen e.g. before saving an entity (like updating the changed timestamp).
5. Implement an access controller if you have non-trivial access logic and override the checkAccess() and checkCreateAccess() methods or specify the admin\_permission in your annotation if you just have a single permission that allows full access.
6. It is recommended although not technically required to provide an interface for your entity class (e.g. NodeInterface for Node) that includes useful (usually get/set/isSomething()) methods for your base fields, so that you can type hint on the interface and get auto-complete for those methods.

Depending on what you need, there will also be further steps, like defining the necessary forms, possibly a render controller and so on, but those should probably be separate questions if you need more information.

Notes:

* Config entities are basically similar, except you need to use the config storage controller (https://drupal.org/node/2119905 will make this easier), you don't need to define table schemas (obviously) but you need to provide a config schema file, see e.g. those for taxonomy vocabularies or node types.
* Content entities don't have their base fields defined as public or protected properties, instead, they are automatically managed in the values and fields properties. Access them either through get()/set() or the corresponding magic methods. ($node-\>title is equal to $node-\>get('title')).
* Help on the documentation there would be very welcome. I've created a basic outline for the content/structure I'd like to have, so just create a new page and get started on e.g. I'm also interested in having simplified tutorials, for config entities, there's one here already that I will move over to the entity documentation when ready: https://drupal.org/node/1809494
* Core has quite a large number of content entity implementations, if you want to see working examples: Node, User, Term, Comment, CustomBlock, ... as the article linked in step 1 explains, you can always find the entity types provided by a module in the Entity namespaace.
* @fago just gave a presentation about Entity API at the DrupalCamp Vienna this weekend, covers a lot of what I wrote here and more.
> 14 votes

---
Tags: entities, 8
---


# Question
Title: Contextual filter and exposed filter related
I am facing a real problem and i can't manage to solve it.

I have some checkboxes in user profile based on a vocabulary. I want to display all articles that have this tags in a view . If user wants to see all articles he should choose on a select list what he want to display. So i want to make a default for that page and if user wants something else to display based on a select option.

Ex: user X has checked in profile page options : management. then he goes in news view and see all articles with tag management. If he change his mind and want to see other categories this should be done from a select.

I have done the first part that with default articles (i make a contextual field with default get ID from logged in user -\>relationship from user and display content that have that terms-\> this is a user entity view that displays related articles) when i put the exposed filter and select another value i get nothing. I think that view searches for that value in user checkboxes preferences in user profile.

What can i do to achive my goal? Thank you

# Answer
> 1 votes
Probably I misunderstood your problem, but I put my solution anyway.

OK I have a view with entities of content type Foo and exposed filters as block, which appears on all pages. I am storing filter values in user entity (same fields as in Foo - taxonomy term reference fields).

When URL has not exposed filters parameters (exposed filters form hasn't submitted) I try to set filters default values from user entity fields:

```
    /**
     * Implements hook_form_FORM_ID_alter
     */
    function mymod_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
     if (! _mymod_isFormSubmit()) {
     //exposed filters form hasn't submitted so I am using values from user entity
     global $user;
     $wrapper = entity_metadata_wrapper('user', $user);
     foreach(_mymod_getFiltersMapping() as $filterName => $fieldName ) {
      $tids = array();
      foreach($wrapper->{$fieldName}->value() as $term) {
        $tids[] = $term->tid;
     }
     $form_state['input'][$filterName] = empty($tids) ? 'All' : reset($tids);
    }
  }
}

```

It isn't working for me yet, I am getting always random values, maybe because usage of Better Exposed Filters form.

---
Tags: views
---


# Question
Title: Conditional fields module - Required fields that are hidden are still required to be filled
I'm using the Conditional Fields module to create dependencies that hide/show certain fields in a shipping/billing information form.

In the form, I have 1 "List (text), select list" field which is used to select the dependees for 3 dependents. The dependents are 2 "List (text), select list" fields and 1 "Text" field. All fields are set to be required in their field settings.

I have each dependent set to be invisible unless its' dependency is triggered. My problem is that after triggering one dependency, the 2 remaining dependents, which are hidden, are still required even though they are hidden. When submitting a form, this causes an error message to display saying:

"x field is required

y field is required"

::My settings for each dependent are as follows::

Condition: Value

Values input mode: None of these values (NOT)

Set of values: "My selected value(s) that trigger(s) the dependency"

Interaction with other dependencies: XOR

Form state: Invisible

Effect: Show/Hide

✓ Hide the dependent if the dependee is not in the form

✓ Hide the dependent if the dependency is not triggered

✓ Hide the dependent if the dependee is not viewable by the user

# Answer
> All fields are set to be required in their field settings.

This is your mistake. If you set the field to be required in the field settings, **it will be required whether it is invisible or not**. So you need to uncheck this setting unless the relevant field will always have a value.

Instead, you should trigger the "make required" action provided by the Conditional Fields module whenever showing the relevant field for input. Unfortunately, the last time I tried this in Conditional Fields, it did not work due to a bug.

**Alternatives**

Field Conditional State is a stable module that works similarly to Conditional Fields. You can use this to properly set required fields.

Or, if you prefer a code-based solution, look into the `#states` API.
> 1 votes

---
Tags: theming, entities
---


title: Use tokens in PHP filter

text:
# Question
Title: Use tokens in PHP filter
i want make a photo gallery with drupal and i need to:

1. a download button for current node picture
2. an embed code that allow visitor to use photo on other Websites. like this:

i have some experience with Drupal and reading PHP codes, but no experience with writing PHP codes. i tried to make a block in bottom of node picture with PHP filter and following content:

```
<pre><a href="<?php t('[node:url]'); ?>" title="<?php t('[node:title]'); ?>"><img src="<?php t('[node:field_image]'); ?>"></a></pre>

```

this code not work. please help me.

many thanks :)

# Answer
To translate the tokens in their values, you can use:

`token_replace`

e.g:

```
$nid = token_replace('[node:nid]', array('node' => $node));

```

You need to be able to pass the required parameters for that token, e.g `$node` for node tokens.
> 2 votes

---
Tags: tokens
---


# Question
Title: Redirect user to prefered language after login
After any user logs in, I want to show all users the same page, but in their prefered language. So, I want to redirect the user to the page URL with the language appended, like http://example.com/pt or http://example.com/en.

What is the best way make this redirect?

# Answer
> 8 votes
You can use the `hook_user_login` which is called after a user successfully log in to the website. This hook passes the user object as an argument that you can use to retrieve the user language.

For the languages, you can make use of the `language_list`, which returns an array with the defined languages in your Drupal website. And for the redirect, `drupal_goto` does the job.

Here is some sample code that could help you further:

```
function YOURMODULE_user_login(&$edit, $account)
{
    // retrieve user language
    $user_language = $account->language;

    // don't do anything if no language is defined
    if (!$user_language) {
        return;
    }

    // verify if language exists
    $languages = language_list();
    if (!isset($languages[$user_language])) {
        return;
    }

    // verify if language is enabled
    if (!$languages[$user_language]->enabled) {
        return;
    }

    // redirect to preferred language homepage
    drupal_goto('<front>', array(
        'language' => $languages[$user_language],
    ));
}

```

---
Tags: 7, users, i18n-l10n
---


# Question
Title: How do I present the user login form from a callback, and redirect them after login?
I need to present the user login form from a callback function that I have registered in hook\_menu(), at that specific URL. When the user logs in, I need to direct them back to that URL to present them with other options. Currently, I call:

```
if (!user_is_logged_in())
    drupal_goto('user/login');

```

Of course, that takes them to the login page. I imagine I need to call drupal\_get\_form() to present the form from here, but how do I direct them back to this page after login?

# Answer
> 2 votes
You can render the `user_login_block` on your page. Once the user successfully log in, they will be redirected to the same page on which the user login block was generated (so the same page actually).

To render the `user_login_block`, you can make use of the `drupal_get_form` and passing the form name as an argument.

```
function YOURMODULE_page()
{
    $build = array();

    // construct your build with parts of the page
    // ...

    if (!user_is_logged_in()) {
        // user not logged in, add the login form
        $build['user_login'] = drupal_get_form('user_login_block');
    }

    return $build;
}

```

---
Tags: 7, forms, users, redirection
---


# Question
Title: Send list of node title and body via email to users
I have a question and answer site.

I would like to send via email a list of the node title and node body of all questions created over a period e.g 24hrs or 1 week to users on my site.

I do not know which module(s) would allow me select nodes of type question and then send the list via email to users on my site.

Thank you in anticipation

# Answer
> 0 votes
Hope this will help you create a module with hook\_cron

```
    function mymodule_cron()  {

      $time_fetch=time();
    $result = db_query("SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, 'node' AS field_data_body_node_entity_type
    FROM
    {node} node
    LEFT JOIN {node_revision} node_revision ON node.vid = node_revision.vid
    LEFT JOIN {node} node_node_revision ON node_revision.nid = node_node_revision.nid
    WHERE (( (node.status = '1') AND (node.type IN  ('question')) AND (node.created BETWEEN $time_fetch+0 AND $time_fetch -604800) ))
    ORDER BY node_created DESC")->fetchAll(PDO::FETCH_ASSOC);
            //WHERE date BETWEEN DATE(NOW( ) + INTERVAL 7 DAY ))->fetchAll(PDO::FETCH_ASSOC);
        $all_user = db_query("SELECT users.mail AS users_mail, users.uid AS uid, users.created AS users_created
    FROM
    {users} users
    WHERE (( (users.status <> '0') ))
    ORDER BY users_created DESC")->fetchAll(PDO::FETCH_ASSOC);

        foreach ($result as $mail_data)
        {
            foreach ($all_user as $user_mail) {
            //dpm($mail_data);
            //dpm($user_mail);
//here i think you can use the drupal_mail function
            //$message = drupal_mail('mymodule', 'message_key', $to, user_preferred_language($user), array('body' => $body, 'subject' => $subject, $from, TRUE));

        }
        }
        }

```

the drupal mail api is here drupal\_mail

---
Tags: nodes, rules
---


# Question
Title: How can I automatically position a block in Drupal 7 (via a script, Drush, etc.)?
I have a bash script that I use to rebuild my dev environment by re-importing my MySQL database and activating/deactivating modules, etc.

Recently, I've realised that I often need the `Switch user` block provided by the Devel module.

So, ideally, in my script, I'd like to automatically enable the module in the left sidebar.

This question on how to place a block with Drush looked promising but it suggests using Drush Extras, which according to the README does not work for Drupal 7.

How can I automatically set the position of the `Switch user` block from the command line?

# Answer
> 3 votes
**Updated answer:**

I just committed https://drupal.org/comment/7000524 to support the Drush block commands in Drupal 7. I also added a shortcut mode, where arguments can be used in place of options in instances where doing so would be unambiguous. When calling block-configure from a bash script, though, you should always use the options form; otherwise, your script would break if a specification became ambiguous (e.g. if someone added a block whose delta was named the same as some region).

So, from the commandline:

```
$ drush block-configure switch_user sidebar_second 10

```

From a bash script:

```
drush block-configure --module=devel --delta=switch_user --region=sidebar_second --weight=10

```

The later works just fine from the command line, of course; it's just more typing.

---
Tags: 7, blocks, drush
---


# Question
Title: Prevent Serialization or Unserialize via ODBC
Drupal, while a great CMS/Website/Intranet platform, is poor at providing users ability to edit datasets as one might in a spreadsheet or openly editable database table. We get forced into form update, form update, form update etc. Point, scroll and click time wasted. I've yet to find the module or View to edit data like a spreadsheet but still maintain database structure.

In Drupal 6, via ODBC we could easily edit node title, node body, comments or other text fields through programs like OpenOffice Base, LibreOffice Base, Microsoft Excel/Access or HeidiSQL. With Drupal 7 the text/data is serialized (BLOBs) and therefore what was easy changes to many text fields at once is now not possible, easily anyway.

1. What Drupal View setting, module or api/hook allows datasets to be edited, or
2. How to unserialize BLOB data for viewing in external programs
3. Stop Drupal 7 from serializing in the first place? or,
4. Other

# Answer
> 1 votes
In normal circumstances you shouldn't edit raw database tables to make changes; there's an extensive API in place which you should use instead (whether that be via the UI, through custom code, interacting via REST, whatever).

Updating tables manually means you deny module hooks the chance to run, potentially leaving your site in an inconsistent state. Not to mention the fact that caches won't be invalidated, leaving your front-end inconsistent for a time.

To directly answer your questions:

A) I'm not sure what you mean by 'datasets' here. If you mean, how do you update a bunch of values for a bunch of entities (e.g. nodes) in one go, then the Views Bulk Operations module should be useful.

B) The data you're referring to is serialised using PHP's `serialize()` function. You can decode it with `unserialize()`. I can't comment on how you'd do that in, for example, Excel. Perhaps you could write VBA functions to mirror `serialize()`/`unserialize()` and apply them to the incoming/outgoing data?

C) You can't stop Drupal from serialising that data, it's baked right in. Well, you could *theoretically* do it, but it would be an awful lot of work. You'd probably also find the need to change a lot of contrib modules who rely on the known schemas.

D) I haven't used it personally, but I've heard good things about the Data module. Might be worth checking in to. Feeds might be of interest too.

To sum up: Providing users the ability to make changes to the site by directly manipulating database tables, outside of the API, isn't really one of Drupal's goals (or not one that I've seen mentioned before). If anything, I'd imagine they want to discourage that for the reasons I've mentioned above.

---
Tags: views, forms, backups
---


title: Why doesn't this code work?

text:
# Question
Title: Why doesn't this code work?
I'm more or lees newbie developing with drupal and now, specifically, I'm trying to create one new entity. I've seen the entity\_example given in examples for developers and also I have read this post recomended in the Entity API docs.

I have understood the basics things. I have created the table for the entity, I have defined de entity with the hook\_entity\_info(), the links for manage page and create one item of this new entity, etc. And it seems to be fine because when I add one item, i can see it on the database.

The problem is when I try to load the entity data. First of all, I have register the url in the hook\_menu().

```
$items['issue/%gissues_issue'] = array(
'title callback' => 'gissues_issue_title',
'title arguments' => array(1),
'page callback' => 'gissues_issue_view',
'page arguments' => array(1),
'access arguments' => array('View Issues'),
'type' => MENU_CALLBACK,
);

```

Also, I have created the permissions in hook\_permission() and two functions, as I have read in docs, for loading one item or multiple items. I show the code of that functions:

```
function gissues_issue_load($issue_id = NULL, $reset = FALSE) {
    $issue_ids = (isset($issue_id) ? array($issue_id) : array());
    $issue = gissues_issue_load_multiple($issue_ids, $reset);
    return $issue ? reset($issue) : FALSE;
}

function gissues_issue_load_multiple($issue_ids = array(), $conditions = array(), $reset = FALSE) {
    return entity_load('issue', $issue_ids, $conditions, $reset);
}

```

When I execute the code, I receive this error message:

> Warning: array\_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 173 of /home/user/public\_html/formacion/includes/entity.inc). Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase-\>execute() (line 2168 of /home/user/public\_html/formacion/includes/database/database.inc).

I think the entity\_load function is not receiving the correct data. The function needs an array with the IDs and it's receiving an array of array. This is what the dpm shows:

```
  (Array, 1 element)
  0 (Array, 1 element)
    2 (Object) stdClass
      issue_id (String, 1 characters ) 2
      bundle_type (String, 13 characters ) general_issue
      [

    entity data

      ]
      rdf_mapping (Array, 0 elements)

```

So that, I'm quite lost. May be its something simple or maybe not, but I can't figure out what I'm doing wrong o what i'm forgetting to do.

Any help would be appreciated.

# Answer
> 0 votes
If your module name is

`gissue_issue`

Then you could have a hook namespace collision with

`hook_load`

In which case the `$nodes` parameter is being passed to your load function as well.

Just a possibility to consider.

---
Tags: entities
---


title: Getting error message on fresh install

text:
# Question
Title: Getting error message on fresh install
I am trying to install drupal using drush site-install and keep getting the following error at the top of the page.

Warning: Illegal string offset 'field' in DatabaseCondition-\>\__clone() (line 1817 of /var/www/mydrupalsite/includes/database/query.inc).

Even when I logout of administrator, the error still pops up at the top of the page. Can anyone explain what is going wrong and how to get rid of these messages? Everything else seems to have installed properly.

# Answer
Make sure you're installing a current version of Drupal 7, that error appears to have been fixed in an earlier version.

https://drupal.org/node/1622886
> 1 votes

---
Tags: database, drush, installation
---


# Question
Title: Link to images(thumb) in a (block)view to the image(original) in another (page)view
I have a unlimited multivalue field image gallery.

Using views i created a page for file entity and got the list of files in the field. The page displays the default original images one by one with a pager.

Created a block for the same view with the files shown as thumbnails, so the user can view all images in the gallery and click on the image he/she wants to see. I can link the thumbnails to content or file which takes me to the original file.

Is it possible i can link them to the corresponding image in the page view.

# Answer
> 1 votes
In your block view, if the "Link image to " option doesn't give you what you need for the thumbnail image field, you can build your own link using "Rewrite Results". You would do something like this:

1. Add content:path or nid to your view, and exclude from display
2. Make sure content:path or nid is first in you list of fields
3. For the thumbnail image field, enable "Output this field as a link " under Rewrite Results
4. use the token for nid or content:path (i.e. \[path\]) to construct the link you need

Note: if you use content:path, you will probably want to enable "Use absolute path" for it's field settings, even though it is excluded from display.

---
Tags: 7, views
---


# Question
Title: Cannot login to turn off maintenance mode after 7.24
I am new to Drupal, and although I managed to understand most of its principles, it seems I broke my site when trying to update it to the latest 7.24 release.

As instructed in UPDATE.txt, I entered maintenance mode and deleted all folders except `sites/`, which I had backup of course. I then copypasted all the new folders (including .htaccess) to my installation, and tried to run the update script. However, the update script said there were no pending updates. After that, the site was in maintenance mode, and even from my already logged in account I could not turn it off. I tried logging in again, and now I'm stuck in maintenance mode, and `/user` page redirects me to the main one. I tried emptying the cache tables, but nothing happened. I also tried copying the folders again, with no results. I enabled "update\_free\_access", and tried running the update script again, but no results.

Is there any way to avoid a blank installation?

# Answer
> 0 votes
If you had previously enabled clean URL's, you may need to uncomment the re-write base again in .htaccess.

Try scrolling down the page, and finding the line, # RewriteBase / then remove the hash.

Or, try accessing your login page via www.yourdomain.com/q?=user

# Answer
> 0 votes
7.24 has a security update and needs to add or change your .htaccess file for you public and temp files directory.

See what you have to add/change in drupal.org and here. I haven't done the 7.24 update yet so, this is as much i can help.

---
Tags: users, updating, maintenance-mode
---


title: Query between 2 tables

text:
# Question
Title: Query between 2 tables
I want the date for the last login for a defined role, but I have a problem with my query with drupal 7.

I have the good answer in phpmyadmin with this query :

```
SELECT login FROM `users` AS u, `users_roles` AS r
WHERE u.uid = r.uid
AND r.rid = 3
ORDER BY login DESC LIMIT 1

```

But an error with Drupal7... I tried this code :s :

```
$query = db_select('users','u')
 ->join('users_roles','r','r.uid = u.uid')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);
$res = $query->execute();

```

Thanks

Edit : Thank for your answer Clive , this code works :

```
$query = db_select('users','u');
$query->join('users_roles','r','r.uid = u.uid');
$query->fields('u',array('login'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'ASC')
 ->range(0,1);

$res = $query->execute();
return $res->fetchField();

```

# Answer
`SelectQuery::join()` returns the alias created, not the query object, so it can't be chained. This should work

```
$query = db_select('users','u')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);

$query->join('users_roles','r','r.uid = u.uid');
$res = $query->execute();

```
> 2 votes

---
Tags: database
---


title: Menu token not working properly

text:
# Question
Title: Menu token not working properly
I am Using menu token module to access pages related particular user, I am getting issue while selecting path in token menu using replacement patterns. can any one explains on what basis it will take the link and direct to the page. i tried to use \[node:content-type:name\], As there are so many content types created in my site, so how it will take the specific content type which is related with the node.

kindly suggest me if there are alternatives for this..

# Answer
Make sure you've chosen the right method under "MENU TOKEN OPTIONS":

With this options enabled, I was able to create a menu item using the token `[node:content-type:name]`
> 3 votes

---
Tags: navigation, 7
---


title: Users cannot login after Upgrade to 7

text:
# Question
Title: Users cannot login after Upgrade to 7
I have upgraded a D6 to D7 site on my localhost. After upgrade I can login using admin credentials as per usual. I have disabled Clean URLs and I see that users are in detabase. Actually all works well however when I try to log in to a user account, I get:

```
The website encountered an unexpected error. Please try again later

```

I get this error also, when I create a user from admin panel. I tested a lot of suggestions but none helped. So appreciate your hints.

# Answer
> 5 votes
To figure out what was the problem, thanks to this post I opened include/error.inc

and replaced

```
print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));

```

with

```
print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.'.$fatal.' '.var_export($error,true))));

```

The new command prints out some useful info that can be used to debug. In my case, it turned out that messaging module caused the problem. I disabled messaging, and could login afterwards.

Note: before going to production, switch back to original error.inc, since the error outputs can be a gift to attackers.

---
Tags: 7, users, upgrading
---


# Question
Title: Cannot trigger CKEditor WYSIWYG in form API
I’m using Drupal 7.18 with CKEditor 4.3 (full package), and trying to get a WYSIWYG field via the form API. My code:

```
function article_edit_form($form, &$form_state, $article)
{
    // ...

    return array(
        // ...
        'content'  => array(
            '#type'    => 'text_format',
            '#title'   => t('Content'),
            '#format'  => 'full_html',
            '#wysiwyg' => true,
            '#input_format' => '1',
            '#value'   => array(
                'value'  => is_null($article) ? '' : $article->content,
                'format' => 'full_html'
            )
        ),
        // ...
    );
}

```

But this only displays a regular `textarea` with a section to choose the “text format”. The CKEditor is installed, enabled and I’m logged as admin.

# Answer
> 0 votes
There are a couple of things that you could try changing:

* `#input_format` and `#wysiwyg` are not in the list of available properties for a text\_format element, so even if they're not causing the error, you should probably remove them.
* You shouldn't set the `#value` of an element like that (unless it's a `value` type itself). Instead you should use `#default_value`. In the case of a text\_format the `#default_value` is expecting the text for the text area (since you've already set the format with `#format`).

I would expect this to work (certainly does for me if memory serves), but if not, check the console for JS errors

```
return array(
    // ...
    'content'  => array(
        '#type'    => 'text_format',
        '#title'   => t('Content'),
        '#format'  => 'full_html',
        '#default_value' => is_null($article) ? '' : $article->content
    ),
    // ...
);

```

---
Tags: forms, wysiwyg
---


# Question
Title: Location field complete values not showing up
while searching for location, the location auto-complete drop down is not showing complete values.

link is http://muslimdistricts.ikonami.com/

# Answer
> 2 votes
It is unclear what you are asking. But having visited the site and clicked like in the example above it looks like the location pop up window has set dimensions and because of this the locations are getting cut off. Look into changing the pop up dimensions or reactions of that box.... Having just looked at it again you need to set the blocks overflow to not hidden. At the moment it is set to hidden so that the autocomplete is hidden when it overflows over the boxes border. To see it in action like the example below inspect the element in your browser and uncheck the overflow:hidden css.

---
Tags: theming
---


# Question
Title: I want to redirect the user to profile page after they log in
I want to redirect the user to profile page after they log in. i tried with some modules but those could not help. i am using D7 version of drupal and tried with login modules

# Answer
> 2 votes
Install and enable the Login Destination module, It have the option to redirect to the specified page.

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

# Answer
> 3 votes
Hope this will help you,

In Drupal 7 you can use **RULES** instead of using any modules only if you looking for redirection.

* Go to `admin/config/workflow/rules/reaction/add` to add new rule
* Now enter the RULE name and select the event on which you want to trigger this **RULE**
* Now its time to give some condition(if required) and to trigger the action.
* In Action select **Page redirect**
* Give the **redirect URL** and and check **Force redirect**
* If the rule is not working means, there may be a other same event with higher weight. Therefore you need to increase you **rules weight**.

---
Tags: 7, users
---


# Question
Title: Sending a JavaScript variable to a PHP function
I am trying to send a value in JavaScript variable to Drupal. I am calling an external js file in `hook_nodeapi()`. I want to send a value from this external js file to Drupal, and want to use this value in Drupal in `hook_block`.
For example

```
hook_nodeapi() {
  // call(external.js)
}
external.js
var sendData =10;

hook_block
{
  case view:
  // need to access sendData value
}

```

I tried this using cookies, but I think that is not the best way. How can this be done?

# Answer
Let's look at what the client can do as an alternative to setting a cookie:

1. Make an AJAX request that lets the server store the variable.
2. Add the variable name and value to the query string of every internal link and to every form submission (not just the next one).

I do not see any benefits of Solution 1, that justifies the extra HTTP request. Especially, you cannot circumvent the necessity for the user to have Cookies enabled, because the value must be stored close to the user and Drupal uses Cookies exclusively to determine the session (and thus the user).

Solution 2 allows for different values within the same session. If this is not one of your requirements, I consider this solution too much of a hassle.
> 1 votes

# Answer
You can check below code to get `base path` value from `js` variable.

```
$settings = drupal_add_js(null, null);

$base_path = $settings['settings']['data'][0]['basePath'];

```

`drupal_add_js()` function will return the `array` of the JavaScript variable. You can trace the `array` in PHP and can get the value of required variable.
> 0 votes

---
Tags: hooks, javascript
---


title: loading a view in popup

text:
# Question
Title: loading a view in popup
hi i'm trying to display a ***view*** in a *popup* but unable to get a solution. i tried

* colorbox node module
* popup views integration module

Is there any better way to display a view as a popup ?

# Answer
> 5 votes
If I need to display a `view` in popup, then I will use ctools module. `Ctools` provide `Modal dialog` functionality to display element in `modal`.

You need to follow below step for the same:

* Create a custom module.
* Create `Menu item` which will interact with `ctools modal`.
* Define `ajax callback` for the menu item and return HTML of the modal using `ajax`.

You can check working example (http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7)

---
Tags: views
---


# Question
Title: Views pager uses wrong URL when using views_embed_view()
I have a custom AJAX app which allows the user to filter some nodes, which uses a View. By custom AJAX app, I mean that this is **not** just a view with AJAX enabled.

The user accesses `/reports` which includes the output of `views_embed_view()`. An AJAX-enabled browser interacts with the page, resulting in an AJAX call to `/reports/ajax` to fetch just the results and save a full page re-load.

It all works, **except** that the results returned by the View in this case use `/reports/ajax` as the base URL for the pager (because that's the path used to invoke the custom AJAX controller), which means that when the user clicks one, they get a page of AJAX response.

I would like to train Views to use a different URL (i.e. `/reports`) for pager requests. Beyond a `str_replace` in the output of `views_embed_view()`, is there another way?

# Answer
Manually set `$_GET['q']` to the appropriate value before calling `views_get_view()`.

Views' pager uses the standard Drupal pager from `includes/pager.inc` which uses this request variable:

```
function theme_pager_link($variables) {
  // (... code omitted here ...)

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

```
> 1 votes

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


# Question
Title: programmatically check if any field in a node is edited
I have a content type blog, it has several fields.If any one of the fields changes I want to call a function. How do I check even if one field has been changed. I tried checking comparing timestamp and revision\_timestamp values available for $node and $node-\>original objects in hook\_node\_presave. But it did not help.
Can someone help me with this?

# Answer
what you could do is add custom validate handler and in there load node

```
$my_node = node_load($form_state['nid']);

```

What this will do is load node with values that are currently in the database. of course you should make sure that above is not invoked if you are adding new node.

Now, you have your 'old' values in `$my_node` and 'about to be saved' values in `$form_state['values']`. Loop through both and compare values.

This is not the most effective way but it should work.

Use `debug()` from devel if you are not familiar with `$form_state['values']`.
> 1 votes

# Answer
See "node\_form\_submit" function in "node.pages.inc" which exists in node module(core). search with this word "@type %title has been updated.". Above this line try your function. I think this is just an option for your need.
> 0 votes

---
Tags: nodes
---


# Question
Title: How can admin create a node on behalf of another user?
Is there any module that allow the administrator user to create content on behalf of another user? Is there any other way to do this?

# Answer
When you create/edit nodes, under *Authoring information*, in the field *Authored by*, you can type any username that exists in your system.
> 2 votes

# Answer
You can use Masquerade module for this purpose. Give the proper permission to the user-type(such as administrator) to use it.

User-type with permission can masquerade as other username and do everything on that user's behalf, including adding node as well.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Views (Search API): Search taxonomy parent and display all children
**Problem**

I have a country taxonomy field. The top level is continents then below that countries:

```
Asia
--China
--Thailand
Europe
--France
--Germany

```
* I'm using search API (with solr backend) to index.
* Views to display the results.
* Views exposed filters to search.

How can I set-up the search, so a search on a parent term (e.g. Asia) displays all it's children (China, Thailand etc.)?

**So Far**

I think the relevant solution if you're not using Search API is described in this page:

Use views to display taxonomy children terms from parent

I think you have to add a contextual filter which sets the rules for taxonomy, however this doesn't seem to be an option in Search API. There are also no contrib modules which solve this problem.

Has anyone tackled this before?

# Answer
> 5 votes
There's a wonderful little checkbox in the Search API workflow tab which enables it.

Head to:

`admin/config/search/search_api/index/*your solr server*/workflow`

(You'll need to have created a server to get to this.)

And then tick the box "Index Hierarchy".

In callback options select the taxonomy field where you would like searching for the parent to include the child.

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


# Question
Title: Give user empty form on form validation error
I'm using braintree.js with a custom form. For those not familiar, braintree.js does client side encryption of the form fields before submission to the server. On my end I get a bunch of gibberish (this is expected). If a form validation error occurs, I want the form displayed again alerting the user of the error but I don't want any of the fields pre-populated because the pre-populated values are now the client side encrypted gibberish. Is there a method of doing this in the \_validate function?

# Answer
I was able to unset the value from within the form validation function. In my case the element is named `foo` and it only validates if it's set to `bar`:

```
function mymodule_myform_validate($form, &$form_state) {
  if ($form_state['input']['foo'] != 'bar') {
    unset($form_state['complete form']['foo']['#value']);
    form_error($form['foo'], 'foo is not equal to bar');
  }
}

```

If the user enters anything but `bar` in `foo`, we set a form error and they presented with the form again without anything in the `foo` field.

I'm not sure how/if the form state array is affected by, for example, the i18n or locale modules, but this should get you started.
> 1 votes

---
Tags: forms
---


# Question
Title: Getting WSOD, can't view any errors even after editing index.php
I've tried entering:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

at the beginning of my index.php file (after begin php tag and it hasn't done anything. When I run cron, it comes back and tells me that everything is ok.

Here's a brief overview of things that have transpired today:

* I updated my views modules and made a database backup (i have no idea how to restore from this, btw)
* I updated to core .24
* I ran cron andfixed errors concerning .htaccess files. I followed this tutorial: https://drupal.org/SA-CORE-2013-003
* I turned off error reporting (cause it's a production server: www.jcoledesign.com is the address)
* All hell broke loose. At first it stopped loading some images, then it stopped loading all CSS, this is likely due to caching
* I added the above code to my index.php file
* I cleared cache, went back and tried to replace my .htdocs files with something more simplistic and still no go.

I'm running out of ideas and nothing I try from here or google seems to work.

Please help and thanks in advance!

# Answer
> 1 votes
I figured it out!

The .htaccess file in sites/defaults/files/ **CAN NOT** include `Deny from all`

The tutorial I referenced earlier mentioned that /temp/.htaccess should have this included, but it didn't say that if you included it in other files that it would crash your site.

*As a side note: It would be great if there was a basic tutorial out there for .htaccess files so that I can get an understanding of everything that's going on here without having to spend months/years learning everything else associated with hosting a drupal website completely inside and out.*

---
Tags: wsod
---


# Question
Title: Different content in same blocks through different contexts
This is probably simple and has likely has already been asked but I can't find it anywhere else on here.

I currently have context, delta, and omega installed. I'm currently using the content block to hold my slider on the home page but it keeps on showing up everywhere throughout the site.

Same for the postscript first and second blocks. I have two different views in there and they keep showing up throughout the site, everywhere those blocks exist.

My question is, is it possible for me to fill those blocks with different content, or should I create my own blocks for the home page instead?

Also, is there a good video tutorial somewhere on using delta and context or just basic page ordering in drupal?

Thanks,

# Answer
> 0 votes
Solved this through using delta. What's not mentioned above is that I was using Omega 3 when I had this problem. I've not used it yet, but I believe Omega 4 handles this differently.

---
Tags: blocks, theming, 7
---


# Question
Title: Is updating the composer.json file & consequently composer.lock in Drupal 8 considered a good practice or hacking the core?
I have been working with another developers on a scaffolding tool for Drupal8 based on Symfony Console component.

The current setup process includes updating composer.json using composer CLI:

COMPOSER\_BIN\_DIR=bin php composer.phar require hechoendrupal/drupal-app-console:dev-master

Maybe writing to core/vendors is not the best practice any suggestions

# Answer
Modifying anything in core is generally not recommended. Unlike other projects that use composer, Drupal already has its composer packages included in core/vendor and you are not supposed to change them, nor the composer.json. Updates to Drupal 8 core would wipe your changes.

There is a module Composer manager that will open a second vendor directory in sites/sitename/vendor (I think). There is some discussion going on in the issue queue, e.g. Is it okay to have duplicates of symfony, guzzle, etc... in sites/all/vendors?. I imagine a future where sites/sitename/vendor could replace core/vendor. But we are not there yet.

I think you should participate in the composer vendor issue queue, this is all work in progress.

EDIT: It should be mentioned that the way Drupal 8 is using Composer is not the way it is recommended. The recommended way is that the *user* should download Drupal and vendor packages via Composer. Instead, it is all pre-packaged. One reason for this is to support shared hosting where you don't have a commandline available, and just want a complete package to upload.
> 1 votes

---
Tags: drush, 8
---


# Question
Title: Change mark-up with a textfield using Ajax
In a form I have a field where the user have to enter the name, after this I have to update a markup with data from an external DB using the textfield as a parameter, How can I do this or even Is this posible?

PD: I am using autocomplete to show a list of users when the user is writing in the field. Thanks.

```
<?php
/*this part is in hook_form_alter*/
$form['submitted']['empleado']['#ajax'] = array(
'callback' => 'ajax_saldo_markup_callback',
'wrapper' => 'saldo-markup-reload',
);
$form['submitted']['saldo']['#prefix'] = '<div id="saldo-markup-reload">';
$form['submitted']['saldo']['#suffix'] = '</div>';
$form['submitted']['saldo']['#markup'] = _busqueda_saldo_vacas($form, $form_state);
/*this part is in hook_form_alter*/

function ajax_saldo_markup_callback($form, $form_state) {
    return $form['submitted']['saldo'];
}

function _busqueda_saldo_vacas(&$form, $form_state){
$username = $form_state['values']['submitted']['empleado'];
/*DB Query's*/

    foreach ($result as $row) { //At the end I get only one data
    $form['submitted']['saldo']['#markup'] = $row->Data;
    }
}
?>

```

With this code It seems to work, with Devel, the property "#markup" changes, but is not displayed, if I change it to "#title", it is displayed.

# Answer
I could make what I was trying to do:

```
<?php
/*this part is in hook_form_alter*/
$form['submitted']['empleado']['#ajax'] = array(
'callback' => 'ajax_saldo_markup_callback',
'wrapper' => 'saldo-markup-reload',
);
$form['submitted']['saldo']['#prefix'] = '<div id="saldo-markup-reload">';
$form['submitted']['saldo']['#suffix'] = '</div>';
$form['submitted']['saldo']['#value'] = _busqueda_saldo_vacas($form, $form_state);
/*this part is in hook_form_alter*/

function ajax_saldo_markup_callback($form, $form_state) {
    return $form['submitted']['saldo'];
}

function _busqueda_saldo_vacas(&$form, $form_state){
$username = $form_state['values']['submitted']['empleado'];
/*DB Query's*/

    foreach ($result as $row) { //At the end I get only one data
    $form['submitted']['saldo']['#markup'] = $row->Data;
    }
}
?>

```
> 0 votes

---
Tags: theming, forms, ajax
---


# Question
Title: Drupal commerce shopping cart pane empty for non-admin users
I have added the shopping cart pane to one of my pages so that it would show up on the review page. This works fine for the admin, but for anonoymous or authenticated users, the shopping cart pane shows up empty for the checkout page and the review page.

Is there a permission somewhere which I need to set? I couldn't find one.

# Answer
You may need to enable the permission for anon at Admin \> People \> Permissions

*"View any product of any type"*

You could try first

*"View any \[type\] product"*

but the former permission may still be required there.
> 1 votes

---
Tags: commerce
---


# Question
Title: How can i limit the drop down list of countries in exposed filter?
I try to use the script https://drupal.org/node/1772498, but I don't get the right db\_query for countries in the nodes. I change the script on these line:

```
$result = db_query("SELECT DISTINCT(l.country) FROM {location} l ORDER BY l.country ASC");

```

and get the error message:

```
Notice: Undefined offset: 1 in DatabaseStatementBase->fetchAllKeyed() (line 2180 of E:\xampp\htdocs\testsite\includes\database\database.inc).

```

It will be great, if somebody can help me!

# Answer
> 1 votes
`fetchAllKeyed` requires a 2-column resultset. You only have 1 column `l.country` in your resultset. I'm infering from your question here ...

* Did you make a views exposed filter ?
* Can you add a relationship to the view on the parent node to filter to the countries set on that node(s)?

# Answer
> 0 votes
I found a nice module collection called views hacks with "Views Selective Exposed Filters". It works very well and limit the list of countries, but now only the short names of countries will be shown.

---
Tags: database, views, location
---


# Question
Title: How do I attach some entity fields (or widgets?) to a form?
I am providing a form to a user to create a product. I want to provide a few fields from a product type, along with some normal Form API input. Example, I only want them to specify the price and SKU. I want the submit handler to take care of creating the title name and any other fields. In this case, a product lives as product entities and as product display nodes. I want to present my user a single form to create and manage products.

I looks like I should be able to do this with the Field API, but I just see how to attached all fields from an entity. I just want to attach a few.

Am I able to do this with the Field API?

EDIT TO ADD MORE INFO:

For example, when a user creates a new product, they will enter a 6 digit SKU. Each product will have that SKU, with another 3 digits appended, specifying a category. I want the user to simply enter the base SKU, like ABCDEF, select category Y and Z, and the submit handler creates the products with the correct SKUs, like ABCDEF-0001, ABCDEF-0002, and creates the node display. There are also specific fields of the product type, so I need the user to populate the fields for these products, using the WYSIWYG filter they would otherwise use on the product create form.

# Answer
I think you can certainly use field\_attach\_form. Take a look at the `$options` argument that is explained in more detail in the \_field\_invoke documentation. For more information you can also have a look at this issue: https://drupal.org/node/1825844

You can include any field of any bundle into any form using this approach:

```
field_attach_form('node', $entity, $form, $form_state, NULL, array(
  'field_name' => 'field_sku',
));

```

When I last used this approach I remember having passed a copy of the original form into field\_attach\_form() in order to prevent my original form from being modified to much. Then I have copied only field element into my original form:

```
$form_tmp = $form;
field_attach_form('node', $entity, $form_tmp, $form_state, NULL, array(
  'field_name' => 'field_sku'
));
$form['field_sku'] = $form_tmp['field_sku'];

```

Just look at the mentioned functions to see what they do. I'm not sure if this last part is needed.

And one more link to explore:
> 10 votes

# Answer
I think you are looking for Inline Entity Form module

> Provides a widget for inline management (**creation, modification, removal**) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.
> 1 votes

---
Tags: 7, entities
---


title: “Create new account” Block in drupal

text:
# Question
Title: “Create new account” Block in drupal
I am working on a Drupal project where I require a "Create new account" form on a content page. Can anybody help me out with this? Is there any module or any alternative to get "Create new account" as a block?

# Answer
> 4 votes
Use this module http://drupal.org/project/formblock

Download and install the module. Navigate to admin/structure/block You can see Registration form as a block and choose the region to appear.

User Registration to appear in a block taken from this source.

# Answer
> 3 votes
You can can create block programmatically. And create your own callback function where you can call drupal\_get\_form and render `user_register_form`.

For example your callback function will look like this: Basic example

```
/**
 * Implements hook_block_info().
 */
function yourmodule_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );

  return $blocks;
}
function hook_block_view($delta = '') {
    switch ($delta) {
    case 'my_block':
          $block['subject'] = t('Register form');
          $block['content'] = yourmodule_block_register_callback();
     }
}

function yourmodule_block_register_callback() {
   $reg_form = drupal_get_form('user_register_form');
   $output = drupal_render($reg_form);
   return $output;
}

```

If you are not familiar with the creation of custom modules - read this.

# Answer
> 2 votes
https://drupal.stackexchange.com/a/21553/23871

Create a new block, copy/paste this code in the body:

```
<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

```

Make sure the block is set to **PHP filter**

---
Tags: 7, blocks, users
---