# Question
Title: Nginx vs Apache - Are there any actual usage comparisons and statistcs out there?
I have a new server to play with, and I am staring at a blank canvas. I can put anything I want on it. While I am comfortable with Apache, I keep hearing how nginx can handle so much more traffic than Apache, by factors of 10, 100, even more. Not only that it's "much much faster."

When I search for articles I can find lots of stuff unrelated to Drupal. Or, when I do come across a Drupal related article it's either 1) someone's configuration file with a quick attempt at explaining how to set it up, or 2) it's someone saying "no, don't use nginx, go with Apache with PHP fcgid" but there is never explanation as of why.

So, when it comes to Drupal, what is the reality here?

As an example, I am looking for something along the lines this 2bits.com article. Here the author has taken a pretty extensive look at Apache mod\_php vs Apache with fcgid, weighing the pros and cons of each, and provided a case study to illustrate the impact in the real world. There is enough information in this article for me to make an educated decision as to which approach would be best for my situation.

While that author compares mod\_php to fcgid, I am looking for the same type of comprehensive, real world look at Apache vs Nginx.

Anyone switched to Nginx and been "blown away" by the difference it made compared to Apache? Even for highly optimized environments that are already using APC, Memcache, and aggressive caching like Varnish, when the only variable that changes is replacing Apache with Nginx, does make enough of a difference in and of itself to merit investing in this newer, alternative technology?

The site that will go on this server gets an avg of 2 million PV a month. LAMP stack running Cent OS 6. 4 core CPU with 8 GIGS of ram. Memcached and APC will be part of the mix. Nothing special about the Drupal install - basically vanilla 7 with about 50 modules.

# Answer
> 62 votes
Strictly speaking, this doesn't answer the question you are asking. I'm hoping it's helpful anyway.

Apache/Nginx/Lighttpd/other web server. Does it matter which one I choose? In short, **No**.

**The much much longer answer:**

*If*, and only *if*, you have a very large percentage of your users being logged in, should you care at all about the performance of your web server. If your users are anonymous, any difference that you can theoretically derive from optimizing at that layers absolute pales compared to making your resources better cacheable. If your css files have proper cache headers on them, the UA won't even ask for them the second time. That matters. If you can cache your pages in Varnish or a similar software solution, then serving that page is a matter of making a hash-lookup, and then returning a large chunk of data directly from RAM. That matters. In both of these scenarios, the HTTP daemon is never even involved, PHP does not get invoked. Drupal does not bootstrap. No large set of modules must be loaded into RAM, no time consuming database queries are executed.

When you perform a full page load, from a cold cache, for a logged in user, on a complex page; *a lot* of things are going on. Yes, the web server is involved in dealing with the incoming request, setting some headers and passing the response back. But the time that takes, is not even relevant in the context of Drupal running a full bootstrap and outputting its response. There could be hundreds of database queries being executed. Highly complex logic in PHP is evaluated by the parser. Lots of modules are being loaded into RAM. Improving the performance of any of those things, are much more likely to make a serious contribution to performance.

For the sake of argument: Let's say you have spent a lot of time performance optimizing everything else.

1. You run APC (Or Optimizer+) and the latest and fastest version of PHP.
2. DB-queries are few.
3. PHP logic has been reduced.
4. You cache what you can in Varnish.
5. You have re-structured your entire site so that you can cache a lot client side, and do lots of heavy lifting in ECMAScript.

If you have a lot of logged in users, and you've dealt with all of the above, then you can probably make a difference but performance tuning, or replacing your web server. However, guess what. Your site is so complex, and the usage patterns of your particular users, is *unique*. There is no generic answer. You will need to setup all different web servers behind a load balancer, and see how they behave, under *your scenario*.

The above was an attempt at logically reaching the conclusion that spending time performance optimizing the web server is likely a bad use of time. I would love to have someone pick holes in the above though, I would probably learn something new from it. :)

Some other notes:

1. During the DrupalCon Copenhagen keynote, PHP creator Rasmus Lerdorf, using Nginx himself, speaking on the topic of Drupal performance, said "People always ask me about web servers ... it really doesn't matter, the web server is pretty much irrelevant". (Roughly at 26:30 in the video)
2. Facebook has spent countless hours on writing Hiphop, a code base significantly larger than Drupal itself, for accelerating PHP-code by a "measly" 100%. I examined Hiphop with `$ wc -l $(find . -type f | grep -v "^\.git" | grep -v "^\.hphp/third_party") | sort -nr | head -n1` and found it to consist of 1.512.481 lines of code. That's an absolutely insane amount of work put in to improving the speed of PHP. I'm guessing that's because the speed of PHP matters greatly to them.
3. Did I mention that good caching is going to have a much greater effect that tuning the web server?
4. With the release of Apache 2.4, Jim Jagielski basically claims that Apache 2.4 is faster than event based servers.
5. I attented Drupal Performance and Scalability with The Dream Team, where just this question came up. All the answers about which to choose, was unrelated to performance. Things like "Which one do you already know how to configure", and "Which one will allow you to build the simplest technology stack", were among the reasons mentioned to pick on over the other. Performance did *not* enter the picture.

# Answer
> 33 votes
OK, although this question is already answered, I'm necromancing once more, primarily because I don't like the implications of these answers that it doesn't make a difference, and because as a web developer, I hate caching with a passion.

The difference between Apache and nginx is not that much "how fast they can serve a request" but how many requests they can serve on the same amount of hardware (especially with limited ressources), which is a somewhat different thing.

Apache is a process-based server. Meaning it forks a process for every request. Nginx is a event based server, meaning is uses an (asynchronous) event-loop instead of processes or threads.

And while a process-based server (like Apache) *can* perform more or less on par with an asynchronous event-based server (like nginx) under light loads, under heavier loads like for example 10'0000 simultaneous requests, nginx uses only a few megabytes of RAM, whereas Apache requires several hundred megabytes for the web server alone (not including the web application, which needs far more ressources itselfs), if it could do it at all.

So under heavier loads, you will see Apache consume far too much RAM, which unsurprisingly degrades performance significantly.

More significantly, a higher RAM consumption means that Apache is being able to serve less requests on the same hardware than nginx, which means Apache requires more hardware for the same amount of users, which means you have a higher TCO (total cost of ownership) with Apache than with nginx, which reduces your ROI (return on investment).

Total memory used by X concurrent connections (less is better)

Requests that can be served per second at X concurrent connections on 1 set of hardware (more is better)

Source: ApacheBench, by dreamhost.com

See also this digital ocean writup.
Apparently, it depends on the Connection Handling Architecture you choose for Apache.

# Answer
> 16 votes
I switch from Apache to Nginx / PHP-FPM a few month ago.

I made some benchmarck with a drupal website, and test several use case. On a VPS server with 1 CPU and 512 Mo RAM

**Drupal with only cache**

**Nginx**

```
ab -n 100 -c 30 xxx
Server Software:        nginx
Document Path:          /
Document Length:        24902 bytes

Concurrency Level:      30
Time taken for tests:   2.775 seconds
Complete requests:      100
Failed requests:        0
Write errors:           0
Total transferred:      2529500 bytes
HTML transferred:       2490200 bytes
Requests per second:    36.04 [#/sec] (mean)
Time per request:       832.394 [ms] (mean)
Time per request:       27.746 [ms] (mean, across all concurrent requests)
Transfer rate:          890.28 [Kbytes/sec] received

httperf --client=0/1 --server=xxx --port=80 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=100 --num-calls=10
Maximum connect burst length: 1

Total: connections 100 requests 1000 replies 1000 test-duration 48.946 s

Connection rate: 2.0 conn/s (489.5 ms/conn, <=1 concurrent connections)
Connection time [ms]: min 470.6 avg 489.5 max 522.2 median 488.5 stddev 9.5
Connection time [ms]: connect 0.2
Connection length [replies/conn]: 10.000

Request rate: 20.4 req/s (48.9 ms/req)
Request size [B]: 74.0

Reply rate [replies/s]: min 20.0 avg 20.4 max 20.8 stddev 0.2 (9 samples)
Reply time [ms]: response 46.8 transfer 2.1
Reply size [B]: header 450.0 content 24902.0 footer 2.0 (total 25354.0)
Reply status: 1xx=0 2xx=1000 3xx=0 4xx=0 5xx=0

CPU time [s]: user 6.50 system 17.58 (user 13.3% system 35.9% total 49.2%)
Net I/O: 507.3 KB/s (4.2*10^6 bps)

```

**Apache**

```
ab -n 100 -c 30 xxx
Server Software:        Apache/2.2.16
Document Path:          /
Document Length:        24902 bytes

Concurrency Level:      30
Time taken for tests:   28.364 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      25346000 bytes
HTML transferred:       24902000 bytes
Requests per second:    35.26 [#/sec] (mean)
Time per request:       850.918 [ms] (mean)
Time per request:       28.364 [ms] (mean, across all concurrent requests)
Transfer rate:          872.66 [Kbytes/sec] received

httperf --client=0/1 --server=xxx --port=80 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=100 --num-calls=10
Maximum connect burst length: 1

Total: connections 100 requests 1000 replies 1000 test-duration 52.261 s

Connection rate: 1.9 conn/s (522.6 ms/conn, <=1 concurrent connections)
Connection time [ms]: min 499.0 avg 522.6 max 591.0 median 518.5 stddev 19.4
Connection time [ms]: connect 0.6
Connection length [replies/conn]: 10.000

Request rate: 19.1 req/s (52.3 ms/req)
Request size [B]: 74.0

Reply rate [replies/s]: min 18.2 avg 19.2 max 19.6 stddev 0.5 (10 samples)
Reply time [ms]: response 46.9 transfer 5.3
Reply size [B]: header 453.0 content 24902.0 footer 2.0 (total 25357.0)
Reply status: 1xx=0 2xx=1000 3xx=0 4xx=0 5xx=0

CPU time [s]: user 6.80 system 18.88 (user 13.0% system 36.1% total 49.1%)
Net I/O: 475.2 KB/s (3.9*10^6 bps)

Errors: total 0 client-timo 0 socket-timo 0 connrefused 0 connreset 0
Errors: fd-unavail 0 addrunavail 0 ftab-full 0 other 0

```

**Drupal with cache and boost**

**Nginx**

```
ab -n 10000 -c 30 xxx
Server Software:        nginx
Document Path:          /
Document Length:        25002 bytes

Concurrency Level:      30
Time taken for tests:   2.275 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      253780000 bytes
HTML transferred:       250020000 bytes
Requests per second:    4395.52 [#/sec] (mean)
Time per request:       6.825 [ms] (mean)
Time per request:       0.228 [ms] (mean, across all concurrent requests)
Transfer rate:          108934.95 [Kbytes/sec] received

httperf --client=0/1 --server=xxx --port=80 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=1000 --num-calls=30
Maximum connect burst length: 1

Total: connections 1000 requests 30000 replies 30000 test-duration 5.971 s

Connection rate: 167.5 conn/s (6.0 ms/conn, <=1 concurrent connections)
Connection time [ms]: min 4.2 avg 6.0 max 13.0 median 4.5 stddev 2.6
Connection time [ms]: connect 0.1
Connection length [replies/conn]: 30.000

Request rate: 5024.0 req/s (0.2 ms/req)
Request size [B]: 74.0

Reply rate [replies/s]: min 5017.2 avg 5017.2 max 5017.2 stddev 0.0 (1 samples)
Reply time [ms]: response 0.2 transfer 0.0
Reply size [B]: header 405.0 content 25002.0 footer 0.0 (total 25407.0)
Reply status: 1xx=0 2xx=30000 3xx=0 4xx=0 5xx=0

CPU time [s]: user 0.79 system 2.56 (user 13.2% system 42.9% total 56.1%)
Net I/O: 125016.7 KB/s (1024.1*10^6 bps)

Errors: total 0 client-timo 0 socket-timo 0 connrefused 0 connreset 0
Errors: fd-unavail 0 addrunavail 0 ftab-full 0 other 0

```

**Apache**

```
ab -n 1000 -c 30 xxxx
Server Software:        Apache/2.2.16
Document Path:          /
Document Length:        25002 bytes

Concurrency Level:      30
Time taken for tests:   0.753 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      25291000 bytes
HTML transferred:       25002000 bytes
Requests per second:    1327.92 [#/sec] (mean)
Time per request:       22.592 [ms] (mean)
Time per request:       0.753 [ms] (mean, across all concurrent requests)
Transfer rate:          32797.26 [Kbytes/sec] received

httperf --client=0/1 --server=xxx --port=80 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=100 --num-calls=10
Maximum connect burst length: 1

Total: connections 100 requests 1000 replies 1000 test-duration 1.148 s

Connection rate: 87.1 conn/s (11.5 ms/conn, <=1 concurrent connections)
Connection time [ms]: min 6.2 avg 11.5 max 14.1 median 11.5 stddev 1.3
Connection time [ms]: connect 0.1
Connection length [replies/conn]: 10.000

Request rate: 870.8 req/s (1.1 ms/req)
Request size [B]: 74.0

Reply rate [replies/s]: min 0.0 avg 0.0 max 0.0 stddev 0.0 (0 samples)
Reply time [ms]: response 1.1 transfer 0.1
Reply size [B]: header 260.0 content 25002.0 footer 0.0 (total 25262.0)
Reply status: 1xx=0 2xx=1000 3xx=0 4xx=0 5xx=0

CPU time [s]: user 0.13 system 0.57 (user 11.1% system 49.5% total 60.6%)
Net I/O: 21544.9 KB/s (176.5*10^6 bps)

Errors: total 0 client-timo 0 socket-timo 0 connrefused 0 connreset 0
Errors: fd-unavail 0 addrunavail 0 ftab-full 0 other 0

```

**benchmark for Authenticated user (page load)**

**Nginx**

```
Page load times : 2.85 s

```

**Apache**

```
Page load times : 5.4 s

```

But the power of Nginx is the cache system

**Drupal *without* Boost and Nginx with cache system enabled**

```
Server Software:        nginx
Document Path:          /
Document Length:        24902 bytes

Concurrency Level:      30
Time taken for tests:   2.437 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      252670000 bytes
HTML transferred:       249020000 bytes
Requests per second:    4103.34 [#/sec] (mean)
Time per request:       7.311 [ms] (mean)
Time per request:       0.244 [ms] (mean, across all concurrent requests)
Transfer rate:          101248.99 [Kbytes/sec] received

httperf --client=0/1 --server=xxx --port=80 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=1000 --num-calls=30
Maximum connect burst length: 1

Total: connections 1000 requests 30000 replies 30000 test-duration 6.044 s

Connection rate: 165.5 conn/s (6.0 ms/conn, <=1 concurrent connections)
Connection time [ms]: min 4.2 avg 6.0 max 11.7 median 4.5 stddev 2.6
Connection time [ms]: connect 0.1
Connection length [replies/conn]: 30.000

Request rate: 4963.7 req/s (0.2 ms/req)
Request size [B]: 74.0

Reply rate [replies/s]: min 4970.1 avg 4970.1 max 4970.1 stddev 0.0 (1 samples)
Reply time [ms]: response 0.2 transfer 0.0
Reply size [B]: header 405.0 content 25002.0 footer 0.0 (total 25407.0)
Reply status: 1xx=0 2xx=30000 3xx=0 4xx=0 5xx=0

CPU time [s]: user 0.72 system 2.68 (user 12.0% system 44.3% total 56.3%)
Net I/O: 123516.8 KB/s (1011.8*10^6 bps)

Errors: total 0 client-timo 0 socket-timo 0 connrefused 0 connreset 0
Errors: fd-unavail 0 addrunavail 0 ftab-full 0 other 0

```

You should use the perusio's configuration Nginx for Drupal

# Answer
> 0 votes
Here is a performance test for ten webservers/varients (e.g. Apache, Nginx, lighttpd, Lightspeed, Hiawatha, Cherokee). Three of the tests relate to Drupal.

I'm thinking Hiawatha may be the best overall choice. Supposed to have full Drupal compatibility, has an emphasis on security (DoS, XSS, CSRF, SQL-injection prevention), and speeds & footprint similar to Nginx.

In two of the three Drupal tests, both Hiawatha and Nginx outperform Apache by about 150%, but in the Drupal static test, Apache marginally outperforms Nginx, while Hiawatha bests the pack by about 10%.

I wouldn't hang my hat on any of these tests, but it does give one a ballpark view of performance in different usage situations. I think performance alone shouldn't be the only consideration. Stability and security may be the more important factors.

# Answer
> 0 votes
here is a **load testing** results for drupal running on same hardware but with different web servers. (nginx and apache)

here is the conclusion of this test:

> under a large traffic with same hardware resources, nginx performs way better than apache.

---
Tags: performance
---


title: How can I remove the site logo?

text:
# Question
Title: How can I remove the site logo?
I want to remove the logo from my site.

I found some instructions on Disabling the Drupal logo in your Drupal 8 theme. My problem is that the instructions say to unselect *Logo* in the toggle section of the theme settings page. I only get four options: *User pictures in posts*, *User pictures in comments*, *User verification status in comments*, and *Shortcut icon*.

I've checked in two sites. One has the vanilla Bartik theme, and the other has a subtheme of Bartik with no changes other than CSS.

How can I remove the logo?

# Answer
> 4 votes
Uncheck the *Use the default logo supplied by the theme* option you find under the *Logo image settings* section. Don't forget to clear the cache.

---
Tags: 8
---


# Question
Title: Sessions / Cookies not working for user login, registration or shopping cart
# The Problem

One of our sites has recently broken. Users can't login or register, and the shopping cart isn't working either.

Drupal does not display any errors. Upon clicking the submit button for the forms, it simply refreshes the page as if nothing had happened.

It's just as if sessions have stopped working altogether, which is a little strange, no?

The rest of the site works perfectly well.

No Drupal updates have been performed and no new modules have been installed.

I've been reassured that this isn't a server problem, but I'm still (really) not sure about that. Since I don't have **SSH** access to the server, I'd like to be sure beforehand.

I'm just looking for possible causes/fixes, and if anyone has had experience with this before, great. Ultimately I will end up checking out the server, but is there any chance it could be caused by Drupal?

# Things I've Tried:

I've checked */sites/default/settings.php* for the **$base\_url** and **$cookiedomain** variables, but they are set properly.

This is not a .htaccess problem, either. Regardless of whether I use clean urls or not (site/user or site/index.php?q=/user) it just doesn't work at all.

# Answer
> 3 votes
This is a very old question, but I stumbled on it while having the same issue.

In my case, the "rewrite" Apache module was turned off. I re-enabled it with:

```
a2enmod rewrite

```

I could access /user, but could not login (it would loop back, with no error message). I assumed that since I could access /user, my rewrites and htaccess were OK. I could login with "drush uli", but no form would work. Even weirder: in some pages that had query parameters (GET, ex: foo?test=1), the GET parameters would not be passed to PHP. I was searching all over the place, and the solution was pretty trivial :)

---
Tags: 7, sessions, cookies
---


# Question
Title: How to show a random image from unlimited image field using Views?
There is an content type called "imagenode". This content type contains title, body and one image field (unlimited images can be uploaded/attached).

Now exactly one node from imagenode is created: 20 Images are attached/uploaded.

Question: How can I create a views block that displays one random image out of these images attached to this one node from type imagenode?

I can create a view with fields and show one image and I can set an offset in order to display onother image. But there seems to be no way to display one random from all attached images.

How can this be solved in Drupal 8?

# Answer
> 3 votes
1) Click on your image field

* Under Multiple Fields Settings, **uncheck** display all values in the same row.

2) Add `Global: Random` as your sort and remove the default sort (content post date).

---
Tags: views, 8
---


# Question
Title: I need a advanced search block (by using views) on home page of site
I'm beginner in drupal. I'm developing a site contains products that are displayed some product blocks by using views module on front page like **featured products** and **top rated products**. Now, I also need to add a **advanced search block** (*by using views module*) on front page like I've attached **image** below. This search will only search from the one type of content named *product* and show another page.

How to add input field name titled, dropdown list, radio buttons and Search button while creating views block?

# Answer
> 0 votes
For Drupal 7 you can create mentioned output via setting Filters and set the option "Expose this filter to the user"

Moreover, you can add checkbox using BEF(Better Exposed Filters).

I hope this helps. :)

---
Tags: views
---


# Question
Title: Show Taxonomy Terms belonging to search_api search result nodes
Using search\_api (and search\_api\_solr) i have a view that shows nodes for (in this case) Organisations in a search\_view. That works very nicely.

Now, I would like to show a list of taxonomy terms that are associated with the nodes in the result set. These terms should be in a list of their own, and I need to be able to access the fields on these terms. (In this case, Districts is the Vocabulary, and each organisation can be active in 1 or more Districts. I need to get to the Geofield on these Districts so I can create an Openlayers map).

When I add a Relationship to the search\_view to the District field, I see the message

"Note: This is a multi-valued relationship, which is currently not supported. Only the first related entity will be shown."

So, that is not the way (yet).

I am stuck thinking about a workaround for this. Any pointer would be much appreciated.

# Answer
This may have drawbacks but I had a situation where i wanted to show the multiple tags that related to content that i had indexed.

Having looked through https://www.drupal.org/node/1378656 i opted to try by using https://www.drupal.org/project/views\_field\_view

Happy to report it worked

Here is the recipe:

* create a new View based on Content for types involved and set just the relevant 'term' field as the display (you don't need to create any views displays).
* set Contextual filter to nid with 'provided default value = raw value from url' (outcome should be if you enter the nid you should see relevant tags in preview). Save
* install/enable https://www.drupal.org/project/views\_field\_view
* over in the view that is rendering the search results (searchapi)
* made sure you have Indexed Content: Node ID field already in your Fields, and set to not display
* add a new field of type Global: View
* in the 'view settings' of this field, find the view you made above, set the right display or use Master if you didn't make any (because you didn't need to),
* in Contextual Filter, check your Replacement Patterns where you should have \[%nid\] == Indexed Content: Node ID (rendered), and enter \[%nid\]
* save and I hope you get to smile like i just did.
> 0 votes

---
Tags: views, search
---


title: Import excel in field collection items

text:
# Question
Title: Import excel in field collection items
I m using field collection items in my content type for particular upload function.

I want to use import excel feature to bulk upload with field collection item fields.

**when i click on import excel upload button the field collection fields filled with excel data.**

Can anyone help me, how to achieve this feature.

Thanks in advance.

# Answer
> 1 votes
Have you checked the **field collection feeds module**? It does exactly what you are looking for.

> Provides feeds integration for field collection module. Require Feeds alpha7 or later version.

# Answer
> 0 votes
It takes few minutes to get things right. The detailed setup manual is available here. Be patient and sef things up well.

I just used it 3 days ago.

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

---
Tags: importing-exporting, entities
---


# Question
Title: field_collection_item not updating / old data preserved
I am using SalesForce suite to pull data from SalesForce to Drupal.

In the SalesForce object I have multiple date fields. These fields needs to map to a field-collection in the node. The field-collection can have multiple (unlimited) values.

So for example in the SalesForce object I have

`sales_force_object -> start_date
sales_force_object -> event_date
sales_force_object -> end_date`

which needs to map to

`node -> the_dates [0] = sales_force_object -> start_date
node -> the_dates [1] = sales_force_object -> event_date
node -> the_dates [2] = sales_force_object -> end_date`

The solution was to add 'temporary' fields on the node, let's call them:

`node -> sync_start_date
node -> sync_event_date
node -> sync_end_date`

When I get data from SalesForce (using pull; and yes the data comes through OK) - I map the values from the SalesForce object to the sync fields. Then just before the node is saved (updated), I use `hook_node_presave` to take values from the sync fields and create the field-collection items. This is the code:

```
  $fc = field_collection_item_load($key_dates_entity_id);
  $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc);
  $fc_wrapper->field_date->set((int) $date);
  $fc_wrapper->save();
  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

```

You can safely assume that `$key_dates_entity_id` is the correct field-collection entity ID.

Inspecting the code I can see the entity is correctly updated (nothing wrong with the data), and when I check the MySQL general-log, I can see the data being saved to the database, **however**, when the set of instructions end, the old (cached) data is also saved. In other words the DB is updated twice - once with the new value, and once with the old values: net result is field collection items are not updated.

I have tried all sorts of combinations - nothing works. Any help please.

# Answer
I would love to tell you why, but I have not been able to figure it out: I just know it works.

Initially I executed the code above in `hook_node_presave($node)`, but obviously it did not work. So I figured I should try `hook_node_update($node)` \- but that did not work either.

Then I discovered `drupal_register_shutdown_function` and now my `hook_node_update` looks like this:

```
function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    drupal_register_shutdown_function('_update_from_sync_fields', $node);
  }
}

```

`node_type` is the type of node I am checking against. Any case, once the node is actually saved - that is all processing is done, db transactions completed, etc - drupal will call my shutdown function. Now when I update the field values, and in specific field-collection fields - they are saved.

Of-course saving these fields and calling:

```
  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

```

at the end of my shut-down function triggers hook\_node\_update again, but fortunately I have a token that tells me - so I do not execute the code again.

This solution works - what I am not happy about is the fact that it executes when Drupal is shutting down.

I think the problem is related to the fact that node\_save starts a DB transaction, and when I update related entity (field-collection) items in `hook_node_save` or `hook_node_presave` I am starting another (nested) transaction. Clearly my transaction updating field-collection items completes, but when the outer (first) transaction then complete, it is writing old/dirty data.

The trick is going to be to clear the dirty data from cache. I was hoping `entity_get_controller('node')->resetCache([$node->nid]);` would do that - but clearly it does not?

So next I changed the `hook_node_update` to :

```
function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    _update_from_sync_fields ($node);
  }
}

```

in other words - from `hook_node_update` I simply call the 'shut-down`function, then I rebuilt the drupal registry (`drush rr\`) and voila - it worked. Now I am even more confused. It is possible that my original code worked all along, but there was something wrong with the registry (or caches). All things being equal, all the examples I read was right.

From hook\_node\_update, load the field collection entity, update and save the entity. The clear the caches and do a `field_attached_presave` and `field_attached_update` like so:

```
  entity_get_controller('node')->resetCache([$node->nid]);
  field_attach_presave('node', $node);
  field_attach_update('node', $node);

```
> 0 votes

---
Tags: 7, entities, crm
---


# Question
Title: How to remove malicious scripts from admin pages after being hacked?
The site running Drupal 7 was hacked and every administration page, e.g.

http://www.anysite.com/en/admin/dashboard

contains script tag in head section with malicious src attribute, e.g.

```
<head>
    ...
    <script src="..."></script>
</head>

```

Those three dots in the src attribute was only for example same as the three dots line above :) In real code there is link to malicious web `gymweb.it`.

How can I remove this script tag? How the head section of admin pages is constructed?

# Answer
> 2 votes
If you're using **Seven** as your admin theme (which is the out of the box default) then the script *may* have been added in a template file inside `/core/themes/seven`

I think the easy approach would be to pretend you're upgrading Drupal 7 and delete all the files and folders with the exception of the `sites` folder.

After you "upgraded" your Drupal, if the problem still persists, then it means it *may* be somewhere in your `sites` folder.

Go to /sites/all/themes/yourtheme/templates and Check all template files **.tpl.php** to see if any evil code was added to them.

Also, check your /sites/all/themes/**template.php** file to see if some evil code was added there, you should only see theme functions and regular Drupal code here.

Keep a lookout for any strange.php file names.

In addition, you can check if some module was added or altered using the Hacked! module.

If still no resolution, then most likely the script is in your Database. Due to you allowing FULL HTML or PHP in your text boxes or your DB was hacked.

# Answer
> 4 votes
If you suspect that your code has been altered, you should track any malicious code which could infect your webroot.

If you've access to the server terminal, try the following suggestions, otherwise sync the files into your local machine in order to run below commands.

Here are few general solution to get rid of the attacker:

1. Use some tools to scan for malicious PHP files (e.g. `php-malware-finder`, `php-malware-scanner`, `phpscanner`).
2. Look for your webroot for any suspicious files consisting `base64_decode`/`eval` which most commonly are used for obfuscation, e.g.

```
grep -R return.*base64_decode  .

```

If you found one, probably you've multiple of them. If so, please check: How to get rid of eval-base64\_decode like PHP virus files thread for further suggestions.
3. If you know some specific pattern of the malware appearing in your source code (which you do), try scanning your code base for this name, e.g.

```
grep -R gymweb .

```

And depending on where these URLs were added, remove extra code or restore to the original version (either from VCS history or your recent backup before the infection).

If above won't help, try these suggestions which are more Drupal oriented:

* When using code under version control (like Git), find the files which are not suppose to be there (`git status`) and remove them (`git clean -f .`).
* Upgrade your Drupal core, to replace any modified files (`drush up drupal`).
* Upgrade contrib modules using drush (`drush upc --no-core`).
* Also scan your entire database for this name:

```
drush sql-dump --ordered-dump | grep gymweb

```
* If this still won't help, compare the code base from the backup before the infection with the current one (either by `diff -r`, using some diff GUI tool or use Git).

Check also:

# Answer
> 2 votes
Quickest way is to re-download drupal, extract it over your drupal directory and overwrite all files. And clear all cache/restart memcached/varnish then check if the script is being included still. If it is, then you probably need to look overwrite all your contrib modules, and lastly check your custom modules/themes. It's most probably an `eval(base64_decode())` call on an encoded bit of PHP code somewhere in your drupal includes. It'll be difficult to find manually.

---
Tags: 7, security
---


title: how to define ECK form url

text:
# Question
Title: how to define ECK form url
I am using ECK I create one form through entity-\>bundle-\>feedbackform-\>managedfield my form is created, but how to get form path, current path is of my feedback form is:- admin/structure/entity-type/feedbackform/feedbackform/add but this path is not for anonymous user. i want to show my form to anonymous user with some simple path

# Answer
> 4 votes
Assuming you have a module called `'helloworld'`, and entity type called `'vechile'` and a bundle called `'car'`.Here is some code that should do the trick.

```
/**
 * Implements hook_menu().
 */
function helloworld_menu(){
$items['feedbackform'] = array(
'page callback' => 'example_my_eck_form_page',
'access arguments' => array('Access feedback form'),// permission
'type' => MENU_CALLBACK,
);
return $items;
}

function example_my_eck_form_page(){
   module_load_include('inc', 'eck', 'eck.entity');
   $bundle_name='car';
   return eck__entity__add('vechile', $bundle_name);
}

function helloworld_permission() {
   return array(
    'Access feedback form' => array(
      'title' => t('Access feedback form'),
    )
  );
}

```

Access feedback form is a custom permission so you still would have to give that permission to the users from admin to be able to access the path.

# Answer
> 0 votes
I haven't tried this with ECK, but I believe that the behaviour should be the same as with any other form. You would simply need to:

* Register a menu callback in a custom module for the "simple path", accessible to anonymous user role (see `hook_menu()`)
* The `'page callback'` can either be
    + a custom function `'example_my_eck_form_page'`, where you `return drupal_get_form('eck_name_of_your_form');`
    + or `'drupal_get_form'` and pass the form name in `'page arguments'` array.

# Answer
> 0 votes
There is a module for that: https://www.drupal.org/project/eck\_pm

Alternatively you could use `hook_entity_info_alter` like so:

```
function MYMODULE_entity_info_alter(&$info) {
  if (isset($info['ENTITY']['bundles']['BUNDLE'])) {
    $info['ENTITY']['bundles']['BUNDLE']['crud']['add']['path'] = 'my/public/path';
  }
}

```

---
Tags: hooks, uri, entities
---


# Question
Title: Admin menu bar covers part of the screen while working in mobile mode
I think that the image I attached says it all - a part of the screen is covered by admin menu in mobile view from my pc (this is the default firefox mobile view).

It's extremely problematic when I need to check something that is at the fold of the page, i.e at the top part of the page beacuse it also being covered and I have no where to scroll-up to, and must logout to view it or check through another browser and this can be tiresome sometimes.

# Answer
There is no configuration settings at `admin/config/administration/admin_menu` for hiding the `admin_menu` at the mobile screen, hence you can do 2 things:

1. Either inspect you site in `incognito` mode of Chrome or `private browsing` in Firefox
2. Permanent solution would be applying `CSS` for this

`@media screen and (max-width: 640px) {
 #admin-menu {
 display: none;
 }
}`
> 2 votes

# Answer
You could also choose to change your backend to a responsive backend. I had good results with the adminimal theme and it's companion adminimal admin menu module. This resulted in a slick responsive backend on mobile devices.
> 2 votes

# Answer
You could add a Media query to your CSS that hides the menu \< a certain width.

Or, you could just pop open a new private window in FF which would get around having to log out.
> 0 votes

---
Tags: theming
---


# Question
Title: want to load the multiple select box field data as per selected category using ajax form alter?
I have list of select box like Team and Player with category option on top of the form. if i select the cricket in that category it should load players and Teams node title based on the category selected using ajax, i have done the ajax code but its working for only one field, please can onyone help to solve this

here is my complete code

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

  switch ($form_id) {
   case "loadtest_node_form":  // If the current edited page is an article form
    /*
    * The wrapper location is the entity reference field that contains the node titles
    * because that's where nodes listed needs to be restricted based on selection
    */
    $form['field_loadtest_player']['#prefix']='<div id="jicustom_test_entity_wrapper">';
    $form['field_loadtest_player']['#suffix']='</div>';
  $form['field_loadtest_team']['#prefix']='<div id="jicustom_test_entity_wrapper1">';
    $form['field_loadtest_team']['#suffix']='</div>';

 $form['field_loadtest_category'][LANGUAGE_NONE]['#ajax'] = array( // adding an ajax attribute
      'callback' => 'jicustom_test_entity_callback1',
      'wrapper' =>'jicustom_test_entity_wrapper1',
      'method' => 'replace',  // the data would replace the field
      'effect' => 'fade',
      'event' => 'change',  // On change of the selection this action would take place
    );
$form['field_loadtest_category'][LANGUAGE_NONE]['#ajax'] = array( // adding an ajax attribute
      'callback' => 'jicustom_test_entity_callback',
      'wrapper' =>'jicustom_test_entity_wrapper',
      'method' => 'replace',  // the data would replace the field
      'effect' => 'fade',
      'event' => 'change',  // On change of the selection this action would take place
    );

// dpm($form);
    // Only when values are set in field_article_test_entity_type, should the options change
    // Also works for nodes that already have entity type selected
    if(!empty($form_state['values']['field_loadtest_player'])){
      $content_type = $form_state['values']['field_loadtest_category']['und']['0']['tid'];
      $form['field_loadtest_player']['und']['#options'] = jicustom_get_nodes($content_type);
    }
    if(!empty($form_state['values']['field_loadtest_team'])){
      $content_type = $form_state['values']['field_loadtest_category']['und']['0']['tid'];
      $form['field_loadtest_team']['und']['#options'] = jicustom_get_team($content_type);
    }
    break;
  }
}

/*
* Get List of node titles based on the content type
*/
function jicustom_get_nodes($content_type){

$result = db_query("SELECT n.title, n.nid
FROM node n
INNER JOIN field_data_field_category  ft ON n.nid = ft.entity_id
WHERE ft.field_category_tid = $content_type AND n.type='player'
ORDER by n.title ASC");
  foreach ($result as $record) {
    $nodes[$record->nid]=$record->title;
  }
  return $nodes;
}
function jicustom_get_team($content_type){

$result = db_query("SELECT n.title, n.nid
FROM node n
INNER JOIN field_data_field_category  ft ON n.nid = ft.entity_id
WHERE ft.field_category_tid = $content_type AND n.type='team'
ORDER by n.title ASC");
  foreach ($result as $record) {
    $nodes[$record->nid]=$record->title;
  }
  return $nodes;
}
function  jicustom_test_entity_callback($form, $form_state){
  return $form['field_loadtest_player'];

}
function  jicustom_test_entity_callback1($form, $form_state){
 return $form['field_loadtest_team'];

}

```

# Answer
> 0 votes
Use reference &$form\_state instead of $form\_state in functions
`hook_form_alter(&$form, &$form_state, $form_id)`

Edit: Ohh yes, I got, there is one should be field\_loadtest\_player you used "field\_loadtest\_category" on both ajax `$form['field_loadtest_player'][LANGUAGE_NONE]['#ajax'] = array(
 ...
 ...
);
$form['field_loadtest_category'][LANGUAGE_NONE]['#ajax'] = array(
 ...
 ...
);`

---
Tags: forms, ajax
---


title: Print $entity info

text:
# Question
Title: Print $entity info
This may be a rookie question, but the docs are quite broad, and im looking for a simple answer.

I am using dpm($entity) to view the entity object, and it gives me the following...

Now I want to access these values in a computed field, I have tried...

```
$id = $entity=>id;

```

> Parse error: syntax error, unexpected '=\>' (T\_DOUBLE\_ARROW)

and...

```
$id = $entity["id"];

```

> Fatal error: Cannot use object of type Entity as array

Can someone tell me what Im doing wrong?

# Answer
> 3 votes
You use the `->` operator for accessing the data attributes in a PHP object.

Use `$entity->id` to access the id of the entity.

If you want to access a value of the field (which is an array), you do it like
`$entity->field_field_name['und'][0]['value']` depending on the type of field.

---
Tags: 7, entities
---


# Question
Title: finding a route to form mode and add it local tasks
I have a content type named "film" and a form mode named "film\_artistic"

in **my\_module.routing.yml**, I have added this entry:

```
my_module.film.artistic:
  path: 'node/{node}/artistic/edit'
  defauts:
    _entity_form: node.film_artistic
    _title: 'Edit artistic info'
  requirements:
    _permission: 'access content'

```

But when I try to reach, let say "**/node/6/artistic/edit**" I got a "Page not found" result

I don't know what I am missing...

My ultimate goal is to have several **form mode** for my film content type (ex: Artistic, Technical,...) and for each of them, I would like to create a "Local Task" sharing the same base\_route: "**entity.node.edit\_form**". For my first local task, I have to add the following in **my\_module.links.task.yml**:

```
film.artist:
  route_name: my_module.film.artistic
  title: Edit artistic info
  base_route: entity.node.edit_form
  weight: 20

```

But of course I can't test it as my main route is not working (node/{node}/artistic/edit)

# Answer
> 0 votes
I could find a solution with an handy module: https://www.drupal.org/project/form\_mode\_control

After installation, you can reach any form by using :

```
 www.your-site.com/node/add/my_content_type?display=machine_name_of_your_form

```

or

```
www.your-site.com/node/{node}/edit?display=machine_name_of_your_form

```

More then this, this module allow you to set permission to access each form mode.

I am still looking for how to add those forms as local task... but the main thing is done

My objective is: if I go to node/add, or node/{node}/edit, I would like to have the default form displayed but also, all the form mode accessible as Tabs (local task)

---
Tags: forms, 8, routes
---


# Question
Title: Ajax problem on node edit page trigger whole submit
I'm facing a very strange problem on one website.

First of all with the module `media` (I'm using the last version of the module). When click on "`Remove`" an image, an ajax request is triggered and seems to go through the entire form submit, displays a message above the field but doesn't remove the image.

If I click on "`Remove`" again then it works normally.

Now when I click on a "`Add more`" button like for a multiple `field_collection`, it works fine the first time for the field I click. If I click on an other multiple field (an other `field_collection`) then nothing happens. I don't know if both problems are related.

When I look into the network, I see Ajax queries with all the datas (some differences like the form token), the response is just not the same.

I'm on jQuery 1.4.4 on admin pages and using the Shiny theme. Drupal is 7.41 and hosted on NGINX 1.6.2-5

I've looked into all the "`form_alter`" I had, to see if something got altered. I even deactivated all my custom modules, but the problem is still there.

Any clue would help :-)

# Answer
> 1 votes
The problem was due to the contrib module `admin_language` not handeling properly the ajax callback url on node edit page.

I had to add these url to be included in the config "Use administration language on only the listed pages." :

```
system/ajax
media/ajax
media/ajax/*
media/*/ajax

```

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


# Question
Title: Rule for sending email when order exceeds a defined weight
I set up some shipping tariffs (with module shipping weight tariff). But now i want to define a rule that sends an email to the shopowner in case the order total weight is over a certain weight. How should this rule be defined? The one i made is not working, it is not kicking in (for sake of simplicity in the below example I chose to show a message instead of sending an email):

```
    { "rules_shipping_weight_alert" : {
    "LABEL" : "Shipping Weight Alert",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-8",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_physical", "commerce_shipping" ],
    "ON" : { "commerce_shipping_collect_rates" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "commerce-order" ], "type" : "commerce_order" } },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_physical_weight" } },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-order" ],
          "operator" : "\u003E",
          "value" : "9",
          "unit" : "kg"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Shipping weight alert!" } } ]
  }
}

```

Any help would be much appreciated!

# Answer
> 0 votes
After some fiddling I've found the solution myself:

```
    { "rules_notice_overweight" : {
    "LABEL" : "Overweight",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_physical", "rules", "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E",
          "value" : "10",
          "unit" : "kg"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Total weight is over 10kg" } } ]
  }
}

```

The problem in my first code example was the trigger "commerce\_shipping\_collect\_rates". It has to be "commerce\_shipping\_calculate\_rate" instead. I hope someone can benefit from that.

---
Tags: commerce, rules
---


# Question
Title: Auto-Fill from on content type to another
I have a content type called **Point-of-Contacts**, basic info for a person. (~600 nodes)

I have another content type, like a form, that has a select list of all **Points-of-Contacts**. When a user selects their desired **Point-of-Contact**, by name from the select list, I need the rest of the info of that **Point-of-Contact** to auto-fill text boxes on the form.

Any ideas?

NOTE: Using Drupal 7

# Answer
In my example I've created two content types with two custom fields in addition to your node reference field:

1. Node type: Point-of-Contact (machine name `points_of_contacts`)

* **Text field:** To field one (machine name `field_to_field_one`)
    * **Text field:** To field two (machine name `field_to_field_two`)
2. Node type: Example (machine name `example`)

* **Node reference:** Point-of-Contact (machine name `field_points_of_contacts`)
    * **Text field:** Field one (machine name `field_field_one`)
    * **Text field:** Field two (machine name `field_field_one`)

Then You need to create a custom module to alter node reference dropdown field to ajax dropdown with callback function.

First create custom module by following this tutorial

Second alter node reference field by implement this hook `hook_field_widget_form_alter`

```
function MODULE_NAME_field_widget_form_alter(&$element, &$form_state, $context) {

  if(isset($element['#field_name']) && $element['#field_name'] == 'field_points_of_contacts') {
    $element['#ajax'] = array(
      'callback' => 'MODULE_NAME_auto_fill_callback',
    );
  }
}

```

Third implement ajax callback function

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

  $commands = array();

  if(isset($form_state['values']['field_points_of_contacts'])) {
    // get selected item/node from dropdown list
    $nid = $form_state['values']['field_points_of_contacts']['und'][0]['nid'];

    // load node by nid
    $node = node_load($nid);

    if($node) {

      if(isset($node->field_to_field_one['und'])) {
        // fill text field
        // edit-field-field-one-und-0-value represent the generated html id of the text field
        $commands[] = ajax_command_invoke('#edit-field-field-one-und-0-value', 'val', array($node->field_to_field_one['und'][0]['value']));
      }

      if(isset($node->field_to_field_two['und'])) {
        // fill text field
        // edit-field-field-two-und-0-value represent the generated html id of the text field
        $commands[] = ajax_command_invoke('#edit-field-field-two-und-0-value', 'val', array($node->field_to_field_two['und'][0]['value']));
      }
    }
  }

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

```

**Note:** change `MODULE_NAME` to your desirable module name.
> 1 votes

# Answer
It must be late now but there is a module called Entity Reference Autofill that can solve this issue.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Using git to fetch changes from testing version to live website
I am maintaining and developing a Drupal website and have a testing/development version of the site in a subfolder of drupal instalation. I started to learn git and I am wondering about how could I use it in my development process. I came up with following solution:

*Make a git repository for live site and clone it in the test subfolder (which will be added into live site's .gitignore file). Make some development in the test directory, test it and when I'm satisfied, switch to the live site repository, fetch and merge the changes.*

Since I am a newbie to git, I'd like to know if this approach can be succesfully used, or if not, which aspects should I change/or come up with completely different solution.

# Answer
> 1 votes
Look into Git-Flow http://jeffkreeftmeijer.com/2010/why-arent-you-using-git-flow/ for a very logical method of dealing with branches and server environments. You can either adopt the methodology and handle the branches yourself or you can download a git module that does it for you from https://github.com/nvie/gitflow

Basically you have a 'master' branch that contains your production code and you use `git pull` to pull it to your PROD server. You also have a 'develop' branch that contains your test code for your DEV server. Once code is ready for production, merge it into 'master', push, then pull to PROD.

# Answer
> 0 votes
I would use a post-update hook that will pull changes into the webroot and perhaps also run some other commands like clearing the caches etc.

First you need to create a bare repository:

```
mkdir /var/git/<repo-production.git>
cd /var/git/<repo-production.git>
git init --bare
cp hooks/post-update.sample hooks/post-update
chmod +x hooks/post-update

```

You then need to modifiy your post-update to something like:

```
#!/bin/sh
cd /var/www/<your_www_root> || exit
unset GIT_DIR
git pull hub master
# if you have drush installed you clear caches here
# drush cc all
exec git update-server-info

```

Then you need to clone out the repository in your webroot:

```
cd /var/www
git clone /var/git/<repo-production.git> <your_www_root>
cd <your_www_root>
git remote rename origin hub

```

Then on your local machine you add the remote like this:

```
git remote add production ssh://root@example.com:/var/git/<repo-production.git>

```

Of course you need to change the above to match your own username, hostname and path to your repository.

You should now be able to push changes to the remote repository, than in turn will deploy any changes into the webroot.

```
git push production

```

Notice that you can setup another bare repository for your staging environment and modify the above so it checkout the code to a different location. A nice approach would then be to add it using `git remote add staging <path_to_staging_repoistory>`. Done this you are able to push your code either to `production` using `git push production` or to `staging` using `git push staging`.

---
Tags: version-control
---


title: How to implement Asset Inventory?

text:
# Question
Title: How to implement Asset Inventory?
I would like to create an Asset Management Inventory for our corporate helpdesk. There is a list of assets (laptop, phones etc) which our ICT staff members can borrow from the helpdesk. Members would not have direct access to the system, the main user would be just a helpdesk admin managing the loans.

These are the entities I'm planning to use but I'm not really sure how should I design my content types and how to link them with each other.

**Borrower Information**

* Full Name
* Username
* E-mail
* Telephone
* Area
* Office No.

**Asset Details**

* Name
* Model
* Scope.

**Loan Information**

* Borrowed On (date)
* To be returned (date)
* Updated On (date).

I was thinking about using a Field Collection as a Loan History as part of every Asset, in which the Borrower and the Loan Information would exist. So every time I need to create a new Loan record, I would choose the Borrower as an entity and fill in the Loan Information. If the Asset or the Borrower doesn't exist in the system, I would like the admin to be able to add them.

I'm not familiar with the Entity Reference module and I don't know if it would fit to my scenario. I need some guidance I'm afraid.

# Answer
Start with creating 3 content types like so:

* **Borrower**, with as fields the various attributed you mentioned within Borrower Information.
* **Asset**, with as fields the various attributed you mentioned within Asset Details.
* **Loan**, with as fields the various attributed you mentioned within Loan Information.

Then use the Entity Reference module to add 2 more fields to **Loan**:

* a 1st entity reference field to indicate the Borrower.
* a 2nd entity reference field to indicate the Asset.

Then use the Views module to build all sorts of lists. Such as a Loan history, which could simply be a list all nodes of type *Loan*, in which you'd also want to add a Views "relationship" to *Borrower* and/or *Asset*. You could also add some Views filter(s) to further limit this list to fit your needs, e.g. to list all available (not borrowed) assets (as in your comment to my answer). For this kinds of lists I often use the dataTables module to make the searching even more flexible/dynamic (in the browser). Refer to my answer to "How to display the data of a View in table format?" for (way) more details on that.

You could easily take this a step further by also adding the Rules module to the mix. E.g. to schedule an eMail reminder to the borrower X days before the "to be returned date". However, for this to work (make sense), you'll also want to add an extra field (of type date) to the **Loan** type to register the actual return date of the **Asset** (which you should also add IMO even if you don't want this extra Rules feature). Assuming you added such return date field, you'd want to check it's value in such eMail reminder (to avoid sending reminders for Assets that were returned already).
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How do I programmatically create an entity with its fields?
I'm using Entity API to work with some entities but I cannot figure out how to create a new entity with its fields attached. I created a bundle and added some fields to that bundle. I'm looking to do this:

```
$a = entity_create(...);

```

return an array:

```
isNew => TRUE,
title => '',
attachedField1 => '',
attachedField2 => '',
etc...

```

I'd then like to be able to simply update the values and then entity\_save() them:

```
isNew => TRUE,
title => 'Title of my entity',
attachedField1 => 'data for attached field 1',
attachedField2 => 'data for attached field 2',
etc...

```

Is this doable? If so, how? I'm having a tough time working with entities.

Here's my entity info:

```
  $return['k_profile'] = array(
      'label' => t('Profile'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'base table' => 'k_profile',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'pid',
        'bundle' => 'type',
        ),
      'bundles' => array(), //added later in hook_entity_info_alter()
      'bundle keys' => array(
        'bundle' => 'type',
        ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'access callback' => TRUE,
      'module' => 'k_profile',
    );

```

# Answer
Here's some code that creates a product programmatically, including fields and properties.

```
/**
 * Create a product programmatically.
 *
 * This is stolen shamelessly from commerce_bpc. However, I'm not comfortable
 * with the field saving using form api. Seems quite odd.
 *
 * @param $product_type
 *   (string) The name of the product type for which products should be created.
 * @param $values
 *   Keyed array with
 *   - 'price' => actual amount owed on this installment; decimal text like '1.50'
 *   - 'amount_paid' => price amount already paid as a decimal text like '1.50';
 *   - 'original_order' => order id of the original order
 *   - 'original_line_item' => line item id of original line item
 *   - 'original_product => product id of the original product from which the
 *     new product is being created.
 * @param $extras
 *   An array for the values of  'extra fields' defined for the product type
 *   entity, or patterns for these. Recognized keys are:
 *   - status
 *   - uid
 *   - sku
 *   - title
 *   Note that the values do NOT come in the form of complex arrays (as they
 *   are not translatable, and can only have single values).
 * @return
 *   The ID of the created product.
 */
function commerce_installments_create_product($product_type, $values, $extras) {
  $form_state = array();
  $form_state['values'] = $values;
  $form = array();
  $form['#parents'] = array();

  // Generate a new product object
  $new_product = commerce_product_new($product_type);

  $new_product->status = $extras['status'];
  $new_product->uid = $extras['uid'];

  $new_product->sku = $extras['sku'];
  $new_product->title = $extras['title'];
  $new_product->created = $new_product->changed = time();

  // field_original_order[und][0][target_id]
  $order = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_order'])));
  $form_state['values']['field_original_order'] = $order;

  // field_original_line_item[und][0][target_id]
  $line_item = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_line_item'])));
  $form_state['values']['field_original_line_item'] = $line_item;

  $product = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_product'])));
  $form_state['values']['field_original_product'] = $product;

  //commerce_price[und][0][amount]
  $price = array(LANGUAGE_NONE => array(0 => array(
    'amount' => $values['price'],
    'currency_code' => commerce_default_currency(),
  )));
  $form_state['values']['commerce_price'] = $price;

  // field_due_date[und][0][value][date]
  $due_date = array(LANGUAGE_NONE => array(0 => array('date' => $values['due_date'])));
  $form_state['values']['field_due_date'] = $due_date;

  // Notify field widgets to save their field data
  field_attach_submit('commerce_product', $new_product, $form, $form_state);

  commerce_product_save($new_product);
  return $new_product->product_id;
}

```
> 4 votes

# Answer
If I'm not mistaken the Node Example in the Examples Project does just what you want.
> 2 votes

# Answer
For those who created their entity with eck, an explanation is here : http://drupal.org/node/1377614

simply put, it should be enough to write

```
$e = entity_create('type',array());
$e->field_a = ...;
$e->save();

```
> 2 votes

# Answer
With the contrib Entity API module, use `entity_create`, for example:

```
try {
  $entity_type = 'entity_type';
  $entity = entity_create($entity_type, array('type' => 'type_or_bundle'));
  $wrapper = entity_metadata_wrapper($entity_type, $entity);
  $wrapper->type = 'some_type'; // When entity type has bundles, you can specify a type.
  $wrapper->isNew = TRUE;
  $wrapper->title = '';
  $wrapper->attachedField1 = '';
  $wrapper->attachedField2 = '';
  $wrapper->some_other_property = 'foo';
  $wrapper->field_some_field = 'bar';
  $wrapper->field_multiple_field = array('foo', 'bar');
  $wrapper->save();
}
catch (EntityMetadataWrapperException $e) {
  watchdog_exception('my_module', $e);
}

```

---

See also: Drupal 7 - Create a Node in Code page which provides the following example:

```
function my_create_a_node() {
  global $user;

  // entity_create replaces the procedural steps in the first example of
  // creating a new object $node and setting its 'type' and uid property
  $values = array(
    'type' => 'YOUR_NODE_TYPE',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  // The entity is now created, but we have not yet simplified use of it.
  // Now create an entity_metadata_wrapper around the new node entity
  // to make getting and setting values easier
  $ewrapper = entity_metadata_wrapper('node', $entity);

  // Using the wrapper, we do not have to worry about telling Drupal
  // what language we are using. The Entity API handles that for us.
  $ewrapper->title->set('YOUR TITLE');

  // Setting the body is a bit different from other properties or fields
  // because the body can have both its complete value and its
  // summary
  $my_body_content = 'A bunch of text about things that interest me';
  $ewrapper->body->set(array('value' => $my_body_content));
  $ewrapper->body->summary->set('Things that interest me');

  // Setting the value of an entity reference field only requires passing
  // the entity id (e.g., nid) of the entity to which you want to refer
  // The nid 15 here is just an example.
  $ref_nid = 15;
  // Note that the entity id (e.g., nid) must be passed as an integer not a
  // string
  $ewrapper->field_my_entity_ref->set(intval($ref_nid));

  // Entity API cannot set date field values so the 'old' method must
  // be used
  $my_date = new DateTime('January 1, 2013');
  $entity->field_my_date[LANGUAGE_NONE][0] = array(
     'value' => date_format($my_date, 'Y-m-d'),
     'timezone' => 'UTC',
     'timezone_db' => 'UTC',
   );

  // Now just save the wrapper and the entity
  // There is some suggestion that the 'true' argument is necessary to
  // the entity save method to circumvent a bug in Entity API. If there is
  // such a bug, it almost certainly will get fixed, so make sure to check.
  $ewrapper->save();
}

```

---

To create a new entity using Drupal core entity - try Examples module, using contrib Entity API - try Model Entities module.

For more examples, search on GitHub.
> 1 votes

# Answer
Model Entities is what you need. It is a a starter kit for entities. You should read the module description and the README file before installing this.

It comes with everything you need so you can actually use it as it is. You can add fields, manage displays and everything else.
> 0 votes

---
Tags: 7, entities
---


title: Import Json data into node

text:
# Question
Title: Import Json data into node
My goal is to import my own data set into Drupal 8 using Migrate modules (migrate\_plus, migrate\_tools).

In Drupal, I use Paragraph module, and here my trouble starts. I've build my own plugin to transform my own data into paragraph. The transformed data is good if i create a new node and attached to it into the transform() function but that's not what I want, it's only to say that my data may be correct (see comments below)

I do import with base field like text, tags or file, and with this, the node will be generated, but I can't figure out why 'return $paragraphs' won't anything.

PS : I un-install/install my module (and the conf migrate\_plus generated) everytime I change my `.yml` file and cache rebuild.

* Drupal (8.1.1)
    + migrate\_plus (8.x-2.x-dev)
    + migrate\_tools (8.x-2.0-beta1)
    + migrate\_source\_json (8.x-2.x-dev)
    + paragraphs (8.x-1.0-rc4)

### Migration configuration for articles (config/install/migrate\_plus.migration.article.yml)

```
id: article
label: Article
migration_group: Articles
migration_dependencies: {}

source:
  plugin: json_source
  path: http://www.example.com/dataset.json
  headers:
    Accept: 'application/json'
  identifier: id
  identifierDepth: 0
  fields:
    - id
    - title
    - paragraphs

destination:
  plugin: entity:node

process:
  type:
    plugin: default_value
    default_value: article

  title: title

  field_paragraphes:
      - source: paragraphs
        plugin: paragraphs_import

  uid:
    plugin: default_value
    default_value: 0

```

### Dataset example:

```
[{
    "id": "1",
    "title": "article 1",
    "paragraphs": [{
        "id": "1",
        "title": "paragraph 1 article 1"
    }, {
        "id": "2",
        "title": "paragraph 2 article 1"
    }]
}, {
    "id": "2",
    "title": "article 2",
    "paragraphs": [{
        "id": "3",
        "title": "paragraph 1 article 2"
    }, {
        "id": "4",
        "title": "paragraph 2 article 2"
    }]
}]

```

### Custom plugin used on 'field\_paragraphes' (/src/Plugin/migrate/process/ParagraphsImport.php)

```
<?php

/**
 * @file
 * Contains \Drupal\my_module\Plugin\migrate\process\ParagraphsImport.
 */

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
 *
 * @MigrateProcessPlugin(
 *   id = "paragraphs_import"
 * )
 */
class ParagraphsImport extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // code only to add 1 paragraph to my node, to make thing easier to start

    // paragraph_txtimg = one paragraph type allowed into my paragraph field

    $paragraphs=array();
    $ppt_values = array(
      'id' => NULL,
      'type' => 'paragraph_txtimg',
    );
    $ppt_paragraph = Paragraph::create($ppt_values);
    $ppt_paragraph->save();

    // IF I uncomment this part, it will create a new node with a paragrah, this works
    // But this is not what I want to do, I want to return the paragraph to the node that will be created by migrate
    /*
      $node = Node::create(array(
        'type' => 'article',
        'title' => 'This is a new article with a fresh paragraph generated !',
        'field_paragraphes' => array(
          array(
            'target_id' => $ppt_paragraph->id(),
            'target_revision_id' => $ppt_paragraph->getRevisionId(),
          ),
        ),
      ));
      $node->save();
    */

    $target_id_dest = $ppt_paragraph->Id();
    $target_revision_id_dest = $ppt_paragraph->getRevisionId();
    $paragraphs[] = array('target_id' => $target_id_dest, 'target_revision_id' => $target_revision_id_dest);

    return $paragraphs;
  }

}

```

# Answer
I finaly found the missing key :
**transform() is called on EACH item** of the source.

```
field_paragraphes:
 - source: paragraphs
   plugin: paragraphs_import # will be called for each value of source: paragraphs

```

And so, the return value should be the paragraph revision definition :

```
<?php

/**
 * @file
 * Contains \Drupal\my_module\Plugin\migrate\process\ParagraphsImport.
 */

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
 *
 * @MigrateProcessPlugin(
 *   id = "paragraphs_import"
 * )
 */
class ParagraphsImport extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // transform() is called on each source value

    $paragraph_options = array(
      'id' => NULL,
      'type' => 'paragraph_txtimg',
    );
    $paragraph = Paragraph::create($paragraph_options);
    $paragraph->save();

    return $paragraph;
  }

}

```
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: How to get a link to entity_reference in ListBuilder?
I have a custom entity (Person) with these fields: ID, nom, prenom, telephoneportable, estactive, adherentid, userID, created, changed.
I created it with baseFieldDefinitions.

adherentid is a 'entity\_reference' link to another custom content entity 'Adherent'.
userID are is a 'entity\_reference' link to standard Drupal 'User' entity.

In the PersonListBuilder, I try to have these ids showed as links to the corresponding entities.

Here is the code for userID (and it's working fine):

```
$row['userid']['data'] = array(
'#theme' => 'username',
'#account' => $entity->getUser(),
);

```

What should be the code for adherentid (can't make it work so far):

```
$row['adherentid']['data'] = array(
'#theme' => '???',
'#account' => $entity->getAdherent(),
);

```

Thanks in advance

# Answer
Finally, that worked for me:

```
$adherent = $entity->getAdherent();
$id = (int) $adherent->id->value;
$row['adherentid']['data'] = array(
  '#type' => 'link',
  '#url' => Url::fromRoute('entity.association_adherent.canonical', array('association_adherent' => $id)),
  '#title' => $adherent->designation->value,
 );

```
> 0 votes

# Answer
One possibility is to use the Link render element, and by using the canonical link for the Adherent entity. This assumes that the Adherent entity type definition has a canonical link, and that the route is defined in your module's routing YAML.

```
$row['adherentid']['data'] = array(
 '#type' => 'link',
 '#url' => Uri::fromRoute('entity.adherent.canonical', ['association_adherent' => $id]),
 '#title' => 'My link',
);

```

Another possibility is to render the field, and use the display mode that provides a link to the entity using the entity label. However this is less accessible in the documentation to look up within a reasonable time.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Imce file/image browser not showing any buttons tab
I am using imce as image browser. I installed imce for filefield module to select files from imce repository and i have given all permissions as in below image

When it will go to imce repository those buttons are not showing, see the below image  I followed this link but that is not working for me. Please help me regarding this.

# Answer
> 1 votes
Try changing the "administrative" theme - I observed this behavior with a custom theme, but it rendered the buttons if I changed themes to one of the standard themes.

---
Tags: 7, files
---


# Question
Title: How do I get the current path of a block?
I need the current path, where my custom block is visible. So, i have written this code

```
class MyBlock extends BlockBase {

  public function build() {
    $currentPath= \Drupal::service('path.current')->getPath();
    return array(
        '#markup' => $currentPath,
    );
  }
}

```

It is displaying the path where it was visible for first time; if I visit node/1, node/2, node/3 consecutively, it will print node/1 every time, because that was what I visited that first.
It might be happening due to block caching, but how do I get the path for the page showing the block?

# Answer
Yes, this is because of block caching. The block is built once for the first request and then will stay in the cache forever, until you clear the cache.

You have to set a cache context on the url path:

```
'#cache' => ['contexts' => ['url.path']],

```

Then the block will get a cached version for every path.
> 9 votes

# Answer
You can also turn off the cache for certain blocks this way:

```
'#cache' => ['max-age' => 0];

```

But it would be better if you can find what is unique in each block and set those as context variables.

https://www.drupal.org/developing/api/8/cache/contexts

For urls alone, there are many variations:

```
url
  .host
  .query_args
    :key
    .pagers
      :pager_id
  .path
    .parent
  .site

```
> 2 votes

---
Tags: 8, caching
---


title: How do I theme a link?

text:
# Question
Title: How do I theme a link?
In Drupal 7 this was possible.

```
$link = array(
  '#type'  => 'link',
  '#title' => t('My Title'),
  '#href'  => 'node/1',
);
drupal_render($link);

```

But I've tried this with Drupal 8, and it does not output anything.

```
$link = array(
  '#type' => 'link',
  '#title' => t('test'),
  '#url' => 'node/1',
);
drupal_render($link);

```

Is there a way I can render a link without having to call the Link plugin directly, or create my own theme function?

I'm theming a field group formatter, which must output a render array.
The use of `drupal_render()` is deprecated and should not be called directly; I'm using it here to make my example clearer.

# Answer
> 10 votes
I think the problem with your Drupal 8 code is that '#url' needs a URL object.

### External URL

```
'#url' => Url::fromUri('https://www.drupal.org'),

```

### Internal URL from a route

```
'#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),

```

In Drupal 8 you are not supposed to render yourself. When porting code from Drupal 7, remove all rendering and return only render arrays.

# Answer
> 2 votes
As an alternative, you can also use `\Drupal\Core\Link::fromTextAndUrl()` or `\Drupal\Core\Link::createFromRoute()`.

Twig can print that as-is, you can also get a render array by calling `\Drupal\Core\Link::toRenderable()`. The resulting render array is the same then as building it from hand.

# Answer
> 1 votes
Here's an example of how to render a link in Drupal 8 with a custom class. It's a little odd, but the options are passed into the URL, not the link function.

```
use Drupal\Core\Url;

$options = array('attributes' => array('class' => 'my-custom-class'));
$url = Url::fromUri('http://www.example.com', $options);
$markup = \Drupal::l(t('Link Text Goes Here!'), $url);

```

This is useful in a field formatter, that expects markup returned. If you are doing this elsewhere, it's best to convert it to a link render array item.

```
use Drupal\Core\Url;

$options = array('attributes' => array('class' => 'my-custom-class'));
$build['examples_link'] = [
  '#title' => t('Link Text Goes Here!'),
  '#type' => 'link',
  '#url' => Url::fromUri('http://www.example.com', $options)
];

```

---
Tags: theming, 8
---


# Question
Title: How to programmatically create an entity and fill in entity reference fields
I'm trying to create an entity that has a number of entity refernce fields, and I'm confused about the best way to do that. so far I've gotten as far as this

```
$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('value' => "2")));

```

Creating the entity works fine, but I can't for the life of me figure out how to fill in the entity references.

# Answer
The column name for a field isn't always `value`; in the case of entity references it's `target_id` if I remember rightly.

Try this:

```
$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('target_id' => "2")));

```
> 2 votes

# Answer
Maybe this can help someone:

```
$entity_ids = array(15,78,45,78);
$count = 0;
foreach ($entity_ids as $id) {
  $count++;
  $node->field_entity_ref[$node->language][$count]['target_id'] = $id;
}

```
> 2 votes

# Answer
When using contrib Entity module, you can use entity metadata wrapper syntax, for example:

```
$entity = entity_create('mytype', array('type' => 'my_bundle'));
try {
  $wrapper = entity_metadata_wrapper('mytype', $entity);
  $wrapper->field_ref = '123';
  $wrapper->field_multi_ref = array('123', '456');
  $wrapper->save();
}
catch (EntityMetadataWrapperException $e) {
  watchdog_exception('my_module', $e);
}

```
> 1 votes

# Answer
If you need add new reference to existing entity references .

```
$counter = 0;
$node_reference = array();
while (!is_null($entity->field_ref['und'][$counter]))
{
    $node_reference[$counter]= $entity->field_ref['und'][$counter];
    $counter++;
}
$node_reference[$counter]= array('target_id' => $release_nid);
$entity->field_ref= array('und' => $node_reference);

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Trying to filter content by two field values (either/or)
I'm trying to filter published content by the values set inside of two fields (one or the other). Right now, I'm successfully filtering my content by one field:

**Contextual Filter**

> If field\_targetuser = logged in uid, than display content.

However, I also want to show content in which field\_universal = YES , regardless of the logged in uid.

Naturally, implementing the first Contextual Filter and than a second only further filters the intial filter. What I'm trying to accomplish:

> Show all content of this type if targetuser matches logged in user id, but ALSO show all content where field\_universal = YES, regardless of what appears in the targetuser id.

Views setup:

# Answer
> 2 votes
It appears that you are trying to do and OR filter in contextual filters, and as @jreynolds mentions, OR conditional are not available in contextual filters out of the box. @jreynolds' solution is to move the arguments into the filters, which is a solution I like very much, but I also hesitate to use a sandbox module if I can avoid it. Instead I'm using Views Contextual Filters OR. Which has a dev version available. With this module installed you need to go into the query settings in the advanced section of your view and check a box next to "Contextual filters OR". The disadvantage of this, of course, is that you can't do more advanced logic like and'ing two filters and or'ing a third.

Another solution is to access the views api in a custom module and change the contextual filter query to be an OR query as explained in This answer.

**UPDATE** I think you should be able to accomplish this by putting both of your filters in contextual filters and using the module I recommended above. You currently search for your user field matching the currently logged in user in contextual filters. Now add a second contextual filter that matches for field\_universal and provides a fixed default value of yes or whatever it is that needs to match in that field. That in combination with the Views Contextual Filters OR module should query for the message is meant for the current user OR the message is a universal one.

# Answer
> 3 votes
You can solve this without any additional modules or coding, just with pure Views + Entity Reference. Here is how:

1. You need to add 1 more relationship to your current View (looking at your screenshot):
    * Entity Reference: Targeted User =\> This is the Entity Reference field that points to a User, what you call "targetuser"
2. You need to add a "User: Current" filter to your view. Once you click on that, you should see the following:  This filter will allow you to select only the nodes where the targeteduser is the same as the logged-in (current) user.
3. You need to place the universalswap in an OR relationship to the new filter inside a FILTER GROUP. Then place that group in an AND relationship to the rest of your filters, i.e. Type = Messages.

That should do it without any additional modules. Here is a screenshot of my final View configuration:  I am logged in as admin (uid:1) and you can see in the results that I am getting all messages that are either "Universal" or targeted at me.

Good luck!

# Answer
> 1 votes
The most straightforward way to do this in my view would be to add field\_targetuser and field\_universal to your fields and exclude them from display then create a views Global: PHP filter with the following filter code in

```
global $user;

if($user->uid == $data->field_targetuser || $data->field_universal == "yes")
{
    return false;
} else {
    return true;
}

```

The code here basically checks to see if the current uid matches the targetuser field or the field\_universal equals yes. If either of these conditions are met the filter returns false which displays the result, otherwise return true which excludes the result.

Hope this is what you were looking for :-)

# Answer
> 1 votes
What you need is a way to move the contextual filters down into the normal filter section of Views where you can apply conditional logic on them (in your case an OR condition)

There is a module for that: Views arguments in filters

> There are at least two problems with arguments as they are currently used in Views:
>
> * Many people find it difficult to wrap their head around how arguments work.
> * It is not possible to use operators on arguments, for example to show all nodes created *after* the timestamp value you provide in an argument, or display all the nodes that in their title *contain* the word/phrase in the argument. There is just "equals" or "not equals". (Unless you more or less code your own argument handlers, which would end up a special case that few others can make use of.)

# Answer
> 0 votes
It appears as though the below view settings fixed the issue. This setup displays Messages for the current user, OR messages in which field\_universalswap = Yes...

Because the field\_targetuser is always the logged in user, it displays current user's messages. If the field\_targetuser does not match the current user, it still displays those messages if field\_universalswap = Yes.

My only tick about this route: It also displays messages I've sent - not sure that's a bad thing yet though...

---
Tags: 7, views
---


# Question
Title: Custom VBO Action to create an Entity that is referenced
I have two entities: *People* and *People Notes*.

The People entity is in another database with the People Notes is in the local Drupal database.

Schema for People:

```
PeopleId
FirstName
LastName
DOB

```

Schema for People Notes:

```
NoteId
uid
PeopleId (entityReference)
Signed (Boolean)

```

From a post I found here, I've created a custom action called Signed to execute a PHP script with the code below -

```
global $user;
$entity_notes_array = array();
$entity_notes_array['uid'] = $user->uid;
$entity_notes_array['field_people_reference']['value'][0] = 1; // Using 1 to test the reference
$entity_notes_array['field_signed']['value'][0] = 1;
$entity_notes = entity_create('people_notes', $entity_notes_array);
$entity_notes->save();

```

I have a view created that uses the People table as its base and then I bring in the People\_Notes table through an entity reference. The view also has a VBO that executes the Signed script.

### Two questions:

1 - How do I save the entity People Notes? The script process with no error messages and it successfully returns with "Action Signed Petition saved", but when I got to see what was created the admin page does not list the new entity.

2 - How do I reference the PeopleId from the view?

### Additional Information on People Notes

```
 /**
  * Implements hook_entity_info().
  */

function people_notes_entity_info() {
    $info = array();

    $info['people_notes'] = array(
        'label' => t('People Notes'),
        'base table' => 'people_notes',
        'entity keys' => array(
            'id' => 'id',
            'label' => 'label',
        ),
        'label callback' => 'entity_class_label',
        'uri callback' => 'entity_class_uri',
        'entity class' => 'PeopleNotesEntity',
        'controller class' => 'PeopleNotesEntityController',
        'views controller class' => 'PeopleNotesViewsController',
        'admin ui' => array(
            'path' => 'admin/peoplenotes',
            'controller class' => 'PeopleNotesUIController',
            'menu wildcard' => '%notes',
            'file' => 'people_notes.admin.inc',
        ),
        'module' => 'people_notes',
        'access callback' => 'people_notes_access_callback',
        'fieldable' => TRUE,
        'bundles' => array(
            'people_notes' => array(
                'label' => t('People Notes'),
                'admin' => array(
                    'path' => 'admin/peoplenotes',
                    'access arguments' => array('admininster notes'),
                ),
            ),
        ),
        'view modes' => array(
            'full' => array(
                'label' => t('Full View'),
                'custom settings' => FALSE,
            ),
            'part' => array(
                'label' => t('Partial View'),
                'custom settings' => FALSE,
            ),
        ),
    );
    return $info;
}

function people_notes_menu() {
    $items = array();
    $items['peoplenotesdemo'] = array(
        'title' => 'People Notes Demo Page',
        'page callback' => 'people_notes_demo_page',
        'access callback' => TRUE,
        'menu' => 'navigation',
    );
    $items['notes/%notes'] = array(
        'title' => 'People Notes Entity Page',
        'title arguments' => array(1),
        'page callback' => 'people_notes_view_entity',
        'access arguments' => 'view notes',
        'page arguments' => array(1),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function people_notes_load($id) {
    $people_notes = entity_load('people_notes', array($id));
    return array_pop($people_notes);
}

function people_notes_save($people_notes) {
  return $people_notes->save();
}

function people_notes_demo_page() {
    $people_notes = entity_load('people_notes', array(1));
    kpr($people_notes);

    return 'Hi Notes from Mark';
}

function people_notes_page_title($people_notes){
  return $people_notes->id;
}

/*function people_notes_view_entity($people_notes) {
    $people_notes_entity = entity_view('people_notes', array($people_notes->id => $people_notes));
    kpr($people_notes_entity);
    return 'Hello Mark';
}
*/
function people_notes_view_entity($people_notes, $view_mode = 'full') {
    //drupal_set_title('(' . $people_notes->id . ')');
    $people_notes_entity = entity_view('people_notes', array($people_notes->id => $people_notes));
    return $people_notes_entity;
}

function people_notes_permission() {
    return array(
        'administer notes' => array(
            'title' => t('Administer Notes'),
        ),
        'view notes' => array(
            'title' => t('View Notes on a person'),
        ),
    );
}

function people_notes_access_callback($op, $people_notes = NULL, $account = NULL) {
    if (($op == 'view' && user_access('view notes', $account)) || user_access('administer notes', $account)) {
        return TRUE;
    } else if ($user_access('administer notes', $account)) {
        return TRUE;
    }
    return FALSE;
}

/*
 * Controller classes are located in the includes direcotory
 *
 */
// ...

```

# Answer
You will need to change the value to target\_id. Entity references do not use value index

```
global $user;
$entity_notes_array = array();
$entity_notes_array['uid'] = $user->uid;
$entity_notes_array['field_people_reference'][LANGUAGE_NONE][0]['target_id'] = 1;
$entity_notes_array['field_signed'][LANGUAGE_NONE][0]['value'] = 1;
$entity_notes = entity_create('people_notes', $entity_notes_array);
$entity_notes->save();

```
> 1 votes

# Answer
Below is the final solution. Both questions have been answered. I finally figured out why the script was not firing. I was having the VBO on the entity (people\_notes) and not the referenced entity (people). Because the people\_notes was being created with the action there was nothing being passed to the action. Once I switched the VBO to people it fired successfully and created the people\_notes entity.

Also @chadpeppers originally suggested entity\_metadata\_wrapper but that did not work due to not have a setter function defined for the uid field. I defined a setter function and then entity\_metadatawrapper worked correctly.

```
global $user;
$entity_notes = entity_create('people_notes', array());
try {
    $wrapper = entity_metadata_wrapper('people_notes', $entity_notes);
    $wrapper->uid->set($user->uid);
    $wrapper->field_people_reference->set($entity->PeopleId);
    $wrapper->field_signed->set(1);
    $wrapper->save();
       drupal_set_message(t('Signature Scrubbed!'));
       watchdog('Signed Petition', 'Signed Petition action fired!');
} catch (EntityMetadataWrapperException $exc) {
    watchdog(
      'Signature Scrubbed Action',
      'See '  . __FUNCTION__ . '() <pre>' .  $exc->getTraceAsString() . '</pre>',
       NULL, WATCHDOG_ERROR
    );
}

```
> 0 votes

---
Tags: 7, entities, views
---


title: How do I update an entity?

text:
# Question
Title: How do I update an entity?
I have defined my own entity: 'game'; created some 'games' with `entity_create`; and loaded one of these 'games' into a form for editing. Now, I want to update the entity with my submit handler. Here is the relevant code inside the handler:

```
$game = entity_load_single('game', $form_state['values']['game_id']);
$wrapper = entity_metadata_wrapper('game', $game);
$wrapper->some_property->set($form_state['values']['some_value']);
$wrapper->save();

```

This throws:

> **Error**
>
> EntityMetadataWrapperException: Entity property some\_property doesn't support writing. in EntityStructureWrapper-\>setProperty() (line 493 of /.../sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

I was looking for a function like `entity_update`, but it doesn't seem to exist. How can I update my 'game' entities? Thanks.

# Answer
> 1 votes
You're probably looking for `entity_save()`.

If you want to use a metadata wrapper for a custom entity properties you need to implement `hook_entity_property_info()` to describe them to the entity module, especially `setter callbacks` which are used to set the value of the property.

# Answer
> 0 votes
If you created your entity via `entity_create` (as you mentioned), you can set/override non-writable properties outside of the entity wrapper during the entity creation, e.g.

```
$entity = entity_create('games',
    array(
      'type' => 'game',
      'changed' => REQUEST_TIME,
      'some_property' => 'some value',
    ));
$wrapper = entity_metadata_wrapper('game', $entity);
$wrapper->save();

```

Otherwise you'll need to write your own `setter callback` as already suggested.

See also: How to fix entity property X doesn't support writing, when setting content type field values?

---
Tags: entities
---


# Question
Title: Get submitted values of webform in hook_alter function
how can i get the submitted field values of webform in hook\_alter function. One more question is how can i call to submit function from hook\_alter function.

# Answer
`hook_alter_form()` is only invoked during form array *build time*, not when the form is submitted, so it's not possible (as is trying to submit a form that isn't rendered to the browser yet). If you want to handle the submitted form values for your own custom processing, add a submit handler to the form array.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'webform_client_form_ID') {
    $form['#submit'][] = 'MYMODULE_webform_client_form_ID_submit';
  }
}

function MYMODULE_webform_client_form_ID_submit($form, &$form_state) {
  // @TODO: process $form_state['values'] as needed.
}

```
> 1 votes

---
Tags: 7, webforms, forms
---


title: How to Manage Content Types

text:
# Question
Title: How to Manage Content Types
I am trying to add custom fields for a Quiz Component (Multiple Choice Question). However, when I go to Home\>Admin\>Structure\>Content types, the only types that appear are Article, Basic page and Quiz (non of the components). I can add my own content type but cannot seem to get the already existing content types to appear in this menu.

In short, how do I control what content appears on this menu.

Thanks for your help and sorry for the noob question. Just getting started out.

# Answer
> 1 votes
The admin/structure/types page lists all the content types implemented by modules, or the content type you created.
In the case of the Quiz module, there are content types created from sub-modules, such as the *Short Answer* module, all listed under the *Quiz Question* package. Once you enable the modules you need, you will see extra content types, on admin/structure/types.

# Answer
> 0 votes
## Try 1

It may be an outdated cache. They should be cleared automatically when you install a module but it is possible it didn't get flushed completely. Perform a full cache flush using drush. Or visit /admin/config/development/performance

This may cause those items to magically appear.

## Try 2

I did this in Drupal 6 I think. Not 7.

I have run into something similar. I created several content types and for some reason one of them was not in this menu. I never figured out why but I was able to fix this by simply editing the management menu directly.

While you're in there check if the menu item is unchecked or in an unusual location. If you still can't find it you can create a new link in the appropriate area.

## Try 3

Check the documentation. As @Clive mentioned in the comments these may be other entity types.

## Try 4

If you don't have too much built roll-back to your db from before the quiz module was installed and install again. Or if you don't have a rollback point, uninstall the module and install again. Not a fun process but it may tweak something in the database.

---
Tags: nodes
---


# Question
Title: views_query_alter Matching all values in IN clause
I have a content type with a list(text) field. In which the admin can set multiple values on the field for the content type. Using a view the information is exposed to the end user. The views has a exposed filter to filter the list(text) field. However multiple options can be selected and need to be checked against the values set by the admin. The way Drupal views does this is by joining the table as many times as the amount of values being searched for, resulting in a very slow query.

I am now looking to do this with the query adjustment below inspired by this post: https://stackoverflow.com/questions/11636061/matching-all-values-in-in-clause

However I have no clue on how to include the HAVING combined with COUNT as suggested in de post from the link above within Drupal.

```
$field_values - array(1, 4)
$query->where[1]['conditions'][0]['field'] = 'field_data_field_listtext.field_data_field_listtext_value';
$query->where[1]['conditions'][0['value'] = $field_values;
$query->where[1]['conditions'][0['operator'] = 'IN';

```

Suggestions on solving the SQl query performance in other maners for exposed filters on list(text) are also very wecome.

# Answer
The following code should allow you to add the SQL code found in the accepted answer to the S.O. post you mentioned to the Views generated SQL code.

```
function YOUR_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'YOUR_VIEW_NAME' ) {
        $value_count = 0;

        // Collect the number of selected values in the exposed filter
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_listtext.field_data_field_listtext_value' ) {
                $value_count = sizeof($query->where[1]['conditions'][$key]['value']);
                break;
            }
        }

        // Add the having expression
        if( $value_count > 0 ){
          $query->add_having_expression(
            0,
            "count(distinct :field_name) = :value_count",
            array(
              ':field_name' => 'field_data_field_list_select.field_list_select_value',
              ':value_count' => $value_count
            )
          );
        }
    }
}

```

Good luck!
> 0 votes

---
Tags: database, views
---


# Question
Title: How do I programmatically render a form, other than the default form?
In a preprocess function we can use this code to render the default form.

```
$default_form = \Drupal::config('contact.settings')->get('default_form');
$entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

$message = \Drupal::entityManager()
   ->getStorage('contact_message')
   ->create(array('contact_form' => $entity->id(),
));

$form = \Drupal::service('entity.form_builder')->getForm($message);

```

How do we render another form? I have tried `$my_form = \Drupal::config('contact.settings')->get('my_form_id');` without success.

# Answer
> 1 votes
A contact form?

your\_form\_id is the form, you don't have to load a setting for that. If you know what contact form you want to display, just replace $default\_form with your form\_id and it should work.

---
Tags: forms, 8
---