# Question
Title: Change decimal separator to comma using commerce-order:commerce-order-total:amount_decimal
I use D7 in a commerce website. I am setting up an email that will be sent to the user who just made an order. In this mail, the token \[commerce-order:commerce\_order\_total\] is used to display subtotal, vat, shipping and total.

As you can see in the screenshot i use EURO as currency where the decimal separator is comma ','. (The translation is in Greek). So far so good. After some information in the email, i need to indicate the exact amount that should be paid. I tried with token \[commerce-order:commerce-order-total:amount\_decimal\] but as you can see the decimal separator is the dot and not the comma...

Is it something i can do to fix that ?

# Answer
> 1 votes
You can achieve it with hook\_commerce\_currency\_info\_alter(). Please do refer the discussion in this thread, you will get an idea. Comma as decimal point

---
Tags: commerce, tokens
---


title: Infinite redirects with drupal_goto

text:
# Question
Title: Infinite redirects with drupal_goto
I am writing my own 403 page, and would like to redirect the user to the login page if the user is not logged in. I use this code in a page callback, but when I am viewing an unauthorized page (say `/user/1`) as anonymous user, I got infinite redirect to `/user/1`.

```
function MODULE_membercheck() {
    global $user;
    if (!$user->uid) {
        //drupal_goto('user/login', array('query' => array('destination' => 'member/check')));
        drupal_goto('user/login'); //these two lines won't work
        return;
    }
    // other stuff.
}

```

## update

It is quite easy to reproduce the problem. Just create a module and add a menu (`member/check`), and redirect anonymous user to login page in the `page callback` function. Then set the default 403 page to this menu entry, and try to open an unauthorized page.

# Answer
> 4 votes
Where is `MODULE_membercheck()` getting called from? It would seem that it's getting called on `user/login` page requests which makes these pages redirect to themselves, hence the infinite loop.

You can either modify the calling of the function to ensure it doesn't get called on the login page or add a check in your function to make sure the current path is NOT `user/login` before doing the redirect, something like this:

```
function MODULE_membercheck(){
  global $user;
  if (!$user->uid && current_path() != '/user/login') {
    drupal_goto('user/login', array('query' => array('destination' => 'member/check')));
  }
  // other stuff.
}

```

# Answer
> 1 votes
Below are 2 options to implement what you're looking for, provided using a contributed module for this is acceptable (if not you may want to use it as a temporary work around).

# Option 1: Use the CustomError module

The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without creating nodes for each of them. Some more details about its features (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

You'll probably be interested mostly in the part about "*Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.*".

# Option 2: Use the Rules module

Assume the path of the "Default 403" page is set to `no_access` (via admin). Then create a rule using the Rules module, with as **Event** something like "After visiting node `no_access`". So that the entire rule would look something like so:

* **Events:** After visiting node `no_access`
* **Conditions:**

1. *User has role(s)* \- `Parameter: User: [site:current-user], Roles: anonymous user`
    2. *NOT Text comparison* \- `Parameter: Text: [site:current-page:url], Matching text: user/login`
* **Actions:** *Page redirect* \- `Parameter: URL: user/login`

# Answer
> 1 votes
I was also running into redirection loop with `drupal_goto()` (was trying to send anonymous users to login page) with no obvious reason. Then I replaced `drupal_goto()` with php's `header()` redirection and it worked well. Not sure what was the problem with `drupal_goto()` but other one saved the day. It's worth trying.

---
Tags: 7, redirection
---


# Question
Title: Can I stop Drupal from trying to get file size from URLs when saving files?
Saving a Drupal file with an S3 URL results in a watchdog message like this:

> PHP Warning: filesize(): stat failed for https://s3.amazonaws.com/\[…\]

This happens because Drupal 7's `file_save()` runs `filesize()` unconditionally on every file's URL before saving, and it seems to fail for all URLs even when it is publicly available. I've verified that the file is available using `curl` and I've subsequently verified that `filesize()` still fails, so this is not a timing issue (there are no special characters in the URL):

```
# curl --head https://s3.amazonaws.com/[…]
HTTP/1.1 200 OK
[…]
Content-Length: 9008
Server: AmazonS3
# php -a <<< "echo filesize('https://s3.amazonaws.com/[…]');"
[…]
PHP Warning:  filesize(): stat failed for https://s3.amazonaws.com/[…] in php shell code on line 1

```

Is there a way of avoiding such warnings when running `file_save()` *not* involving silencing errors globally?

# Answer
> 0 votes
Via another question, a workaround is to write a custom error handler which ignores only this specific message:

```
function filesize_for_url_ignoring_error_handler($severity, $message, $file, $line, $context) {
    global $originalErrorHandler;
    if (strpos($message, 'filesize(): stat failed for https://') !== 0) {
        $originalErrorHandler($severity, $message, $file, $line, $context);
    }
}

class […] {
    public function […] {
        $originalErrorHandler = set_error_handler('filesize_for_url_ignoring_error_handler');
        $file = file_save($file);
        restore_error_handler();
    }
}

```

Not ideal, but it works.

---
Tags: files
---


# Question
Title: How do I use page_callback or pageshow to display an existing article, view, page, block, or a slide show?
can someone give me these examples to show an article or a block, page that already existing in a drupal website using pageshow or page\_callback?

I currently can only successfully showing a link of the article, and then it lead me to the node. Here is my custom js code:

```
/**
 * Implements hook_menu()
 */
function intro_menu() {
  var items = {};
  items['intro'] = {
    title:'Introduction',
    page_callback: 'intro_page',
    pageshow: 'intro_page_pageshow'
  };
  return items;
}

function intro_page() {

 try{
  var content = {};
  content['my_stuff'] = {
    //markup: '<p>Nice stuff!</p>'
    theme: 'link',
    text: 'SlideShow',
    path: 'node/12'
  };
  return content;
 }
 catch (error) { console.log('intro_page - ' + error); }
}

function intro_page_pageshow() {
 // drupalgap_alert('My pageshow event has been called!');
}

```

After some trying, I can now do it with the following code:

```
    //page_callback
function intro_page() {
  return '<div id="my_node_3"></div>';
}

function intro_page_pageshow() {
 // drupalgap_alert('My pageshow event has been called!');
 try{
        var nid = 3;
        node_load(nid, {
        success:function(node){
         var content = node.content;
         $('#' + 'my_node_' + nid).html(content).trigger('create');
          }
        });
  }
  catch (error) { console.log('intro_page_pageshow - ' + error); }
}

```

But it's just the content, not the whole node.

I am still trying to display a page of slide show... The problem is I cannot find the node id from a "page". I tried the "path", but it does not work.

# Answer
> 0 votes
If you want your app's front page to show a node, then you can just set the front page to that node, in `settings.js`:

```
drupalgap.settings.front = 'node/12';

```

Under the hood DrupalGap already has a page\_callback (and pageshow) that can load and render all core entity types. As you noticed with nodes, you simply linke to `node/[nid]` to view a node.

As for blocks, DrupalGap does not interface with blocks stored in Drupal, instead DrupalGap can create its own blocks for display in the app: http://docs.drupalgap.org/7/Blocks

---
Tags: javascript
---


title: Exporting menu along with code

text:
# Question
Title: Exporting menu along with code
I am new to Drupal 8, been developing only with D7 until now and I have a question regarding menus. I need to create this basic main menu for the page, but I am not sure how to export it and send to the test site, later to production environment. What is the best way to export something like this without features? I've heard something about `hook_install()` functions in the profile that allow this, but I cannot really find any information about this. Can someone please provide me with some guidance? Thank you in advance.

# Answer
As far as I know, the menu itself is exportable by the built-in config management but the links are not (because the menu is config, the links are content). So when you export the configs and import it on the target environment, you get an empty menu.

What you could do is manually create the menu links programmatically during deployment. One technique is to use a "deployment module", where you use a dummy module and take advantage of `hook_update_N`. As for creating the menu items in Drupal 8, this answer can probably help you.
> 1 votes

---
Tags: 8, features, taxonomy-terms
---


title: When to use Bundles vs Entity Types

text:
# Question
Title: When to use Bundles vs Entity Types
I have a design question:

I have several models that lend themselves to inheritance very well.

I have an `animal` object that has attributes that are shared between the `dog`, `cat`, and `hamster` objects very nicely. However, the source of the `dog`, `cat`, and `hamster` are all from different APIs.

So what I started doing was to build my module around each of the APIs, with the necessary 'fields' effectively hardcoded in the module `animal`. I knew that this horrifically violates the DRY principle; but am from the D6 (barely D7 era and hadn't really been introduced to entity types). This was using custom tables, and custom 'models'. This also means that I have to create the views, and all the other stuff associated with it myself.

So then I realized that I could actually use `entity types` for this. The core `animal` module exposes only what it needs to (a small set of fields). And the `dog`, `cat`, and `hamster` modules all extend the `animal` entity type thus giving me access to all the shared data without having to repeat myself **and** the added bonus of having views, handlers and the other stuff for almost free (a bit of boilerplate that is copy and paste...).

My questions are thus:

1. Is this thinking right, that content entity types are the way to go?
2. I know what I gain, but what do I lose by doing this?
3. Is this a good approach, i.e. is it fair to extend a base entity type?
4. Is it better to create `bundles` for each of the `dog`, `cat`, `hamster` or just use the extending of the `animal` content type?
5. When do you use a bundle vs extending a content type?

# Answer
> 8 votes
Yes, using content entity types for this seems like a good idea.

In regards to entity types vs. bundles, which one is better for you depends on your exact requirement (I only noticed after already writing most of this that you already mentioned and specifically asked about entity types vs. bundles, so might be too much explanation, but too lazy to rewrite now :)).

# Entity types

You create separate content entity types. Whether you use inheritance for sharing the base field definitions or for example a trait is up to you. The inheritance only exists in code, the data itself knows no hierarchy, it is stored in separate tables.

But yes, sharing code there is perfectly valid. Drupal 8.4 for example adds a base class for publishable entity types: EditorialContentEntityBase, see https://www.drupal.org/node/2870643.

The advantage of this is that you can build each entity type with exactly the base fields that you need, which results in an optimized storage (1-4 base field tables, depending on whether you need revisions and/or translation support and separate tables for multi-value fields). However, the main drawback is that there is no API, neither views nor entity query that allows you to list different types of animals in a list. If that's a requirement, then this might be a no-go.

# Bundles

You create a single animal entity type and different bundles for the different types of animals. This is like the node entity type and bundles. They share the same base fields and storage, additional type-specific fields can be added as configurable fields or maybe also per-bundle base fields (I honestly have no idea how well that actually work - and I'm supposed to be one of the maintainers of the entity system). This is the opposite of the above, it's easy to create lists with different animals but you might end up with a considerable amount of per-field tables if you have a lot of fields on your dogs/cats etc.

In regards to downsides, content entities are pretty heavy, they have a complex structure based on typed data and are therefore slower than plain custom objects. Their storage, while extensible, is also limited in various ways, you can only load full entities and there is no support for bulk update for example (but you can implement some things in a custom storage handler). But you get a ton of features for that, the mentioned views integration, widgets/formatters, cache handling/invalidation, revision and translation support and so on.

---
Tags: 8, entities
---


title: Cache max-age and varnish ESI

text:
# Question
Title: Cache max-age and varnish ESI
I need to display a custom block on my homepage. This custom block retrieves some data that are not managed by Drupal. Since no event will happen in Drupal to say that those data have changed, the max-age cache property seems the way to go, and it's OK for me. The block appears exactly as expected, but the problem is thst the cache for this block seems to never expire. Actually, the block is never refreshed.

After researching, I found Setting cache max-age to 0 has no effect on Block built using BlockBase? that explains max-age cache property doesn't work as expected for anonymous requests. After adding the mentioned trigger, everything seemed to be all-right on my development environment.
Once on the production environment, it's the same as before: The block is never refreshed. Talking to the hosting provider, I was told that Varnish is used to cache the whole page, and I should use an ESI (*Edge Side Include*) to render this block with its own cache logic managed by Varnish.

I don't really know how to implement it in a clean way in Drupal. My first idea is to use a controller, render the block markup, and return in a response, forcing the needed cache-control header. This is the code I thought of for such controller.

```
$block_manager = \Drupal::service('plugin.manager.block');
$plugin_block = $block_manager->createInstance('my_block_id');
$buildedBlock = $plugin_block->build();
$renderedBlock = \Drupal::service ('renderer')->render ($buildedBlock);

$response = new Response(
    $renderedBlock,
    Response::HTTP_OK,
    array('content-type' => 'text/html')
);
$response->setSharedMaxAge(60);
return $response;

```

I feel it is a totally unclean way to do this. Does anybody a better approach to propose? Would my code work?

# Answer
> 3 votes
max-age 60s is pretty low for the frontpage. Does the data really update that frequently or is it just that it *could* update but usually it doesn't happen every minute?

One possible approach to solve this would be to fetch that external data on a cron job that runs every minute. If and only if you detect a change, you invalidate a cache tag, which invalidates your frontpage. This approach is interesting when the data does not actually change that often most of the time. Because your cache is valid as long as possible.

And it has the added benefit that you do not rely on the external system when users are actually accessing your frontpage. Your block simply delivers the data from state which you update in the cron job.

That said, if you do want to influence the max-age header, then you need to implement your own Response subscriber. You could also use a module like https://www.drupal.org/project/cache\_control\_override, but you have to carefully test different pages to see if it might disable caches in more places than you expect, e.g. a language switcher block can currently do that.

> And uninstall the Internal Page Cache, it caches even uncacheable responses like this and you don't need it if you use Varnish

If and only if you have cache tag invalidation configurated and integrated with Varnish. If not, my recommendation would be to use the internal page cache module and set the default external max-age to a very short time, e.g. 1 minute. Then varnish can cache responses for that long and will revalidate against the internal page cache after that time.

---
Tags: 8, caching, proxies
---


# Question
Title: Search user by field value using Drupal Search Api
I have a set of users with field\_first\_name and field\_last\_name, and i want to create a user search using the search api, to search for users using those fields, but it doesn't seems to be working.

Here is my code:

```
$query = Index::load('default_index')
      ->query(array(
          'offset' => 0,
          'limit'  => 12,
      ))
      ->keys($text)
      ->addCondition('search_api_datasource', 'entity:user')
      ->execute();

```

It's not fetching any of my users per name. I am missing something?

# Answer
On the first hand, can you check if your content is being indexed properly ? If yes, then I would recommend using the default search box provided by drupal, and see if you get results.

Assuming you are using search api solr module.
> 1 votes

---
Tags: 8, search
---


# Question
Title: Is it possible to filter by Content Type Variant in Views?
I have 3 Variants of a Content Type. On one Variant I am listing nodes of that Content Type with a View. I'd like to control what the View returns by limiting the results to 1 variant of the content type.

I've looked through the filter options but haven't found anything that works. Would anyone know if this is possible?

# Answer
> 0 votes
i agree with Niall comment, if is only one contentype, use only one variant and control what to display in views, use content panes views, set contextual filters, relations, and how to pass parameters between views and panels in views ui middle column, pane views are design to "talk" with panels, make several views as needed, add them all to panel variant, and control wich pane to display in panel rules settings. If there are more than one contentype, add a variant for each one.

---
Tags: 7, views
---


# Question
Title: Publish Content in Drupal by One Editor Only
Im a new Admin for an Educational E learning Portal Developed by drupal, the current status of publishing a Content is to be verified or reviewed by two Moderators or Editors. My Question is : How to make (1) Editor publish a content after Reviewing instead of 2?

The Current flow, A "teacher" publish an Educational Content as ( needs review: , then an Editor Reviews that content and then he chooses ONE OF THE FOLLOWING: 1) initial approve 2) send back to Edit " to the teacher" 3) Publish - BUT in order to publish another Editor must review and Publish it to be available as a published content.

the used workflow is the default workbench Flow, But nothing there mentions that 2 Editors must Review,

where can i Find such a code to edit? in which module Block ?

Thank you!

# Answer
> 1 votes
As far as i know, Workbench moderation module works based on user roles. The permission to change the state from needs review to published can be given to one or more roles. It is not possible to give permission to specific person.

In your case:

* Create a new state 'Ready to Publish'
* Add two state transitions, Needs Review -\> Ready to Publish and Ready to Publish -\> Published
* Make sure you remove the state transition Needs Review -\> Published (Or you can revoke the permission for this state transition to editor role)
* Create a role called 'Publisher'
* Assign this role to second editor
* Give state transition permission Needs Review -\> Ready to publish to editor role
* Give state transition permission Ready to publish -\> Published to editor role.

With the above steps, teacher posts the content which will be in needs review state. Editor can review the content and can change the state to 'Ready to Publish'. Now, the second editor who has the role 'Publisher' can review the content and can publish.

---
Tags: 7
---


# Question
Title: Facets rendering on all pages irrespective of value dynamicaaly form contextual filter in views
I m trying to add facets using facets module in drupal 8. i have created listing of all products using views page. on listing page, facets are showing properly as per brand information added from admin panel.

All products listing Page:

but when i go to the detail page of every individual product,facet blcok show only single value of that brand only. check below image for more reference:

Here on detail page , i want to show complete list of facets as shown in first image. how to do that??? any idea??

# Answer
I believe, this is the default behaviour, where the facets are filtered based on the result set. What you want may not be achievable OOB. But this is not a bug, it is a correctly working behaviour.
> 0 votes

---
Tags: views, search
---


# Question
Title: Getting the values and url of an entity reference field using entity query then store it inside a variable
I'm trying to figure out how I can output the values and url of the entity reference field values and display them inside the twig. Here is a sample of the code that I have constructed. I can't seem to find out what else is missing

```
        // Entity Query for Academic Experience Entity Reference Field
        $academicExperience = $query->get('node')
                                    ->condition('status', 1, '=')
                                    ->condition('type','programs')
                                    ->sort('created')
                                    ->execute();

        foreach ($academicExperience as $key => $academic_menu) {

             $academicNode = _nodeLoad($academic_menu);

             //Entity Reference Field
             $variables['academic_menu'][$key]['menu'] = $academicNode->get('field_academic_experience_ref')->value;
        }

```

---

```
                {% for academic in academic_menu %}

                    <span>{{ academic['menu'] }}</span>

                {% endfor %}

```

# Answer
> 2 votes
> Getting the values and url

Sounds like you want to link to the referenced node, so I will assume that you want to do that.

* No need to use entity query at all.

You can do it like this, assuming your content type is Article:

```
function mytheme_preprocess_node(&$variables) {

  $node = $variables['node']; // gets current node object

  if ($node->getType() == 'article') { // checks if content type is article

    $reference_links = array(); // creates empty array
    foreach ($node->field_academic_experience_ref as $item) { // loop through ref field
      if ($item->entity) { // gets referenced node object
        $reference_links[] = $item->entity->toLink(); // gets ref node link, adds to array
      }
    }

    $variables['academic_menu'] = $reference_links; // creates variable

  }

}

```

Then in twig

```
{% for reference_link in academic_menu %}
   {{ reference_link }}
{% endfor %}

```

---
Tags: theming, entities
---


# Question
Title: How do I add a script to page.tpl.php only for anonymous users?
I want to do something like this, but it seems like I'm missing something.

```
<?php
  if (user_is_anonymous()) {
    print <script></script>
  }
?>

```

# Answer
Apart from the obviously invalid PHP (which I'm assuming is just the result of your snippet, and that your actual code is at least syntactically valid), no, you're not missing anything. That's the correct way to conditionally add a script to a template.

The only logic improvement you can make is to use the `$logged_in` variable which is already available to page.tpl.php. As a style/convention improvement, you could also follow Drupal's standards and use the alternate block syntax:

```
<?php if (!$logged_in): ?>
<script>...</script>
<?php endif; ?>

```
> 2 votes

# Answer
If you go to https://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/7.x

and scroll down a bit and click on `view source` you'll see in the comments there is a `$logged_in` variable that you can use.

so simply do

```
if ($logged_in == FALSE) {
  // your PHP code
}

```
> 1 votes

---
Tags: theming, javascript
---


# Question
Title: Drupal 7.36 configuration error: Call to undefined function field_attach_load()
I tried to configure Drupal 7.36 with WAMP and result back with the below error after clicking "configure site". I am using Window7. Please help!

Fatal error: Call to undefined function field\_attach\_load() in C:\wamp\www\sdg\includes\entity.inc on line 320

# Answer
> 1 votes
It looks like this issue has cropped up because of a myriad of potential causes, and some have been fixed while others have not.

The first step, assuming this is an installation from scratch, would be to *empty your database and try again*. I've had the initial install go wrong once and just trying again went fine.

There is an extensive list of fixes at https://www.drupal.org/node/481758. In the unlikely case of Drupal's issue queue going away, here is the main text. I'd recommend going to the link and reading through the (extensive) comments to see if specifics match your situation.

> In certain circumstances, the following error (or something similar) may be displayed during the installation process:
>
> > Fatal error: Call to undefined function field\_attach\_load() in ~\modules\user\user.module on line 270
>
> This error seems to be caused by a problem during the Drupal system installation, causes installation to fail after only creating 31 database tables, and will make requests to the front page of the site display a 'Page not found' error. This seems to happen as a result of various different configuration problems, browser issues, etc. Some of the things you should try to change before throwing your hands up in frustration:
>
> 7: Make sure you're not reaching the configured max\_execution\_time for PHP is not being reached.
>
> 25: Switch back to the default php.ini, restart Apache, and see if install works.
>
> 27: Make sure dependencies\[\] = field is defined in your install profile's .info file.
>
> 34: Using a different browser (e.g. use Chrome instead of Safari) during installation may help.
>
> 36: Switching the bundled jQuery to version 1.7.1 might fix the problem, at least for Safari users.
>
> 37, 42, 54: Dropping the entire database and installing again might fix the problem.
>
> 45, 141: Limiting the database name length to \< 8 characters may fix the problem.
>
> 57: Make sure the database user Drupal is using has all permissions for the database (GRANT ALL ON \[db\]).
>
> 59: Make sure your browser's cookies are enabled when performing an installation.
>
> 61: Restarting php-fpm fixed the problem.
>
> 66: Setting the $cookie\_domain variable in settings.php fixed the problem.
>
> 82: The problem could be related to install.php not loading field.attach.inc at whatever bootstrap level it is running at.
>
> 88: Make sure the $base\_url variable in settings.php is correct.
>
> 92: Ensuring the database name had only lowercase ASCII characters fixed the problem.
>
> 108: Make sure your Apache configuration doesn't do anything that might cause cookies to be dropped.
>
> 135: If it's an install in an existing Drupal directory, temporarily move all the modules in sites/all/modules out of the Drupal tree while installing.
>
> 137: Disable the php opcache module before proceeding with installation As you can see, there are a TON of different things that can cause this issue. The root cause is installation fails during module installation, and won't ever continue past that point until the database is dropped and recreated again.

# Answer
> 1 votes
SAme error on a xampp installation.

Solved setting the collation of the DB to utf8\_general\_ci.

# Answer
> 0 votes
`Solved setting the collation of the DB to utf8_general_ci.`

And before that drop all tables from data base, because in new base I see some tables, not all needed tables, that drupal created before fail. And it fail and fail if I set utf8\_general\_ci and not delete that tables.

---
Tags: 7, installation
---


title: How can I turn a field into a link?

text:
# Question
Title: How can I turn a field into a link?
I've got a content type with fields whose values are URLs. I'd like to use a view to display these as links, using the field label as link name, something like `<a href="{field_value}">{field_label}</a>`.

I've got the field values displaying correctly. I just can't figure out how to turn them into links like above (or if this is even possible).

How can I achieve this?

# Answer
You can use REWRITE RESULTS with REPLACEMENT PATTERNS

```
<a href="[field_value]">Any Text</a>

```

**Example**
If i want to edit any node

```
<a href="node/[nid]/edit">Any Text</a>

```
> 1 votes

# Answer
use hook\_views\_pre\_render()

```
MYMODULE_views_pre_render(&$view) {
  if ($view->name == '<Your-view-name>') {
    foreach($view->result as $key => $row) {
      // change field values to href, or whatever for every row
    }
  }
}

```

OR, if this looks too complex and cumbersome, you can go for template preprocess for one of the templates under **Theme information** in Views UI.
> 0 votes

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


title: How to customize login form page?

text:
# Question
Title: How to customize login form page?
I am trying to customize the login Form using the following code.

```
$elements  = drupal_get_form("user_login");
$form      = drupal_render($elements);
print $form;

```

It render Username, Password field and the log-in button without..

**What's the correct way to render the login form?**

# Answer
Add the following code in the *template.php* for your theme. Replace *mytheme* with the effective machine name of that theme.

```
function mytheme_theme($existing, $type, $theme, $path) {
  return array(
    'user_login' => array(
      'arguments' => array('form' => NULL),
      'render element' => 'form',
      'template' => 'templates/user-login',
    ),
  );
}

```

Then create the *user-login.tpl.php* template file with the following code.

```
<?php
  print drupal_render($form['name']);
  print drupal_render($form['pass']);
?>
<div class="user-login-links">
  <span class="password-link"><a href="/user/password">Forget your password?</a></span> | <span class="register-link"><a href="/user/register">Create an account</a></span>
</div>

<?php
  print drupal_render($form['form_build_id']);
  print drupal_render($form['form_id']);
  print drupal_render($form['actions']);
?>

```
> 1 votes

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


title: "Cannot read property 'icons' of null"

text:
# Question
Title: "Cannot read property 'icons' of null"
With Drupal 8.0.0-rc2, no matter what, I get this error in the JS console:

> Uncaught TypeError: Cannot read property 'icons' of null

I think I have defined everything correctly, so I don't know what causes this error or what I missed.

Plugin definition:

```
/**

* @file
 * Contains \Drupal\codesnippet\Plugin\CKEditorPlugin\CodeSnippet.
 */

namespace Drupal\codesnippet\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\ckeditor\CKEditorPluginConfigurableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;
use Drupal\Core\Url;

/**
 * Defines the "codesnippet" plugin.
 *
 * @CKEditorPlugin(
 *   id = "codesnippet",
 *   label = @Translation("CodeSnippet"),
 * )
 */
class CodeSnippet extends CKEditorPluginBase implements CKEditorPluginConfigurableInterface {
  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return array(
      'codeSnippet_dialogTitleAdd' => t('Insert Code'),
      'codeSnippet_dialogTitleEdit' => t('Edit Code'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return array(
      'CodeSnippet' => array(
        'label' => t('CodeSnippet'),
        'image' => drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/codesnippet.png',
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) {
    $form_state->loadInclude('editor', 'admin.inc');

    $styles = $this->getStyles();

    $form['highlight_style'] = array(
      '#type' => 'select',
      '#title' => 'Highlightjs Style',
      '#description' => t('Select a style to apply to all highlighted code snippets. You can preview the styles at !link.', array('!link' => \Drupal::l('https://highlightjs.org/static/demo', Url::fromUri('https://highlightjs.org/static/demo/')))),
      '#options' => $styles,
      '#default_value' => !empty($form_state->storage['editor']->settings['plugins']['codesnippet']['highlight_style']) ? $form_state->storage['editor']->settings['plugins']['codesnippet']['highlight_style'] : 'arta.css',
    );

    return $form;
  }

  /**
   * Returns available stylesheets to use for code syntax highlighting.
   */
  private function getStyles() {
    $styles = preg_grep('/\.css/', scandir(drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/lib/highlight/styles'));
    $style_options = array();

    foreach ($styles as $stylesheet) {
      $style_options[$stylesheet] = $stylesheet;
    }

    return $style_options;
  }
}

```

The icon on the toolbar when editing the text format appears just fine, I can drag it in and out of the active toolbar, and my settings form shows. But due to the JS error generated, it does not work.

The plugin used is available on ckeditor.com, I dropped it into the plugins/codesnippet/js folder untouched.

I can't find any other examples of custom plugins using anything called 'icons'.

# Answer
> 0 votes
Latest release of Drupal (8.0.0-rc3) fixes this. CKEditor was upgraded.

# Answer
> 1 votes
@Kevin are you sure the fix was due to CKEditor being upgraded in that Drupal version? I'm getting the same kind of issue trying to add the Link plugin, on Drupal 8.1.1, which is using CKEditor version 4.5.8.

Trying to find more insight on this issue.

edit: upon manually upgrading CKEditor to version 4.5.9 I'm getting much more illuminating error messages:

> Uncaught Error: \[CKEDITOR.resourceManager.add\] The resource name "link" is already registered.
>
> Uncaught TypeError: Cannot set property 'getLinkAttributesParser' of undefined
>
> Uncaught TypeError: Cannot read property 'icons' of null

So looks like this is colliding with the Link plugin that comes with Drupal (which is lacking some features). So I'll find a way to sidestep this name space collision and will update here.

edit: renaming the plugin proved unfruitful. Still getting:

> Uncaught TypeError: Cannot read property 'icons' of null

# Answer
> 0 votes
You can check the Click to tweet module here-\> ( https://www.drupal.org/project/tweet\_text) It also does somewhat like you need:

> The easiest way to promote, share & track your content on Twitter.
>
> Provides an input filter and CKEditor plugin for making text in content tweetable, just by clicking on the sentence or phrase itself! It uses the CKEditor plugin through which you can add the link for text ,userhandle and the description in any sentence or paragraph ,which is to be tweeted.

Disclaimer: I wrote this module.

---
Tags: 8, wysiwyg
---


# Question
Title: Using token_replace in php filter with webform2pdf
I'm trying to use submission id of webform in webform2pdf.

My problem it is possibility of usage result of token\_replace in php filter.

```
<?php
  $node = node_load(53470);
  $sid_token = '[submission:sid]';
  $sid = token_replace($sid_token, array('node' => $node));
  print 'strlen($sid) = '. strlen($sid);
  foreach (str_split($sid) as $position => $symbol) {
    print 'Position ' . $position . ', symbol ' . $symbol . '<br>';
  }
  print 'echo($sid) = '; echo($sid);
?>

```

\[submission:sid\] must return string '145', but result is:

```
strlen($sid) = 16

Position 0, symbol [
Position 1, symbol s
Position 2, symbol u
Position 3, symbol b
Position 4, symbol m
Position 5, symbol i
Position 6, symbol s
Position 7, symbol s
Position 8, symbol i
Position 9, symbol o
Position 10, symbol n
Position 11, symbol :
Position 12, symbol s
Position 13, symbol i
Position 14, symbol d
Position 15, symbol ]

echo($sid) = 145

```

As I understand it means that token\_replace function is called after php filtered expression execution but I need to use result of $sid inside php

```
<?php $submission = webform_get_submission(53470, $sid); ?>

```

# Answer
When you use `token_replace()`, you need to provide it with a proper data array. Since you provide it with a node, your token replace can only replace `[node:*]` tokens (exceptions for global tokens such as `[site:*]`). If your submission is a node, you should be able to use `[node:nid]` instead.

If you were to use `$sid = token_replace($sid_token, array('submission' => $node));`, you can use tokens like `[submission:*]`, but only with node properties (`nid` instead of `sid`).

If your submission is of another entity type, you will have to provide that as data as well.
> 0 votes

---
Tags: 7, tokens
---


# Question
Title: Different roles depending on a user's field
I have a problem that I have not a clear idea of how to solve it, the problem is the following: We have a user form registration where there's a mandatory field that is Country. I have also a content type that is called mobility that has a field, incoming country (among others). The thing is that now, I have to make that only users of for example USA, can modify the contents where USA is the incoming country.

I've seen that this could be "done" by just allowing a user from a certain country to view the USA contents but it's not the perfect approach since when I'm in a link like "../content/id/edit" i could try different id's and be able to modify a content that I would not be able theoretically. The only way I see to do it "well" would be to do some approach like having one role for each country but is not scalable.

Any solid approach to solve this problem?

PD: I can't solve it by IP (there's a module) because this user when (s)he registers, choose the country that is from (explaining why would be a bit long but it's a correct approach for what we are looking for)

# Answer
> 0 votes
You should be able to do this with a custom module and without roles. There is plenty of documentation around for creating custom modules, so I will not go into those details.

In your .module file, make use of hook\_node\_access:

```
function MODULENAME_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  // Only work on edits.
  if ($type == 'contry_content_type' && $op == 'edit') {
    // Field get items returns an array.
    $user_countries = field_get_items('user', $account, 'country_field_name');
    $content_countries = field_get_items('node', $node, 'node_country_field_name');

    if ($user_countries[0] == content_countries[0]) {
        return NODE_ACCESS_ALLOW;
    }
  }

  // Returning nothing from this function would have the same effect.
  return NODE_ACCESS_IGNORE;
}

```

---
Tags: 7, users
---


title: Image Optimaization

text:
# Question
Title: Image Optimaization
Dears,

i have images with 2000 * 700 pixel and i have to render those images in two different places one with original diminution while the second is with 100 * 60 pixel so each time i have to load the full size for the image which cause a performance issue, how i can render a different image size (do image resizing) according to my UI design

we tried a lot of modules but since its a physical path we could not find a solution .

Regards

# Answer
> 0 votes
You don't need a third-party module for this. Assuming the image is part of the content, Drupal comes with Image Styles which allows you to alter on-the-fly how an image is rendered. See the Adding and Changing Styles section of the linked document for more details.

In summary, go to Administration \> Configuration \> Media \> Image styles. Then you define a style. You'll most likely need the "scale" effect for this. Set width to 100 and leave height blank to preserve the ratio. Then save. Then on whatever you are using to configure rendering of content (manage display, panels, views, etc.), set the formatter of the image to render the image, and to use the style you just defined (by default, this is the setting with the Original value).

If you mean to do this programmatically, you can call the style directly using `theme`. See this answer for more details on how to do that.

Under the hood, Drupal will take the image, resize it using whatever toolkit is configured (by default it's GD) to whatever the image style defined. It does not alter the original image, but creates a copy. A quick way to know if this is working is if you inspect the image and see that the url has the name of the image style.

---
Tags: media, performance
---


# Question
Title: How can I edit the html of the title of my node page
I have a content-type "foo" and some nodes with that type. Now, if you go to one of the node pages, e.g. /node/22, you see the node title as the page title.

I can edit the html of the whole page using node--foo.tpl.php but I can't edit the title/titles html.

How can I change the html of the title div on such a page for a specific content-type?

# Answer
> 0 votes
Depending on your current theme, the title may be found in the `node.tpl.php`, the `page.tpl.php` (usually this one) or `html.tpl.php`. Enable theme debugging to toggle theme debug comments. That way, you see which templates control which portions of the page.

Add the following to `settings.php` and refresh a couple of times (clear cache if it becomes stubborn). Then inspect the page.

```
$conf['theme_debug'] = true;

```

With theme debugging on, you'll also see the progression of template name suggestions in the comments, with the top most/most specific/longest name being selected first.

You can also add to this list by altering the `theme_hook_suggestions` property in the variables argument of the appropriate `hook_preprocess_` hook. If I remember correctly, there's no suggestion content type suggestion for templates. If so, you'll have to add one.

---
Tags: 7, nodes
---


# Question
Title: How do I deal with serialization unsetting object members?
Let's say I have a plugin that uses an injected service to get some object. The object is expensive but can't be serialized, so I can only store it as long as my plugin instance lives.

To keep it away from `DependencySerializationTrait`, I declare it private.

```
class MyPlugin extends SomePluginBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\module\ServiceInterface
   */
  protected $service;

  /**
   * @var \Drupal\module\SomeUnserializableThing
   */
  private $data;

  /**
   * Constructor
   *
   * @param \Drupal\module\ServiceInterface $service
   */
  public __construct(ServiceInterface $service) {
    $this->service = $service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('my_module.service'));
  }

  /**
   * {@inheritdoc}
   */
  public getData() {
    if (!$this->data) {
      $this->data = $this->service->loadData();
    }
    return $this->data;
  }

}

```

Unfortunately, after serializing and unserializing the instance doesn't have *any* reference to the member - not even NULL. What happens in ::getData is that the `!$this->data` check causes an E\_NOTICE error *even though that variable is explicitly defined in the class*.

Are we back to the dark age of `isset()` and `empty()` here, or do I need to implement \__wakeup() for all my classes to explicitly initialize their private members to NULL? Both seem unpalatable...

# Answer
> 0 votes
\__sleep() works by returning properties that need to be serialized. A private property is invisible, won't show up in $vars and therefore is also not serialized and just silently dropped.

Either don't use private (it only serialized *services*, I assume data is not a service), or override \__sleep(), call the parent and then add data to the list of properties to be serialized.

---
Tags: 8
---


# Question
Title: How do I style a node page for a specific content type?
I have a content-type "foo". As you know, you can look at such a node by using it's nid and going to /node/nid. I'd like to create 100% custom markup and CSS for this page.

I want code and files and only code and files. So, what I'd expect is a MVC architecture, meaning, that there's a template file to which all the node related data is passed and I can easily change the markup. But since Drupal isn't MVC at all, it somehow gets very complex and I absolutely don't get the architecture here. I'm not sure can use one template only; if so what's the naming pattern?

Can someone tell me the cleanest and easiest way to create the HTML for the node page?

# Answer
> 0 votes
The easiest way is to create a new template file called `node--[node-id].tpl.php`, for example `node--10.tpl.php`

Then you just need to copy/paste your code from the node.tpl.php you have on your actual theme and change it like you want. For the CSS, the cleanest way I think is to add a custom class in your template high enough to be able in your CSS to target it.

You can have a look at this answer that explains the difference between `node--[node-id].tpl.php` and `page--node--[node-id].tpl.php`

---
Tags: 7, nodes
---


# Question
Title: How to pass theme variables in #theme in a form element?
I need to pass product variable defined in hook\_theme() and invoked in #theme but not sure how to pass product variables in #theme Please suggest.

```
    function storeinv_theme() {
      return array(
        'storeinv_pickup' => array(
          'variables' => array('product' => NULL),
        ),
      );
    }

    function storeinv_uc_product_description($product)      {
      $description = array(
        'pickup' => array(
          '#product' => array(
             '#type' => 'value',
             '#value' => $product,
           ),
           '#theme'  =>'storeinv_pickup',
           '#weight' => 1,
         ),
      );

       return $description;
}

    function theme_storeinv_pickup($product){

            $data = $product['#value']->data;

            if (isset($data['pickup']['store_id']))
            {
                    $store_id = $data['pickup']['store_id'];
                    $day = $data['pickup']['day'];
                    $date = date( 'l m/d/Y g:ia', strtotime( $day ) );
                    $result = views_get_view_result('field_altstoreid_value','default');
                    foreach($result as $k => $v){
                      if ($store_id == $v->field_altstoreid){
                            $name = $v->title;
                            return "<p>Pickup " .$date."at " . $name." </p>";
                      }
                    }
            }
            else {
                    return '';
            }
    }

```

# Answer
Minor syntax change required...

```
function storeinv_uc_product_description($product)      {
  $description = array(
    'pickup' => array(
      'product' => array('#type' => 'value', '#value' => $product),
      '#theme'  =>'storeinv_pickup',
      '#weight' => 1,
    ),
  );
  return $description;
}

```

Your `product` variable doesn't need to be prefixed with a hash character. Thats used for specific keys/properties of the render array.
> 0 votes

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


# Question
Title: Change path prefix URL for multilanguage
I''ve got my drupal 8 content in 5 languages and now I'm trying to change path prefix foreach lang (e.g: zh-hant by zh).

The problem cames when trying to edit some content type and I've got a 404 error. There's no problem for the content with the new path prefix

* old url --\> www.mysite.com/zh-hant/mycontent
* new url --\> www.mysite.com/zh/mycontent (works fine on front)
* new edit url --\> www.mysite.com/zh/mycontent/edit (Crashes with a 404)

# Answer
> 0 votes
your node edit link should be rather something like

www.mysite.com/zh/node/NODE\_ID/edit

I guess you are using the alias of the node and you are appending "/edit", which would not work usually.

---
Tags: nodes
---


# Question
Title: Show translated content in view listing page when accessing translated site
I have a view that filters for a specific content type (accommodation) and shows a paginated list for the user.

The site has a second language (Welsh) and a few of the content nodes have Welsh translations.

In theory, I should be able to visit the accommodation view, and if I was on the Welsh site (http://www.example.com/welsh/accommodation) I should see the Welsh nodes listed.

Sadly, this is not the case exactly.

My view is able to filter the Welsh translated nodes, but the view is spitting out the English text (title, URL, description etc) and not the Welsh versions.

This makes it pretty pointless, especially the fact that the URLs are rendered as the 'normal' English URLs and do not point to the Welsh site.

I've tried a tons of various view options but cannot fathom how to render the translated information.

# Answer
Turns out is was Panelizer causing issues. The site was using v3.0-beta, and Panelizer is currently on v4.0.

I also found a ticket about Panelizer not supporting translations in older versions.

For now, I have removed Panelizer and I am now able to get the correct results.
> 0 votes

# Answer
Have you added a filter to the view for the translation language?

You should be able to set one to only show content in the language of the current page (Which should be welsh if your language detection is setup and working correctly)
> 0 votes

---
Tags: views, 8, i18n-l10n
---


# Question
Title: Unable to show form using controller (module)
I want to make custom page in drupal with form, I checked few examples showing page in drupal via module and example of form via module, i tried to merge them but no success. I made a custom page using drupal module with template (twig) file.

Below is my controller code

```
namespace Drupal\booktestdrive\Controller;
use Drupal\Core\Controller\ControllerBase;

class BiveController extends ControllerBase {
  public function show() {
    $form_class = '\Drupal\booktestdrive\Form\TestForm';
    return [
        '#theme' => 'bive_page_theme',
        '#form' => \Drupal::formBuilder()->getForm($form_class),
    ];
  }
}

```

Template file code

**bive\_page\_theme.html.twig**

```
<section> hii
{{ form }}

</section>

```

**i also created form at src/form/BiveForm.php**

```
namespace Drupal\bive\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class BiveForm extends FormBase {
  public function getFormId() {
    return 'booktestdrive_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['first_name'] = array(
      '#type' => 'textfield',
      '#attributes' =>array('placeholder' => t('First Name*')),
      '#required' => TRUE,
    );

    $form['last_name'] = array(
      '#type' => 'textfield',
      '#attributes' =>array('placeholder' => t('Last Name')),
      '#required' => FALSE,
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }

    public function validateForm(array &$form, FormStateInterface $form_state) {

      if (strlen($form_state->getValue('candidate_number')) < 10) {
        $form_state->setErrorByName('candidate_number', $this->t('Mobile number is too short.'));
      }

    }

  public function submitForm(array &$form, FormStateInterface $form_state) {

   // drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('candidate_name'))));

    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

   }
}

```

**Routing.yml**

```
bdrive.book:
  path: '/brive'
  defaults:
    _controller: 'Drupal\brive\Controller\BriveController::book'
    _title: 'Test'
  requirements:
    _permission: 'access content'

brive.form:
 path: '/brive-form'
 defaults:
   _title: 'Application form'
   _form: '\Drupal\booktestdrive\Form\BriveForm'
 requirements:
   _permission: 'access content'

```

# Answer
> 0 votes
You need define new function theme **bive\_page\_theme** before call it. You can see docs and example. In your case, you can write more code in file **.module**

```
/**
 * Implements hook_theme().
 */
function Your_Module_theme($existing, $type, $theme, $path) {
    return [
        'bive_page_theme' => [
            'variables' => [
              'form' => NULL,
            ],
            'path' => $path . '/templates',
        ]
    ];
}

```

and create file **bive\_page\_theme.html.twig** in folder **templates** of module. Clear cache and go to page.

# Answer
> 0 votes
use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Render\Renderer; //Here declare your class class TestController extends ControllerBase { protected $renderer; public function \__construct(Renderer $renderer) { $this-\>renderer = $renderer; }

```
public static function create(ContainerInterface $container) {
    return new static(
        $container->get('renderer')
    );

```

public function content() { $markup = $this-\>renderer-\>render(\Drupal::formBuilder()-\>getForm('Drupal\questions\Form\QuestionForm'));

```
   return [
  '#type' => 'markup',
  '#markup' => $markup,
];

```

} } in your controller you can do like this also

---
Tags: views, theming, forms, 8
---


title: How can I add class for div .form-item?

text:
# Question
Title: How can I add class for div .form-item?
I am using Drupal 7 and I need to change classes for ALL input textfield wrappers (class='form-item'). How can I do this without JS? please help

I could change form's, form-submit's and submit-wrapper's (form-actions) classes with this code in template.php:

```
    function mytheme_form_alter(&$form, &$form_state, $form_id) {
        $form['actions']['submit']['#attributes'] = array('class' => array('my_class', 'my_own_class'));
    }

```

but I cant do anything with textfields and their wrappers

# Answer
> 1 votes
You can override the output of theme\_form\_element() function in your theme's template.php file. Just copy the function from includes/form.inc file and put it in template.php as MYTHEME\_form\_element(), and you can now change classes for only text fields with something like this before initializing $output variable :

```
if($element['#type'] == 'textfield'){
  // Add a class specific to textfields
  $attributes['class'][] = 'custom-textfield-class';
}

```

This code is not tested, but it should work. You should clear drupal cache after implementing the function in template.php.

---
Tags: theming, forms
---


# Question
Title: What is the difference between "Limit allowed HTML tags and correct faulty HTML" and "Correct faulty and chopped off HTML"?
In CKEditor Filter processes (/admin/config/content/formats/manage/filtered\_html) there are filters.

If you use "Limit allowed HTML tags and correct faulty HTML" do you still also need the other one, or does this one do all that, plus limit?

# Answer
> 1 votes
"Limit allowed HTML tags and correct faulty HTML" does not correct unclosed tags in HTML. SO it doesn't REALLY fix "faulty HTML" at all.

You also need "Correct faulty and chopped off HTML".

---
Tags: input-formats
---


# Question
Title: Database query not working when field is queried as a string
I'm not sure if this is a Drupal issue or a SQL issue but here I go.

I have a database table storing addresses. The schema of the relevant fields look like this:

```
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| address        | varchar(255) | NO   | MUL | NULL    |       |
| address_number | varchar(7)   | YES  | MUL | NULL    |       |
+----------------+--------------+------+-----+---------+-------+

```

I have a page with a search form that searches this table

The problem: whenever I query my table the address\_number field is not working. It doesn't show any results for the address\_number field.

I called `__toString()` on my query and I narrowed down my problem to this:

When address\_number is queried as a string, it doesn't work. i.e. `WHERE address_number = '1600'` returns no results.
However when queried as a number it does return results. i.e. `WHERE address_number = 1600` does work.

How do I change my Drupal database query to make this function properly?

Here is a simplified version of my query:

```
  $fields = array( //This is simplified, there are more fields
    'address',
    'address_number',
  );
  $query = db_select('MY_TABLE_NAME', 'p')
    ->fields('p', $fields)
    ->extend('PagerDefault');
  $query->condition('address_number', $address_number));
  $query->condition('address', '%' . $address . '%', 'LIKE'));
  // Repeat for other fields
  $result = $query
    ->limit(50)
    ->orderBy('p.PRIMARY_KEY')
    ->execute();
  return $result;

```

# Answer
So I did not figure out why this behavior was happening, I did however figure out how to fix it.

In the upload function for inserting data into this table I cast the address\_number to an int and now the query works even if the address\_number is a string or an int. i.e `WHERE address_number = '1600'` or `WHERE address_number = '1600'` both work.
> 0 votes

---
Tags: database
---


# Question
Title: How do I add a custom sorting variable to a view?
I have a view that displays a list of items. Each item has a date field called "Featured Until". This can be set to a future date. If the data is in the future, I want this item to be seen as "featured" and appear at the top of the view.

I can't just sort by "featured until date", because that would still be an issue when the featured date is passed.

Is there any easy way to do this on a view?
Should I perhaps consider just adding a new boolean field called "Featured" and then use cron to update this value when the featured date is passed?

(I don't prefer the second option because I would need to add a cron task for updating.)

# Answer
Have you created a custom theme, or are you using a contrib theme? If you have created a custom subtheme, then you can override the template for this particular view at the appropriate level (e.g. something like views-view-fields.xxx.yyy.twig) and then you can implement custom logic that tests if that particular field is greater than today's date, and then inject a CSS class, or change the markup, etc.

If are not subtheming or just don't want to go down that road, you can do as you suggested and have a "Featured field". There is a module called Computed Fields (which helps you create derived fields, essentially) which *may* facilitate you doing this: https://www.drupal.org/project/computed\_field. I've not tried it myself for your particular use case, but it may be worth exploring.
> 0 votes

---
Tags: views
---


# Question
Title: Does calling query() on a container prevent SQL Injection?
According to this link, `db_query` is now deprecated, and should be replaced by calling `query()` on a container containing a service injected with a database connection.

How do you prevent SQL Injection when using `query()`? The docs only cover how to do so when using `db_query()`, which is deprecated.

Thanks.

# Answer
What reported there for `db_query()` is still valid for the method that you should use. In short, use placeholders when building the query, instead of concatenating the query string with unsafe input (e.g. the input obtained from from the user).

In Drupal 8 procedural code, you would use `\Drupal::database()->query()` instead of `db_query()`, but you would still avoid using code similar to the following one.

```
$count = \Drupal::database()->query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = '. $_GET['user'])->fetchField();

```

The correct code would be the following one.

```
$count = \Drupal::database()->query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = :name', [':name' => $_GET['user']])->fetchField();

```
> 4 votes

# Answer
If you take a look at the one significant line of code in `db_query`:

```
return Database::getConnection($options['target'])->query($query, $args, $options);

```

you can see it just proxies the arguments straight through to the connection's `query` method; if `db_query` is safe, the connection's `query` method is guaranteed to be safe too, because `db_query($sql, $args);` and `$connection->query($sql, $args);` are identical operations.

So all you need to do is maintain a combination of safe query string and parameters, and just pass them to the connection's `query` method instead. Your queries will be safe.

As an aside, `db_query()` only helps to prevent SQL injection if it's used properly. You can't save people from themselves. Case in point, these are perfectly valid:

```
db_query("SELECT * FROM foo WHERE var = '$_GET[baz]'");

Database::getConnection($options['target'])->query("SELECT * FROM foo WHERE var = '$_GET[baz]'");

```

but potentially deadly. Little Bobby will be on his way in no time.

Same goes for any other method. If you use parameters, and don't do crazy things like string interpolation/substitution to put user-supplied input into your SQL string, you're as safe as you can be.
> 2 votes

---
Tags: 8, database
---


# Question
Title: Passing extra image data (EXIF date) to the browser upon adding an image in a form
I am currently using EXIF module to import the DateTimeOriginal tags but it does not display the tag in the form right after uploading the image and I would really prefer to see that info while still filling the form as it affects what I should fill in manually.

I noticed that the image size is displayed next to the image file name after the image has been uploaded, found the code in core/modules/image/image.field.inc that basically hard codes what will be rendered to be sent back to the client in an ajax response. I added a call to exif\_read\_data() right there and appended my DateTimeOriginal tag after the file size and it works fine!

But surely editing core files is not the right way to do that - there must be some hook to use but I can't seem to figure out which one. Besides I would prefer my tag (and maybe other info like image width and height etc) to be neatly accessible via js on the client to update other fields in the form dependent on it.

I would appreciate any advice on what is the right place to put that code.

# Answer
hook\_preprocess\_image\_widget() worked for me.
> 0 votes

---
Tags: 8, ajax, media
---


title: Why are my CSS changes not being saved?

text:
# Question
Title: Why are my CSS changes not being saved?
I have a file for my homepage in the directory `libraries/css/2017-06_Su****.css` I'm making changes to the url path of where the background image is being pulled from and the path change is not taking changes. It's still the old path.

I tried cleaning cache, turned off caching and ran `drush cc` all

This is my css:

```
.banner-background{
 background:url(https://www.no******.org/images/homepage/2017/06/Summer2017_header_1170x470.jpg);
    }

```

I'm changing this to:

```
.banner-background{
            background:url(https://www.no******.org/images/homepage/2017/06/Summer2017_header_1170x470__.jpg);
    }

```

It keeps showing up as this below no matter what I do

```
.banner-background{
 background:url(https://www.no******.org/images/homepage/2017/06/Summer2017_header_1170x470.jpg);
    }

```

I'm wondering why when I modify my css in drupal 7 why the changes aren't being saved although all caching is turned off.

# Answer
I had this problem too, nothing seemed to help. It turned out that the problem was that the page for which the css did not follow the changes was created by a custom plugin. That plugin has a method that returns an array that is used for rendering.

If not specified, caching is default on, and the cached css was always used. In my case specifying the cashing had immediate effect.

In function `build` (which returns the render data), I changed

```
    return array(
        '#markup' => "<div class='taxoblock'>REST HTML</div>",);

```

to

```
    return array(
        '#markup' => "<div class='taxoblock'>REST HTML</div>",
        '#cache'    => array (   'max-age'   => 0 ));

```
> 1 votes

# Answer
Have you tried going to "Home › Administration › Configuration › Development \> Performance" and disabling "Aggregate and compress CSS files"? After doing it, refresh cache.

Regards
> 0 votes

# Answer
Use the Advanced CSS/JS Aggregation module and put it into development mode.
> 0 votes

---
Tags: theming
---


title: Switch homepage

text:
# Question
Title: Switch homepage
What's the best way to deliver a different homepage per user role?

Currently I have an EventSubscriber that redirects the request, but would like to deliver the page at / rather than doing a 302 to /the-other-homepage

# Answer
Your best option is to use Panels/Page Manager module. Override the default homepage and this will give you a lot of different control options.

What you'd want to do from there is to setup different variants based on the different homepage you want to deliver. Use selection rules to select which role gets access to which version of the homepage.
> 4 votes

---
Tags: 8
---


# Question
Title: Custom field with ajax, callback not fired
I want the user to make select the car that he owns. So i am creating a custom field with multiple selects (brand, model, fuel supply, cubic capacity and horse pover).

As i select the brand, no problem showing the models, but as soon as i select the model, the callback is not called.

```
<?php
/**
 * @file
 * Contains \Drupal\test\Plugin\Field\FieldWidget\UsatoWidget.
 */

namespace Drupal\test\Plugin\Field\FieldWidget;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\WidgetBase;

/**
 * Plugin implementation of the 'social' widget.
 *
 * @FieldWidget (
 *   id = "usatoWidget",
 *   label = @Translation("Usato widget"),
 *   field_types = {
 *     "usato"
 *   }
 * )
 */
class UsatoWidget extends WidgetBase {
  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $marche=$modelli=$alimentazioni=array();
    $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('marche');
    foreach($terms as $term)
        $marche[$term->tid]=$term->name;

    $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('alimentazioni');
    foreach($terms as $term)
        $alimentazioni[$term->tid]=$term->name;

    $element['usato_marca'] = array(
      '#type' => 'select',
      '#title' => $this->t('Marca'),
      '#options' => $marche,
      '#prefix' => '<div id="usato_marche_ajax">',
     '#suffix' => '</div>',
      '#ajax' => array(
        'callback' => 'Drupal\test\Plugin\Field\FieldWidget\UsatoWidget::ajaxHandlerMarca',
        #'callback' => [$this, 'ajaxHandlerMarca'],
        'wrapper' => 'usato_modelli_ajax',
        'event' => 'change',
        'method' => 'html',
        'progress' => array(
            'type' => 'throbber',
            'message' => 'Caricamento modelli',
        )
    )
    );

    $element['usato_modello'] = array(
      '#type' => 'select',
      '#title' => 'Modello',
      #'#options' => $modelli,
      '#prefix' => '<div id="usato_modelli_ajax">',
      '#suffix' => '</div>',
      '#ajax' => array(
        #'callback' => [$this, 'ajaxHandlerModello'],
        'callback' => 'Drupal\test\Plugin\Field\FieldWidget\UsatoWidget::ajaxHandlerModello',
        'wrapper' => 'usato_alimentazione_ajax',
        'event' => 'change',
        'method' => 'html',
        'progress' => array(
            'type' => 'throbber',
            'message' => 'Caricamento alimentazioni',
        )
        )
    );

    $element['usato_alimentazione'] = array(
      '#type' => 'select',
      '#title' => 'Alimentazione',
      #'#options' => $alimentazioni,
      '#prefix' => '<div id="usato_alimentazione_ajax">',
      '#suffix' => '</div>',
    );

    $element += [
      '#type' => 'fieldset',
    ];

    return array('value' => $element);
  }
public function ajaxHandlerModello(array &$form, FormStateInterface $form_state) {
        $ajax_response = new AjaxResponse();
        $output=array();
        $triggering_element = $form_state->getTriggeringElement();

        $query = \Drupal::entityQuery('node');
        $query->condition('status', 1);
        $query->condition('type', 'auto');
        $query->condition('field_modello',$triggering_element['#value']);
        $count_budget = $query->execute();

        $nodi=node_load_multiple($count_budget);
        foreach($nodi as $id=>$result){
            $term = taxonomy_term_load($result->get('field_alimentazione')->getString());
            if($term)
                if(!in_array($term->getName(),$output))
                $output[$id]=$term->getName();
        }

        $form['usato_alimentazione'] = array(
          '#type' => 'select',
          '#title' => $this->t('Alimentazione'),
          '#options' => $output,
          '#prefix' => '<div id="usato_alimentazione_ajax">',
          '#suffix' => '</div>',
        );

        $ajax_response->addCommand(new HtmlCommand('#usato_alimentazione_ajax', $form['usato_alimentazione']));
        return $ajax_response;
    }

  public function ajaxHandlerMarca(array &$form, FormStateInterface $form_state) {
        $ajax_response = new AjaxResponse();
        $output=array();
        $triggering_element = $form_state->getTriggeringElement();

        $query = \Drupal::entityQuery('node');
        $query->condition('status', 1);
        $query->condition('type', 'auto');
        $query->condition('field_marca',$triggering_element['#value']);
        $count_budget = $query->execute();

        $nodi=node_load_multiple($count_budget);
        foreach($nodi as $id=>$result){
            $term = taxonomy_term_load($result->get('field_modello')->getString());
            if($term)
                if(!in_array($term->getName(),$output))
                $output[$id]=$term->getName();
        }

        $form['usato_modello'] = array(
          '#type' => 'select',
          '#title' => 'Modello',
          '#options' => $output,
          #'#prefix' => '<div id="usato_modelli_ajax">',
         #'#suffix' => '</div>'
         '#ajax' => array(
        #'callback' => [$this, 'ajaxHandlerModello'],
        'callback' => 'Drupal\test\Plugin\Field\FieldWidget\UsatoWidget::ajaxHandlerModello',
        'wrapper' => 'usato_alimentazione_ajax',
        'event' => 'change',
        'method' => 'html',
        'progress' => array(
            'type' => 'throbber',
            'message' => 'Caricamento alimentazioni',
        )
        )
        );

        $ajax_response->addCommand(new HtmlCommand('#usato_modelli_ajax', $form['usato_modello']));
        return $ajax_response;
    }
}

```

I am sending an email inside the ajaxHandlerModello function so I know for sure that is not triggered, how can't it work?

# Answer
You're creating form elements in your ajax callback. You cannot do this, as the form has already been cached before this point, and the settings generated. You need to create any form elements inside the formElement() method. You can determine if the form has been submitted by checking values in the $form\_state - no values for your elements will exist on the initial form build, and will exist in ajax callbacks.
> 2 votes

---
Tags: 8, entities, ajax
---


# Question
Title: Sharing article to facebook adds reserved html characters in heading (&amp #039)
I have a drupal 7 site, and after sharing posts to facebook, I saw strange behaviour. When I use quotes in heading, after sharing the article i see '"e; and #039, what causes this and how can I avoid it? I use addtoany drupal7 module.

# Answer
Those are the encoded values of the characters. Before you share it to the facebook, check any hook if module is providing to decode it and then share it.

You'll have to use htmlspecialchars\_decode($str); to do that.
> 0 votes

---
Tags: social-network
---


# Question
Title: How do I a use a template file to theme a mulit-step form?
I am creating a multi step form, and displaying that through a template file. The first step of the form displays fine, but when I go to the second step, the first step titles are also displaying.

How can I check which form fields are displayed? The form fields for the first step should not appear when the second-step form fields are shown.

# Answer
> 1 votes
The first thing to do is to save the current step to an element in your form:

```
$form['step'] = array
(
  '#type' => 'value',
  '#value' => $form_state['step'], // or however you are storing the step
);

```

Then, in the preprocess function form your template, you can turn this into a variable that can be used:

```
function THEME_preprocess_THEMEKEY(&$vars)
{
  $form = $vars['form'];
  // This sets up the variable
  $vars['step'] = $form['step']['#value'];
}

```

Now, in your template you will have a $step variable available that you can use for choosing which elements to output:

```
<?php if ($step == 1): ?>
  // output step 1 fields here
<?php elseif ($step == 2): ?>
  // output step 2 fields here
<?php endif; ?>

```

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


# Question
Title: How to dynamically pass a user field value to jQuery?
I have a notification bar with a counter, it actually prints the user's "notifications" field value (if it's greater than 0):

```
<div id=container>
<a href="#" class="activity_link">Activity</a>
<?php
global $user;
$user_fields = user_load($user->uid);
$user_notifications = $user_fields->field_notifications['und']['0']['value'];
if ($user_notifications > 0) {
echo '<div class=blob>'.$user_notifications.'</div>';
echo '<div style="display:none">'.flag_create_link('unmark_notifications', $user->uid).'</div>';
}
?>
</div>

```

And a jQuery function that resets the value to 0 on click:

```
    (function ($) {
      Drupal.behaviors.scriptjs =  {
        attach: function(context, settings) {

        $('.activity_link').click(function() {
        $('.activity_menu').toggle();
        $('.blob').fadeOut('normal');
        $('.flag-unmark-notifications .flag-action').click();
        $('.flag-unmark-notifications .unflag-action').click();
    });
    }
   };
  })(jQuery);

```

The problem is that when a new notification is received you need to refresh the page to see it.

What I've thought to do is to pass the user's "notifications" field to jQuery and update accordingly..

Is this the best way to do it or should I think about using Node JS?

How would you listen for a field value change event and then refresh the counter?

# Answer
You can use Block Refresh module. Put the notification's content in a block and using this module refresh block in some interval of time. In block template write your own condition or logic.
> 0 votes

# Answer
You could create 2 menu items;

1. check the notifications, json delivery (let's call it menu item 1)
2. render the container. custom html (let's call it menu item 2)

On your JS file, you could use a SetInterval ajax call to check your menu items 1 (check the json data) and then if your condition match, use jQuery.load to get the fragment you want on the 2nd menu item or the whole page to replace the current block.

For the notification menu item 1, I recommend you to use High-performance JavaScript callback handler to optimise the callback.
> 0 votes

# Answer
An overview of tasks what you need to do :

* Add a js file to your module, or wherever your notifications update logic is (strictly not in the .tpl file as its against the standards, but if you really want to add here - instead add it in the tpl's preprocess function)
* In this js file, fire an ajax request `$.ajax()` looking out for notifications count (this will actually be a Drupal menu callback doing the querying job in the backend)
* If the query results reveal \> 0 notifications, return the number back to your js file (in the `$.ajax`'s `.success()` callback)
* The `.success()` should update only the notification counter by using its DOM identifier (.blob in your case) - use html(response.data) to update

You have now a fully functional Ajaxified notification counter
> 0 votes

---
Tags: entities, javascript
---


title: How to add a tab to shop pages?

text:
# Question
Title: How to add a tab to shop pages?
I'm on Drupal 8 with Commerce 2.

I created a view page to display the list of products in the stores.

Here is the way of my sight :

/store/3/produits

Can not add a tab to shop pages.

I am desperate.

Can you explain why the "Edit" tab on the page is missing ?

**Here is my view, it is very simple :**

**Here is my page "Produits", there is no tab :**

# Answer
**UPDATE:** install Commerce Multistore module and have store/ID/edit, store/ID/products, user/ID/stores views tabs created by default for you

**UPDATE:** Add store/ID/edit, store/ID/products, user/ID/stores views tabs

Tabs can be automatically created for you by Views.

**WDTutorials** video: Tabs With Views in Drupal 8

You have to create a views' page having **/some-path** which lists some entities (nodes, fields or products as in your question). Then you need to make it a **Default menu tab** (parent menu tab). So, if no any child tabs are present then the content for this tab will be displayed. It might be seen a bit confusing but you should choose **Already exists** option while creating this (newly created) menu tab. After that just create as many duplications of this page as you need and choose for each duplication a **Menu tab** option (child menu tab). Again, you might be confused which menu or menu entry to choose for children menu tabs. Actually, it does not matter a lot. For your view you may choose **Products** entry though **\<Main navigation\>** menu might be also a good choice. Do not ignore **weight** option assigning a proper value for each child tab. It helps to place tabs in the exact order you want. Leave **0** weight for the parent tab increasing it by 1 for each next tab.

Then, edit the path so it looks like **/some-path/child-1** and add a filter criteria for a child tab (page). In the video the filter criteria is a node's published/unpublished status and in your case it should be a store ID. The ID of a particular store might be found on the **/admin/commerce/stores** by hovering over a store's **Edit** tab.

See more on the relative drupal.org issue: https://www.drupal.org/node/2880510#comment-12185171
> 1 votes

---
Tags: views, 8, commerce, navigation
---


title: Taxonomy term name issue

text:
# Question
Title: Taxonomy term name issue
```
$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('category');
var_dump(tree);

```

the above snippet gives the following output:

```
array (size=4)
  0 =>
    object(stdClass)[389]
      public 'tid' => string '5' (length=1)
      public 'vid' => string 'category' (length=8)
      public 'langcode' => string 'en' (length=2)
      public 'name' => string 'General' (length=7)
      public 'description__value' => null
      public 'description__format' => null
      public 'weight' => string '0' (length=1)
      public 'changed' => string '1501133997' (length=10)
      public 'default_langcode' => string '1' (length=1)
      public 'depth' => int 0
      public 'parents' =>
        array (size=1)
          0 => string '0' (length=1)
  1 =>
    object(stdClass)[393]
      public 'tid' => string '6' (length=1)
      public 'vid' => string 'category' (length=8)
      public 'langcode' => string 'en' (length=2)
      public 'name' => string 'OBC' (length=3)
      public 'description__value' => null
      public 'description__format' => null
      public 'weight' => string '0' (length=1)
      public 'changed' => string '1501134006' (length=10)
      public 'default_langcode' => string '1' (length=1)
      public 'depth' => int 0
      public 'parents' =>
        array (size=1)
          0 => string '0' (length=1)
 .....

```

My question is how can i get the name i.e.,general,obc etc (i mean taxonomy term name) from the above snippet...i am new to drupal..plz help..

# Answer
You can try this :

```
  $tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('category');

  foreach ($tree as $key => $term) {
    $term_name = $term->name;
    var_dump($term_name);
  }

```

View this topic.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Views php field or filter to a file or module
If I already have a view with a php filter or a php field, in drupal 7, how can I convert my whole view into a page? (prevent code injections or other security risks) What is the right way to resolve this? Writing a module or a tpl.php file? Thanks

# Answer
Found the answer here

Custom Views Field Handler https://kalamuna.atlassian.net/wiki/display/KALA/Custom+Views+Field+Handler
> 0 votes

---
Tags: views, theming, security
---


# Question
Title: Get node id for page which is set for 403 and 404
I want to get the node number (nid) for the node which is set for 403 and 404 pages in drupal configuration system. Can you please help me for this ?

# Answer
You need to use

```
variable_get('site_403');
variable_get('site_404');

```

It will return a string like "node/1", then you just have to parse this string to get back the node ID.
> 1 votes

# Answer
You don't mention if this is via code or just admin screens. Through the admin screens you can view/edit what page is set for the 403 and 404 pages:

"Configuration \> System \> Site information"
> 0 votes

# Answer
Thanks all for answering this, I tried this

```
global $conf;
print_r($conf['site_403']);

```

It is working fine.
> 0 votes

---
Tags: 7, configuration
---


# Question
Title: Access a template variable from another template (or theme hook)
I have two templates (and two corresponding preprocess hooks), one rendering a Paragraph, one rendering items from this paragraph.

How to access a variable available in the parent paragraph template (or preprocess Hook) from the items rendering template (or item preprocess hook) ?

paragraph--paragraph-row.html.twig

```
{{ content.MyVARIABLE }}  //it works

```

field--paragraph--paragraph-row2.html.twig

```
<div class="row">
  {% for item in items %}
     <div class="col-sm-{{ 12 // parent.MyVARIABLE  }}">
         {{ item }}
    </div>
{% endfor %}
</div>

```

THANKS !

David

# Answer
You can't access easily variables from other templates. But you can use the entity objects to access field values.

For a nested paragraph you find the parent paragraph in `element['#object']`:

*field--paragraph.html.twig*

```
{{ element['#object'].field_my_field.value }}

```
> 2 votes

---
Tags: theming, 8, hooks, paragraphs
---


title: How to make hidden field not required?

text:
# Question
Title: How to make hidden field not required?
```
$form['questionfield_form_fieldset'][$i]['answer_type'] = [
        '#type' => 'radios',
        '#title' => $this->t('Select Answer Type'),
        '#options' => array(
          'select' =>t('Drop Down'),
          'radios' =>t('Radio'),
          'rating' =>t('Rating'),
        ),
        '#description' => $this->t('Select the way answer will disply eg. in radio button or in selectbox(Dropdown)'),
        '#default_value' => $config->get($form_count . '.' . $drupal_form_id . '.' . 'answer_type'),
        '#required' => TRUE,
      ];

      $form['questionfield_form_fieldset'][$i]['answer_box_id'] = [
        '#type' => 'textarea',
        '#title' => $this->t('Answer for above question'),
        '#description' => $this->t('Add your answers for above question here.'),
        '#default_value' => $config->get($form_count . '.' . $drupal_form_id . '.' . 'answer_box_id'),
        '#required' => TRUE,
        '#states' => array(
      'visible' => array(
        array(
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'select')),
        'or',
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'radios')),
      ),
        ),
    ),
      ];

```

I want to make answer\_box\_id as not required when user click rating radio button .

# Answer
You need to remove `'#required' => TRUE` from the render array.

States only control "soft" changes through javascript. They don't (and can't) have any effect on the backend validation; if they could, it would be trivial for anybody to bypass the server-side validation for a field just by setting some CSS styles on it. That would not be a good situation to get into.
> 2 votes

# Answer
Hello I solve as below..

```
$form['questionfield_form_fieldset'][$i]['answer_box_id'] = [
        '#type' => 'textarea',
        '#title' => $this->t('Answer for above question'),
        '#description' => $this->t('Add your answers for above question here.'),
        '#default_value' => $config->get($form_count . '.' . $drupal_form_id . '.' . 'answer_box_id'),
        //'#required' => TRUE,
        '#states' => array(
      'visible' => array(
        array(
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'select')),
        'or',
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'radios')),
      ),
        ),
      'required' => array(
        array(
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'select')),
        'or',
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'radios')),
      ),
        ),
    ),
      ];

```
> 1 votes

---
Tags: theming, 8, forms
---


# Question
Title: Drupal 7 update field programatically and generate field names
I'm here still learning with drupal 7 but now I have a new question about a node create programmatically,I hope you can help me.

I want to generate all node fields names programmatically and then set a lavue on each one.

To store each field from node I generate the names of the field witn an array with each name, this is because I want to make function to indicate the names of the fields of the node that I want to fill.

The problem is that my code is not working to fill the nodes, maybe because my fields names are bad generated. I generate and fill them this way:

```
    $nodefields = array('areaid', 'areaname');

    foreach ($nodefields as $fieldname) {
            $node->$fieldname['und'][0]['value'] = $row->$fieldname;
            }
    node_save($node);

```

The rows are obtained by a query to a external db (column has the same name as the field), that's fine, the records are ok, if I fill them manually like:

```
$node->areaname['und'][0]['value'] = $row->$areaname;

```

Works ok, but I can't make it work with a loop to generalize that part.

# Answer
> 1 votes
Your problem is that below code does not work as you probably expect.

```
$node->$fieldname['und'][0]['value'] = $row->$fieldname;

```

You expect this to work like this:

```
$fieldname = 'name';
$node->name['und'][0]['value'] = $row->name;

```

but PHP will probably do something like this:

```
$fieldname = 'name';
$fieldname['und'][0]['value'] = $row->name;
$node->$row->name;

```

Instead, try to wrap your variable name in curly brackets to have it replaced first:

```
$node->{$fieldname}['und'][0]['value'] = $row->$fieldname;

```

# Answer
> 0 votes
I think you might be missing brackets

```

$nodefields = array('areaid', 'areaname');
foreach ($nodefields as $fieldname) {
  $node->{$fieldname}['und'][0]['value'] = $row->{$fieldname};
}
node_save($node);

```

---
Tags: 7, nodes
---


title: Uploading Image as part of product

text:
# Question
Title: Uploading Image as part of product
I am working on a website for a youth organization. They desire to sell sponsorship for organization on site, and we are using Drupal 8.

We are able to create a product and a product variation. We can't find out how to create a field that will accept an end-user submitted image when added to the cart.

How can we achieve this?

# Answer
**Documentation & Background Knowledge is Limited**

It's the truth, we are an organization moving from Ubercart on Drupal 6 to Commerce V2 on Drupal 8. There's a steeeep learning curve.

So, our situation is that we want local businesses to upload a graphic as part of their sponsorship. Eventually, we will use this image as part of an advertisement block, but at the moment, our question, HOW do we get this image upload as part of a product.

**Assumptions**

Drupal 8 installed, with Commerce installed V2.

**Steps to Create Upload Field (Image)**

1. Create Order Type - I created an Order Type "Sponsorship". I used the Default workflow (might have to change in the future). DONE
2. Create Order Item Types - I created an Order Line Type, named it "Sponsorship", and selected Order Type "Sponsorship".
    1. Then I went to Manage Fields for the Order Item Type "Sponsorship" that I just created and added an Image field to that Order Item Type.
    2. I named the Field "Ad" - as this should be an image uploaded by the sponsor.
3. Product Variation Type - Because I have other products, I wanted a stand along variation for the "Sponsorship".
    1. I created a Product Variation Type - **Advertisement**, as I felt I had used **Sponsorship** too many times. When I created that **Advertisement** variation, I ensured that I selected **Sponsorship** from the Order types.
    2. I was a bit lost here, but a key point, create the product type variation BEFORE creating the Product Type.
4. Product Type - I then created the **Sponsorship** Product Type, selecting **Advertisement** as the Product Variation.
5. I finally created by product **Front Page Sponsor** and when doing so I selected **Sponsorship** as the Product Type, and completed the balance of the product as normal.

I hope this helps others as well..
> 0 votes

---
Tags: commerce
---