# Question
Title: Block Email Addresses During Registration Using Rules
I am trying to setup a rule to block all temporary email forwarding domains from being registered on a Drupal site. I have seen the user restrictions module but I would like to do this using rules.

**I'm curious if this is the most efficient way to setup the rule? I'm not sure if account:mail should be used since the account does not exist yet?**

Here is what I have so far:

```
{ "rules_email_domain_name_validation" : {
    "LABEL" : "Email Domain Name Validation",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "email", "validation" ],
    "REQUIRES" : [ "rules", "user_restrictions" ],
    "ON" : { "user_presave" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "account:mail" ],
          "match" : "(@0815.ru|@0clickemail.com|@0-mail.com|@0wnd.net|@0wnd.org|@10minutemail.com|@20minutemail.com|@2prong.com|@30minutemail.com|@33mail.com|@3d-painting.com|@4warding.com|@4warding.net|@4warding.org|@60minutemail.com|@675hosting.com|@675hosting.net|@675hosting.org|@6ip.us|@6url.com|@75hosting.com|@75hosting.net|@75hosting.org|@7tags.com|@9ox.net|@a-bc.net|@afrobacon.com|@ajaxapp.net|@ama-trade.de|@ama-trans.de|@amilegit.com|@amiri.net|@amiriindustries.com|@anonbox.net|@anonymbox.com|@antichef.com|@antichef.net|@antispam.de|@azmeil.tk|@baxomale.ht.cx|@beefmilk.com|@big-post.com|@binkmail.com|@bio-muesli.net|@bobmail.info|@bodhi.lawlita.com|@bofthew.com|@brefmail.com|@brennendesreich.de|@broadbandninja.com|@bsnow.net|@bugmenot|@bugmenot.com|@bumpymail.com|@bund.us|@casualdx.com|@centermail.com|@centermail.net|@chogmail.com|@choicemail1.com|@cool.fr.nf|@correo.blogos.net|@cosmorph.com|@courriel.fr.nf|@courrieltemporaire.com|@crazymailing.com|@cubiclink.com|@curryworld.de|@cust.in|@dacoolest.com|@dandikmail.com|@dayrep.com|@deadaddress.com|@deadspam.com|@despam.it|@despammed.com|@devnullmail.com|@dfgh.net|@digitalsanctuary.com|@discardmail.com|@discardmail.de|@disposableaddress.com|@disposeamail.com|@disposemail.com|@dispostable.com|@dm.w3internet.co.uk|@dm.w3internet.co.ukexample.com|@dodgeit.com|@dodgit.com|@dodgit.org|@doiea.com|@donemail.ru|@dontreg.com|@dontsendmespam.de|@drdrb.com|@drdrb.net|@dropcake.de|@dumpandjunk.com|@dump-email.info|@dumpmail.de|@dumpyemail.com|@e4ward.com|@email60.com|@emaildienst.de|@emailias.com|@emailigo.de|@emailinfive.com|@emailmiser.com|@emailsensei.com|@emailtemporario.com.br|@emailto.de|@emailwarden.com|@emailx.at.hm|@emailxfer.com|@emeil.ir|@emz.net|@enterto.com|@ephemail.net|@e-postkasten.com|@e-postkasten.de|@e-postkasten.eu|@e-postkasten.info|@etranquil.com|@etranquil.net|@etranquil.org|@evopo.com|@explodemail.com|@faecesmail.me|@fakeinbox.com|@fakeinformation.com|@falseaddress.com|@fastacura.com|@fastchevy.com|@fastchrysler.com|@fastkawasaki.com|@fastmazda.com|@fastmitsubishi.com|@fastnissan.com|@fastsubaru.com|@fastsuzuki.com|@fasttoyota.com|@fastyamaha.com|@filzmail.com|@fizmail.com|@fly-ts.de|@fr33mail.info|@frapmail.com|@front14.org|@fux0ringduh.com|@garliclife.com|@get1mail.com|@get2mail.fr|@getonemail.com|@getonemail.net|@ghosttexter.de|@girlsundertheinfluence.com|@gishpuppy.com|@gowikibooks.com|@gowikicampus.com|@gowikicars.com|@gowikifilms.com|@gowikigames.com|@gowikimusic.com|@gowikinetwork.com|@gowikitravel.com|@gowikitv.com|@great-host.in|@greensloth.com|@grr.la|@gsrv.co.uk|@guerillamail.biz|@guerillamail.com|@guerillamail.net|@guerillamail.org|@guerrillamail.biz|@guerrillamail.com|@guerrillamail.de|@guerrillamail.net|@guerrillamail.org|@guerrillamailblock.com|@h.mintemail.com|@h8s.org|@haltospam.com|@hatespam.org|@hidemail.de|@hochsitze.com|@hotpop.com|@hulapla.de|@ieatspam.eu|@ieatspam.info|@ieh-mail.de|@ihateyoualot.info|@iheartspam.org|@imails.info|@inbax.tk|@inboxalias.com|@inboxclean.com|@inboxclean.org|@incognitomail.com|@incognitomail.net|@incognitomail.org|@insorg-mail.info|@ipoo.org|@irish2me.com|@iwi.net|@jetable.com|@jetable.fr.nf|@jetable.net|@jetable.org|@jnxjn.com|@junk1e.com|@kasmail.com|@kaspop.com|@keepmymail.com|@killmail.com|@killmail.net|@kir.ch.tc|@klassmaster.com|@klassmaster.net|@klzlk.com|@koszmail.pl|@kulturbetrieb.info|@kurzepost.de|@lags.us|@letthemeatspam.com|@lhsdv.com|@lifebyfood.com|@link2mail.net|@litedrop.com|@lol.ovpn.to|@lookugly.com|@lopl.co.cc|@lortemail.dk|@lr78.com|@m4ilweb.info|@maboard.com|@mail.by|@mail.mezimages.net|@mail2rss.org|@mail333.com|@mail-4server.com|@mail4trash.com|@mailbidon.com|@mailblocks.com|@mailcatch.com|@maildrop.cc|@maileater.com|@mailexpire.com|@mailfa.tk|@mailfreeonline.com|@mailimate.com|@mailin8r.com|@mailinater.com|@mailinator.com|@mailinator.net|@mailinator2.com|@mailincubator.com|@mailismagic.com|@mailme.ir|@mailme.lv|@mailmetrash.com|@mailmoat.com|@mailnator.com|@mailnesia.com|@mailnull.com|@mailshell.com|@mailsiphon.com|@mailslite.com|@mailtemp.info|@mail-temporaire.fr|@mailzilla.com|@mailzilla.org|@malahov.de|@mbx.cc|@mega.zik.dj|@meinspamschutz.de|@meltmail.com|@messagebeamer.de|@mierdamail.com|@mintemail.com|@moburl.com|@moncourrier.fr.nf|@monemail.fr.nf|@monmail.fr.nf|@msa.minsmail.com|@mt2009.com|@mt2014.com|@mx0.wwwnew.eu|@mycleaninbox.net|@mymailoasis.com|@mypartyclip.de|@myphantomemail.com|@myspaceinc.com|@myspaceinc.net|@myspaceinc.org|@myspacepimpedup.com|@myspamless.com|@mytrashmail.com|@neomailbox.com|@nepwk.com|@nervmich.net|@nervtmich.net|@netmails.com|@netmails.net|@netzidiot.de|@neverbox.com|@nnot.net|@nobulk.com|@noclickemail.com|@nogmailspam.info|@nomail.xl.cx|@nomail2me.com|@nomorespamemails.com|@no-spam.ws|@nospam.ze.tc|@nospam4.us|@nospamfor.us|@nospamthanks.info|@notmailinator.com|@nowmymail.com|@nurfuerspam.de|@nus.edu.sg|@nwldx.com|@objectmail.com|@obobbo.com|@oneoffemail.com|@onewaymail.com|@online.ms|@oopi.org|@opayq.com|@ordinaryamerican.net|@otherinbox.com|@ourklips.com|@outlawspam.com|@ovpn.to|@owlpic.com|@pancakemail.com|@pimpedupmyspace.com|@pjjkp.com|@politikerclub.de|@poofy.org|@pookmail.com|@privacy.net|@proxymail.eu|@prtnx.com|@punkass.com|@putthisinyourspamdatabase.com|@qq.com|@quickinbox.com|@rcpt.at|@recode.me|@recursor.net|@regbypass.com|@regbypass.comsafe-mail.net|@rejectmail.com|@rklips.com|@rmqkr.net|@rppkn.com|@rtrtr.com|@s0ny.net|@safe-mail.net|@safersignup.de|@safetymail.info|@safetypost.de|@sandelf.de|@saynotospams.com|@selfdestructingmail.com|@sendspamhere.com|@sharklasers.com|@shiftmail.com|@shitmail.me|@shortmail.net|@sibmail.com|@skeefmail.com|@sky-ts.de|@slaskpost.se|@slopsbox.com|@smellfear.com|@snakemail.com|@sneakemail.com|@sofimail.com|@sofort-mail.de|@sogetthis.com|@soodonims.com|@spam.la|@spam.su|@spam4.me|@spamavert.com|@spambob.com|@spambob.net|@spambob.org|@spambog.com|@spambog.de|@spambog.net|@spambog.ru|@spambox.info|@spambox.irishspringrealty.com|@spambox.us|@spamcannon.com|@spamcannon.net|@spamcero.com|@spamcon.org|@spamcorptastic.com|@spamcowboy.com|@spamcowboy.net|@spamcowboy.org|@spamday.com|@spamex.com|@spamfree24.com|@spamfree24.de|@spamfree24.eu|@spamfree24.info|@spamfree24.net|@spamfree24.org|@spamgourmet.com|@spamgourmet.net|@spamgourmet.org|@spamherelots.com|@spamhereplease.com|@spamhole.com|@spamify.com|@spaminator.de|@spamkill.info|@spaml.com|@spaml.de|@spammotel.com|@spamobox.com|@spamoff.de|@spamslicer.com|@spamspot.com|@spamthis.co.uk|@spamthisplease.com|@spamtrail.com|@speed.1s.fr|@supergreatmail.com|@supermailer.jp|@suremail.info|@tagyourself.com|@teewars.org|@teleworm.com|@teleworm.us|@tempalias.com|@tempemail.biz|@tempemail.com|@tempe-mail.com|@tempemail.net|@tempinbox.co.uk|@tempinbox.com|@tempmail.it|@tempmail2.com|@tempomail.fr|@temporarily.de|@temporarioemail.com.br|@temporaryemail.net|@temporaryforwarding.com|@temporaryinbox.com|@thanksnospam.info|@thankyou2010.com|@thisisnotmyrealemail.com|@throwawayemailaddress.com|@tilien.com|@tmailinator.com|@toiea.com|@tradermail.info|@trash2009.com|@trash-amil.com|@trashemail.de|@trashmail.at|@trash-mail.at|@trashmail.com|@trash-mail.com|@trashmail.de|@trash-mail.de|@trashmail.me|@trashmail.net|@trashmail.org|@trashmail.ws|@trashmailer.com|@trashymail.com|@trashymail.net|@trillianpro.com|@tryalert.com|@turual.com|@twinmail.de|@tyldd.com|@uggsrock.com|@upliftnow.com|@uplipht.com|@username.e4ward.com|@username.otherinbox.com|@venompen.com|@veryrealemail.com|@veryrealmail.com|@viditag.com|@viewcastmedia.com|@viewcastmedia.net|@viewcastmedia.org|@webm4il.info|@wegwerfadresse.de|@wegwerfemail.de|@wegwerfmail.de|@wegwerfmail.net|@wegwerfmail.org|@wetrainbayarea.com|@wetrainbayarea.org|@wh4f.org|@whatpaas.com|@whyspam.me|@willselfdestruct.com|@winemaven.info|@wronghead.com|@wuzup.net|@wuzupmail.net|@wwwnew.eu|@xagloo.com|@xemaps.com|@xents.com|@xmaily.com|@xoxy.net|@yep.it|@yogamaven.com|@yopmail.com|@yopmail.fr|@yopmail.net|@ypmail.webarnak.fr.eu.org|@yuurok.com|@zehnminutenmail.de|@zippymail.info|@zoaxe.com|@zoemail.org|@trbvm.com|@20mail.it|@20mail.eu)",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "user_restrictions_block_mail" : { "account" : [ "account" ] } } ]
  }
}

```

# Answer
If I were to do this task I would create a custom hook\_form\_validate and then add it to the registration form with hook\_form\_alter

Then in your validate function you can do your custom php in there to check if the email address is what you want. If it's not you can use form\_set\_error to add an error to the form and that way you can provide a custom message to the user too
> 0 votes

# Answer
Drupal has a feature that allows you to either completely block or moderate all user registrations by adopting one of them :

1. Core approval features
2. E-mail verification
3. Block certain user details
4. Captchas
5. Honeypots / Secret form fields
6. Block by location
7. Secret codes
8. 3rd party spam tools
9. Delayed roles
10. Warning message

More Details
> 0 votes

---
Tags: users, rules
---


# Question
Title: How to trigger a Rules action based on which content pane of a panel is used?
I have a page with a path like `www.example.com/newsroom`. On this page nodes are displayed with help of **2 different views**:

1. View 1 : contains voted nodes by user.
2. View 2 : contains not voted nodes by user.

The 2 views are **content panes** and `www.example.com/newsroom` is a panel page. So there is no difference in the path of both views, and the user can see both views together.

I am using the Rules module to perform some action when vote is cast on any of node. And using Rules one can check the path from where a user performs an action on a node, simply by using the token `[site:current-page:url]`. But in my case that is `www.example.com/newsroom` (no matter where the vote is related to).

Is there any way that I can differentiate if a node on that page is voted from via View 1 or View 2? As `[site:current-page:url]` returns path `www.example.com/newsroom` ... Based on which view it is, I want Rules to perform different actions. So how to check in Rules if the node being voted on is from View 1 or View 2?

I do have different classes of both views, but I'm not sure how to check those with Rules.

Any suggestions?

# Answer
Have a look at the Rules panes module. Some details about it (from its project page):

> Rules Panes allow embedding Rules components as content panes in Panels (or so).
>
> By default any parameters for the component are entered manually by the end user, but they can also be pre-populated with CTools contexts on the page (which will also hide the form input).

So if you can find a way to transform your "*... rules to perform some action ...*" in a Rules component, you should be good to go.

Some pointers to some more docu/demos about it (also mentioned on its project page):
> 2 votes

---
Tags: views, rules
---


# Question
Title: How to change bean's block view mode programmatically?
I have created a block entity using bean module.

It has three image fields. Image1, Image2 and Image3.

I want to show only one image depending upon current time. I have three time values. For this I have created 3 view modes each for one time value.

Now I'm stuck that how will change the view mode based on time value programmatically.

I have used the following code.

```
function glue_site_block_view_alter(&$data, $block) {
  if ($timevalue1 == $value1) {
    $data['content']['bean']['block_delta']['#view_mode'] = 'view_mode1'
}

```

# Answer
You can use hook\_entity\_view\_mode\_alter()

```
function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
    if ($timevalue1 == $value1) {
      $view_mode = 'view_mode1';
    } elseif {
      .......
    }
}

```
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How to build a user authentication workflow with AngularJS using RESTful module?
I'm building a single page app with AngularJS and Drupal as the backend. I'm using the RESTful module. However, I do not have much to go on to build a user authentication workflow.

There are several techniques to authenticate users with a SPA. For example, storing session information in a cookie or in a token. In order to keep a persistent authentication with a token, AngularJS stores the token in local storage. I've been reading that this causes security risks because other scripts are able to access local storage.

Also, RESTful comes with a token authentication module which stores tokens on the server.

The first question is which form of persistent authentication to use? Do I have to completely make the SPA headless Drupal? If the app is headless, using token authentication, do I have to completely remove all the out of box user authentication workflow, for example, resetting a user's password, from the app? Is there a hybrid solution? If the information is being consumed and altered by mobile apps and other non standard means, is using cookie authentication out of the question? If that is the case, on a desktop app, how do I prevent users from accessing user URIs? Basically, I have no clue what is going on and there isn't much information about secure solutions.

# Answer
> -1 votes
Do headless means no layout and block display at all ? i believe u can leave CAS drupal module do the job ( and a connection menu )

---
Tags: 8, services, users
---


# Question
Title: How to list all nodes referencing a node in a tree view
I have a content type **Company** with an entity reference field which can be referencing a content of the same type (Company), this field is also set to have multiple values.

What I want to achieve is to list all the companies referencing a company, as a recursive tree (may be only first 2-3 levels).

For Example I have 5 Companies: CompanyA, CompanyB, CompanyC, CompanyD, CompanyE. Each of them referencing one or more companies. Let's say:

**CompanyA:**

* CompanyC
* CompanyE

**CompanyB:**

* CompanyA
* CompanyD

**CompanyC:**

* CompanyA

**CompanyD:**

* CompanyB
* CompanyC
* CompanyE

**CompanyE:**

* CompanyB

If am viewing the CompanyA, I would like to have a list like:

**Companies Referencing CompanyA:**

* CompanyB
    + CompanyD
    + CompanyE
* CompanyC
    + CompanyA
    + CompanyD

I hope I was clear enough to explain my goal.

# Answer
I have achieved this with Views and Views Field View.

1. I have added a View, showing Content of type Company and created a Block with display format HTML List of fields.
2. Added a relationship **Entity Reference: Referenced Entity** `Content entity referenced from field_reference_company`
3. Added a contextual filter **Content: Nid** with the relationship I've just added.
4. Provided a default value **Content ID from URL** to the contextual filter.
5. Added the fields:
    * **Content: Nid**, excluded it from display.
    * **Content: Title**
    * **Global: View** and selected the view itself with Master Display, set as Contextual filters: `[!nid]`

That's it.
> 2 votes

# Answer
You can achieve this using **Relationships** and **Format-\>Settings-\>Grouping Field**.

1. Create a relationship with **Content using field\_reference**, give it the admin title *referrer1*.
2. Create a relationship with **Content using field\_reference**, give it the admin title *referrer2*, and specify that it uses the relationship *referrer1*.
3. Add a contextual filter for **Node id** with **Provide default value** and **Content ID from URL**.
4. Add 2 fields to the view: **Content: title** using *referrer1* and **Content:title** using *referrer2*.
5. Go to **Format-\>Settings** and specify **Grouping field nr 1** as *Referrer1: content title*.
6. Edit the field *Referrer1: content title* and tick **Exclude form display**.

When you enter a node id of, for instance, *Company E* in the **Preview with contextual filters** box, you should see preview results like:

```
A
 -B
 -C
D
 -B

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Get yesterday's content with contextual filter in views block
I have a view and I try to show only yesterday's content. I add a contextual filter "Content: Created date". If I select "Current Date" from "Provide default value" its works perfectly. But I select "PHP Code" its not working whatever I write. I try a lot of format.

In this topic there is a solution but its not work either;

```
return date("d", strtotime("-1 day"));

```

How can I do that?

# Answer
> 0 votes
Try this one

```
Content: Post date (>= -1days)

```

Instead of this

```
return date("d", strtotime("-1 day"));

```

# Answer
> 0 votes
Do you really need a contextual filter, or did you read you need one?

It can be done with a regular Views filter on the Content: Post date. (I am not sure if this requires the date module).

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


# Question
Title: Aquia Desktop - How to import a MySql database that is too big
I am using Aquia Dev Desktop. I have a MySql database dump that is too big to upload into Aquia Dev Desktop. What are my options? I am using a Mac, so would appreciate Mac based options

**Steps I have tried:**

I think the problem is the cache table. If I could empty (not delete) this table, I should be able to upload it into Acquia Dev Desktop.

1) Downloading MySQLWork Bench to delete the cache table. MySQl Work Bench has a Data Import option. However, it requires the password of the Acquia Dev Desktop, which I don't have.

2) Downloading Sequel-Pro to delete the cache table Again this requires the username/password of the database.

# Answer
Unfortunately, it doesn't seem possible to fix this when using Aquia Desktop as the username/password for Aquia Desktop are unknown.

In future, the best option is to install the Back up and Migrate module: https://www.drupal.org/project/backup\_migrate

This will automatically clear all the cache tables each time when backing up. You can, of course, empty the cache when using PHPmyAdmin, but this module is more foolproof as you don't have to worry about forgetting.
> 0 votes

# Answer
1. configure Mysql my.ini

change the value of myisam\_sort\_buffer\_size from 8M to whatever your sql size is.

I will say if your file size is 100 change the value to myisam\_sort\_buffer\_size = 156M.

2. Restart your mysql.
3. using terminal navigate to mysql bin directory
4. run the command: `mysql -u username -p yourdatabasename <yourmysqldatabasefile`

enter the password for the user, if there is no password the user than just press enter.
> 1 votes

---
Tags: database
---


title: Programmaticaly hide post information

text:
# Question
Title: Programmaticaly hide post information
I would like to programmatically hide the post information.

I don't know where the author name and the creation date is stored in the database, but I would like to hide them.

How can I achieve this?

# Answer
> 4 votes
i find....

```
variable_set('node_submitted_'.$my_content_type, false);

```

# Answer
> 3 votes
You can use an implementation of `hook_preprocess_HOOK()` to set `$display_submitted` variables used in (good practices following) node templates to control whether or not to display the information.

```
function XYZ_preprocess_node() {
  $node = $variables['node'];
  $variables['display_submitted'] &= ($node->type != 'content-type')
}

```

Where `XYZ` is the name of a custon module or theme, and`content-type` is the machine name of the content you want to hide the publishing information for.

# Answer
> 2 votes
Try deleting the following lines in your theme `node.tpl.php` template:

```
<?php if ($display_submitted): ?>
    <div class="meta submitted">
      <?php print $user_picture; ?>
      <?php print $submitted; ?>
    </div>
<?php endif; ?>

```

---
Tags: nodes
---


# Question
Title: fastest between hook_js vs hook_menu to get JSON via REST
I'm trying to figure out if in my case it makes sense to use the High-performance JavaScript callback handler module. Between js/MODULE/example.json (`hook_js()`) and example.json (`hook_menu()`), the difference of time is not huge, but I think `hook_js()` is faster.

In a case I'm not using any Drupal function, variable or session, and I'm only calling another server with REST. Can I bypass all the bootstrap functions, or do I have to use the first layer (`DRUPAL_BOOTSTRAP_CONFIGURATION`)?

What would be the faster solution?

```
function MODULE_js(){
    return array(
      // Example URL is /js/MODULE/example.json
      'example.json' => array(
        'callback' => 'my_json',
        'includes' => array('unicode', 'locale', 'language'),
        'dependencies' => array(),
        'bootstrap' => DRUPAL_BOOTSTRAP_CONFIGURATION,
        'access callback' => 'access_callback',
        'access arguments' => array(),
        'page arguments' => array(),
        'skip_hook_init' => TRUE,
        'delivery callback' => 'drupal_json_output',
      ),
    );
}
function access_callback (){
    return true;
}

function MODULE_menu()
    $items['example.json'] = array(
        'type' => MENU_CALLBACK,
        'page callback' => 'my_json',
        'page arguments' => array(),
        'access callback' => true,
        'delivery callback' => 'drupal_json_output',
    );
return $items;
}

function my_json(){
    //call with curl/rest and return a json
    return 'json';
}

```

# Answer
Actually, as the project documentation says, you should use http://example.com/js.php?q=js/mymodule/callback instead of http://example.com/index.php?q=js/mymodule/callback, and basing on the test reported from the maintainer, the previous is faster than the latter (59.371 ms per request versus 446.846 ms per request). Since you are waiting a reply from another server, probably you would not notice that difference too.

For you second question, if you are going to use the *High-performance JavaScript callback handler* module in the way shown in the documentation, js.php bootstraps Drupal at `DRUPAL_BOOTSTRAP_DATABASE` level. In any case, if you are not using any Drupal function nor the session, and you are using just plain PHP functions or classes, then you don't need to bootstrap Drupal at all. Keep in mind that this means you cannot use any function implemented by Drupal modules too.
> 2 votes

---
Tags: 7
---


title: Use route annotation

text:
# Question
Title: Use route annotation
I'm trying to create my first module. I'd like to know if I can use annotation route like Symfony instead of separated files.

For example, can I use the second snippet instead of the first one?

```
hello_world_settings:
  path:  '/hello/world'
  defaults:
    _content:  '\Drupal\hello_world\Controller\HelloWorldController::myCallbackMethod'
  title: 'Hello World'
  requirements:
    _permission: 'access content'

```

```
/**
 * @Route("/hello/world",name="hello_world")
 * @Method({"GET"})
 */
 public function myCallbackMethod() {

```

# Answer
> 6 votes
AFAIK, Drupal doesn't support any of the Symfony route annotations. The code is present in vendor/, but not used by core.

The closest thing is the concept of Entity links, which are part of the Doctrine annotations on the entity class. These link names can be used in the `::toUrl()` method to generate the canonical link for an entity, the edit link, etc. However, the routes still need to be defined in the routing.yml file.

---
Tags: 8, routes
---


# Question
Title: Is there any File Manager Module for drupal 7
I need a module as like as File manager. We need to view, edit, modify and delete the files and also with permission option.

# Answer
> 3 votes
There are many modules available for managing files.

Reference URL : https://drupal.org/module-categories/file-management

Try this module : https://drupal.org/project/elfinder i think it suits your requirement.

# Answer
> 0 votes
I think the most robust file manager is Plupload. It does indeed have permissions that can be set. You can add functionality to it such as unzipping and selecting multiple files.

https://www.drupal.org/project/plupload

---
Tags: 7, files
---


# Question
Title: When should I be using database transactions?
I know this is a question that depends on the details of a specific situation, and a rather open-ended question at that. But, nevertheless, are there any good guidelines out there about when database transactions ought to be used in the course of everyday module development? I've begun to worry that I should be doing transactions a lot more than I currently am (which is to say almost not at all), but it would obviously be wrong to go off on a frenzy of wrapping transactions around everything. Any thoughts out there?

# Answer
When you're running multiple queries in the same function/context that change data in the db, and the failure of any one of those queries would leave your data in an inconsistent state...that's when you should be using a transaction.

To the best of my knowledge there's no point in wrapping single queries in a transaction (it seems redundant. The query will either fail or succeed and you can catch those on an individual basis). Even if you're running multiple queries that *won't* leave data in an inconsistent state should one of them fail, I would say the same thing goes. You can catch errors for each query individually, and fail/continue gracefully.
> 4 votes

# Answer
Transactions are also useful to speed up inserts. When doing multiple inserts the difference could be dramatic. Anyhow you need to measure it to be sure if it works for your code.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Similar Products don´t get grouped on review Page
When adding multiply quantities of the same product they don´t get grouped but splitted to each line on the overview checkout pane.

-Example-

Instead of:

> Product: PLAYSTATION QTY 3

It shows:

> Product: PLAYSTATION QTY 1
>
> Product: PLAYSTATION QTY 1
>
> Product: PLAYSTATION QTY 1

I know this is a view, I tried to configure it to grouping, but with no change. Even this module did not help: https://www.drupal.org/project/views\_aggregator

What can I do to have all similar products grouped and sum quantity?

# Answer
> 2 votes
You have to go to `admin/structure/types/manage/YOUR_DISPLAY_TYPE/display`, search for the *product field / add\_to\_cart form* and set it to **combine like items : enabled**

That's it.

---
Tags: commerce
---


title: Does Drupal work with PHP 7?

text:
# Question
Title: Does Drupal work with PHP 7?
I have working development project of Drupal 7 using PHP 5.x. I changed the PHP version to PHP 7 using nginx webserver. It does not work and I have got the following error message:

```
 Fatal error: Uncaught Error: Undefined class constant
 'MYSQL_ATTR_USE_BUFFERED_QUERY' in
 C:\xampp-2\htdocs\d738\includes\database\mysql\database.inc:46 Stack
 trace: #0 C:\xampp-2\htdocs\d738\includes\database\database.inc(1689):
 DatabaseConnection_mysql->__construct(Array) #1
 C:\xampp-2\htdocs\d738\includes\database\database.inc(1479):
 Database::openConnection('default', 'default') #2
 C:\xampp-2\htdocs\d738\includes\database\database.inc(2570):
 Database::getConnection() #3
 C:\xampp-2\htdocs\d738\includes\cache.inc(348):
 db_escape_table('cache_bootstrap') #4
 C:\xampp-2\htdocs\d738\includes\cache.inc(329):
 DrupalDatabaseCache->getMultiple(Array) #5
 C:\xampp-2\htdocs\d738\includes\cache.inc(56):
 DrupalDatabaseCache->get('module_implemen...') #6
 C:\xampp-2\htdocs\d738\includes\module.inc(723):
 cache_get('module_implemen...', 'cache_bootstrap') #7
 C:\xampp-2\htdocs\d738\includes\module.inc(892):
 module_implements('system_theme_in...') #8
 C:\xampp-2\htdocs\d738\modules\system\system.module(2502):
 module_invoke_all('system_theme in
 C:\xampp-2\htdocs\d738\includes\database\mysql\database.inc on line 46

```

This error means that Drupal 7 is using obsoleted MySQL functions and it is not support with PHP any more!

However, I don't think Drupal still uses this obsoleted PHP extension. So I have a strange error as I think!

# Answer
> 4 votes
Search and edit your **php.ini** file, you must search this line:

```
;extension=php_pdo_mysql.dll

```

remove the `;` and save the file, then restart your webserver.

---
Tags: 7
---


# Question
Title: Why can only admin user access the print version of a view?
I have installed the Printer, email and PDF versions module and I have a view named *XXX* and the admin can access to the print version of the *XXX* view with the path `/printpdf/XXX`.

If I change the user to other user without admin permission, I get this message

> Access denied
>
> You are not authorized to access this page.

I don't know how to allow non admin users to access the print version of a view.

I set this permissions for non admin users like so:

* Bypass views access control.
* Access the printer-friendly page.

But such user still does not have access to the print version of a view.

Is there a way to achieve the access with non admin users?

# Answer
# PDF version (print\_pdf)

Head over to your "permissions" page, located at `admin/people/permissions`. Then in the field near the top, which says "Filter list", just type "pdf".

That'll give you a narrowed down list of all permissions that have "pdf" in their description. One of them is "Access the PDF version", which is the permission you want to fine tune to fit your requirements. And each of them is preceded by a line, in bold, which shows the name of the module the permission is related to.

The "narrowed down" list in my case shows only 2 permissions (the 2nd one is because I have 1 other module enabled that also has a PDF-related permission). So hard to not catch the one I should be looking for, right?

# Printer friendly pages (print) and send by eMail (print\_mail)

`print_pdf` is one of the sub-modules of the Printer, email and PDF versions module. Other submodules of it are `print` (= Printer friendly pages) and `print_mail` (send by eMail). Some more details about those sub-modules:

* The `print` submodule has a similar permission, which is "**Access the printer-friendly page**" (= View the printer-friendly pages and the links to them in the original pages).
* The `print_mail` submodule has a similar permission, which is "**Send by email**" (= Provides the ability to send pages by email and the links to them in the original pages). **Attention**: if you want to use this eMail feature, make sure you do not (repeat NOT) allow that for anonymous users. Because if you do allow that, you open up a huge spamming opportunity for your anonymous users ... imagine a spammer using it enters an eMail Id of somebody that the spammer wants to spam ... typically with a message content that is 100% spam, instead of what you'd expect (something like "hey, have a look at this interesting URL" ... But: the message will arrive with something like "from = an eMail id related to your website".

**PS**: Permission "Bypass views access control" should be used carefully (do not grant it to anybody unless you really have a need for it ... in this case it does not seem to be needed to solve your access issue).
> 2 votes

# Answer
I have a help at this moment from a friend. The solution is simple, just search the permission *Access the PDF version* in admin/people/permissions and set the permission to the users. The problem was that the permission page is too long and if you search for *print* you will never find *Access the PDF version\` permission*
> 5 votes

---
Tags: views
---


# Question
Title: In a managed_file upload field, how do I prevent an overflow with long file names?
I have a form using the field type of `managed_upload`. Things are working fine accept when the file name is long.

Given the snippet of code, below. Might there be a way to override CSS or inject any CSS to keep the `fieldset` or this `span` from overrunning the `sidebar_second` region?

```
  $form['file_fs'] = array(
    '#type' => 'fieldset',
    '#title' => t('Files'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  $form['file_fs']['file'] = [
    '#title' => t('Documents'),
    '#type' => 'managed_file', ,
    '#upload_location' => 'private://',

  ];

```

# Answer
> 0 votes
I would suggest adding a class to the fieldset and adding a class to the css file of your theme.

Add something like this to the fieldset.

`'#attributes' => array('class' => array('my-fieldset'));`

And then something like this to your css file

`.my-fieldset {max-width: 100%;}`

---
Tags: 7, forms, theming
---


# Question
Title: Theme suggestions not working for custom templates
I have a custom theme hook that I have a tpl for but my theme suggestions are not working. It appears that they are not even being looked for. I am guessing that I am missing something.

Code:

```
function MYMODULE_theme() {
  module_load_include('inc', 'mymodule', 'theme/mymodule.theme');
  return mymodule_theme_theme();
}

function MYMODULE_theme_theme() {
  $path = drupal_get_path('module', 'MYMODULE') . '/theme';

  return array(
    'mymodule_theme' => array(
      'variables' => array('module' => NULL, 'key' => NULL, 'body' => NULL),
      'template' => 'mymodule-theme',
      'pattern' => 'mymodule_theme__',
      'file' => 'mymodule.theme.inc',
      'mail theme' => TRUE,
      'path' => $path,
    )
  );
}

function MYMODULE_preprocess_mymodule_theme(&$vars) {
  $module = $variables['module'] ? $variables['module'] : basename(__FILE__, '.theme.inc');
  $functions = array();
  $variables['theme_hook_suggestions'][] = $functions[] = 'MYMODULE_theme__' . $module;
  if (isset($variables['key'])) {
  $variables['theme_hook_suggestions'][] = $functions[] = 'MYMODULE_theme__' . $module . '__' . $variables['key'];
  }
  foreach ($functions as $function) {
    $function = "MYMODULE_preprocess_$function";
    if (function_exists($function)) {
      $function($variables);
    }
  }
}

```

The theme hook suggestions are being applied as the new preprocess function works.

```
function MYMODULE_preprocess_MYMODULE_theme__MODULE__KEY(&$vars) {
  dpm($vars);
}

```

`$vars` gets printed.

However my `MYMODULE-theme--MYMODULE--KEY.tpl.php` is not being called.

The base `MYMODULE-theme.tpl.php` does work. Theme debug output:

```
<!-- THEME DEBUG -->
<!-- CALL: theme('MYMODULE-theme') -->
<!-- FILE NAME SUGGESTIONS:
   * MYMODULE-theme--MYMODULE--KEY.tpl.php
   * MYMODULE-theme--MYMODULE.tpl.php
   x MYMODULE-theme.tpl.php
-->

```

Any ideas?

**EDIT:** I forgot the calls I have tried. Here they are:

```
$output = theme('MYMODULE_theme', array('body' => $body, 'key' => $key));

```

and I even tried:

```
$output = theme(array('MYMODULE_theme', 'MYMODULE_theme__MYMODULE__KEY), array('body' => $body, 'key' => $key));

```

# Answer
Have you tried making the template name and pattern in the hook\_theme implementation uppercase like this:

```
  'template' => 'MYMODULE-theme',
  'pattern' => 'MYMODULE_theme__',

```

You can also try to remove the pattern completely. It doesn't seem to be necessary at least in the example use case.

Preprocess functions for theme suggestions doesn't work in Drupal 7, and that's why you are manually calling them in your preprocess function. They are being added to the array so they are called but they are not in the correct format so that theme system could handle them.
> 0 votes

---
Tags: 7, theming
---


title: New region shows up weird

text:
# Question
Title: New region shows up weird
If you visit http://balancesocialmedia.com/, under the carousel, there are 4 boxes of content; they are block views with col-md-3 as CSS class.

The new region I created is called content\_bottom.

```
regions[content_bottom] = 'Content Bottom'

```

I then put this code in the page--front.tpl.php under content region (near the bottom of this snippet).

```
  <section<?php print $content_column_class; ?>>
  <?php if (!empty($page['highlighted'])): ?>
    <div class="highlighted jumbotron"><?php print render($page['highlighted']); ?></div>
  <?php endif; ?>
  <?php if (!empty($breadcrumb)): print $breadcrumb; endif;?>
  <a id="main-content"></a>
  <?php print render($title_prefix); ?>
  <?php print render($title_suffix); ?>
  <?php print $messages; ?>
  <?php if (!empty($tabs)): ?>
    <?php print render($tabs); ?>
  <?php endif; ?>
  <?php if (!empty($page['help'])): ?>
    <?php print render($page['help']); ?>
  <?php endif; ?>
  <?php if (!empty($action_links)): ?>
    <ul class="action-links"><?php print render($action_links); ?></ul>
  <?php endif; ?>
  <?php print render($page['content']); ?>
  <div class="container">
  <div class="row">
   <?php if ($page['content_bottom']): ?>

    <?php print render($page['content_bottom']); ?>
    </div></div>
   <!-- /.section, /#content bottom -->
<?php endif; ?>
</section>

```

I tried moving the code under the closing section tag, removing the container and row class but the first block view is always renders a bit funny.

Also, I can move the blocks to the content region and shows up as expected. I can't track down what's different between the two regions.

Does anyone see where I'm messing up?

# Answer
> 1 votes
You seem to have CSS that removes the top margin from the first block:

```
.block:first-child h2.block-title, .page-header {
   margin-top: 0;
}

```

You can override this by simply adding this piece of CSS in your CSS file:

```
.region-content-bottom .block h2.block-title {
  margin-top: 21px;
}

```

---
Tags: 7, theming
---


title: payment processing with stripe

text:
# Question
Title: payment processing with stripe
I was just wondering if there was any module that implements the stripe api for payment processing. I'm using drupal 7. Stripe is a new payment processor that people say is better than paypal so I'd like to try them out. they're at **stripe dot com**

# Answer
> 1 votes
There's no ready module for this, since stripe.com has https://stripe.com/api so it should be made as custom module for payment

# Answer
> 0 votes
Yes! Check out the Webform Stripe module which provides a lightweight, powerful integration between Webform and Stripe. From the project page:

> Webform Stripe adds super simple Stripe integration to Webforms, so that submissions can be "purchased".
>
> With this, you can use webforms for event registrations, online donations, or even for simple products where you need to gather additional information from a user.
>
> It uses Stripe Checkout to collect payments as the form is submitted.
>
> There are lots of ways to collect payment for Webforms. Most of them are difficult or require lots of modules. This is super simple solution. If you require more complex workflows or integration with your store, consider the myriad of options available for Commerce, Ubercart, or Payment.

---
Tags: 7, commerce
---


# Question
Title: How to add the image url in the head tag
Do youknow how to add the image url to the head tag?

This is what I've tried so far

Example

```
<head>
     <meta property="og:image" content="  {{ file_create_url(node.field_image.0.entity.uri.value) }}        "/>
     <meta property="og:image:secure_url" content="  {{  file_create_url(node.field_image.0.entity.uri.value)  }} " />
</head>

```

Thanks!

# Answer
Or possibly a better solution - use the metatag module and you can customise this through the CMS globally or for specific pages. "og" stands for Open Graph so you just need to pop your data in the relevant open graph section

https://www.drupal.org/project/metatag
> 1 votes

# Answer
Probably the best place to do this is in a node preprocess function and then attach it for the render array. How it could be:

```
/**
 * Implements hook_preprocess_node().
 */
function themename_preprocess_node(&$variables) {
  // Load the image field values from the node.
  $image_field = $variables['node']->get('field_image')->getValue();
  // Get the first item of the field values.
  $image_field = reset($image_field);
  // Load file by the file id.
  $image = file_load($image_field['target_id']);

  // Create the actual HTML by creating a render array.
  $og_image = [
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => [
      'property' => 'og:image',
      'content' => $image->toUrl(),
    ],
  ];

  $variables['#attached']['html_head'][] = [$og_image, 'og:image'];
}

```
> 0 votes

---
Tags: nodes, media, 8, uri
---


# Question
Title: Using Slick Carousel with Views - How to setup a slideshow with View
I'm trying to setup a slick carousel slideshow. I've created a content type for the images and added a few nodes to the content type with images. I then created a View block...but see no option to format with 'slick carousel'. This article says to choose 'slick carousel' instead of format: unformatted list (but I don't see this option).

The only place I see the ability to choose 'slick carousel' is in the content: image field itself under 'Fields'. But when I choose it there - not surprisingly - it shows no results. If I leave it as the default it shows the images. But, of course, I want not just a block of the images from the nodes but a SLIDESHOW.

Does anyone know how to make this work with Slick Carousel? Thanks.

*Note: I have installed the required libraries and the .min.js file*

# Answer
> 1 votes
Use the Slick views module.

> Slick views adds a new display style to views called **Slick carousel**. Similar to how you select **HTML** List or **Unformatted** List as display styles.

---
Tags: javascript
---


# Question
Title: Preprocess execution is not where my view is
I'm trying to create a preprocess function to my custom view. Template is called as expected but my preprocess is called at beginning of html and left my entire page blank.

If I change to default template (`views_view_unformatted.html.twig`) the execution of `theme_preprocess_views_view_unformatted()` works as expected, right on my view is. But if change to `views_view__custom.html.twig` the execution of `theme_preprocess_views_view__custom()` occur at beginning of html!

This is the normal behavior? Or something is wrong? I just want to create my custom view template and create a preprocess function for it.

# Answer
In Drupal 8 it is possible to have preprocess functions for the theme suggestions.

So let's say if your template for the View is views-view--test-view--block-1.html.twig, you would have following preprocess functions:

* THEMENAME\_preprocess\_views\_view\__test\_view\__block\_1
* THEMENAME\_preprocess\_views\_view\__test\_view
* THEMENAME\_preprocess\_views\_view
> 0 votes

---
Tags: 8, theming
---


title: Don't show submenu

text:
# Question
Title: Don't show submenu
The following code is for menu--main.html.twig; the submenu is not printed in Drupal 8.

```
{# All menu and submenu items #}

{% for item in items %}
{# Menu with submenu #}
{% if item.below %}
{{ item.title }}
{# Menu -> Submenu #}
{% for item in item.below %}
{% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
{% endfor %}
{# Menu without submenu #}
{% else %}
{# Menu - Link #}
{% if item.title == 'Home' %}
{{ item.title }}
{% endif %}
{% if item.title == 'About' %}
{{ item.title }}
{% endif %}
{% if item.title == 'Pages' %}
{{ item.title }}
{% endif %}
{% if item.title == 'Blogs' %}
{{ item.title }}
{% endif %}
{% if item.title == 'Parfolio' %}
{{ item.title }}
{% endif %}
{% if item.title == 'Contact' %}
{{ item.title }}
{% endif %} {% endif %} {% endfor %}

```

# Answer
> 0 votes
The code looks like a recursive function; it follows the menu tree by invoking itself or a separate twig.

Did you copy the code and put it into menu--main.html.twig? Then you have to change the include statement with the correct path to invoke the correct twig.

# Answer
> 0 votes
In order to remove the children links from being printed, you have to remove:

```
{# Menu -> Submenu #}
{% for item in item.below %}
  {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
{% endfor %}

```

---
Tags: theming, 8
---


title: Disable/remove javascript

text:
# Question
Title: Disable/remove javascript
does anyone know how to disable a javascript loaded by drupal?

```
<script src="/profiles/ncr/themes/contrib/bootstrap/js/bootstrap.js?ny8c02"></script>

```

I tried the following in the **template.php** file but no luck.

```
function bootstrap_ncr_js_alter(&$javascript) {
    $path = drupal_get_path('module', 'js_theme');
    unset($js[$path . '/bootstrap.js']);
}

```

# Answer
> 0 votes
So it seems like the JavaScript file you are trying to remove is actually coming from a theme. You were also trying to unset array item in non existing variable $js. You could try if this works for you:

```
function bootstrap_ncr_js_alter(&$javascript) {
  $path = drupal_get_path('theme', 'bootstrap');
  unset($javascript[$path . '/js/bootstrap.js']);
}

```

---
Tags: theming, javascript, hooks
---


# Question
Title: Programmatically check if a D8 version exists for all site modules
I am listing all modules used by site on our platform. Given a module name, how could I programmatically check if a Drupal 8 version is available?

# Answer
> 3 votes
The easiest way would be to consume the update feed, e.g.:

http://updates.drupal.org/release-history/module\_filter/8.x

Gives you

```
<error>No release history available for module_filter 8.x.</error>

```

While

http://updates.drupal.org/release-history/views/8.x

gives you

```
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Views</title>
<short_name>views</short_name>
<dc:creator>merlinofchaos</dc:creator>
<type>project_module</type>
<api_version>8.x</api_version>
<project_status>unsupported</project_status>
<link>https://www.drupal.org/project/views</link>
<terms>
<term>
<name>Projects</name>
<value>Modules</value>
</term>
<term>
<name>Maintenance status</name>
<value>Seeking co-maintainer(s)</value>
</term>
<term>
<name>Development status</name>
<value>Under active development</value>
</term>
</terms>
<releases>
<release>
<name>views 8.x-3.x-dev</name>
<version>8.x-3.x-dev</version>
<tag>8.x-3.x</tag>
<version_major>3</version_major>
<version_extra>dev</version_extra>
<status>published</status>
<release_link>https://www.drupal.org/node/1595020</release_link>
<download_link>http://ftp.drupal.org/files/projects/views-8.x-3.x-dev.tar.gz</download_link>
<date>1382152087</date>
<mdhash>b1adfb5f2d048e004fd830754546c8f9</mdhash>
<filesize>491125</filesize>
<files>
<file>
<url>http://ftp.drupal.org/files/projects/views-8.x-3.x-dev.tar.gz</url>
<archive_type>tar.gz</archive_type>
<md5>b1adfb5f2d048e004fd830754546c8f9</md5>
<size>491125</size>
<filedate>1382152087</filedate>
</file>
<file>
<url>http://ftp.drupal.org/files/projects/views-8.x-3.x-dev.zip</url>
<archive_type>zip</archive_type>
<md5>67579f47179eeeadf43b7d7501b9cf81</md5>
<size>816701</size>
<filedate>1382152088</filedate>
</file>
</files>
</release>
</releases>
</project>

```

# Answer
> 3 votes
For non programmatical way.

Download and install the Upgrade Status Module

# Answer
> 1 votes
nothing to be particularly proud about but in case it can help somebody out :

```
 foreach ($list_modules as $name => $modules){

$feed_url="http://updates.drupal.org/release-history/".strtolower($name)."/8.x";
$xml = simplexml_load_file($feed_url);

 $d8='no D8 version';
foreach($xml->children() as $child)
{
    $childname= $child->getName();

    if($childname == "releases")
    {
        $d8='';
        foreach ($child->release as $release){
            $d8.=$release->version.' - ';
        }
        $output.='<a href='.$feed_url.'><div class="versiond8">'.$d8.'</div></a>';
    }
}

if ($d8=='no D8 version')
    $output.='<div class="versiond8">'.$d8.'</div>';

$module_url='https://www.drupal.org/project/'.$name;
$output.='<a href='.$module_url.'><div class="drupal_site">module doc</div></a>';

}

```

# Answer
> 0 votes
While you can programatically check whether a D8 version is nominally available, the reality is much more complex. Sometimes they are available but not working, sometimes they are deprecated in favour of a new module, sometimes in core, other times there is a fully working but unofficial version that a programtic approach would not find.

I see no worthwhile alternative to looking closely at each module.

# Answer
> 0 votes
Simply to track for your own purposes so you can monitor the general state of your site, see http://d8upgrade.org/

I started using their service a while back when you had to send them a list of modules. They now claim to have a way to scan your site and build the list automatically. They also maintain a module database for modules with over 300(?) users.

---
Tags: 8
---


# Question
Title: Bootstrap theme doesn't work on mobile device (but work on computer, even when resize browser to min width)
While on mobile device:

* Main Menu (the default one): On top I see the site name with beside the "toggle navigation" button (which don't respond) and above a vertical list of menu items. And the menu has no more border, background-color, etc...
* Views carousel: I see a vertical list of images id ("1.", "2.", "3.", etc...) and above a vertical list of my images.

# Answer
I tried from another mobile (mine is nexus 4) and the problem doesn't appear.

Finally, I installed the module bootstrap\_library and the problem disappeared.
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: How can I generate a list of PDF Forms based on user input?
I am looking to make a user-friendly "form" for the HR department but am not sure how to do it.

My goal is to display a list of PDF forms based on the type of employee is being hired.

The HR user would be asked to select option that pertain to the type of worker that is being hired (hourly/salary, type of employee, etc.)

Based on what is answered, certain forms will be given to the user to download.

How can I accomplish this task?

# Answer
> 2 votes
It may not be the best way, but an easy way to do this would be to use core's taxonomy module. From the module's docs: "Taxonomy, a powerful core module, gives your sites use of the organizational keywords known in other systems as categories, tags, or metadata. It allows you to connect, relate and classify your website’s content."

In a nutshell, I'd suggest to create a taxonomy vocabulary for your type of workers, and add a term for each (hourly, salary, etc.) and attach a file field to the vocabulary, where you can upload and attach the PDFs for each term. Then on the front end, you can create a view that lists all of the file fields attached to that term.

---
Tags: forms
---


# Question
Title: How to add a percentage column to drupal views?
I use Views Aggregator Plus to calculate sum of a column.

items data
A 20
B 40
C 10
\____________
Total 70
Then I want to add additional column for percentage.

-----------------------------------------
Item Data Percentage
-----------------------------------------
A 20
B 30
C 50
-----------------------------------------
100
----------------------

I know Global:Math expression. But I don't know how to get the sum, the sum field(Total) is not available. Only `[value]`, `[value_1]` and `[value_2]` available for A, B and C respectively.

Is there a way to add a percentage column?
I have seen this question in another page with unclear answer.

# Answer
Use `php_view` module to add column to calculate the percentage

```
$field_one = 50;
$field_two = 350;

$new_column = ($field_one / 100) * $field_two;

```
> 0 votes

---
Tags: views, entities
---


# Question
Title: Include View In Node That References Other Nodes Based On Joined Field
I'm getting a little confused trying to get this one, thought I'd get some help.

I have two content types (`A` and `B`) both with the same list field (`My List`). I want to include a view in content type `A` that finds all nodes of content type `B` with the same `My List` value.

I've looked through Context, Entity Reference (which I didn't really get) and Views Relationships and Contexts but couldn't make much sense of it.

What's the best way to accomplish this?

## **Edit:**

I've added an image of my desired output (from actual site) and the current fields of content type's `A` and `B`.

An important note is that the Views block/whatever showing content type `B` needs to be shown in the **normal node page** of content type `A`.

**I know this isn't the best way to do this, but this feature wasn't planned and the client just wants it to work as fast as possible**

## **Content Types Fields:**

*I've excluded irrelevant fields such as path and meta tags.*

**Content type A:**

```
Title - text
Body - HTML (w/ text inside)
Department - List

```

**Content type B:**

```
Title (name) - text
Description - text
Department - List

```

## **Desired Output:**

# Answer
Create a View to show nodes of Content Type `B`, add a Contextual Filter for your field `My List` and save the view.

Install the Views Field View module and then in the ***Footer*** region of your View of Content Type `A` add the `Global: View (Views field view)` and configure under the ***View settings*** the ***Name*** and ***Display*** of your B View and the token for the ***Contextual filters***.

To use the value of the `My List` field as a token, you must have in the ***Fields*** of your view this field selected.

**Edit** after your comment ("*I'd prefer to keep using the regular node page.*")

You can use the EVA module, it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity, in your case the node of Type A. In the contextual filter of the view you need select the `My List` field in the ***Entity Content Settings*** of the View using a token.

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.
> 2 votes

---
Tags: views, nodes
---


title: Add js conditional in theme.info

text:
# Question
Title: Add js conditional in theme.info
Add JS in themes.info

scripts\[\] = js/style.js

scripts\[\] = js/custom.js

scripts\[\] = js/common.js

But I Want to custom.js and common.js Add Conditionally

custom.js add only Front Page

And

custom.js add all page escape Front Page.

I want to add js only From themes.info File.

# Answer
> 1 votes
You can do it by using this

```
function yourtheme_preprocess_page(&$vars) {
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/your-front-script.js');
  }
}

```

---
Tags: theming
---


# Question
Title: Modal with content depending on opening hours
I need the user to enter opening hours for their helpline in the CMS along with two sets of text, one that will be displayed if the user views it during their opening hours & another which is displayed outside of their opening hours.

This content needs to be displayed in a modal on specified pages when a link is clicked (a 'modal box' is like a JavaScript overlay on the page).

The way I have been trying to approach the problem (taken from a suggestion else where on Stack Exchange) was to use the Office Hours & Colorbox Node modules together. Unfortunately unless I've misunderstood what Colorbox Node does or how it works I cannot get it to open a modal at all, I can't actually get it to do anything.

Below are the steps I've taken to install the Office Hours & the Colorbox Node modules so hopefully someone can spot what I've done wrong. I am more than open to other suggestions to solve this problem though.

Using the two modules mentioned my plan was to create a custom template which would read the current date & time, compare it to what has been entered into the Office Hours module then display the appropriate text from one of two text area fields in the CMS.

1. Created fresh Drupal 7 install
2. Installed Office Hours 7.x-1.4 module (https://www.drupal.org/project/office\_hours)

2a. Installed required module Date api 7.x-2.9 (https://www.drupal.org/project/date)
3. Installed Colorbox node 7.x-3.5 module (https://www.drupal.org/project/colorbox\_node)

3a. Installed required module colorbox 7.x-2.10 (https://www.drupal.org/project/colorbox)

3b. Installed required module Libaries 7.x-2.2 (https://www.drupal.org/project/libraries)
4. Created new content type with the Office Hours field
5. Created new node setting the new office hours
6. Created test page with link to office hours page, link has class of "colorbox-node" which should show a modal?

This is what the link tag currently looks like:

```
<a class="colorbox-node" href="/node/1?width=600&height=600">Test link</a>

```

# Answer
> 0 votes
I've managed to work it out, was a very simple problem.

When I installed the colorbox module (not colorbox node) I just installed the module but I need to copy the colorbox plugin into the Drupal libraries directory as well. Soon as I knew found this out and did it, it has started working.

# Answer
> 0 votes
if you run your site under an url like example.com/dat/fresh/site/, remove the first slash in the href, like:

```
<a class="colorbox-node" href="node/1?width=600&height=600">Test link</a>

```

or change to full path, like:

```
<a class="colorbox-node" href="/dat/fresh/site/node/1?width=600&height=600">Test link</a>

```

---
Tags: 7, javascript
---


title: Apache solr access protected parameters

text:
# Question
Title: Apache solr access protected parameters
I wanted to access the keyword being searched in the Apache Solr. Thus i used the hook\_apachesolr\_process\_results Hook to access the $query variable.
But I am unable to access the keyword as it is inside a SolrBaseQuery **\[params:protected\]** object.
It throws a error saying **Fatal error: Cannot access protected property SolrBaseQuery::$params**
Is there any way of accessing the protected parameters of Apache Solr or is there any other approach to get the keyword being searched.

# Answer
> 0 votes
It's always a good idea to read through the code for a class you're trying to work with.

For example, a quick look through the code yields `SolrBaseQuery::getParams()`, whose responsibility is to ensure accuracy for, and return, the protected `$params` array.

---
Tags: search
---


title: Fieldsets for site builders

text:
# Question
Title: Fieldsets for site builders
In Drupal 7, it's possible to group fields for a content type with fieldsets, vertical tabs and so on.

Where are this options in Drupal 8? I didn't find something in the *Manage fields* or *Manage form display* tab.

# Answer
That functionality is provided by the Field Group module.

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

There is a Drupal 8 version available.
> 3 votes

---
Tags: entities, 8
---


title: Views Grid, Image link to content

text:
# Question
Title: Views Grid, Image link to content
In my content type I have a thumbnail where I put the link to the image I want to embed into a view.

For the fields I have Content: Title \[hidden\] Content: Thumbnail

In views for the Content: Thumbnail I check "ReWrite Results" and add

```
<div class="vid-thumb">
     <img src="http://img.youtube.com/vi/{{ field_thumbnail }}/0.jpg">
</div>
<div class="vid-title">{{ title_1 }}</div>

```

This displays the YouTube thumbnail in my view. The problem I am having is trying to make it so the user can click on the thumbnail to get to the content instead of having to click on the title which I display below.

I know twig can be used in the "Rewrite Results" but I wasn't sure what to call in there to add it to an href tag

```
<a href="{{ ???.??? }}"><img src="blah"></a>

```

# Answer
> 2 votes
You should be able to select the Path as a field as well. Then use that as a replacement token.

```
<a href ="{{ path }}"><img src="blah"></a>.

```

Optionally you can use the title as anchor title or alt attribute, but then you have to make sure to uncheck the "Link to Content" box.

```
<a href ="{{ path }}" title="{{ title }}"><img src="blah" alt="{{ title }}"></a>.

```

---
Tags: views, 8
---


# Question
Title: How to post the node link in social networking if node is published?
I want to post the node link along with its title in social media (Twitter, Facebook, and Google+). Node link should be posted only if the content is published.

I have used the HybridAuth and Facebook OAuth (FBOAuth) module for Twitter, Google+, and Facebook login.

How can I achieve this?

# Answer
> 2 votes
For Facebook and Twitter you should be able to get this to work using the Rules module, though for Google+ this sounds like a business opportunity (read: no known solution as of today). Read on for more details about each of them ...

# Facebook

The Facebook Rules module can be used to post to user's wall, via the Rules module. Some more details about Facebook Rules (from its project page):

> Facebook rules module extends FBOauth permissions and integrates with Rules module.
>
> Once the user's Drupal Account is connected to his/her FaceBook Account, FaceBook Rules can be used to set up actions based on particular events or triggers.
>
> It provides following rules:
>
> * Events:
>
> + User logged in using Facebook connect.
>     + User connected existing own account to Facebook.
>     + User registered using Facebook connect.
>     + User registered using Facebook connect, requires admin approval.
> * Condition: User's Drupal account is connected to Facebook account.
> * Action: Post to user's wall.

# Twitter

After you enable the Twitter module, and its sub-module Twitter Actions, you can use the Rules module to create an action that will post a tweet to a specific Twitter account.

Have a look at Post Automated Tweets Using Rules and Twitter Actions for more details about it.

# Google+

For Google+ I'm not aware of any working solution. Yes there is the Google+ module (which only has a dev version for D7 ...). And yes Google+ does have an API, but this module doesn't implement it.

Therefor I think the best you can find (to start from) is what is described in How to post in google plus wall?. Starting from there, you may get that to work also if you'd write your own (custom) Rules (Event(s), Condition(s) or Action(s)), similar to what is described in the answer to the question about "How to login-redirect users to their profile page on specific days only?".

PS: Using the Rules module to make something happen when something gets "published" should be a no-brainer (that's like Rules lesson 101, which I assume does not need any more explanation).

# Answer
> 1 votes
I would think very carefully about what you want to achieve by auto posting, and what level of upkeep you want to invest in this. Do you really want everything going to every one ?

Think of things that can go wrong (post a typo, then repost it, update all your articles - all the posts re-broadcast, apis change - I've seen them all).

What I would probably do in the first instance is look at something that polls your site, and posts for you, rather than having it sit within a site. That takes away some of the upkeep of apis and the like.

Zapier is excellent for this - RSS by Zapier lists a number of the possible integrations by creating an RSS feed on your site and having Zapier use that.

IFTTT is also excellent for this.

I'd also add buffer into the mix that handles timing of pushing content cleverly, so you push it at a good time, when it's likely to be read.

These can all post to all the networks for you, and add many more features besides.

To achieve what you want, my suggested approach would be something like the following:

* create a view for published content you want to post, add a field (defaulting to true if you'd like) to specify include.
* set up an integration with either IFTTT or Zapier to poll these feeds.
* set that integration up to push these items into buffer and have buffer manage the posting for you.

I know it's not a sexy code based solution - but I'm of the opinion just because you can do it with Drupal, you shouldn't also look at what else has been done, and how others achieve this kind of thing (getting off the island).

This way is scalable, reliable - takes away a lot of the integration pain, and in my experience works really well.

---
Tags: 7, social-network
---


# Question
Title: How to create slideshow having both video and image slides
I am using Views Slideshow module for slideshow banner in my Home page, I create slides with images but I also want to add **videos** in that slider.

I have installed video module to create **video** field for slide content type, but I don't know how to call this in slider with the condition auto play on page load?

# Answer
From what I can see, the Views Slideshow module can just about incorporate videos, but I'm not sure whether or not you need the video module specifically for it, as even though it might include views plugins, it's probably more down to whether or not the slideshow itself is capable of playing videos rather than what the view outputs. These 2 links might be useful for you

Display flash, video, photo in slideshow

HOWTO - Make Video available in Views Slideshow
> 0 votes

---
Tags: 7, files, views
---


title: THEME.libraries.yml having no effect

text:
# Question
Title: THEME.libraries.yml having no effect
My `THEME.info.yml` file reads:

```
name: 'name'
type: theme
description: 'description'
core: 8.x
base theme: stark
screenshot: images/image.png
libraries:
  - THEME/navbar

```

and my `THEME.libraries.yml` reads:

```
navbar:
  css:
    theme:
      css/navbar.css: {}
  js:
    js/scrolling.js: {}
  dependencies:
    - core/jquery

```

From all the guides I've found online, this *should* mean that navbar.css and scrolling.js get included on all pages that use the theme. But that isn't happening. What have I done wrong here, or what steps do I need to take to figure out why it isn't working?

---

In case it's relevant, the file structure is:

```
drupal_root
    themes
        custom
            THEME
                css
                    navbar.css
                js
                    scrolling.js
                images
                    image.png
                THEME.info.yml
                THEME.libraries.yml
                THEME.theme

```

---

The jQuery code in scrolling.js is just:

```
$(window).on("scroll", function() {
  if ($(this).scrollTop() > 50) {
    document.getElementById("logo").style.width = '150px';
    document.getElementById("logo").style.marginTop = '0px';
  } else {
    document.getElementById("logo").style.width = '300px';
    document.getElementById("logo").style.marginTop = '20px';
  }
});

```

---

When I manually add

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="{{ theme_path }}/js/scrolling.js"></script>
<link rel="stylesheet" href="{{ theme_path }}/css/navbar.css">

```

to the top of `html.html.twig` everything works fine. But as I understand it, this is not considered the proper way of going about things, so if possible I'd prefer to do it using libraries.

---

The extremely helpful comment added by (I think) Ivan Jaros which was unfortunately and rather rudely removed helped me to find that I needed to add `<head-placeholder token="{{ placeholder_token|raw }}">`, `<css-placeholder token="{{ placeholder_token|raw }}">` and `<js-placeholder token="{{ placeholder_token|raw }}">` to my `html.html.twig` file. This helped somewhat: it's now including the CSS file. However:

1. It *didn't* manage to include the js file, for whatever reason.
2. The head-placeholder token is mostly useful, but seems to be overriding the favicon that I had already specified. Is there a way to keep the other stuff it gives without the link rel="shortcut icon" that it's including from core?

# Answer
To get the CSS to appear, I needed to put `<css-placeholder token="{{ placeholder_token|raw }}">` into the `html.html.twig` file's header. For JavaScript, `<js-placeholder token="{{ placeholder_token|raw }}">` seems to add some useless cruft, and the actual JavaScript created added to the library (including the jQuery dependency) is inserted in through `<js-bottom-placeholder token="{{ placeholder_token|raw }}">`, which goes at the bottom of the body of the page.

`<head-placeholder token="{{ placeholder_token|raw }}">` adds some useful metadata, but was overriding my custom favicons. Moving it up to the top above where I had defined the favicons seems to have fixed this.

To get the JavaScript to work in *all* browsers, it needed to be wrapped in `(function ($) {` and `})(jQuery);`, so my full JS code ended up as:

```
(function ($) {
  $(window).on("scroll", function() {
    if ($(this).scrollTop() > 50) {
      document.getElementById("logo").style.width = '150px';
      document.getElementById("logo").style.marginTop = '0px';
    } else {
      document.getElementById("logo").style.width = '300px';
      document.getElementById("logo").style.marginTop = '20px';
    }
  });
})(jQuery);

```

Without wrapping it, it didn't work in anything but Chrome, but with the wrapping as suggested by @No Sssweat, it worked in everything *but* Chrome.
> 1 votes

# Answer
In D8 believe you need to wrap your code around this tags in order for Drupal to recognize it.

```
(function ($, Drupal, window) {

 // code goes here

})(jQuery, Drupal, window);

```

So try

```
(function ($, Drupal, window) {
   $(window).on("scroll", function() {
     if ($(this).scrollTop() > 50) {
       document.getElementById("logo").style.width = '150px';
       document.getElementById("logo").style.marginTop = '0px';
     } else {
       document.getElementById("logo").style.width = '300px';
       document.getElementById("logo").style.marginTop = '20px';
     }
   });
})(jQuery, Drupal, window);

```
> 1 votes

# Answer
If you want to add your custom css or any custom js for global then you should add this into global libraries.For better understanding please follow the theme instructions. Theme Instructions Drupal 8

global-css: css: theme: css/style.css: {}

After Changing in libraires then i have put into hook\_preprocess\_page in my themename.theme file as given below:

```
function MYTHEMENAME_preprocess_page(&$variables) {
 if ($variables['is_front']) {
 $variables['#attached']['library'][] = 'mycustompopup/fancybox/lib/jquery.mousewheel-3.0.6.pack.js';
 $variables['#attached']['library'][] = 'mycustompopup/fancybox/source/jquery.fancybox.css';
 $variables['#attached']['library'][] = 'mycustompopup/fancybox/source/jquery.fancybox.pack.js';
}
}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to share content title, image and body on Instagram?
I want to share content's title, image and body on Instagram of my Drupal website,

But I am not able to find the solution.

Any suggestions?

# Answer
> 2 votes
If you want to show Instagram feeds in your website (as in revision 2 of your question ...), then there are typically 3 modules to pick from (quotes are from their project pages):

> ... integrates with Instagram and creates a block containing your most recent instagram posts.

> This is a Feature module. It allows you to create Instagram feeds for your site that will download images from Instagram using filtering by hashtags and / or usernames.

> In this early implementation the module will interact with the Instagr.am API and be able to fetch media items. Advanced methods like relationships between Instagr.am users and such will be added later on.

**Note**: posting **to** Instagram doesn't seem to be available, since that isn't allowed through their API (by design).

---
Tags: blocks, hooks
---


# Question
Title: How to redirect a user to previous page after successful login?
I have added flag links to content pages for anonymous user. When user clicks on that link, the user should be redirected to user login page but after successful login the user should be redirect to last visited page.

I have used this code of a previously posted thread:

```
<?php
  global $user;
  if(!$user->uid) {
  // $flag: bookmark or make_feature, $action: flag, $content_id: $nid.....
  $flag_link = flag_flag_link($flag, $action, $content_id);

  $flag_link = flag_flag_link($flag, $action, $content_id);
  $flag_url = $flag_link['href'];

  //echo implode("/",arg());
    if(isset($flag_link['query']['token'])) {

      $flag_url .= '?'.$flag_link['query']['token'];

    }
  print l(t('SAVE '), 'user/login' , array('query'=> array('destination' => $flag_url)));
  print l(t('LIST'), 'user/login' , array('query'=> array('destination' => $flag_url)));
  } else {
    print render($content['links']['flag']);
  }

```

By using this code, anonymous user can redirect to login page but not to last visited page.

# Answer
According to one of the comments (from OPer) below the question, it is possible to make the code excerpt in the question work in this case via a slight change in this line of that code:

```
print l(t('SAVE '), 'user/login' , array('query'=> array('destination' => $flag_url))

```

It should use `current_path()` instead of `$flag_url`, so that the corrected line looks like so:

```
print l(t('SAVE '), 'user/login' , array('query'=> array('destination' => current_path()))

```

**Note**: This answer is (just) a polished version of one of the comments (from OPer) below the question. But by posting it as an actual answer, I'd hope it'll be more easy to digest (and not so hard to find the answer somewhere in the comments). Hopefully also more easy to "find"?
> 1 votes

# Answer
The following implementation of hook\_user\_login() will override the redirect path set by user\_login\_submit().

As with the default behavior, setting the destination in the query string overrides this redirect.

```
<?php

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {
  $edit['redirect'] = $_GET['q'];
}

```
> 2 votes

---
Tags: redirection, flags
---


# Question
Title: How to create a CSV file to migrate my Commerce Products with the Feeds module?
How do you create CSV files?

I have a new Drupal Commerce website and I want to migrate all my products from my previous Drupal 7 Commerce site. I want to use the Feeds module to import my products.

I have not been able to find a way "to create a CSV file". Any suggestions?

> How do I create a CSV file from my current drupal commerce to my new one?

# Answer
> 2 votes
You can use the Forena module. Here is a quote from that page:

> ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

> Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are **CSV**, XLS, DOC, HTML, etc.

So if you'd install Forena in your "old" site, then these are the steps for creating such CSV files are:

* a custom **SQL query** (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
* a custom **report** (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
* saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

These steps do not require any PHP coding.

**Bonus**: instead of CSV format, you also have an option to format it as either XML or JSON. For more details on that, refer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

**Alternative**: not sure if it would fit your requirements, but you could also use the Feeds integration of Forena. In this case you'd install Forena in your new site, and use Forena to enable Feeds to just go get your data in your old site. Checkout the video tutorial about this topic (specific to this Feeds integration).

For an **online demo** (prior to installing/testing Forena), checkout these links:

Disclosure: I'm a **co**-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.

# Answer
> 1 votes
To extract your info you could use the Forena Reports module. Checkout this video tutorial Getting Started with Forena and/or the answer from @Pierre.Vriens to this question.

---

Another option, would be to extract all the fields individually as a CSV using **phpmyadmin** or any other database viewer. Then put them all into 1 CSV file using MS Excel.

---

**The least technical option** would be to **create a View table of all your fields** (using Views module) and then all you do is highlight all and copy and paste to MS Excel.

Use Microsoft Excel to create columns for each field.

* Save As **CSV (Comma delimited)(\*.csv)**

# Answer
> 1 votes
The tried and true method is to use Views with Views Data Export. CSV exports can work just fine or exporting small batches of products without a lot of extra information. However, if you have a bunch of HTML information or data that doesn't fit in CSVs (e.g. rich HTML), then you can also export to XML or JSON.

You can then use Feeds extensible parsers to parse the rich data and have it import as expected.

---
Tags: 7, commerce, feeds, importing-exporting
---


# Question
Title: Creating two entities at once using entity metadata wrappers
I'm currently facing a situation where I need to create a new instance of a certain entity and attach a file to it.

Since the main entity should 'reference' the file (the same way a node references a user, by an entity property) there are several things I can do.

## Method 1

* Save the main entity
* Save the file
* Update the main entity with the file id.

## Method 2

* Save the file with temporary status
* Save the main entity with the file id.
* Update the file to a permanent status.

Since both methods would require me to perform 3 operations in a row I thought it might be simpler to do this with an entity metadata wrapper like this:

```
// Create the file entity.
$f = entity_create('file', array(
  'uid'               => $data->uid,
  'filename'          => $data->filename,
  'url'               => $data->uri,
  'filemime'          => $data->filemime,
  'filesize'          => $data->filesize,
  'status'            => 1,
));

// Create the main entity.
$e = entity_create('main_entity', array());
$entity= entity_metadata_wrapper('main_entity', $e);

$entity->title       = $data->title;
$entity->...         = $data->...
$entity->file        = $f;

$entity->save();

```

This however saves the main entity with `$entity->file = 0`, and the file does not show up in `file_managed`. Which conflicts with the answer to "How to set value of file field with entity\_metadata\_wrapper" that implies I can use a new stdClass().

Is there some other error in my entity metadata implementation, or is it not possible to save (create) two entities at once like this?

## Update

Apparently my understanding on entity metadata wrappers was completely wrong; While reading the comments on the Entity metadata wrappers documentation page I assumed I could do things like this:

```
// Changing the author's email.
$wrapped_node->author->mail->set('foo@bar.baz');
// Adding to the answer of @Zakaria Elhariri.
$wrapped_node->field_page->status->set(0);
// Save the changes.
$wrapped_node->save();

```

I thought saving the main entity would update the nested entities, so I'd expect the email of my account to be changed and the linked node of Zakaria Elhariri's answer to be unpublished. But none of this is true. Why is this is the examples?

> To update the user's mail address one could use
>
> `<?php
>  $wrapper->author->mail->set('sepp@example.com');
>  ?>`

Or is entity metadata wrapper broken somehow?

# Answer
Without saving the first entity i dont think its possible.

**This is KO :**

```
  // Create the first entity.
  $page = entity_create('node', array('type'=>'page'));
  $entity_page = entity_metadata_wrapper('node', $page);
  $entity_page->title = 'page test!';
  //$entity_page->save();

  // Create the second entity.
  $article = entity_create('node', array('type'=>'article'));
  $entity= entity_metadata_wrapper('node', $article);
  $entity->title = 'article without reference KO';
  $entity->field_paage = $paage;
  $entity->save();

```

**This is OK :**

```
  // Create the first entity.
  $page = entity_create('node', array('type'=>'page'));
  $entity_page = entity_metadata_wrapper('node', $page);
  $entity_page->title = 'page test!';
  $entity_page->save();

  // Create the second entity.
  $article = entity_create('node', array('type'=>'article'));
  $entity= entity_metadata_wrapper('node', $article);
  $entity->title = 'article with reference OK';
  $entity->field_paage = $paage;
  $entity->save();

```

with the second code you have 2 entity (article and page) with the first node page is a reference for the content article.

What you need is save in the first time your file object.

**To Update some fields (tested) :**

```
  $wrapper = entity_metadata_wrapper('user', $user);
  $wrapper->mail->set('sepp@example.com');
  $wrapper->field_first_name->set('First name');
  $wrapper->save();

```
> 2 votes

---
Tags: entities
---


# Question
Title: How to seperate products images folders based on product display categories?
I am building a drupal 7 commerce site, I have installed inline entity form module and adding products from inside the products displays. Since I will have thousands of product displays and products, I thought of finding a way to automatically separate pictures into sub-folders at time of adding the product displays and products. So I have installed this module Filefield Paths I managed the image field in the product display and set the path setting to: *`pictures/products-displays/[node:field-taxonomy-terms:1:root]`* (as per below screenshot)

So it uploads the image, to a folder named as per the product parent category, under products displays folder. Which is exactly what I want. a nicely organized pictures structures.

The problem is not with product display images. It is with product images. I want to have the same things for products where I need images of products to be saved under

*`pictures/products/(parent category of the product display this product belongs to)`*

I understand that:

* The product categories vocab is a reference field for Product Display and not product
* A product can belong to more than one product display, so there there is no reference on the product data to the product display it belongs to, only the other way around.

So I thought my only workaround to get the category of the product display to which the product belongs to is to use the `page url`. (I edit my products from the same page of product display edits..remember I am using inline entity)

So `[current-page:url:args:value:1]` will give me the product display node id, when I am on the page of product display and its products editing. What I need is to get the parent category of that product display node id and use it for the path. in other words **I need to have a token that will get me the parent category of the product display id on the page** I know the below does not work... but just to give an idea about the logic

```
 [[current-page:url:args:value:1]:field-taxonomy-terms:1:root]

```

# Answer
What you are proposing to do won't really work since you cannot embed tokens within tokens. You're going to need to split the images up based on something else. Here are some options:

* Product type `[commerce_product:type]` (e.g. "shirt" - *I haven't checked this one.*)
* Date `[current-date:custom:Ym]` (e.g. "201512")

Furthermore, unless you have hundreds of thousands of images, you're likely not going to see much of a performance degradation. If you *do* have that many images, perhaps you should consider using a CDN or some external system to offload image handling.
> 1 votes

---
Tags: commerce, tokens, files, entities
---


# Question
Title: Cron job stops when another one is running
I have two cron jobs in my site (I'm using Elysia Cron). They are set in my own module. One runs every minute and one every hour. Code below:

```
function mymodule_cronapi($op, $job = NULL) {
    $items['Import J Data'] = array(
        'description' => 'Import J Data',
        'rule' => '* * * * *',
        'callback' => 'mymodule_import_j_data_cron',
    );
    $items['Import Q Data'] = array(
        'description' => 'Import Q Data',
        'rule' => '0 * * * *',
        'callback' => 'mymodule_import_q_data_cron',
    );
    return $items;
}

function mymodule_import_j_data_cron($what) {
    mymodule_j_save_f_data();
    mymodule_j_save_c_data();
}

function mymodule_import_q_data_cron($what) {
    mymodule_q_save_data();
}

```

In my server (centOS), i have the following line in my crontab (with correct MYKEY and url):

```
* * * * * root wget -O - -q -t 1 http://.../cron.php?cron_key=[MYKEY] >/dev/null 2>&1

```

When the second job runs (the one set to run every hour), the other one stops and I get the following error in my site log:

> Attempting to re-run cron while it is already running.

The firs job runs for about 15-20 minute. After it ends, the other one starts again.

My question is, it's not possible to have both cron jobs running at the same time? Am I missing some settings in elysia cron?

# Answer
It looks like ultimate cron can run parallel jobs.
> 1 votes

---
Tags: cron
---


# Question
Title: drush sqlc import causing Mysql 1045 (28000) Error Acces. How to resolve it?
I'm trying to move a live Drupal 7.39 site to my local Acquia dev set up which installs Drupal 7.41.

I follow what I think is standard procedure, which is to get a clean install, copy my site's sites folder, and then upload the database and run the update script.

I'm using the drush command `drush sql-drop -y && drush sqlc < dump.sql`. The first part of the command runs, the database tables are dropped, but then I get a `1045 error (28000)` for my database user.

What perplexes me, is that the first part of the call works, but it fails in the second part. The sql file is too large to import through phpmyadmin, and I'm really dumbfounded here.

Should I update the live site to 7.41 before migrating it? I don't want to do this because I don't want to do updates on the live site.

What is causing this issue? I think it's a conflict with the SQL settings in the settings.php file, but they match the database user and authentication but I don't know enough about the guts of drush to figure out how to fix this.

# Answer
To reduce the possibility that the size of your database is what is causing your problem, I would try to use the Backup and Migrate module.

In doing so, you can exclude all sorts of tables (which might reduce the size tremendously), similar to what I described in my answer to the question about "How to get an import of a very large Drupal database working?".

PS: my answer to your 2nd question (= Should I update the live site to 7.41 before migrating it?) is **No**, because you should not have to update a live site to create a development environment. If you have a need for them to be at the same level (to start from), then rather do the opposite: have your local site start from 7.39, then sync your database, and if needed (only) then upgrade your local site to 7.41. You'd get the same result, without touching your live site, right?
> 2 votes

# Answer
So, this was solved by changing the order I did things in, updated DB first, and then copied the sites folder, and then finally ran the update script. From what it seems is that if you copy the codebase before migrating the database drush get confused about which credentials to use. This was an issue with earlier versions of drush Drush Mysql access errors with sqlc.
> 1 votes

---
Tags: 7, drush, migrations
---


# Question
Title: How do I replace comma with a line break in a views field?
I am working with a custom view handler that renders a comma separated list. This field is used throughout the site this way.

Now, I have a new view that needs to render the list using line breaks instead of commas. Is there a way to do this in the view settings?

I don't want to hard-code the new view name in the view handler code to render it differently. Do I have to create a views template to solve this?

# Answer
> 1 votes
The solution is to create an additional options form field for your views field. Which is done using the `options_form` and `options_definition` methods. This will allow you save a value using the options form and access that value in the render method.

```
class my_handler_my_field extends views_handler_field {

  /**
   * {@inheritdoc}
   *
   * Perform any database or cache data retrieval here. In this example there is
   * none.
   */
  function query() {

  }

  /**
   * {@inheritdoc}
   *
   * Modify any end user views settings here. Debug $options to view the field
   * settings you can change.
   */
  function option_definition() {
    $options = parent::option_definition();
    $options['separator'] = array('default' => ', ');
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    $form['separator'] = array(
      '#type' => 'textfield',
      '#title' => t('My Field'),
      '#default_value' => $this->options['separator'],
    );

    // The path is set by render_link function so don't allow to set it.
    $form['alter']['path'] = array('#access' => FALSE);
    $form['alter']['external'] = array('#access' => FALSE);

    return $form;
  }

  /**
   * Render callback handler.
   *
   * Return the markup that will appear in the rendered field.
   */
  function render($values) {
    $separator = !empty($this->options['separator']) ? $this->options['separator'] : ', ';
    ......
    return $rendered_value_with_the_right_separator;
  }
}

```

# Answer
> 1 votes
You can use the `options_form()` method on your field handler to provide a setting. That setting could be a text field in which you enter separator to be used, `,` or `<br>` or whatever you need. Or that setting could be a select list that contained only `,` and `<br>` options.

Here is an example of an field handler that uses that method:

http://cgit.drupalcode.org/views/tree/modules/node/views\_handler\_field\_node\_link.inc?h=7.x-3.13

The key pieces are the `options_form()`

```
  function options_form(&$form, &$form_state) {
    $form['text'] = array(
      '#type' => 'textfield',
      '#title' => t('Text to display'),
      '#default_value' => $this->options['text'],
    );
    parent::options_form($form, $form_state);

    // The path is set by render_link function so don't allow to set it.
    $form['alter']['path'] = array('#access' => FALSE);
    $form['alter']['external'] = array('#access' => FALSE);
  }

```

and then the usage of the option

```
  $text = !empty($this->options['text']) ? $this->options['text'] : t('view');

```

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


# Question
Title: Change edit link URL in the content administration page
I been trying to recreate something in the admin section of Drupal from a previous.

In the content, when you roll over the "edit" link. It shows the link like this: https://www.example.com/dolor-melior/edit?destination=admin/content

But I needs it to be: https://www.example.com/node/1/edit?destination=admin/content

I have Pathauto, Redirect and Global Redirect modules installed.

# Answer
> 2 votes
Go to `YOUR_SITE/admin/config/search/path/delete_bulk` check ***All aliases*** and click in ***Delete aliases now!***

---
Tags: nodes, uri
---


# Question
Title: Some Drush master-branch commands report DB problem in Drupal 8
I use Drupal 8.0.0 in a Windows 10 home, WAMP environment.

When I run for example `drush up`, I get:

> The drush command 'up' could not be executed. Drush was not able to start (bootstrap) the Drupal database

* Every action is done when I am in the sites folder (C:\wamp\www\sname\>).
* This is a brand new environment - I've only one DB named equally as it's user.

## Update:

After I tried to follow this similar (but surly not identical!) thread, I added a fifth value to the Path Environment variable, restarted the Win CLI, and than when I ran `drush up` at the sites' folder, I got another, brand new error:

> wget nor curl executables found.

I need to further explore this but if you have an idea, please shoot...

**Drush status**

```
 C:\wamp\www\sname>drush status
 Drupal version         :  8.0.0
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  sname
 Database name          :  sname
 PHP executable         :  php.exe
 PHP configuration      :  C:\wamp\bin\php\php5.5.12\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\drush-master\drush.php
 Drush version          :  8.1-dev
 Drush temp directory   :  C:\Users\Beni\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp\www\sname
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_mkuaR5uFQ7VCjh1_FFBuZzWXkUsz-sA7Klv4HO_2yLJG33wfJJabdavO7QKzyIRWiQoWA3IJbg/sync

```

**Drush sql-conf**

```
C:\wamp\www\sname>drush sql-conf
Array
(
    [database] => sname
    [username] => sname
    [prefix] => Array
        (
            [default] =>
        )

    [host] => localhost
    [port] => 3306
    [namespace] => Drupal\Core\Database\Driver\mysql
    [driver] => mysql
)

```

# Answer
> 2 votes
Drush is giving a very accurate error message

> wget nor curl executables found.

You can either install Curl separately as benos suggests above or install more Unix tools. Since you might need Git anyway, why not install Git for Windows? Then you get a proper Bash prompt. If you prefer to use Command or Powershell you can select to update the PATH variable when installing so Git (and the Unix tools) are available there too.

# Answer
> 0 votes
This is due that for some reason Drush can't find your database. First make sure that your WAMP running on and your Drupal is been connected to a database. If you still have this problem you can try it out a Drush aliases, which is not ideal but it will solve your problem.

> You MUST create a local drush alias for the site using the following for

```
<?php
/**
 * Local alias
 * Set the root and site_path values to point to your local site
 */
$aliases['yoursitename'] = array(
  'uri'  => 'http://yoursitename:8082',
  'root' => 'C:/Dev_Server/Dev_Sites/yoursitename',
  'db-url' => 'mysql://yourdatabaseusername:password@127.0.0.1:3306/yoursitename',
    'databases' =>
      array (
        'default' =>
        array (
          'default' =>
          array (
            'driver' => 'mysql',
            'username' => 'yourdatabaseusername',
            'password' => 'yourpassword',
            'port' => '',
            'host' => '127.0.0.1',
            'database' => 'yourdatabasename',
          ),
       ),
    ),
);

```

For a more details explanation of how to do this please refer to - https://www.drupal.org/node/1393232#comment-9239657

# Answer
> 0 votes
What worked for me without creating a local Drush alias, was to install CURL for my 64-86 Windows 10 home environment, and than setting it's Path Environment variable (to CURL's bin folder).

---
Tags: drush, 8
---


# Question
Title: Drush Make and the Windows maximum path length
When building Commerce Kickstart on Windows, using Drush Make, a customer has this problem:

```
copy(C:\Users\User\AppData\Local\Temp\make_tmp_1449319094_5662dab66a8f0
\__build__\profiles\commerce_kickstart\modules\contrib/commerce_discoun
t/modules/commerce_discount_usage/includes/views/handlers/commerce_disc
ount_usage_handler_field_commerce_discount_analytics.inc): failed to
open stream: Invalid argument filesystem.inc:267

```

It results in the Drush error "Project commerce\_discount (7.x-1.0-alpha6) could not be downloaded".

The build works on non-Windows platforms.

I notice that the file path is 264 characters long, and I suspect this is a problem of the Windows `MAX_PATH` constant (variously quoted on the web as being 255, 256, or 260 characters).

Is there a way to get around this?

I should note: I have read the drupal.org issue about Kickstart on Windows (https://www.drupal.org/node/1648992)

# Answer
The Drush temporary directory can be set manually in the environment variable `TEMP`. So something like:

```
mkdir -p /c/drushtmp
TEMP=/c/drushtmp drush make [...]

```

can neatly solve the MAX\_PATH problem for the temporary directory.
> 1 votes

# Answer
What about temporarily changing the TMP and/or TEMP variable to C:\tmp (in stead of C:\Users\User\AppData\Local\Temp)? It might be just enough ;-)
> 1 votes

# Answer
It appears there is an MSDN article that has a solution:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath

> To specify an extended-length path, use the "\\?\\" prefix. For example, "\\?\D:\very long path".

So, perhaps you can modify the install script to use this prefix before trying to install?
> 0 votes

---
Tags: 7, commerce, drush
---