# Question
Title: Commerce - Hide Add-to-Cart form from Anonymous users
I am constructing a site that will serve mainly agents (authenticated users), but should still show all of the products (without prices) for anonymous users. When logged in, only agents should see the Add-to-Cart form on the product display page, and anonymous users should instead see a link to an "Ask a Question" page.

Is this possible? I looked through the permissions table and could not find a way to prevent access to the cart form by anonymous users.

The only thing I can think of doing is customizing my `node--product-display.tpl.php` file:

```
<?php
    if ($logged_in) {
      print render($page['content']);
  } else {
      // something else
  }
?>

```

I'll have to print the rest of my fields out manually, but as far as I know, this is the only way to print the *Add to Cart* form. I'm a bit uneasy about this, so I'm humbly looking here for another solution. thanks

# Answer
> 6 votes
From the link : http://www.drupalcommerce.org/node/2528 with an condition for anonymous user added.

> It's taken me a while but I've finally cracked it! I've used hook\_form\_FORM\_ID\_alter() (that took me some learning and meant I had to create my own, admittedly trivial, module!). So in my module I've got the following which sets #access for the submit form to false which stops it being rendered (see http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_referenc...).
>
> In the future, I'll be able to extend this to disable the button on certain conditions (say when there's no stock but I want to show what combinations are possible). It would also presumably be an easy way of changing, say, the text for the button, such as "Buy" instead of "Add to cart".

```
  function mymodule_form_commerce_cart_add_to_cart_form_alter (&$form, &$form_state, $form_id) {
global $user;
    if ($user->uid == 0) {
    // Disable the Add to Cart submit button

  $form['submit'] = array('#access' => FALSE);
        }
    }

```

# Answer
> 0 votes
I added a notice to the accepted answer.

```
function hook_form_commerce_cart_add_to_cart_form_alter (&$form, &$form_state, $form_id) {
  global $user;
  if ($user->uid == 0) {
    // Disable the Add to Cart submit button
    $form['submit'] = array('#access' => FALSE);
    // Display notice to login
    $form['notice'] = array(
      '#prefix' => '<div class="login-notice">',
      '#markup' => t('<a href="/user/login">Login</a> / <a href="/user/register">Register</a> to buy this product before its gone.'),
      '#suffix' => '</div>',
    );
  }
}

```

---
Tags: commerce, users
---


# Question
Title: How can I save a file in specific folder?
I want to upload files to specific folders. How can I achieve this programatically.
How can I modify below code such that upload\_location should be dynamic.

```
    $form['document'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array('file_validate_extensions' => array('xml')),
    '#upload_location' => 'public://',
    '#submit' => array('custom_document_submit'),
    );

```

# Answer
In form submit action you can give the destination path.

```
function formname_form_submit($form, &$form_state) {
    $destination = $form_state['values']['foldername_name'];
    $validators = array();
    $file = file_save_upload('file', $validators, 'public://'.$destination);
}

```

More about file\_save\_upload get https://api.drupal.org/api/drupal/includes!file.inc/function/file\_save\_upload/7.x.

more related links https://stackoverflow.com/questions/1253094/howto-drupal-file-upload-form
> 2 votes

---
Tags: 7, forms, files
---


# Question
Title: Access from different Network, one allow admin roles the other not
I have a Drupal 7 site on a server wich can be accessed by 2 differents Network (A and B). On both Network I use SAML to authentificate the users and affect them their roles (including back office roles) with SAML attributes. When an user logs in from network A to my site he must have his back office options but when he logs in from network B he must not have them.

I want to block any administration feature, not just back office access so blocking urls will not be enough. I don't want to see the edit/view tabs on content in the front office. I don't want them to have access to content that is not published (even if they have access to it on network A). Like the users had no back office role at all when they are on network B.

I am able to detect wich network the user is using on each visit and I have some code that allows me to affect the back office roles only if he comes from network A.

But if the user logs in first on network A then on his mobile access the site from network B and logs in he will lose his back office role on A unless he logout/login again.

Is there a way to disable all back office (admin) features on each visit if coming from network B? And not on each login? Aka a solution not involving removing his back office roles so he keep them when on network A.

# Answer
Ok so the best solution I found wich might even work with a cache engine and without altering core was to remove the roles from the global $user in a hook\_boot() :

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

  // if the user is connected and I am on network B
  if ($user->uid != 0 && variable_get('networkB', FALSE)) {
    // then we remove the role BO from the global $user
    // wich are stocked in a variable (roles_back_office) as a string (rid separated by pipes).
    foreach(explode('|', variable_get('roles_back_office')) as $rid) {
      if (isset($user->roles[$rid])) unset($user->roles[$rid]);
    }
  }
}

```
> 0 votes

---
Tags: 7
---


title: Drupal 8 convert json to Array

text:
# Question
Title: Drupal 8 convert json to Array
I´m getting data from web service in Drupal 8:

```
$uri = "http://localhost:8888/drupal8/tipo_receta.json";
 try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'application/json')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }else{
        print $data;
    }
  }
  catch (RequestException $e) {
      return FALSE;
  }

```

I have this JSON source:

```
{
    "document_type ": "receta",
    "recipe_doc_id ": 1,
    "recipe_title": "Título de la receta",
    "recipe_description": "Descripción con todos los pasos de una receta",
    "recipe_ingredients": [
        {
            "ingredient_doc_id": 33,
            "ingredient_doc_hid": "ing_pera",
            "ingredient_name": "pera",
            "ingredient_value": "2 peras"
        },
        {
            "ingredient_doc_id": 54,
            "ingredient_doc_hid": "ing_manzana",
            "ingredient_name": "manzana",
            "ingredient_value": "300 grs. De Manzana"
        }
    ]
}

```

This is my result on the page:

```
C:\wamp64\www\drupal8\core\themes\bartik\bartik.theme:142:string '{
    "document_type ": "receta",
    "recipe_doc_id ": 1,
    "recipe_title": "Título de la receta",
    "recipe_description": "Descripción con todos los pasos de una receta",
    "recipe_ingredients": [
        {
            "ingredient_doc_id": 33,
            "ingredient_doc_hid": "ing_pera",
            "ingredient_name": "pera",
            "ingredient_value": "2 peras"
        },
        {
            "ingredient_doc_id": 54,
            "ingredient_doc_hid": "ing_manzana",
         '...

```

How can i get an array so i could filter the data like this?

```
if($data['recipe_doc_id'] == "1"){
print $data['recipe_title'];
}

```

# Answer
Use the `Json::decode()` method:

```
use Drupal\Component\Serialization\Json;

...

$decoded = Json::decode($data);

```
> 12 votes

---
Tags: 8
---


title: Redirect to default node url

text:
# Question
Title: Redirect to default node url
I have an question about drupal's redirect.

Well I implemented hook\_menu for the path: "node/%node/boost".

And I set all callbacks from default node path: "node/%node".

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['node/%node/boost'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );

  return $items;
}

```

So I would get the node from my custom URL

but I got the redirect to default node URL like "node/123".

Any idea how can I load nodes from the my custom URL?

Thanks

**UPD**

If I change "page callback" function to the my custom function "my\_module\_page\_view", for example:

```
/**
 * Callback.
 */
function my_module_page_view($node) {
  return 'Hello Drupal!';
}

```

I will see the text "Hello Drupal!" on the page with URL "/node/1/boost".

But if I use the next code:

```
/**
 * Callback.
 */
function my_module_page_view($node) {
  return node_view($node);
}

```

I will get redirect from "/node/1/boost" to "/node/1"

# Answer
> 0 votes
Well It was a monkey's code in the one custom module: It implements `hook_node_view()` and, if the path was similar to node/1/bla-bla, it redirected users to node/1.

---
Tags: 7, nodes, routes, redirection
---


title: Display Language specific content

text:
# Question
Title: Display Language specific content
I created two languages

English and French

I am facing problem when content is not translated into french by default its displaying english content.

How to display only french content if i select french language

# Answer
Try the below module.

https://www.drupal.org/project/select\_translation

Install the module and Add filter in view by selecting(content translation:select translation) field

And select this option : use current language ; if not available use original language
> 1 votes

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


# Question
Title: Node reference field auto complete in views
I have content type master program and slave program.

Slave program have node reference field with master program

I created a view for filter and show the slave program list

For node reference field it is showing as dropdown

but I want to display as autocomplete textfield.

I searched view\_auto\_complete and node\_reference\_autocomplete modules

I dont know how to implement these

Can any one help me ?

# Answer
> 2 votes
Views Autocomplete Filter done the tricks.

Add autocomplete functionality to the views filter text fields.

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


# Question
Title: Quick Uninstall/Reinstall of a Custom Module
I'm working on creating a module and I'm slowly getting familiar with the Field API and what all settings work on various fields and what don't. While I'm doing this, it seems that the only way to update a custom content type is to disable the module, uninstall it, then re-enable it.

Is there an easy way to do this? Right now, it's a somewhat laborious process that requires a handful of clicks to do the same thing over and over. I'm looking for a script or module to handling this very quickly with (ideally) a single click.

# Answer
> 32 votes
**Solution 1. Devel + Drush:**

You can use devel drush command for module re-installation with all the module dependencies:

```
drush devel-reinstall modulename

```

There is also alias for this command

```
drush dre modulename

```

**Solution 2. Drush:**

This is something that I would typically use drush for

```
drush pm-disable mymodule
drush pm-uninstall mymodule
drush pm-enable mymodule

```

You could also use it to define your own custom commands to combine these into a single command.

# Answer
> 8 votes
If you don't have shell access the Devel module provides such functionality. Install it and visit *mysite.com/devel/reinstall*.

# Answer
> -2 votes
For those of you that want a script that does the devel command without the devel: https://github.com/nategd/drupal\_module\_restart

---
Tags: installation
---


# Question
Title: Where does the Entity Registration module store the signup data and how to delete it?
I am running Drupal 7.50. I'm using the Entity Registration module, and I have set up a small classroom enrollment content that I used to test this out.

My questions:

* Where does Entity Registration store the signup data?
* How do I see the information collected?
* How do I delete it?

# Answer
> 0 votes
> Where does Entity Registration store the signup data?

Looking at the module's .install file, those data should be stored in the table with name ***registration***. Especially these columns of it should be close to what you're looking for:

```
  'count' => array(
    'description' => 'How many spaces this registration should use towards the total capacity for this event.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 1,
  ),
  'user_uid' => array(
    'description' => 'The uid of the user associated with this registration.',
    'type' => 'int',
    'not null' => FALSE,
    'default' => 0,
  ),
  'author_uid' => array(
    'description' => 'The uid of the user who created this registration.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ),
  'state' => array(
    'description' => 'The {registration_state}.name of this registration.',
    'type' => 'varchar',
    'length' => 32,
    'not null' => TRUE,
    'default' => '',
  ),
  'created' => array(
    'description' => 'The Unix timestamp when the registration was created.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ),
  'updated' => array(
    'description' => 'The Unix timestamp when the registration was most recently saved.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,

```

> How do I see the information collected?

**Option 1**: Just browse this table, using your preferred tool to do so.

**Option 2**: Use the Views module to create an appropriate view of it, as suggested also in its community documentation, i.e.: "***Not happy with the default tabular list of registrations? No problem, registrations and their fields are all Views friendly. You can override the default event registrations list, create additional ones, etc***". You probably want to enable its registration\_views submodule for this.

> How do I delete it?

It may be straight forward to just delete the relevant rows in the "registration" table mentioned above. However because of its integration with the Rules module, I'd rather use this module, possibly combined with the Views Bulk Operations module, to perform such deletes

---
Tags: 7, database, entities
---


# Question
Title: How to get Page Manager to react on path alias before node/%node
I have a CTools Page Manager Panels Variant that I want to apply to a whole load of different content, based on paths. Basically I want this Page Manager Page to handle all paths matching:

```
foo/*/*

```

Some paths will be node path aliases, some will be generated in other ways, i.e. not nodes.

I've set up a Page Manager Page with one Variant on the path `foo/%blah/%baz`, and this works well.

The problem is that if `foo/bar/whatnot` is a node's path alias, Page Manager sees this as `node/1234` (it's menu path), and reacts with a different variant (`node/%node`), never considering the page page/variant I want.

My understanding of Drupal's "fitness" logic for menu router items would mean that my thing would win if the node's path alias was used, because `foo/%/%` has a fitness of 4, whereas `node/%` has a fitness of 2.

Is there any way to achieve this?

# Answer
If you want to override the default path like `node/%node`, `taxonomy/term/%taxonomy_term` and so on then there is a module for that: Page manager existing pages. Some more details about this module (from its project page):

> Page manager existing pages allows you to override/configure Drupal menu paths so you can create variants with Page manager, which is bundled in the CTools project.

Here is an introduction from the author: Overriding any Drupal path with Page manager existing pages.
> 1 votes

---
Tags: 7, panels, path-aliases, chaos-tool-suite
---


title: How to display blocks as a toggle?

text:
# Question
Title: How to display blocks as a toggle?
I am displaying a list of Views blocks on the user page.

I want to create a menu/list of links on the sidebar of the page, and when I click the link "Block 1" it shows only the "Block 1". When I click "Block 2" it shows the block 2 and so on... All the other blocks must be hidden.

I could create several pages with the views and could link to those pages, but the thing is: I need to be in the user page, because the views have filters related to the user URL. So it has to be all in the same page.

What is the best way to do this?

Please see the picture explaining how I want the page.

# Answer
> 2 votes
The Quick Tabs module may meet your needs.

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content... Once created, the Quick Tabs blocks show up in your block listing, ready to be configured and enabled like other blocks.

You would create a Quick Tabs instance (Admin \> Structure \> Quicktabs) with the views blocks you want to display. You are able to configure URL arguments to pass to the block's contextual filters.

Then display the block of the Quick Tabs instance on the user page.

There are various tab styles offered by the module or you can style the tabs with your own CSS.

# Answer
> 1 votes
As per your confirmation (comment), I'm assuming that to **click the link Block 1**, that link must have some relative path, say `/path/for/link/in/block1`. Same for block 2, like `/path/for/link/in/block2`, block 3 and block 4.

In that case, you can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the appropriate menu block is shown on the appropriate pages).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by the variations below to make it match your specific question.

### For your block 1:

Within the block visibility settings of this block, use this Rules Component:

```
{ "rules_block_visibility_show_block1" : {
    "LABEL" : "Show block 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "path\/for\/link\/in\/block1",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

Remark: depending on how your actual path looks like, you may want to use a Regular Expression (regex) in your Rules Condition instead (which gives you way more flexibility, provided you're familiar with RegEx).

### For your block 2:

Within the block visibility settings of this block, use this Rules Component:

```
{ "rules_block_visibility_show_block2" : {
    "LABEL" : "Show block 2",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "path\/for\/link\/in\/block1",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

### For your block 3, 4, etc:

Yet another similar rule: just change the "1" (or "2") to "3" (or "4").

# Answer
> 0 votes
I think in your case is best to use jquery for doing such a thing. Meaning put id's on your menu/list links like menu-1, menu-2 and so on and also put an id on your blocks like block-1, block-2 and so on.

Also use a wrapper around all your blocks with position:relative and use position:absolute on your blocks so every block is stacked upon others.

Then use a simple jquery script that targets your corresponding id's that either manipulates the positioning of your blocks or their z-index.

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


# Question
Title: How do I create a variable to check last time hook_cron() implemented from a custom module was ran?
We have a custom module for which we need to run on a daily basis. I am not sure it is working, as I am unable to store the time correctly.

Does the following code allow me to create a variable, and use it to store the last time cron ran?

```
function mymodule_cron() {
  if (variable_get('mymodule_last_run', 0) <= strtotime('-1 day')) {
    // Omissis.
    variable_set('mymodule_last_run', time());
  }
}

function mymodule_info($options) {
  $variable['mymodule_last_run'] = array(
    'title' => t('Last Run', array(), $options),
    'type' => 'datetime',
    'default' => t(time(), array(), $options),
  );
}

```

# Answer
You are implementing the wrong hook. What you are trying to implement is `hook_variable_info()`, used from the Variable module. Hook name apart, that hook implementation seems correct.

Instead of using `variable_set()`, you should use `variable_set_value()`. The equivalent of `variable_get()` is `variable_get_value()`.

See the project page for more information about how to use the module API, Variable API for a list of available functions, and variable.api.php for a list of hooks used from the Variable module.

The code you want to use should be similar to the following one.

```
function mymodule_cron() {
  if (variable_get_value('mymodule_last_run') <= strtotime('-1 day')) {
    // Omissis.
    variable_set_value('mymodule_last_run', REQUEST_TIME);
  }
}

function mymodule_variable_info($options) {
  $variable['mymodule_last_run'] = array(
    'title' => t('Last Run', array(), $options),
    'type' => 'datetime',
    'default' => 0,
  );
}

```

Notice that `variable_get_value()` doesn't need the default value, since it gets it from the `hook_variable_info()` implementation done from your module. If you need to use a different default, you call the function as `variable_get_value('mymodule_last_run', array('default' => REQUEST_TIME)`.

As for your original code, you don't call `t()` as `t(time(), array(), $options)` because:

* The first argument of `t()` must be a literal string, not the value returned from a function
* `time()` returns an integer; even if it would be casted to a string, `t()` doesn't change an integer in any way, for example returning `'1,000'` when receiving `1000` as first argument.

If the Variable module is expecting a string (e.g. `'19700318T19:00'`) as default value for a variable of type *datetime*, you need to use a different function.
> 1 votes

---
Tags: 7, hooks, cron, configuration
---


# Question
Title: Programmatically querying via SearchApiAcquiaSearchService
I am working on a site where querying using **SearchApiSolrService** is successful. However, when I deploy to Acquia Cloud and attempt to access the Acquia Search using the **SearchApiAcquiaSearchService** I get a 403 Forbidden.

Response

```
SearchApiException: "403" Status: Forbidden: Forbidden in SearchApiSolrConnection->checkResponse() (line 544 of ...sites/all/modules/contrib/search_api_solr/includes/solr_connection.inc).

```

The subscription information is correct (via Acquia Agent). Here's a piece of the code:

Code Sample

```
$server = search_api_server_load('my_acquia_solr_server');
$index = search_api_index_load('my_base_index');
$query = new SearchApiQuery($index);
$query = ... lots of random filters here that work for SearchApiSolrService calls so ignoring ...
$solr = new SearchApiAcquiaSearchService($server);
$result = $solr->search($query);

```

Thoughts?

Note: If you were to replace the **SearchApiAcquiaSearchService** with the regular **SearchApiSolrService**, the non-Acquia versions of the site integrate with Solr perfectly fine.

# Answer
The solution to this (also updated on the Drupal.org node commented above) is:

To skip this part:

```
$solr = new SearchApiAcquiaSearchService($server);
$result = $solr->search($query);

```

And simply do:

```
$result = $query->execute();

```
> 0 votes

---
Tags: search, acquia-cloud
---


title: How to add catchpa to entityform

text:
# Question
Title: How to add catchpa to entityform
form IDs for my entity forms is not listed in the catchpa general settings.
Can anyone explain how I add the catchpa?

# Answer
Hope this will help you,

In Drupal 7 if you are using **Captcha** module, you can achieve it by the following steps

* Let say you want to add Captcha to Article node form
* Get the node form for which you want to add the Captcha, you an achieve it by using

```

    //Implements hook_form_alter() for node_form().
    function hook_form_alter(&$form, &$form_state, $form_id) {
        //use drupal_set_message to print the form ID
        drupal_set_message("<pre>" . print_r($form_id,1) . "</pre>");
    }

```
* After printing the node article form
* *Get form id alternative (For developers)* : Go on the page where your form is displayed. Next, use developer tools of your browser to show DOM structure. The form\_id is displayed like the orange box on screenshot (Chrome example):
* After enabling the Captcha module go to `admin/config/people/captcha` and add the node article form id and save the configuration.
* Go to node article form and you can see the captcha(for non admin)

Note:

* Configure the captcha setting as per your requirement.
> 7 votes

# Answer
To add a CAPTCHA to an Entityform Type in Drupal:

1. Install or enable the contributed Captcha module.
2. Determine which Entityform Type(s) you want a CAPTCHA added to:

Admin \> Structure \> Entityform Types
`admin/structure/entityform_types`
3. From the list of Entityform Types, copy the *Machine Name* of the Entityform Type (e.g. `contact_us`).
4. Configure the Captcha module:

Admin \> Configuration \> People \> CAPTCHA
`admin/config/people/captcha`
5. Within the Form Protection fieldset, add the *Machine Name\** of the Entityform Type as the Form ID value.

> \*Note: the Form ID expected by the Captcha module is the Entityform Type machine name appended with the string of text `_entityform_edit_form`.
>
> For instance, if your Entityform Type machine name is `contact_us`, the complete Form ID would be `contact_us_entityform_edit_form`.

You can verify this by viewing the HTML source of an Entityform Type and cross-referencing the form's ID attribute:

`<form class="entityform" id="contact-us-entityform-edit-form" ...>`

Keep in mind, the actual value has hyphens replaced with underscores, as common in Drupal.
6. Select the appropriate Challenge Type or use the defaults.
7. Save the Captcha configuration changes.

To verify the CAPTCHA has been successfully added, open a private browsing session (e.g. a Chrome Incognito window) and view the Entityform Type, or simply view the form while logged-out of Drupal.
> 2 votes

# Answer
In the CAPTCHA config page the last in the list of form ID table will be an empty text box. You can enter the form ID of your entity form there, choose the type of challenge and save.

You need help finding the form id please find it in the answer here How to list all the form IDs
> 0 votes

# Answer
I know this kind of circumvents your original question, but I must discourage using a captcha at all; it is really a disservice to your users.

One great alternative is the Mollom module. It evaluates the contents of the form and only displays a captcha if it really looks like spam. It is quite accurate and a very easy installation - just go to `Configuration` \> `Mollom`.

But my first step towards spam prevention (especially for smaller sites) is a homemade module that adds a few hidden 'honeypot' fields to a form. Humans can't see these fields so if they are non-empty, the form is assumed to be spam and is rejected.
> 0 votes

---
Tags: entities
---


title: How do I edit the output of a field?

text:
# Question
Title: How do I edit the output of a field?
I am creating REST API using Services Module in Drupal 7.

I have created a View to Get lists of Groups. In this views, I have added a Field privacy which will tell if the group is Private or Public.

I am getting this Output if group is Private:

```
privacy":{"value":"1"},

```

and if the group is Public :

```
"privacy":[]

```

How can I edit the output of this field so that it become easier for app developer ? I want to have something like this in output :

```
For Private : privacy":{"value":"1"},
For Public  : privacy":{"value":"0"},

```

Or something like this which look good.

# Answer
> 0 votes
From the code you can use hook\_services\_request\_postprocess\_alter() to alter whatever you want from your response.

You can always use arguments to make your changes more specific:

```
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  // In my response, I include the request string in the '_links' array.
  // I can use this now to determine which resource was requested.
  if (strpos($result->_links['self']['href'], 'api/1.0/widget')) {
    // Now I know I'm dealing with a widget request, so I'll
    // add the random string here...
    $result->String = "This is a string that I'm adding to the widget response";
  }
}

```

As result you can see in your response:

```
Array (
  [_links] => Array (
    [self] => Array (
      [href] => /api/1.0/widget/12345
    )
  )

  [count] => 1
  [_embedded] => Array (
    [0] => Array (
      [id] => 12345
      [type] => widget
      [path] => /node/157601
    )
  )
  [String] => 'This is a string that I'm adding to the widget response'
)

```

Read more Drupal: Alter API response with Services API, where is this example was taken from.

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


title: Drupal multisite on a shared hosting

text:
# Question
Title: Drupal multisite on a shared hosting
Is there a way to install Drupal multisite feature (it needs access to http.conf and http.vhosts) on a Shared Hosting with shell access? It also needs to hosts projects with different databases.

I know there is a module named: Domain Access for share Drupal database with affiliated sites but this is not actual I want.

# Answer
There is no good answer for this, as it will vary host-to-host.

Sometimes, shared hosts use management tools that map domains to accounts to directories. This makes it hard(er) to do the Apache `ServerAlias` settings. I have worked with shared hosts that have let this happen.

Sometimes, hosts will map domains to user accounts and run Apache in FastCGI mode, which may complicate things.

You need to contact your host to see what is possible.
> 1 votes

# Answer
I'd suggest giving it a try first. Rather than worrying about httpd.conf access, you can just use inbuilt tools to do that.. If your host has cPanel, you ***can*** host a Drupal multisite without manual edits to httpd.conf file.

Just make use of Parked Domain thin in cPanel correctly. All you need to do is, pointing extra domains to the main domain.

http://drupal.org/node/1068894

This is an article I authored a long time ago, for Domain Access module docs but I think it was updated several times to include cPanel and Direct-Admin specific instructions. It's not very limited to Domain Access. Just follow the same instructions.

In brief, if you "park" a domain, that's similar to aliasing. You can point any domain to the main domain that you purchased your account for. But you will not be able to point to an `addon domain` which is a limitation for shared hosting accounts.

Also, as you have shell access, you can symlink.

I don't want to mention any commercial names. But if you really need to know a shared host that allow this type of multisites, that host's name mention an animal name.
> 1 votes

# Answer
From my own experience I can say it would work with webfaction.com cloud (not shared) for around $20/month. I run D7 and D8 websites on it.

I also managed to build my own stack with apache and php-fpm as local user (yes, you have shell access and can compile whatever you like). Benefit is also you can add additional php modules like twig.so and uploadprogress.so. They running a nginx as frontend server and will "connect" to your local running apache/nginx process.
> 0 votes

---
Tags: multi-sites
---


title: Commerce usps won't get rates

text:
# Question
Title: Commerce usps won't get rates
Drupal 7, commerce shipping 2.0, and usps shipping method. Configured the product types with weight and dimension physical field. All products have weights and dimensions. All USPS services checked. The username and the connection address are set. The shipping service pane is in the correct sequence in checkout (after shipping info). At shipping services during checkout I get "No shipping rates found for your order. Please continue the checkout process."

# Answer
I had added the weight and dimension fields to the existing products using defaults. I needed to save each product for these to take effect. Works now.
> 1 votes

# Answer
Seems like you got USPS Shipping to work in Drupal Commerce. I have also been trying to get this thing to work, but without much success. I also added the weights and dimensions as defaults. Then, upon seeing your post, saved them all again. I stil get the "No shipping rates found for your order. Please continue the checkout process." message.

Can you please guide me with step-by-step instructions for the whole process? I will be very grateful.

Thanks in advance, Jasper
> 0 votes

---
Tags: commerce
---


title: Error while enabling a core module

text:
# Question
Title: Error while enabling a core module
I need to enable the 'Aggregator' module on my Drupal 7 website. When I do that, I get a error message saying:

> DatabaseSchemaObjectExistsException: Table aggregator\_category already exists. in DatabaseSchema

I researched on this and what it means is that the table for the module already exists in the DB. Now in case of contributed modules I can disable them, uninstall it and make a fresh install and re-enable. I am not sure what can be or should be done in case of core modules.

Any guidance is greatly appreciated.

# Answer
> 0 votes
You somehow have aggregator uninstalled with its tables existing, which should not be. By examining aggregator\_schema() in aggregator.install you can see that upon installation aggregator will create several tables named aggregator\_(something). Table names correspond to the keys of the array returned by aggregator\_schema(). If any of those tables exist you must delete them from the database before attempting to enable the aggregator module. As always, back up and understand how to restore your database first before attempting something like this and rehearse on a test system.

# Answer
> 0 votes
That is not different from third-party modules that aren't installed. If for any reason, the module cannot be installed because its tables are already present in the database, you need to manually delete its database tables, and then try installing the module again.
You say you need to enable the module, but its database tables are only created when the module is being installed. When modules are already installed, and they are re-enabled, Drupal doesn't try to create its database tables.

To delete the database tables created from the module, you can use the following script. Save it in the same directory containing the index.php file used Drupal, execute `cd` to make that directory the current directory, and run it.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$file = DRUPAL_ROOT . '/modules/aggregator/aggregator.install'
if (is_file($file)) {
  require_once $file;

  // Make sure the installation API is available
  include_once DRUPAL_ROOT . '/includes/install.inc';

  // Get the schema from the module.
  $schema = call_user_func_array('aggregator_schema', array());
  foreach ($schema as $table) {
    if (db_table_exists($table['name'])) {
      db_drop_table($table['name']);
    }
  }
}

```

---
Tags: 7, database, feeds
---


# Question
Title: Why is ddebug_backtrace coming up blank?
I've been using the Devel module for a couple of years now but every time I try to get a backtrace I run into issues. I remember getting it working once, but I don't remember how.

It seems like using `dpm(ddebug_backtrace());` should do the trick. I have tried it with no argument, `TRUE`, and `FALSE`, and I have also tried removing the dpm function it's wrapped in.

I have dpm calls directly above and below this code that print variables appropriately, but the most I get out of `dpm(ddebug_backtrace());` is a blank line in the Krumo output.

Suggestions mightily appreciated.

# Answer
If you see the source, you can see that ddebug\_backtrace() only returns values if the variable error\_level is set to 1 or greater.

```
// Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
// (This is Drupal's error_level, which is different from $error_level,
// and we purposely ignore the difference between _SOME and _ALL,
// see #970688!)
if (variable_get('error_level', 1) >= 1) {

```

So one of the ways to make it return values is by either changing the error\_level from admin/config/development/logging, or change it temporarily in the code like so:

```
variable_set('error_level', 1);
dpm(ddebug_backtrace(TRUE));
variable_set('error_level', 1);

```

As Ian Bullock says, debug\_backtrace() would return values because it ignores the variable and the content is essentially the same. But ddebug\_backtrace() returns a more readable output.
> 3 votes

# Answer
For me the command had to be called without the extra `d`

`dpm(debug_backtrace());`
> 8 votes

# Answer
In the instances where I've been like, "WTF! Where's my dpm output at?", it's either been:

1. A permissions issue with an impersonated user not having `access devel information` perm.
2. A theme page that isn't outputting the `$messages` var.

Hope that helps.
> 1 votes

---
Tags: debugging
---


# Question
Title: How to add "Content type B" from within "Content type A" and then display both together?
I have the following scenario:

Content type A
Content type B

Content type A is added by the admin role.
Content type B is added by the students role.

Once Content type A is created, then on that link, like node/20 or content-type-A/20, I am looking to have an node add form for Content type B.

then the content type B that was added from this form, should be related and displayed with the existing content from content type A.

For example,
Content type A: title: Bread is good

So now, when you go to node/20 you see Title: Bread is good
then here you should have a form for Content type B with fields say title and some radio buttons. The student role user inputs the form and then submits.

Now the node/20 should display Title: bread is good and the fields associated with content type B that the student inputted.

And more students should be able to continue adding to this. This is something like a one-to-many relationship. Content type A has many Content type B associated with it.

I hope someone can help explain to me how to get this done

# Answer
> 3 votes
**For the first part** of your problem you can use Entity reference to create the relation between the content types:

> Provides a field type that can reference arbitrary entities:
>
> * A generic entity reference field
> * Four widgets:
>     + Two implemented on top of the Options module (Select and Radios/Checkboxes),
>     + Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

**For the second part**, one content type form inside another content type form you have this modules:

The Inline Entity Form module:

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

Entityreference Autocreate

> A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

> Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

> Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

> It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.
>
> The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

***Important:*** The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.

**For the third part**, the visualization of one entity (or more entities) inside another entity I think that you can use the EVA: Entity Views Attachment module, is very easy to use.

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

I think that you should see this: Drupal 7 Node Reference Tutorial

# Answer
> 2 votes
Sounds like you could use Inline Entity Form with a reference field on type A to allow adding the type B nodes while viewing it, combined with some access control like Field Permissions. (If I'm not mistaken it should allow displaying the inlined node form while viewing the parent node, not just when editing it.)

For more layout flexibility I also suggest Display Suite and related modules.

# Answer
> 2 votes
> Once Content type A is created, then on that link, like node/20 or content-type-A/20, I am looking to have an node add form for Content type B.

You can use Form Block module to achieve this part.

> now the node/20 should display Title: bread is good and the fields associated with content type B that the student inputted.

To link Content type A with content type B you have 2 possible ways:

**Route 1** you will need to create a taxonomy vocabulary with terms, and add a tax term reference field. Then edit node A and B, and add the same term name.

OR

**Route 2** Entity Reference and add a Entity reference field to content type B only. Then when the B form gets filled out you need to reference it to a node of type A. `**<------**` This is the tricky part if you want this to be automatically filled with the nid of the content type A node you're on. You will have to use jQuery or a custom module (using hook\_node\_presave) to achieve this. Unfortunately, I don't have time to boot-up a D7 server and test a solution for this.

Now, create a block view, and under Advanced, Add Contextual filter of NID (content ID) and provide ID from url.

Add Relationship of Terms of the node (if you decided to go with route 1)

OR

Add Relationship of Referencing Entity (if you decided to go with route 2)

Lastly, Add/place block view to the content type A nodes.

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


title: Views Data Export Permissions Problem

text:
# Question
Title: Views Data Export Permissions Problem
I have Views Data Export installed, which creates a CSV file attached to every node. This file has all of the data from a field collection field arranged as a CSV.

The only user that should be able to download this CSV file is the admin (user 1) and the user that created the node.

In Views Data Export, I can select Role as a permission, and assign it to all "Managers", but that means each "Manager" can download other Managers data if they get the URL right. Anyone wanting to maliciously steal data, or sneak a peak at how much their colleagues are earning can simply guess the URL of the CSV file.

How would I restrict this download to the author of the node?

I have tried installing Path Rules, and creating a Rule that checks that the path of the CSV ends with CSV, and then runs a condition to check that the Nid of the currently logged in user matches one created by the author, but the download happens automatically regardless. There doesnt seem to be a path check before it is downloaded.

Stuck here scratching my head, would welcome even the slightest suggestion, or just a fresh pair of eyes! Thanks.

**OK, some progression...**

I delved into creating a views custom access like so...

Added `files[] = couples_page_custom_access_plugin.inc` to a custom module info file

Added the following to couples\_page\_custom\_access\_plugin.inc

```
<?php

  /**
   * Access plugin that provides property based access control.
   */
  class couples_page_custom_access_plugin extends views_plugin_access {

    function summary_title() {
      return t('Couples Page Check User is Author');
    } // summary_title()

  /**
   * Determine if the current user has access or not.
   */
    function access($account) {
      return couples_page_custom_access($account);
    }

    function get_access_callback() {
      return array('couples_page_custom_access', array());
    }

  }

```

Then added this to a custom module...

```
  function couples_page_custom_views_plugins() {
    $plugins = array(
      'access' => array(
        'test' => array(
          'title' => t('Couples Page Check User is Author'),
          'help' => t('this is a custom access plugin'),
          'handler' => 'couples_page_custom_access_plugin',
          'path' => drupal_get_path('module', 'couples_page_custom'),
        ),
      ),
    );
    return $plugins;
  }

  function couples_page_custom_access($account = NULL) {
    global $user;
    $access = false;
    $account = user_load($user->uid);
    $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

    // If the UID of the currently logged in user matches the UID of the node author return true.
    if ($account == $node->uid) {
      $access = true;
    }
    return $access;

  }

```

But its not really working. If I set $access = true it works, and $access = false, it doesnt, so I know the plugin is working. It must be the logic in the last bit here...

```
function couples_page_custom_access($account = NULL) {
        global $user;
        $access = false;
        $account = user_load($user->uid);
        $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

        // If the UID of the currently logged in user matches the UID of the node author return true.
        if ($account == $node->uid) {
          $access = true;
        }
        return $access;

      }

```

Perhaps I am not getting the author uid of that node correctly? I will look into it.

# Answer
> 0 votes
I found the problem.

I was using user\_load() in an earlier example, and was still using it rather than the uid.

The final access check should be...

```
function couples_page_custom_access($account = NULL) {
    global $user;
    $access = false;
    $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

    // If the UID of the currently logged in user matches the UID of the node author return true.
    if ($user->uid == $node->uid) {
      $access = true;
    }
    // Else check if the current user is admin so we can download what we like.
if (in_array('Admin', $user->roles)) {
  $access = true;
}
    return $access;

  }

```

I also added a check to return true if the current user is an Admin.

I really hope this helps someone else, and saves the time it took me to get to this!

Still, every days a school day!

---
Tags: 7, views
---


title: How do service tags work?

text:
# Question
Title: How do service tags work?
In the user.services.yml, it defines a theme negotiator service as such:

```
  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

```

This class determines whether or not the current user sees the admin theme when on the user path.

How does this work? What looks at this and knows when and where to call and instantiate that class? How is it correlated (beyond implementing the interface) to the service below:

```
  theme.negotiator:
    class: Drupal\Core\Theme\ThemeNegotiator
    arguments: ['@access_check.theme']
    tags:
      - { name: service_collector, tag: theme_negotiator, call: addNegotiator }

```

Is `service_collector` something that finds defined services and makes them available by `tag` name?

What other basic examples of this exist around Drupal 8 core?

# Answer
> 4 votes
Tags are used to find services while building the container by so called compiler passes. They are not available during runtime of the container.

You can find the default compiler passes in `CoreServiceProvider::register()`.

Usually, the tag related compiler passes all do the same thing. Find all services and add them to a service, so that when that service is instantiated, it has a list of service objects that it can do something with.

Thats why this has been abstracted with the service\_collector tag, which tells it to pass all services with the tag to the provided method. That's done in `TaggedHandlersPass::process()`

---
Tags: 8
---


# Question
Title: Object of type stdClass cannot be printed when received JSON response
I have:

```
$result = $client->request('POST', 'http://'.$core_address.':'.$core_port.$core_uri, [
    'body' => json_encode([
        'a' => $a,
        'b' => $value['v'],
        'x' => $value['x'],
    ]),
    'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
    ],
]);

$output = json_decode($result->getBody());

```

i catch the output and print it like:

```
drupal_set_message($output);

```

problem is: if output just a flat string, it work like a charm but when it receive json like:

> {'x': \['Not a valid integer.'\], 't': \['Not a valid string.'\], 's': \['Not a valid string.'\]}
>
> 192.168.yyy.xxx - - \[28/Jul/2016 00:14:59\] "PUT /Module HTTP/1.1" 200 -

it give me error:

> Uncaught PHP Exception Exception: "Object of type stdClass cannot be printed." at /path/to/Drupal/Core/Template/TwigExtension.php line 443, referer: https://url.com/admin/core/my/module/path

why? why?

# Answer
> 1 votes
Short answer: because that is how the API was written.

Long answer is that they do not know how the object should be printed.

To cast an object to a string, you need the object to have a \__toString method, which the object in question does not contain.

If you want to print the stringified version of the object then don't transform to an object using json\_decode.

---
Tags: 8
---


# Question
Title: Imagecache custom action: scale image to width defined by other field
I would like to define a custom image style with imagecache\_actions module, where the image is scaled to a width (in pixels) given by a interger field in the same node. How is this accomplished?

# Answer
> 1 votes
You would need to create a custom module to do this. Something like this... Create two files in a folder, for example, we'll call this User Defined Width.

**user\_defined\_width.info**

```
name = User Defined Width
description = A module that allows a user to define an image width.
core = 7.x

```

**user\_defined\_width.module**

```
<?php

function user_defined_width_image_effect_info(){
  $effects=array();
  $effects['advance_resize']=array(
    'label'=>t('User Defined Width'),
    'help'=>t('Resize to a size defined by the user.'),
    'effect callback'=>'user_defined_width_effect',
    'dimensions callback' => 'image_resize_dimensions',
    'form callback' => 'image_resize_form',
    'summary theme' => 'image_resize_summary',
  );
  return $effects;
}

function user_defined_width_effect(stdClass $image, $width, $height) {
      // Your logic here.

  $image->resource = YOUR_IMAGE;
  $image->info['width'] = YOUR_WIDTH_FIELD;
  $image->info['height'] = YOUR_HEIGHT_FIELD;
  return TRUE;
}

```

This should get you started, but the more I think about it, the more I think you are going to run into all sorts of problems with image caching, as image styles are stored in sites/default/files. You will need to override this some how and make sure the file regenerate on every page load. This wont be good for performance, but could probably be achieved with something like Image Style Flush

---
Tags: media
---


# Question
Title: Print just the value of Views field inside of views-view-fields template
I cannot for the life of me figure out how to print the value of a field in the 'fields' template. Currently, I'm doing this to strip the unnecessary html (don't laugh):

```
<?php $shortContent = $fields['field_short_name']->content; ?>
<?php $shortText = strip_tags($shortContent); ?>
<?php $strategy = $fields['title']->content; ?>
<?php $cleanStrategy = strip_tags($strategy); ?>
<?php $company = $fields['field_money_manager_company']->content; ?>
<?php $cleanCompany = strip_tags($company); ?>

<?php echo '<img class="logo" src="/sites/all/themes/trust/img/mmx-logos/' . $shortText . '-logo.png" />'; ?>

<div class="row-heading">
    <?php echo '<h2>' . $cleanCompany. '</h2>'; ?>
    <?php echo '<h3>' . $cleanStrategy . '</h3>'; ?>
</div><!--end row-heading-->

```

How can I just get the value of the fields without having to print the entire 'content' and then strip the unnecessary elements?

# Answer
> 2 votes
I guess you want to create a row header which contains some value from other fields. If it is your case, I will suggest you this solution.

---

Use **fields** in **format**

Add field **Global: custom text**

Then you can use the token, which is the value of field, with your custom HTML structure.

Please note that **custom text** field must be placed after the field you want to use. In my case, it is title. You need to exclude it from display, otherwise, there will be 2 titles.

# Answer
> 1 votes
> How can I just get the value of the fields without having to print the entire 'content' and then strip the unnecessary elements?

You can by using `raw` instead of `content`

```
<?php $fields['field_name']->raw; ?>

```

---

Alternatively, you could keep using `content`, but strip all the unecessary markup that views provides. My answer here shows you how to.

---
Tags: views, theming, entities
---


# Question
Title: commerce_line_item VS field_data_commerce_line_items
Right now, I am touching the database for drupal 7. I searched about the difference between "commerce\_line\_item" table and "field\_data\_commerce\_line\_items" table. But no luck.

Does anyone know the difference between them? Also, is there any reference that I can follow to check the table explanation?

I really appreciate anyone's help.

**UPDATE**

Based on everyone's help and my own opinion, I drew a simple diagram for these two tables:

# Answer
`commerce_line_item` is the base table of entity with same name. The entity is defined from the sub module **commerce\_line\_item** in Commerce project. You can find the definition from its code repository

**commerce\_line\_item.module**

```
/**
 * Implements hook_entity_info().
 */
function commerce_line_item_entity_info() {
  $return = array(
    'commerce_line_item' => array(
      'label' => t('Commerce Line item'),
      'controller class' => 'CommerceLineItemEntityController',
      'base table' => 'commerce_line_item',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'line_item_id',
        'bundle' => 'type',
        'label' => 'line_item_id', // TODO: Update to use a custom callback.
      ),
      ...

```

**commerce\_line\_item.install**

```
function commerce_line_item_schema() {
  $schema = array();

  $schema['commerce_line_item'] = array(
    'description' => 'The base table for line items.',
    'fields' => array(
      'line_item_id' => array( ... ),
      'order_id' => array( ... ),
      'type' => array( ... ),
      'line_item_label' => array( ... ),
      'quantity' => array( ... ),
      'created' => array( ... ),
      'changed' => array( ... ),
      'data' => array( ... ),
    ),

    ...

```

---

`field_data_commerce_line_items` is a field created by **commerce\_order**, which is another sub module in Commerce module during installation. You can find this behaviour here

**commerce\_order.module**

```
/**
 * Implements hook_modules_enabled().
 */
function commerce_order_modules_enabled($modules) {
  commerce_order_configure_order_fields($modules);

  ...
}

/**
 * Ensures the line item field is present on the default order bundle.
 */
function commerce_order_configure_order_type($type = 'commerce_order') {
  // Look for or add a line item reference field to the order type.
  $field_name = 'commerce_line_items';
  commerce_activate_field($field_name);
  field_cache_clear();

  $field = field_info_field($field_name);
  $instance = field_info_instance('commerce_order', $field_name, $type);

  if (empty($field)) {
    $field = array(
      'field_name' => $field_name,
      'type' => 'commerce_line_item_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'entity_types' => array('commerce_order'),
      'translatable' => FALSE,
      'locked' => TRUE,
    );
    $field = field_create_field($field);
  }

  ...

```

Please note that the field type here is `commerce_line_item_reference`, which is defined in `commerce_line_item` module as well.

**commerce\_line\_item.install**

```
/**
 * Implements hook_field_schema().
 */
function commerce_line_item_field_schema($field) {
  if ($field['type'] == 'commerce_line_item_reference') {
    return array(
      'columns' => array(
        'line_item_id' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => FALSE,
        ),
      ),
      'indexes' => array(
        'line_item_id' => array('line_item_id'),
      ),
      'foreign keys' => array(
        'line_item_id' => array(
          'table' => 'commerce_line_item',
          'columns' => array('line_item_id' => 'line_item_id'),
        ),
      ),
    );
  }
}

```

According to the schema defined above, `commerce_line_item_reference` acts exactly similar as a entity reference, which helps each **order** can be connected to a number of **line items**.
> 1 votes

# Answer
My answer concerns the structural and not the semantic difference between the two.

The table field\_data\_commerce\_line\_items corresponds to a standard drupal field. On the other hand commerce\_line\_item is a table that is managed by one of the modules in the commerce module family.

The table field\_config\_instance describes the relationships between drupal fields (which are actually tables such as field\_data\_commerce\_line\_items) and higher level entity types (i.e. node) and bundles (i.e. content type) that reference them.
> 1 votes

---
Tags: 7, commerce, database
---


# Question
Title: What is the best way to make sure Array in PHP are closed correctly
I wonder how to determine when to close an array. I edited a aliases.drush.php and added a database array but now, while I have multiple array I got a syntax error. Is there a easy rule to remember how to close an array without getting syntax errors when a file has about 300 lines?

# Answer
> 3 votes
It is no longer necessary to put `databases` into your Drush alias file. In older versions of Drush, a `databases` record in an alias file could be used to allow Drush to do an sql-sync to or from a remote system that did not have Drush installed. This feature is no longer supported, and the `databases` record is no longer necessary.

To answer your specific question, though, any php nested array must have balanced parenthesis. Make sure that you have one `(` for every `)`. Folks usually keep track of their parenthesis via indentation -- add a level of indentation for each `(`, and remove it for each `)`.

# Answer
> 1 votes
> how to close an array without getting syntax errors when a file has about 300 lines

Choose a suitable IDE / code editor is very important for coding. Most of the IDE / code editor have aids to help code completion or syntax error detection.

For example, in SublimeText, you can install below packages for help:

---
Tags: drush
---


# Question
Title: When should I use Backdrop CMS rather than Drupal 8?
From what I've heard, Backdrop is basically an alternative to Drupal 8.

* Is deciding which one to use simply a matter of preference and ideology, or are there specific use cases for each?
* If I'm upgrading from 7, how do I decide which way to go?

# Answer
> 20 votes
Backdrop CMS is a good choice if:

* You are currently spending a lot of time managing your configuration using Features module. Backdrop includes built-in Configuration Management tools that allow you to deploy configuration across environments using JSON files, which should save a lot of time compared to Features.
* Your needs are met by the current selection of Backdrop Contributed modules or you are capable of porting modules to Backdrop (it takes a few hours per module generally speaking). References from: Lullabot, Tag1, and Backdrop documentation.
* You are familiar with Drupal 7 code and would like to transfer that knowledge to a newer system that will be supported in the future. Backdrop code is nearly identical in concepts, though there are several new additions to manage configuration. Drupal 8's code base is significantly different in many fundamental concepts.
* You have an existing Drupal 7 site that you would like to upgrade. Backdrop includes an upgrade path (via update.php) that can upgrade your existing Drupal 7 site to Backdrop. Drupal 8 does not include an upgrade path from Drupal 7; the plan is to provide migration tools to move from Drupal 7, but at this point, it is not yet working. Backdrop does not yet have a port of the Migrate module, but it probably will in the future (since porting modules from Drupal 7 is fairly trivial).
* You want to upgrade/build a site right away. Backdrop 1.0 had been out for about 2 months now and is stable. Drupal 8 may be coming out some time later this year (though we can only estimate the date). Drupal 8 does not yet support upgrades even between beta versions, so if you build a site on it now, you won't be able to upgrade it when the final version comes out.

Other features that Backdrop includes:

* Backdrop is slightly faster than Drupal 7 out of box because of it's lighter core. Generally it's about the same speed as D7 but since D8 is slower than D7, Backdrop is faster than D8.
* Backdrop has a built-in Panels-like module (Layout) that replaces the old Block system. Blocks are given new powers like contextual information, advanced conditional selection, multiple instances, control over markup, and config-based settings.
* Updated libraries (e.g. new jQuery versions).
* Responsive, HTML5 elements, and better mobile support out of the box.
* All the other features listed on the Backdrop CMS homepage.

# Answer
> 10 votes
Backdrop is a fork of Drupal 7. You don't upgrade to Backdrop, you convert. There is some documentation here (https://backdropcms.org/upgrade) on converting a Drupal 7 site to Backdrop.

In terms of which to use, that is the preference of the developer. Some of the things that Backdrop feels are important are here (https://backdropcms.org/philosophy).

In the most general sense, Backdrop remains Procedural, where as D8 moves to more Object Oriented.

# Answer
> 10 votes
Reasons to decide for Drupal 8 instead of Backdrop CMS are **(\*)**:

* D8 is better Internationalization.
* D8 has a Symfony-like architecture.
* D8 has a more robust out of box experience.
* D8 has a much larger support community.

**(\*)**: These bullets are quotes from a comment from quicksketch (from around 'end 1Q2015'), added to his answer to this question also. It ends with "Maybe there should be a whole separate question for that answer" ... Hence "this" answer.

**PS**: There are more reasons then those above ... CMI, TWIG, etc ... Try Drupal (8) to experience them yourself.

# Answer
> 0 votes
Backdrop should be an attractive upgrade to Drupal 7. The concepts already in Drupal 7 have been sensitively extended. The stated intent is to refine not to replace the core. Further, the target market for Backdrop is focused on smaller organizations. Drupal 8 by design has the sophistication to address the needs of larger organizations. It makes sense that there be two open source CMS that are built on a solid security foundation, one aimed at smaller organizations, the other at larger ones. My take is that if Drupal 7 has the concepts you need in your site, then Backdrop is a more promising path forward than Drupal 8. But all of this will depend on Backdrop winning a strong community of supporters. Backdrop makes excellent market sense, and that means that it's likely to evolve in whys that will continue to make it a good fit for smaller organizations. Drupal 7 will be ending. In which future market do you better fit, the smaller Backdrop or the larger Drupal 8?

---
Tags: 8
---


# Question
Title: Using Zurb Foundation without installing the required dependencies: npm, gulp, bower, etc
I just created a sub theme for zurb foundation 6 on drupal 8, and reading the docs it tells me to do a **npm install** and a **npm bower**

When doing a npm install I get the following errors:

I fixed that by figuring out how to update npm and node and that solved that issue. Now I have to install bower and do a **bower install**.

My question is: Do I have to install all these things in order to setup foundation to work? I prefer not to use SASS as I work in a team of devs and sometimes the backend dev goes in to edit the css files without knowing that they have to first turn on a sass compiler before doing that.

# Answer
> 1 votes
Alternatively, you could simply use the ZURB Foundation theme

> Do you like grid systems? How about rapid prototyping? Do you believe in mobile first? Then this theme is for you! Foundation is made by ZURB. **This theme implements the Foundation framework for Drupal**.

# Answer
> 0 votes
This page helped alot on making a sub theme: http://drupal-bootstrap.org/api/bootstrap/docs%21Sub-Theming.md/group/sub\_theming/8

It's not exactly related to foundation, but the concepts are the same and instructions are clearer.

> 1. Copy over one of the starterkits you have chosen from the `./bootstrap/starterkits` directory into the `themes` directory.
> 2. Rename the directory to a unique machine readable name. This is your sub-theme's "machine name". When referring to files inside a sub-theme, they will always start with `./THEMENAME/`, where `THEMENAME` is the machine name of your sub-theme. They will continue to specify the full path to the file or directory inside it. For example, the primary file Drupal uses to determine if a theme exists is: `./THEMENAME/THEMENAME.info.yml`.
> 3. Rename `./THEMENAME/THEMENAME.starterkit.yml` to match `./THEMENAME/THEMENAME.info.yml`.
> 4. Open `./THEMENAME/THEMENAME.info.yml` and change the name, description and any other properties to suite your needs. Make sure to rename the library name as well: `- THEMENAME/globalstyling`.
> 5. Rename the sub-theme configuration files, located at: `./THEMENAME/config/install/THEMENAME.settings.yml` and `./THEMENAME/config/schema/THEMENAME.schema.yml`.
> 6. Open `./THEMENAME/config/schema/THEMENAME.schema.yml` and rename `- THEMENAME.settings:` and `'THEMETITLE settings'`
>
> > **WARNING:** Ensure that the `.starterkit` suffix is not present on your sub-theme's `.info.yml` filename. This suffix is simply a stop gap measure to ensure that the bundled starter kit sub-theme cannot be enabled or used directly. This helps people unfamiliar with Drupal avoid modifying the starter kit sub-theme directly and instead forces them to create a new sub-theme to modify.
>
> ### Enable Your New Sub-theme
>
> In your Drupal site, navigate to `admin/appearance` and click the `Enable and
>  set default` link next to your newly created sub-theme. Now that you've enabled your starterkit, please refer to the starterkit's documentation page to customize.

---
Tags: 8, theming
---


# Question
Title: Cloned Seven/Bartik themes don't show up
I copied bartik and seven theme from core/theme folder into the /theme folder.

* I renamed both into xbartik and xseven.
* I renamed all the files named bartik to xbartik and seven to xseven.
* I did a find a replace in the info and theme files to the corresponding name change of xbartik and xseven.
* Did a flush cache and it doesnt show up.

What else could I be missing in this process?

# Answer
> 0 votes
> I renamed all the files named bartik to xbartik

When you say all the files, I hope you also did **bartik.schema** in the `/config/schema` folder.

> I did a find a replace in the info and theme files to the corresponding name change of xbartik and xseven.

You need to do this **for all files**, including files like bartik.schema, bartik.libraries.yml bartik.breakpoints.yml.

---
Tags: theming, 8
---


# Question
Title: Parameters and key value pairs for VotingAPI
My services definitions list notes that to 'select votes' using VotingAPI I have to POST the parameters 'type' (mandatory), and to 'set votes' I have to post a 'votes' array (mandatory) and 'criteria' array (optional). What are the key pair results I need to call these APIs? For 'type' I have tried 'percent', 'points', 'node', 'vote, but none of those work. For the votes array I need entity ID but how/where can I find the entity ID? I am needing to set and select votes which have been submitted on nodes. Thank you

# Answer
I solved it. The entity ID is the node id (nid) if you are voting on a node for example. eg for nid of 75, it is entity\_id: 75. Other parameters are 'percent', 'points' or 'options' for vote type. And for tag it is 'vote' or whatever custom tag you created as a field. The 'value' of course is the number you are voting. If you are using standard settings for 5star, you enter eg 20 (for 1 star), 40, 60, 80 or 100 (5 stars). The mandatory parameters are entity\_id, tag and value. I've read the system can work out the other details, eg user id from the currently logged in user.

eg this format worked for me: let newVote = \["votes":\[\["value":100,"uid":32,"entity\_id":1,"entity\_type":"node","tag":"vote","value\_type":"percent"\]\]\]

see Votingapi REST server call internal server error - 'services exception: missing entity ID'
> 1 votes

---
Tags: nodes, services, rating
---


title: Getting arguments from URL

text:
# Question
Title: Getting arguments from URL
How do I get arguments from the URL? in other words, what is the equivalent of the `arg()` function of Drupal 7 and previous versions?

# Answer
As reported in the arg() is deprecated and will be removed change record, the Drupal 8 (procedural) equivalent of `arg()` is the following one.

```
$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);

```

As the change record makes notice, not all the times that is the correct code to use. Depending from the context, you should use code similar to the following one.

* Check if a path is for an administrative page

```
if (\Drupal::service('router.admin_context')->isAdminRoute()) {
  // Your code.
}

```
* Add CSS or JavaScript conditionally, basing on the page being visited

```
function mymodule_page_attachments(array &$attachments) {
  if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
    $attachments ['#attached']['library'][] = 'my_module/my_library'; // you'll need to define in mymodule.libraries.yml
  }
}

```
* Load the currently viewed node

```
$node = \Drupal::routeMatch()->getParameter('node');

```

Notice that in the first and last case, in Drupal 7 you should not use `arg()`, but respectively `path_is_admin()` and `menu_get_object()`. The typical *beginner-Drupal-developer* error is using `arg()` also in those cases.
> 17 votes

# Answer
arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6 by mentioned

```
$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
print_r($arg); exit();

```

The output would be parameters in url except basepath or (baseurl),

```
Array
(
   [0] =>
   [1] => node
   [2] => add
)

```
> 5 votes

---
Tags: uri
---


title: Content list empty to Administrator

text:
# Question
Title: Content list empty to Administrator
Using Drupal7, I am logged in as administrator, and I am getting an empty content list, even if there are many nodes created by the administrator user before this.

Even if I add nodes as administrator, the list is still empty.

>

Here is the content view configuration's screen

Why does this happen? How can I fix it?

# Answer
From the screenshot you show, it's clear that you installed and enabled the Administration Views module. In fact, for a fresh Drupal 7 installation, the admin/content page would appear as in the following screenshot.

>

I installed it on my test, and it works fine for me.

>

Once you install and enable the module, that administrative page is replaced from a view. If you changed the view, it could be it is filtering out the nodes to show in that page.
Go to admin/structure/views/view/admin\_views\_node/edit and check the filter criteria aren't too much restrictive. By default, that view has only exposed filter criteria; if you find any not-exposed criterium, that is something manually added to the view, and it could be causing the issue you are seeing. A filter for the content type can cause what you see, but so a filter for the creation date, and many other filters.

As reference, this is the setting page for the view as it comes after installing the *Administration Views* module.

>

Also, the view has a setting for caching it (as any view); if it has been changing from *None* to *Time-based*, then either the query results or the render output could be cached for too long. The default values are *1 hour* for both.

>

The other reason could be that the view is being filtered by the author name. If I put three spaces in the *Author* field, and then I click *Apply*, I get the following.

>

Now the list says *No content available.* even if I still have those two nodes you saw in the previous screenshot. That is because the author name doesn't contain three spaces.
The same happens if I enter three spaces in the *Title* field.

To be sure the exposed filter criteria aren't causing any issue, click on the *Reset* button right to the right of the *Apply* button. That will reset the values for those filters.
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: How to add new form field dynamically on selected change using ajax
I'm trying to make dynamic form in my module: I have one field of type select containing some options, and when selecting one option a new field should be added dynamically to the form which in turn will contain another list of options. here what I try to do but nothing seems to work correctly

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $this->controller = new Place_AdsController();
    $terms = $this->controller->content();

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['level1'] = array(
        '#type' => 'select',
        '#description' => 'Please select level one term',
        '#options' => $terms,
        '#attributes' => array(
            'class' => array(
                'mycategory'
            ),
        ),
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => 'Drupal\Place_Ads\Form\Place_AdsForm::level1SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    return $form;
}
public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    if ($form_state->getValue('level1') != false) {
        $form['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => $terms,
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
        );
        $form_state->setRebuild(TRUE);
    }

    return $ajax_response;
}

```

# Answer
> 2 votes
Build form elements in buildForm() only, not in ajax callback. The ajax callback is only for preparing the ajax response. When the ajax callback is called, buildForm() has already run with the updated $form.

Your ajax response is empty. You didn't add any ajax command to it. See ajax examples how you can do this.

But in your case you don't need any code in ajax callback. It would be enough to simply return the changed part of $form in a div container.

For this put an empty container in buildForm() and move the select form element from the ajax callback to buildForm() and put it in the container, if the condition in $form\_state is met:

```
$form['ajax_wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'ajax-wrapper'],
];

if ($form_state->getValue('level1') != false) {
        $form['ajax_wrapper']['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => $terms,
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
        );

```

And the ajax callback:

```
public function ajaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['ajax_wrapper'];

```

change #ajax to:

```
'#ajax' => [
  'callback' => '::ajaxCallback',
  'wrapper' => 'ajax-wrapper',
],

```

---
Tags: 8, forms, ajax
---


title: Searchable exposed filters on views

text:
# Question
Title: Searchable exposed filters on views
I have an exposed filter of a taxonomy vocabulary (localities) and I want the user to be able to search on it in order to find the desired values more easily.

I am using BEF at the moment. I found the jquery ui multiselect widget but it does not seem to work with views filters.

Thanks

# Answer
> 0 votes
Check this answer.

I also faced same kind of issue and I followed the below url and its worked for me

http://codekarate.com/daily-dose-of-drupal/drupal-7-views-autocomplete-filter

# Answer
> 0 votes
I found the answer...

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

it works as well for taxonomies with multiple selection values.

Hope this helps someone.

---
Tags: views, javascript, input-formats
---


# Question
Title: Why JQuery 2.x was removed since jquery_update-7.x-3.0-alpha2?
I noticed Version 2.1 of JQuery was removed from JQuery Update module since 7.x-3.0-alpha2. Is there any particular reason for that I should be aware of?

# Answer
Version 2.1 has not been removed; its files are still present in the 7.x-3.x-dev development snapshot.
What eventually was done is updating the version 2.1 files to version 2.1.4, since they don't keep multiple 2.1.x versions (e.g. 2.1.0, 2.1.1., 2.1.3).
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Adding a block where an admin can create users on the fly
What methods are there for creating users on the fly for Drupal 8 in a block? I'm creating a page where the admin can create content, but also there is a user reference field. I currently have it expose current users in the system that you can choose from. In order for me to create a new user to the list, I have to goto the admin/people/create page, but what methods are there to expose this user creation form on the content creation page?

I tried inline\_entity\_form but that doesn't work as it is still in alpha. It's best if I can just do this in core. Ajax isn't necessary as reloading the page is ok.

# Answer
> 0 votes
Well, it's a great opportunity for you to learn how to write a custom block, and a custom form in it:

1. Create a new block in one of your module
2. Create a custom form in it.
3. Place your block somewhere in your page. You are done!

For both block and form creation there are nice articles just for Drupal 8.

Good luck!

---
Tags: users, 8, blocks
---


# Question
Title: How to create custom date display format that displays event duration
I am new to Drupal. I want to display event date like,

`"28/07/2016 | 02 PM to 04 PM"`

Default date formats display date like,

`"28/07/2016 - 02 PM to 28/07/2016 - 04 PM"`

How can I create such custom display format?

# Answer
> 3 votes
Do the following:

1. Administration » Configuration » Regional and language » Date and Time
2. There you will see a tab for format.
3. Create a new format string "Y-M-d".
4. Make this as your default for all date fields and you won't see the seconds any more.
5. You don't need the date module for basic formatting.

**UPDATE: From following comment,**

If you want optional End time, use Timefield module

> Timefield is a Field API field for storing simple non-timezone time values, with an optional end time, utilizing a simple JQuery timepicker widget for input.

# Answer
> 0 votes
Using `hook_date_formats()` you can create date format

**Example:**

```
function app_common_date_formats() {
  $formats = array();
  $formats[] = array(
    'type'    => 'test_custom_date_format',
    'format'  => 'd-M-Y',
    'locales' => array(), );
  foreach ($formats as $format) {
    variable_set('date_format_' . $format['type'], $format['format']);
  }
return $formats;

```

}

---
Tags: datetime
---


# Question
Title: Configuration form and submission handler
I am using the following code for Drupal 6.

```
 foreach (variable_get('cleanupeditform_formkeys', 0) as $key => $value ) {
    $form['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key] = array(
      '#type' => 'checkbox',
      '#title' => t('Hide ') . $value,
      '#default_value' => variable_get(CLEANUPEDITFORM_HIDEPREFIX . $key , 1),
    );
  }

```

I need to convert this code to Drupal 8.

In `buildForm()` I generate the form. I need to save the checkboxes values, and I am using the following code.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
     foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: 0) as $key => $value ) {
       parent::submitForm($form,$form_state);
       $this->config('cleanupeditform.admin_settings')
         ->set('element', $form_state['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key])
         ->set('element', $form_state['cleanupedit_allow'][CLEANUPEDITFORM_ALLOWPREFIX . $key])
         ->save();
     }
     parent::submitForm($form, $form_state);
  }

```

Please help me to find out a solution.

# Answer
There are the following errors in that code:

* You call `parent::submitForm($form, $form_state)` inside the `foreach()` loop, when it should be called once, outside the loop
* You keep setting *element*, which means you are only saving a single value
* Your code is still accessing the `FormStateInterface` object as an array, as it was done in Drupal 7

I cannot comment about the `\Drupal::state()->get('cleanupeditform_formkeys')` part, except that I would probably inject the service as dependency, but I would rather use the following code.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: []) as $key => $value ) {
    $this->config('cleanupeditform.admin_settings')
      ->set(CLEANUPEDITFORM_HIDEPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_HIDEPREFIX . $key))
      ->set(CLEANUPEDITFORM_ALLOWPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_ALLOWPREFIX . $key))
      ->save();
  }
  parent::submitForm($form, $form_state);
}

```
> 1 votes

---
Tags: forms, 8
---


# Question
Title: How to change the user-profile.tpl.php file to a customized outline like Linkedin for Drupal 7?
I'm using Drupal 7.9 for an internal website. I'm trying to customize the "user-profile.tpl.php" file so it shows the fields that I've customized in the "admin/config/people/accounts/fields" to be shown below:

\<\<\>\>image block on the left\<\<\>\>

"**Full Name**
Job Title/Position

Your Organization Name Here, INC
1234 Your Address Here
Long City Name, ST 12345

(P) 555-123-1234
(E) emailaddress@somecompany.com"

But I'm having an issue writing the PHP in the "user-profile.tpl.php" file (I didn't touch the user-profile-category.tpl.php or the user-profile-item.tpl.php files)

This is what I've coded, which obviously is printing everything out wrong.

```
<div class="profile" style="float:left; width:100%;">

<div class="profile-image" style="width:20%; float:left;">
    <?php if ($user_picture): ?>
      <div class="user-picture">
        <?php print $user_picture; ?>
      </div>
    <?php endif; ?>
</div>

<div class="profile-info" style="width:80%; float:left;">
    <h1><?php print render($user_profile['field_profile_full_name']) ?></h1>
    <p><?php print render($user_profile['field_profile_job_title']) ?></p>

    <h3><?php print render($user_profile['field_profile_organization']) ?></h3>
    <p><?php print render($user_profile['field_profile_address']) ?><p>
    <p><?php print render($user_profile['field_profile_city']) ?>, <?php print render($user_profile['field_profile_state']) ?> <?php print render($user_profile['field_profile_zip_code']) ?></p>

    <h3>(P)<?php print render($user_profile['field_profile_business_phone']) ?></h3>
    <h3>(E)<?php print render($user_profile['field_profile_e_mail_address']) ?></h3>

</div>

</div>

```

When it prints on the page, everything still has a bunch of page breaks and space in between the info. And the address line isn't included in one block, it puts it on a new line each item.

How do I write the code so I can get the format outlined above?

# Answer
You can utilize views module to achieve what are you looking for, with some CSS styles.

While using views you have two options view user information:

**Option 1:**

1. Create block view (Users)
2. Select user fields you want to display
3. Then add `Contextual filters` (User: Uid)
4. From the configuration page make sure to select `Provide default value`
5. Then from `Type` drop down menu select `User ID from logged in user`.
6. Then apply changes.
7. Save view.
8. Under Structure -\> Blocks locate the new created view in `content region`
9. Configure the block to appear only on the user account page `user` and `users/*`
10. Then you need to clear the original drupal content in the user view account page by apply this custom module.

**Code:**

```
function mymodule_menu_alter(&$items){
  $items['user/%user']['page callback'] = 'mymodule_user_view_page';
}

function mymodule_user_view_page() {
  return array();
}

```

**Option 2:**

1. Create page view (Users)
2. Apply steps 2-6 as **Option 1**
3. Add Path `user/%user` under `Page Settings`
4. Save view.
> 1 votes

# Answer
This seems working.

However there is a issue regarding this implementation.

**Users registered after creating this view block are not able to see any detail in My profile page.**

Only the users registered before creating this block view are able to see their profile page .
> 0 votes

---
Tags: theming, users
---


# Question
Title: How to send email depending upon hidden component value (which will get from url)?
**xxx.com/apply-job/node/1949?jobCode=IR/001&functionalArea=HR**

I have a form in the above `url`, the form components are

```
Name

Email

Resume

```

And also I have `jobcode`, `functionalarea` as hidden field, those field default value is

`%get[jobCode], %get[functionalArea]`

**My question**: How to send email to different address depends upon the hidden component value (functional area component)?

# Answer
# Webform rules

If you'd use the Webform Rules module, you have the power of the Rules module available to produce such eMails. Some details about Webform Rules (from its project page):

> This module adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event?
>
> Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

# Rules URL argument

And to make the value of URL arguments available as a new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 1 votes

---
Tags: webforms, emails
---


# Question
Title: Where can I find custom content type templates file?
Sorry for ask this easy question, I know the net its full of tutorials, but the info is a bit confusing since they are always showing the diference between D7 and D8 (i didn't use a CMS before so it is not helpfull enough)

My "news" custom content displays itself without classes, with the title of every field in the content and I want to modify the creation template. Am I allowed to do that? or its supposed to reach this goal through other way?.

Thanks in advance

# Answer
> 2 votes
I suppose that you want to create custom template for the content type. To do this create a file called **"node--content-type-name.html.twig"**. And save this file in your theme's template directory. Then in this template file define the html structure. Type the field name which you want to display in your template like **{{ content.field\_name }}**.

To find the field name just goto content type -\> manage fields, there you will find the machine name of that particular field.

**P.S :** This solution is for Drupal 8

# Answer
> 2 votes
It's all in here Twig Template naming conventions

```
Nodes
Pattern: node--[type|nodeid]--[viewmode].html.twig
Base template: node.html.twig (base location: core/modules/node/templates/node.html.twig)

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

1. node--nodeid--viewmode.html.twig
2. node--nodeid.html.twig
3. node--type--viewmode.html.twig
4. node--type.html.twig
5. node--viewmode.html.twig
6. node.html.twig
Note that underscores in a content type's machine name are replaced by hyphens.

```

The higher the number the less specific, For example, the last one (6) it affects everything.

While (1) affects a specific node with a specific view mode, Ex: `node--1--teaser.html.twig` will only affect /node/1 with teaser view.

For your case, you want to use (4), so in your case, its **node--news.html.twig**

---
Tags: theming, 8, files
---


title: Leaflet views how add marker by click?

text:
# Question
Title: Leaflet views how add marker by click?
I'm using the module Leaflet and IP Geolocation Views & Maps to display the marker, I need to give the ability to add markers with the mouse click. I'm trying to add a mark on the map Leaflet, with the following code. But for some reason it does not work, if someone can tell what is the reason?

```
(function ($) {
    $(document).ready (function(){
        $(document).bind('leaflet.feature', function(e, lFeature, feature){
        lFeature.on('click', function(e) {
          var lMap = Drupal.settings.leaflet[0].lMap;
          var marker = lMap.marker(e.latlng).addTo(lMap);
        })
      });
    });
})(jQuery);

```

# Answer
I got a solution as follows:

```
(function($){
    $(document).ready(function(){

    var lMap = Drupal.settings.leaflet[0].lMap;
    lMap.on('click', function(e) {
            marker = new L.marker(e.latlng).addTo(lMap);
    });

    });
})(jQuery);

```
> 0 votes

---
Tags: views
---


# Question
Title: How to pass dynamic file location in Form API?
my requirement is to upload files to specific folders. How can I achieve this by using form api. How can I modify below code such that upload\_location should be dynamic. Uploaded file should save into the Folder name provided by the user.
I tried below code but not worked.

**#submit element is not calling custom\_document\_submit function.**

```
 $form['folder_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Folder Name'),
  );
  $form['document'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array('file_validate_extensions' => array('xml')),
    '#upload_location' => 'public://',
    '#submit' => array('custom_document_submit'),
    );
function custom_document_submit($form, &$form_state){
  $destination = $form_state['values']['folder_name'];
  $validators = array();
  $file = file_save_upload('document', $validators, 'public://'.$destination);
}

```

# Answer
> 0 votes
I would suggest using ajax to update the `#upload_location` on demand.

However, ajax on `managed_file` element is quite tricky. Because `managed_file` has its own ajax handling for uploading file. It only rebuilds the file element itself and returns lack of data from other fields during during file upload ajax. So it need to be fixed in some ***hacky*** way

Example code:

```
function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];
  $values = &$form_state['values'];

  $form['folder_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Folder Name'),
    '#submit' => array('mymodule_custom_form_folder_name_submit'),
    '#ajax' => array(
      'callback' => 'mymodule_custom_form_folder_name_ajax',
      'wrapper' => 'edit-file-ajax-wrapper',
      'event' => 'keyup',
    ),
  );

  // HACK: manually construct the folder_name value.
  // $form_state['values'] is empty for other field in file upload ajax
  // because it only rebuild the element rather then the whole form.
  if (!isset($values['folder_name']) && !empty($input['folder_name'])) {
    $values['folder_name'] = form_type_textfield_value($form['folder_name'], $input['folder_name']);
  }

  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#disabled' => empty($values['folder_name']) && empty($input['folder_name']),
    '#upload_validators' => array('file_validate_extensions' => array('jpg')),
    '#upload_location' => !empty($values['folder_name']) ? 'public://' . $values['folder_name'] : 'public://',
  );

function mymodule_custom_form_folder_name_submit(&$form, &$form_state) {
  unset($form['file']['#disabled']);
  $form_state['rebuild'] = TRUE;
}

function mymodule_custom_form_folder_name_ajax(&$form, &$form_state) {
  return $form['file'];
}

```

---
Tags: 7, forms, files
---


title: Print $base_url

text:
# Question
Title: Print $base_url
How can I print `$base_url` in a template?

# Answer
`$base_url` is not available to template files, but you can easily add it to every template file by implementing `hook_template_preprocess_default_variables_alter()` in a theme or a module.

```
function mytheme_template_preprocess_default_variables_alter(&$variables) {
  $variables['base_url'] = $GLOBALS['base_url'];
}

```

Then, in your template file, you just print its value with the following code.

```
{{ base_url }}

```
> 10 votes

# Answer
After a little research. You can't do that. You have to use preprocess functions, controllers, or alter hooks to provide $base\_url later on in your twig template file.
> 1 votes

---
Tags: theming, 8, uri
---