# Question
Title: How to implement Commerce USPS Shipping?
I have installed the following modules:

1. Commerce Shipping module (7.x-2.2)

Shipping UI
2. Commerce USPS module (7.x-2.0)
3. Commerce Physical Product (7.x-1.x-dev)

Checkout without shipping is working fine.Now in checkout settings I have enabled shipping service and info.

I am able to see USPS shipping method config and rules which are set to default (for now). I tried using different rules but can't see any shipping method in the checkout screen.

I have set production account username and url of the USPS.com (this probably isn't the problem).

I want to know step by step procedure to configure the shipping method and rules to add USPS shipping service.

I have 3 products types from which only one will have shipping service,I can see "Shipping" line item type but how to implement it to the product type so that shipping is shown on the checkout screen or is it optional?

# Answer
> 1 votes
Have a lok at the README.txt that comes with the Commerce USPS module, here is the content of it:

> # About this module
>
> Commerce USPS module provides shipping calculations from the USPS WebTools API
>
> # Dependencies
>
> This module depends on the Commerce module (http://www.drupal.org/project/commerce).
>
> In addition, the following modules are required:
>
> # Installation
>
> 1. Install and enable the module and all dependencies (be sure to use the latest versions of everything). Add dimensions and weight fields (new field types via the Commerce Physical module) to all shippable product types. Populate dimensions and weight fields for all products.
> 2. Configure the "Shipping service" checkout pane so that it is on the "Shipping" page. The "Shipping service" checkout pane MUST be on a later page than the "Shipping information" pane. (admin/commerce/config/checkout)
> 3. Configure the USPS settings (admin/commerce/config/shipping/methods/usps/edit). You'll need to create USPS WebTools account and obtain a username via https://secure.shippingapis.com/registration/.
>
> # Limitations
>
> Eventually, all of these limitations may be addressed. For now, be warned.
>
> 1. Single "Ship from" address for all products.
> 2. Doesn't ensure product dimensions are less than default package size dimensions. In other words, if you have a product that is 1x1x20 (volume=20) and your default package size is 5x5x5 (volume=125), even though the product won't physically fit in the box, these values will be used to calculate the shipping estimate.
> 3. Doesn't play Tetris. For example, if you have an order with 14 products with a combined volume of 50 and your default package size has a volume of 60, the shipping estimate will be for a single box regardless of if due to the packaging shape they don't actually fit in the box.
> 4. Doesn't limit the weight of packages. If you're trying to ship a box full of lead that weighs 600lbs, this module will let you (instead of breaking the order into more packages).
> 5. Doesn't account for packing material. If you need to account for packing material, then you may want to adjust product dimensions accordingly.
>
> # Methodology
>
> Calculating estimated shipping costs is a tricky business, and it can get really complicated really quickly. Knowing this, we purposely designed this module with simplicity in mind. Here's how it works:
>
> 1. Every order must contain at least one package.
> 2. The number of packages is determined by calculating the total volume of all products in the order, dividing by the volume of the default package size, and rounding up.
> 3. The weight of each package is determined by dividing the total weight of all products in the order by the number of packages.
>
> If you need custom functionality, you have several options:
>
> 1. Determine if it is something that can be generalized to suit a number of users and submit it via the issue queue as a suggestion for inclusion in this module.
> 2. Hire one of the maintainers to create a custom module that interfaces with Commerce UPS to add your custom functionality.
> 3. Break open a text editor and start coding your own custom module.

Apart from that, the module's project page contains this extra info:

> Please refer to the README.txt file for additional information about how this module works and how to set it up.
>
> 1. Install and enable the module and all dependencies.
> 2. Add dimensions and weight fields (new field types via the Commerce Physical module) to all shippable product types.
> 3. Populate dimensions and weight fields for all products.
> 4. Configure the USPS settings (admin/commerce/config/shipping/methods/usps/edit). You'll need to create USPS Web Tools account and obtain a username https://secure.shippingapis.com/registration/ and call USPS to have the account moved into production (tell them you are using 3rd party software).

---
Tags: 7, commerce
---


title: Views entity reference field condition

text:
# Question
Title: Views entity reference field condition
OK, so this is a bit tricky, let's see if you can follow my problem: (just let me know which part you don't understand 1,2,3...) I am using **Drupal 7**

1) I have 2 content types: **Workers** and **Documents**

2) In the content type **Documents** I have the **entity reference field** of all the workers. (Eg. I want to add a document/node that refers to a specificic worker John)

3) In the content type **Documents** there is a **list field** the user can select two options: red or green (it's a field where the user can say the document is OK to use)

4) Everytime I add a Document, I have to select red or green in that field.

5) Right now, I am displaying a view with all the nodes/documents from the content type **Documents** refering to the **title** and **List field** (red or green). Something like this:

Document 1 ------------------ red

6) On another page, I am displaying a view with a list of all workers (Content type Workers) and **here comes the tricky part:**

I want to add a field in this view displaying red or green based on this condition: IF (all the Documents from the entity reference "specific worker" have "green" on the field): display green. IF (one of the Documents has the field "red"): display red

It will diplay something like:

John --------------- green

How can I achieve this with views? Do I need to write code? Thank you.

# Answer
Here is a zero coding solution.

Create a new view:

* CONTEXTUAL FILTER add `Node id` (since workers is a content type), so we have the id of the worker.
* RELATIONSHIP add `Referecing Entity`, checkmark require relationship.
* Fields: Add `Title`

+ At top you will see a select box, select the relationship option.
    + Unchecked Link this field to the original piece of content
    + Click on NO RESULT BEHAVIOUR, put `Green`
    + Click on REWRITE RESULTS, **checkmark Rewrite the output of this field**, put `Red`
* In FILTER CITERIA add `type` and select Workers.
* In FILTER CRITERIA add the List Field (the one that contains Red or Green) and put is equal to `Red` and select relationship option at top.

for PAGER put 1 item.

---

Install and enable Views Field View

Now in your List of All Workers view:

In FIELDS add Node ID and checkmark hide field from view.

In FIELDS now Add the View Fields view field.

* Select the previous view we created.
* For argument, Click on replacement patterns, and use the Node ID token to pass as an argument.
> 2 votes

---
Tags: 7, views
---


title: No "webform" link in operations column

text:
# Question
Title: No "webform" link in operations column
i'm new to Drupal and PHP in general, so this may be obvious - But I'm working with Drupal 7 with module webform installed. Recently, i don't know why the link stopped appearing in the Operations column on the Content list page in the admin. Any help would be appreciated!

# Answer
> 1 votes
Hi make sure you are enable the webform functionality like this check http://prntscr.com/bur06a
if not working then follow tutorial

---
Tags: 7, webforms
---


# Question
Title: passing page arguments to drupal 8 from controller to form controller
This is my code in routing.yml file

```
test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'

```

I need to get the value of node in the form controller buildForm function.

How can I access that? Any help?

# Answer
Update the `.routing.yml` file like so:

```
test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'
    node: \d+
  options:
    _node_operation_route: TRUE

```

Then use it in your form controller the following way:

```
namespace Drupal\test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

class Test extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $form['placeholder'] = [
      '#markup' => t('This is the form for @node_title.', [
        '@node_title' => $node->getTitle(),
      ]),
    ];

    return $form;
  }
}

```
> 3 votes

# Answer
There are one way with two approaches:

Either calling the request service statically:

* `$request_param= \Drupal::request()->query->get('myparam');`

Or call it via Dependency injection:

```
return new static(
  $container->get('request_stack')
);

```

And then just add to the end of the constructor's argument list: `RequestStack $request_stack`

And save it as own property, which you can use later: `$this->requestStack = $request_stack;`
> 0 votes

---
Tags: 8
---


title: create book navigation menu tree

text:
# Question
Title: create book navigation menu tree
I have a book with few children article nodes. I would like to create a navigation block tree, that can be placed anywhere on page.

Problem: Normally if I place book navigation block using context (on book and article content type) - the menu shows all links with the link to main book. However, if I try to print inside tpl.php like this

```
$block = module_invoke('book', 'block_view', 'navigation');
print render($block['content']);

```

The menu shows only child items. How to show the parent book as well?

# Answer
This code worked for me:

```
$blockObject = block_load('book', 'navigation');
    $block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
    $output = drupal_render($block);
    print $output;

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Writing Drupal 7 queries using drupals DB abstract. (Similar to an entity wrapper)
Drupal (7) uses an abstact for handling DB-s.

I'd like to write dynamic queries where i can use drupals abstract.

There's entity wrapper for entities and I'm Looking for something similar to DB-s.

Is there anything like that?

# Answer
If by *level of abstraction close to the one given by entity wrappers*, you mean a module/library that would allow to write code similar to the following, no, there isn't anything like that.

```
$field_value = database_wrapper('table')->table_field;
database_wrapper('table')->set('table_field', $new_value)->save();

```

The level of abstraction that would offer, in the case of reading the database, would not be worth the code you would write to implement it, and it would just save a few method calls. In fact, `$field_value = database_wrapper('table')->table_field;` would be equivalent to the following Drupal 7 code.

```
$result = db_query("SELECT table_field FROM {table}");
foreach ($result as $record) {
  // Use $record->table_field;
}

```

Also for writing, the Drupal 7 code is not much complicated to require a wrapper.

```
db_insert('table')
  ->fields(array(
    'table_field' => $new_value,
    ))
  ->execute();

```

Real code would be more complicated than this, but a wrapper that should consider every case would be even more complicated.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to create rule to change user role based on points (using User Points module)?
I'm using the User Points module which allow me to grant points to user. So far so good.

I need to create a rule to fire this condition/action: When user points are granted, then check if the user has more than 10 points. If so then add the "Master" role to this user.

I try using the Rules Condition "Data comparison", but I can't find the value something like "***total points of the user***".

Can I do this in any way?

# Answer
Have you tried the user points contrib module. I am specifically referring to

**userpoints\_role**

Users join/leave roles as they earn/lose certain points threshold.
> 3 votes

# Answer
Your question is about using Rules and find '... *something like "total points of the user" ...*' (and related to Rules Event "When user points are granted to a user"). So have a look at this Rules example (in Rules export format):

```
{ "rules_grant_new_role" : {
    "LABEL" : "Grant a new role",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "11" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have at least 11 points (actually you have [total-points:value] points ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

```

The above rule does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 11, it will show an appropriate message about that (just replace that with a Rules Action to grant a role to fit your case).

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

The clue to make this rule work is the very first Rules Action "***Load user points of a user***". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".
> 1 votes

---
Tags: rules, userpoints
---


# Question
Title: Is there a way to tell a browser to not cache a particular custom page?
A custom module I'm building has a page callback that creates and Inbox listing. When a user clicks an item in the inbox, another page callback displays the message, and it updates the database to record that it's been read.

The problem is that when the user presses Back, they get back to their local cache of the inbox which suggests it has not been read. If they reload, it's OK.

Is there a way (in `hook_menu`?) to flag that a page should not be cached/expires immediately?

# Answer
If I understand your expectation correctly, it's less of a Drupal and more of a browser thing. When the user presses the Back button, if you *don't* want the browser to show a copy of the web page that it might already have, the `Cache-Control` header in your initial response must have `no-store`. Drupal by default, doesn't have this. You can confirm this by checking the definition of this function.

Simply overwriting the `Cache-Control` header seems to fix this on Opera 16, Firefox 23 and Chrome 30. However, on Safari 6, it doesn't. Turns out that it might be a known issue. So, we might have to turn to a Javascript hack for that.

In summary, including the snippet below in your page callback should do the trick for you. I have assumed Drupal 7.

```
// Add no-store in Cache-Control.
drupal_add_http_header(
  'Cache-Control',
  'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  FALSE
);
// Hack for Safari
drupal_add_js('jQuery(window).unload(function(){});', array('type' => 'inline'));

```

This seems to work on a fresh Drupal 7.22 install for an authenticated user. If the page in question has been asked to be stored in the Drupal cache or if you are using a contributed module that also messes with the response headers, this might not work as is for you.

**Useful References**
> 7 votes

# Answer
To avoid particular page being cached, you may try either of the following:

1. Add the following in page callback function of `hook_menu`:

> drupal\_page\_is\_cacheable(FALSE);

drupal\_page\_is\_cacheable(): Determines the cache ability of the current page. Set it to `FALSE` if you want to disable caching for that page.
2. Use the cacheexclude module: This module provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.

If you want to disable the cache for particular page than you try the cacheexclude module that provides the UI for adding pages that doesn't need to be cached.
> 2 votes

# Answer
Try changing the following global variable on the page load:

```
$GLOBALS['conf']['cache'] = FALSE;

```

but the problem is that you cannot use this in `hook_boot()`, because it's already too late to disable the caching. But there is a patch for it, see: Allow hook\_boot() to disable page cache. Unless you'll add it into your settings file.

See also: Dynamic Cache and CacheExclude modules.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How to periodically deduct user points for flagged nodes?
I have a node which is published. And I have a global flag, which users have to mark to make nodes visible in Views. This is easy to do.

But then I need to charge 40 user points for every day that node remains flagged. And when user doesn't have enough points anymore, then node must be unflagged.

**Possible realization what I tried:**

**via CRON:** I tried to make a rule for that, but when I add an Event (= *On CRON Run*), then I cannot add an action with user points. Some people say it should be an extra script for cron, but I don't know how to make it.

**via Rules:** I tried to make a rule on Event "*When node is flagged*" and make a Scheduled Rule with the same -40pts for user nextday. It works only once until the Scheduled Rule completed or until cron is running. So I cannot make a loop properly.

I've no more ideas to get it working. Maybe I just lost something while making Rules?

# Answer
> 0 votes
# Part 1 - Deducting user points

### Repeat the daily deduction of user points

Use the rules scheduler as explained in the video about "Repeating scheduled events". The "clue" here is:

* as the last action of your rule, you reschedule the same rule to be executed again after +1 day(s).
* the very first time you need to trigger the execution of this rule manually (from the Rules UI). Or you can use the Rules Event "when node is flagged".

### Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

# Part 2 - Stop deducting if insufficient user points

The 2nd part of your question is about "*... when user doesn't have enough points anymore, then node must be unflagged ...*". The challenge with that is that there is no Rules Condition like "If user has less then X user points".

However, to also make that work, you can use a Rules Action "Load user points of a user", as an alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user". Have a look at my answer to "How to create rule to change user role based on points (using User Points module)?", which includes an sample rule that uses this Rules Action.

So all you have to do is to further enhance your rule as in Part 1, by using the Conditional Rules module so that your Rules Action will look something like so:

> Load user points balance
>
> **If** user points balance \> 40
>
> **then** reschedule the same rule to execute in 1 day.

---
Tags: 7, rules, flags, cron, userpoints
---


# Question
Title: How to make 2 Rules work that use the very same Rules Event?
On a D7 site I have two rules (using the Rules module) reacting on the same event which is 'After saving a new entityform submission'.

When the actual event occurs only 1 gets fired, even though I've played around with Rule weights. So either I can give precedence to 1 of them or get them to fire at the same time but no luck.

Any help/suggestions would be much appreciated.

# Answer
2 separate Rules using the same "after update something" event, that's asking for problems.

You should try to rework/redesign those 2 rules somehow. Here are a few ways to do so:

* If both rules don't have any Rules Conditions, then move all the Rules Actions of 1 rule to the other rule (and think of the best "order" to execute all Rules Actions).
* If Rule 1 has a Rules Condition (say) "*Condition1*" and Rules Action (say) *Action1*, and Rule 2 has a Rules Condition (say) "*Condition2*" and Rules Action (say) *Action2*, then use the Conditional Rules module to merge both rules together (also), with a Rules Action (not Rules condition!) that looks like so:

> Conditional
>
> If Condition 1 then Action 1
>
> Conditional
>
> If Condition 2 then Action 2

**Note**: if appropriate, first perform anything related to Rule 2, then Rule 1
> 1 votes

---
Tags: 7, entities, rules
---


title: How are upload files stored?

text:
# Question
Title: How are upload files stored?
I have a custom content entity. For this entity, I want add multiple uploaded files.

After I set this up, I looked at the database and saw:

> file\_managed =\> stores all files uploaded by a managed\_file field
>
> file\_usage =\> links between your entity and the table file\_managed

So for the managed\_file field form, I don't need to create a field into my entity content (database), I just add a field into the EntityForm directly:

```
  $form['image'] = array(
      '#title'=>t('Image du produit'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://produits/',
      //'#default_value' => array(),
      '#description' => t('png jpge jpg'),
      '#upload_validators' => array(
          'file_validate_extensions' => array('png jpg jpeg'),
      ),
      '#multiple'=>true,
  );

```

And then I can upload multiples files.

Then in my submit :

```
public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;

      foreach ($form_state->getValue('image') as $image) {
          $file = \Drupal\file\Entity\File::load($image);
          $file->setPermanent();
          $file->save();

      $file_usage = \Drupal::service('file.usage');
      $file_usage->add($file, 'boutique', 'produits_entity',$entity->id());

      }
}

```

I store image reference into the file\_usage table and set it permanent. At this point all is good.

But I need to load all files when user want edit my entity, I can load this from the file\_usage table and build my

> '#default\_value' =\> array($images)

I want to know if it's a good practice and if Drupal 8 work like that.

# Answer
> 1 votes
> I don't need to create a field into my entity content (database), I just add a field into the EntityForm directly
>
> ...
>
> I want to know if it's a good practice and if Drupal 8 work like that.

No, what you described is not good practice. For a Drupal entity to interact easily and correctly with a field, you should add the field to the entity, not add the widget to the form. It is probably possible to make it work but it will be harder to build and maintain.

---
Tags: 8, database, entities, files
---


# Question
Title: How can I get other content type data in current content type?
I want to put one condition in my template file of `contenttype1`. The condition is if `contentype2` contains a field value `X` then I want to print one block in `contentype1`. So how can I get `contenttype2` field values in `contenttype1` template file.
To get more clarity, with the `contentype2` fields I am creating a views block. I want to display that block in `contentytype1` template file. So I want to check a field condition of `contentype2`. If that field has any value then only I want to display that views block in `contenttype1` otherwise it should not display. Thanks in advance for any suggestions.

# Answer
What you need to do is make `X` a taxonomy term.

1) Go to taxonomy and create a vocabulary (ex: Colors)

2) Inside Colors vocabulary, add terms. (ex: Red, Blue, Green, Yellow etc..)

3) Go to `contentype1` manage fields and add a new field of type: Taxonomy Term Reference. Then select the vocabulary (colors).

4) Now edit your `contentype1` nodes and give them a taxonomy term. Ex: Node 1 blue, Node 2 red, Node 3 blue, ...etc

5) Repeat steps 3) and 4) but with `contentype2` this time.

6) Create a block view of `contenttype2` (You will see it lists all the `contentype2` nodes)

7) Under Advanced, add Relationship of Terms of the node, checkmark Colors and checkmark require relationship.

8) Add a contextual filter of Taxonomy Term and for when filter is not available, set it up like this (using screenshot from another answer):

Once you add the contextual filter, your view preview will go blank, which is normal. Go to a `contentype1` node, where you placed the view block, and you should see `contenttype2` nodes that have the same taxonomy term as the current `contentype1` node that you're viewing.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to change a file field value with entity_metadata_wrapper
I need to remove a file field value, and instead, assign a new value to it. The file field contains video and the new video is in the videos directory. This is my code to delete a file field value (which works well)

```
    $node = node_load(37);
    // Get the language for the file field.
    $lang = field_language('node', $node, 'field_video');
    // load the file
    $file = file_load($node->field_video[$lang][0]['fid']);
    // unset the field for the node
    unset($node->field_video[$lang][0]);
    // delete file from disk and from database
    file_delete($file);
    // Save the node.
    node_save($node);

```

But this code which assigns a new value, reports an error. I get this code from How to set value of file field with entity\_metadata\_wrapper

```
    $node = node_load(37);
    $realpath="";
    if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
      $realpath = $wrapper->realpath();
    }
    $file_path = $realpath."\\video_file\\sarmaye.mp4";
    $file = new stdClass;
    $file->uid = $node->uid;
    $file->filename = pathinfo($file_path, PATHINFO_BASENAME);
    $file->uri = $file_path;
    $file->filemime = file_get_mimetype($file_path);
    $file->display = '1';
    // Make it permanent, otherwise it will get deleted later.
    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
    $file = (array) $file;
    $items = array($file);
    $ewrapper = entity_metadata_wrapper('node', $node);
    $ewrapper->field_video->set($items);
    $ewrapper->save(true);

```

But it reports this error

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'D:\xampp\htdocs\MySiteName\sites\default\files\video\_file\sarmaye' for key 'uri': INSERT INTO {file\_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> sarmaye.mp4 \[:db\_insert\_placeholder\_2\] =\> D:\xampp\htdocs\MySiteName\sites\default\files\video\_file\sarmaye.mp4 \[:db\_insert\_placeholder\_3\] =\> video/mp4 \[:db\_insert\_placeholder\_4\] =\> 4877369 \[:db\_insert\_placeholder\_5\] =\> 1 \[:db\_insert\_placeholder\_6\] =\> 1468934410 ) in drupal\_write\_record() (line 7361 of D:\xampp\htdocs\MySiteName\includes\common.inc).

# Answer
You have to set the uploaded file object rather then the initial file object. Please check the return value of file\_save() function.

The error explained that there is duplicate key uri, which means the code is trying to save the initial file object again.

`$ewrapper->field_video->set()` only accept `(array) $file` but not `$items`.

```
$file = file_save($file);
$file = (array) $file;
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_video->set($file);
$ewrapper->save(true);

```
> 2 votes

---
Tags: 7, nodes
---


title: Wrap link around an element in twig

text:
# Question
Title: Wrap link around an element in twig
I have a twig template for a custom block, I want the entire block to be wrapped in a link. I'm using the link field, but I'm not sure how to get the url from the field within the twig template. This seems like it should work, but doesn't:

```
{{ content.field_link.0.getUri() }}

```

I've looked at `url()` and `path()`, but they are dealing with routing, so I don't think that's what I'm looking for.

Note, I would like to use either external or internal links in the field.

# Answer
> 1 votes
Ah, I was missing the `['#url']` part of the array. In order to get the url from the link field I called:

```
{{ content.field_link.0['#url'].getUri() }}

```

I do miss the ability to copy-paste from `dpm()`.

---
Tags: theming, 8, navigation
---


# Question
Title: How to change the path when cloning the Taxonomy term view?
I am trying to clone the default Taxonomy Term view to a new view.

I have a Block with the list of contents when I was clicking one of the content inside the Block, it goes to this path: taxonomy/term/%.

But I want to change the path to blog/%

I have changed the Path in the view's settings to (blog/%) from (taxonomy/term/%),But when I will click the content in the block goes to the same Taxonomy/term/% not to new wanted path.

How to change the taxonomy/term/% path to blog/% ?

# Answer
To change the path that user's will see, you don't actually want to update the view path (which is not obvious), you need to change the path of the taxonomy vocabulary and its terms. The Pathauto module makes this easy by creating a pattern for your blog taxonomy at: /admin/config/search/path/patterns (once pathauto is installed and working)
> 1 votes

---
Tags: 7, views, path-aliases
---


# Question
Title: How to stopping spam when using Print_mail (submodule of Print)?
I am using the Printer, email and PDF versions module to be able to email and print articles. This module allows you to send an email to anyone. The issue is, that this feature opens it up for spamming.

Is there a way to stop that or can you suggest another module?

# Answer
> 2 votes
# About sending eMail using the print module

Even though this module can be used for printing, creating PDFs and sending an eMail, your question seems to only be about the sending eMails part of it.

Yes you're right: if you grant access to the eMail part of it to anonymous users, then that is a huge spam risk: any spammer can use it to enter **any** (repeat any ...) eMail ID ... to have "your site" send that eMail (and who knows what the content, from the spammer, might be) ... to the eMail Id "requested" by the spammer.

"***The way to stop that***" (spamming), as in your question, is to not grant that permission to use the eMail function of it to anonymous users.

If you do grant that permission to logged in (+ registered) users, then you have at least a trace which user used the eMail part of it.

# Recommended alternative

Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

If you want to see it at work in an existing module (as an example), then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its **Answers Notification** sub-module. This sub-module allows **logged in users** (not anonymous users ...) to subscribe to selected nodes (such as "questions"), so that they receive notifications (using the Message Stack) when Questions receive Answers.

---
Tags: 7, emails, advertising
---


# Question
Title: How to load all remaining content of a view after clicking a "load more" link?
I have a view block that list contents.

What I want to do is to show only 5 items in this view and a `load more` link at the bottom of the view and if this link clicked, then show **all remaining** content of the view.

I tried the Views Load More module and the Views Infinite Scroll module. The Views Load More module didn't work, the Views Infinite Scroll module works good but I couldn't do what I want. It has an option to show X items per "show more" link clicked but it doesn't have an option to show all the remaining content of the view.

**How to load all remaining content of a view after clicking a "load more" link?**

# Answer
You need Views show more module with ajax under views advanced setting. This module provides Initial item selection option, and rest of the item you can put in the section of on-click.

**Steps-**

1. Download and enable the module.
2. Select **show more pager** in the Pager section as shown in the image. Then go for setting for that. Now in my case I took 15 items, and I want to initially show 5 items and on clicking rest of the item. So I did put 5 under the **Initial items** and 10 items under **Items to display** as shown in second image. And under Animation section select **Scroll to new content.** Save this, so pager setting ends here.
3. Under advanced setting of views enable, **Use Ajax: Yes**

**Views Block UI**

**Pager UI**

**Out put image:**

**Initial stage**

**After clicking show more**

It does not require the page refresh to load content.
> 3 votes

---
Tags: 7, views, javascript
---


# Question
Title: Views selective filters show terms hierarchy
I'm using Views Selective Filters, trying to expose taxonomy terms filters with its depth/hierarchy.

Whenever I configure a filter with criterion Content, for instance *Country (field\_country)* where *field\_country* is a term, I have this extra setting window to choose the widget :

Instead, with the same field, but selective filter option, **that extra settings window doesn't appear**.

The *Exposed form style* is provided by Better Exposed Filters, but I let the default style for that filter.

Is there a configuration step I'm missing ? A necessary module combination to achieve that ? Meanwhile, I updated to Views selective filters dev version, plus a patch providing taxonomy weight ordering for the filters. This is the relevant part, from `views_handler_filter_selective.inc` :

```
/**
 * Get list of options for current view, only at runtime.
 */
protected function get_oids() {
//...
// Sort values.
  $sort_option = $this->options['selective_display_sort'];
  switch($sort_option) {
    case 'WEIGHT':
      $terms = taxonomy_term_load_multiple(array_keys($oids));
      usort($terms, function($a, $b) {
        return $a->weight - $b->weight;
      });
      $oids_ordered_by_weight = array();
      foreach ($terms as $term) {
        $oids_ordered_by_weight["$term->tid"] = $oids[$term->tid];
      }
      $oids = $oids_ordered_by_weight;
      break;
  }

```

And I'm trying now to figure out how to overwrite that to show hierarchy instead.

# Answer
I realised the BEF desired option "Nested checkboxes" was missing for all selective filters. Since into `better_exposed_filters_exposed_form_plugin.inc`, the missing option depends on :

```
if ($bef_nested) {
  $display_options['bef_ul'] = t('Nested Checkboxes/Radio Buttons');
}

```

So I added the following :

```
/* line 314 */
if ($filter instanceof views_handler_filter_selective) {
  $bef_nested = TRUE;
}
/* line 493 */
if ($bef_nested) {
  //...
  $bef_options[$label]['more_options']['bef_select_all_none_nested'] = array(
    '#disabled' => !$filter instanceof views_handler_filter_selective &&(!$filter->options['expose']['multiple'] || !$filter->options['hierarchy']),

```

I know this is a very quick hack and should be improved for general use. **Alternate proposals are warmly welcome.**

Last, I had to patch also Views selective filters handler, resulting in :

```
case 'HCHY':
  $options = array();
  //get remaining terms tids
  $remaining_terms = taxonomy_term_load_multiple(array_keys($oids));
  $tids = array();
  foreach ($remaining_terms as $term) {
    $tids[$term->tid] = $term->tid;
  }
  //get vocabulary tree
  $anyterm = array_shift($remaining_terms);
  $tree = taxonomy_get_tree($anyterm->vid);
  if ($tree) {
    //we flag the terms to avoid displaying them more than once
    $flagged = array();
    //we keep tree items if they match with current selection
    foreach ($tree as $trm) {
      if(in_array($trm->tid, $tids ) && !in_array($trm->tid, $flagged) ){
        //so we always keep its parents displayed
        $parents_all = taxonomy_get_parents_all($trm->tid);

        if($anyterm->vid == '3'){//country vocab, Three levels taxonomy
          switch (count($parents_all)) {
            case 3:
              $parent = $parents_all[1];
              $gd_parent = $parents_all[2];
              break;
            case 2:
              $gd_parent = $parents_all[1];
              break;
            default:
              break;
          }
          //Add the gd_parent to options
          if(!in_array($gd_parent->tid, $flagged) && !is_null($gd_parent->tid)){

            $gd_parent_depth = get_term_depth($gd_parent->tid)-1;
            $choice = new stdClass();
            $choice->option = array($gd_parent->tid => str_repeat('-', $gd_parent_depth) . $gd_parent->name);
            $options[] = $choice;
            $flagged[] = $gd_parent->tid;
          }
          //Add the parent to options
          if(!in_array($parent->tid, $flagged) && !is_null($parent->tid)){

            $parent_depth = get_term_depth($parent->tid)-1;
            $choice2 = new stdClass();
            $choice2->option = array($parent->tid => str_repeat('-', $parent_depth) . $parent->name);
            $options[] = $choice2;
            $flagged[] = $parent->tid;
          }
        }

        //last, add the term itself to options
        $choice3 = new stdClass();
        $choice3->option = array($trm->tid => str_repeat('-', $trm->depth) . $trm->name);
        $options[] = $choice3;
        $flagged[] = $trm->tid;
      }
    }
  }
  $oids = $options;

/*
 * Returns a term depth (https://www.drupal.org/node/886526#comment-7708315)
 */
function get_term_depth($tid) {
  $limit = 5;
  $depth = 0;
  while ($parent = db_select('taxonomy_term_hierarchy', 't') ->condition('tid', $tid, '=') ->fields('t') ->execute() ->fetchAssoc()) {
    $depth ++;
    $tid = $parent['parent'];
    if ($depth > $limit) {
      break;
    }
  }
  return $depth;
}

```

Both are necessary, usual nested checkboxes from BEF do not work as is. This might be useful for some of you.
> 1 votes

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


# Question
Title: Access denied when using webform submissions email link
Interim admin here- no experience- just trying to keep the wheels turning until a new hire made. Drupal 7.43.

Site has "contact us" form implemented as a webform, with email notification to certain addresses, who get email of the form:

> Submitted on Monday, July 18, 2016 - 4:48pm Submitted by anonymous user: IP.IP.IP.IP Submitted values are: Full Name Test2 Email test2@example.com Message This is an example The results of this submission may be viewed at: http://thenameofthesite.com/node/XXXXX/submission/YYYYY

where XXX and YYY are ids.

Users receiving the email complaining that clicking on the link gives a page on the site with:

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

In the admin for the Webform contact form, under Access control, anonymous user is checked for both "View any webform content" and "View own Webform content".

Users are claiming this worked before, and I don't have the experience to gainsay them. Any suggestions on what else I can try?

# Answer
Those permissions are for viewing the webform itself - you would need to set permissions to view/edit/delete the submissions. You can find these settings under "Webform" at `/admin/people/permissions`
> 1 votes

---
Tags: webforms, emails
---


# Question
Title: How to use inline_entity_form in Drupal 8?
I am building 2 custom Content entity types: one is a Node type representing a type of food, called "food". This food may have multiple varieties, which will differ with regards to specific details, so I wish to store information about the varieties in a separate database table, and to accomplish this I have defined a second entity type called "food\_type" which serves to provide additional information related to the "food" node.

Within the Food form, I want to also fill out all the fields for the related food\_type. I am trying to accomplish this using inline\_entity\_form.

Following the documentation, I have done the following things for food\_type:

* Added a dependency of inline\_entity\_form in food\_type.info.yml (there are no other dependencies)
* Created food\_type/src/Controller/FoodTypeInlineEntityFormController.php, which contains the following code:

```
namespace Drupal\food_type\Controller;

/**
 * Controller routines for Food Type pages.
 */
class FoodTypeInlineEntityFormController extends EntityInlineEntityFormController {

 /**
   * Overrides EntityInlineEntityFormController::entityForm().
   */
  public function entityForm($entity_form, &$form_state) {

    return parent::entityForm($entity_form, $form_state);
  }
}

```
* Added the following code to `food_type_install()` in food\_type.install:

```
$entity_info['food_type']['inline entity form'] = array(
    'controller' => 'FoodTypeInlineEntityFormController',
);

```
* Defined `'\Drupal\food_type\Controller\FoodTypeInlineEntityFormController::entityForm'` as the \_controller default under entity.food\_type.form in food\_type.routing.yml

I cannot enable the food\_type module. Attempting to do so yields the following error:

> Fatal error: Class 'Drupal\food\_type\Controller\EntityInlineEntityFormController' not found in {directory}\sites\all\modules\custom\food\_type\src\Controller\FoodTypeInlineEntityFormController.php on line 9

I assume this is caused because I do not include a `use` statement in FoodTypeInlineEntityFormController.php for `EntityInlineEntityFormController`. From Googling, it seems that such a statement is not used in example code that uses this module at all, and it's supposed to simply work when the inline\_entity\_form module is enabled. However, I for sure have inline\_entity\_form enabled and am still getting this error.

I would like to try a `use` statement, but the `EntityInlineEntityFormController` class does not seem to exist at all in the module code, as far as I can tell from searching. I am using 8.x-1.0-alpha6.

I am very new to drupal development and believe I am probably doing something else wrong, but I am completely at a loss here as to how to proceed or troubleshoot. Can anyone please help me or point me in the right direction?

Thank you in advance.

# Answer
> 5 votes
In order to implement Inline Entity form in D8, all you need to do is set your entity reference field to use the IEF widget - simple or complex. That is all. No additional work.

Here is how we set it up in Drupal Commerce for products, programmatically.

```
$form_display = commerce_get_entity_display('commerce_product', $product_type->id(), 'form');
$form_display->setComponent('variations', [
  'type' => 'inline_entity_form_complex',
  'weight' => 10,
  'settings' => [
    'override_labels' => TRUE,
    'label_singular' => 'variation',
    'label_plural' => 'variations',
  ],
]);
$form_display->save();

```

This tells the `variations` field, which is a Product Variation entity reference, to use IEF as the way to manage field values.

---
Tags: entities
---


title: Field updated date in view

text:
# Question
Title: Field updated date in view
I am using Drupal 7 and I have a view displaying the Updated date. Unfortunately, the Updated date changes every time I save the node, even if no changes are made.

How can I configure the Updated date to be changed only if changes in fields are made??

P.S: I tried with "Rules", setting as action "Set a data value" and Data selector "node:changed", but it shows me this message: "The selected data property doesn't support writing."

# Answer
The **Updated date** field is a core property (`node.changed`) of Drupal nodes, representing when it's database record changed. You'd probably have to do some core hacking to rework this property to change only when fields change.

As an alternative, you might want to consider a module like Track Field Changes which logs when specified fields are changed and provides Views integration.
> 0 votes

---
Tags: 7, rules, datetime
---


# Question
Title: Facet blocks are not shown with Facet API Pretty Paths activate
I've enabled Facet API Pretty Paths and the Face blocks are not shown once I select a category.

For example: the Facet Blocks (color and prices) are not shown for the link: /products/field\_brand/simple-threads-68

These are: Drupal 7.44 Facet API Pretty Paths: 7x-1.4 Profile: Commerce Kickstart (commerce\_kickstart-7.x-2.38)

Thanks, Araujo

# Answer
> 0 votes
Ok... I got the 'error'

The Facet blocks are visible for the URL: products When you install Face Pretty Paths, the URL is modified including the segment of the search result. I just added the "products/\*" to the visibility of the block.

Show block on specific pages -\> Only the listed pages: products/\*

---
Tags: search
---


# Question
Title: add render array to custom entity in controller
I have a custom entity, with a controller class that extends `EntityViewController` much like the node module does in core. The `view` method in this class returns a render array `$build` and it is called by the router for my entity.

I would now like to attach some more content to this render array, specifically some articles from another site. I have a class of my own that I am able to implement like this inside the `view()` function:

```
$client = new FrontpageArticlesBuilder();
$articles = $client->toRenderArray();

```

Where `$articles` is a render array. I would like to know how I can append this render array to my existing `$build` render array returned by `view()` method in my controller.

# Answer
You can simply add this to the build array with an arbitrary key name. The only condition is of course that it does not already exist. Every key that does not start with a '#'-sign will be interpreted as another render element or an array of nested render elements.

```
$build['articles'] = $articles;

```
> 1 votes

---
Tags: 8, page-controller
---


title: Can you debug a site with Drush?

text:
# Question
Title: Can you debug a site with Drush?
I have 3 Drupal 8 sites. 2 have premium themes and one is Bartik themed.

When I built the 2 the sites with premium themes in Ubuntu I could log in fine but when I log in to them when online (CentOS server) the sites crashes with the error:

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

This doesn't happen with the Bartik site.

I wonder if I could debug the problem somehow with Drush or if there is anything else than `drush wd-show` just to make sure I cover the most I can with it?

The only way I know to debug problems with drush is drush wd-show.

Is there any command that could help me understand why site logins fail on that particular environment?

## Update - Error from Drush & Cpanel error log:

> \[Tue Jul 19 14:50:11.393827 2016\] \[:error\] \[pid 15721\] \[client 79.177.142.239:33948\] Uncaught PHP Exception RuntimeException: "Failed to start the session because headers have already been sent by "/home/zantech0/public\_html/yoursitename.com/themes/business/includes/skins-menu/skins\_menu.inc" at line 2."
>
> at /home/zantech0/public\_html/yoursitename.com/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php line 140, referer: http://yoursitename.com/user/login

Head of the file:

# Answer
> 5 votes
That error is often caused by PHP files that generate output they should not. Generally it's caused by errors like having a closing ?\> and then a blank line at the end of the file. It's possible that a blank line was added during whatever process you used to move the file to the production server (git, lots of editors, and a few FTP clients will sometimes do this automatically).

In your case I would check `/home/zantech0/public_html/yoursitename.com/themes/business/includes/skins-menu/skins_menu.inc` to see if it does something that generates output (and therefore triggers PHP to send response headers).

# Answer
> 1 votes
Not all errors, especially if you are installing drupal on a new server, are logged in drupal (drush wd-show).

An example is if there is an error in settings.php in the database settings.

To debug this check the php settings:

Is there a line `log_errors = On`?

Then locate the error in the error log of the webserver.

Or set the php option `display_errors = On` to get the error on screen. But remember to remove this on the production server after you found the error.

---
Tags: drush, debugging
---


title: Update.php does nothing

text:
# Question
Title: Update.php does nothing
I'm trying to do a minor security upgrade to Drupal 8.1.7 When I load update.php it gives me a blank page (no errors).

I upgraded all of the software with the exception of the root .htaccess and robots.txt files.

I'm getting this error:

> PHP Parse error: syntax error, unexpected T\_STRING, expecting T\_CONSTANT\_ENCAPSED\_STRING or '(' in /home/energy/public\_html/index.php on line 11

The line causing the error is the following one.

```
use Drupal\Core\DrupalKernel;

```

# Answer
Drupal 8 requires PHP 5.5.9. If you are using PHP 5.2.9, it doesn't recognize as valid a line like `use Drupal\Core\DrupalKernel;` since namespaces were introduced in PHP 5.3.

If you were already running a stable release of Drupal 8 before, check you didn't change in someway the PHP version used from your site.
> 5 votes

---
Tags: 8, updating
---


# Question
Title: Filter articles by tag equal to the node title
I'm trying to create view which will show all Articles which tag is equal to title of currently being viewed node (which content type is not Article).

Adding filter Has taxonomy term = \[title\] does not see token. My question is how to pass current page title to filter or this is done with contextual filters?

For example, I have the *Author* content type. On *Author* nodes, I want to add a view which shows the last three articles which have tags equal to the title of the node. (In my case, it's the author's name.)

*Author* is not a type of user, nor a role assigned to users.

I managed to get something (but not good enough to work):

* View: Unformatted list of fields
* Filter criteria: Content type (=Article)
* Contextual filter: Content:Tags
* Provide default value: Taxonomy term ID from URL
* Validator: Taxonomy term (Tags) + Transform dashes in URL to spaces in term name filter values

When I try to preview the results (Preview with contextual filters), with "chuck-norris" it returns the result as expected, but it doesn't work with "author/chuck-norris", so it doesn't show result on page for Chuck Norris. I also tried with different options (e.g. default value Rawvalue from URL, path component **2**, with checked Use path alias).

# Answer
> 1 votes
> I'm trying to create view which will show all Articles which tag is equal to title of currently being viewed node (which content type is not Article).

Instead of being equal to title, you can approach it like this.

Go to your Author content type, and in Manage fields, add a taxonomy term reference field. Select Tags.

Edit your Author Content Type and give it the same tag as the title.

In other words, you tag the Chuck Norris node with the Chuck Norris tag, which means now your Chuck Norris node as a term ID.

Then in your view

---
Tags: 7, views
---


# Question
Title: How to load page content by url programmatically in custom region
How to load page content **/node/add/page** programmatically in custom region? Example of custom region (https://jsfiddle.net/makbuk/1vetkgL2/).

I have found this How to get a node by its url alias? but it dosn't work for me.

```
$alias = "some/path/to/a/page";
$path = drupal_lookup_path("source", $alias);
$node = menu_get_object("node", 1, $path);

```

# Answer
> 0 votes
You can accomplish this with the Form Block module

> Enables the presentation of user registration, site wide contact, or **node creation forms in blocks**. This is particularly useful for including forms on panels.

Then in blocks (`/admin/structure/block`), assign the Form Block to your desired region.

---
Tags: theming, uri
---


# Question
Title: drupal ajax changes my fieldset to a copy of the incorrect fieldset
Hi I'm a newbie to drupal and I'm practicing using drupal 7 forms #ajax.

I have 2 fieldsets the ingredient fieldset and the steps fieldset.

when I click add step it works fine but when I click add ingredient and remove a step from the step fieldset the step fieldset turns into ingredient field set

here's my form and functions

```
function recipe_new_recipe($form, &$form_state) {
$form = array();

$form['#tree'] = TRUE;

// Fieldset for details of recipe
$form['details_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Recipe Details'),
);

$form['details_fieldset']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipe name'),
    '#description' => t('Name of the recipe'),
);

$form['details_fieldset']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#description' => t('Recipe description'),
    '#resizable' => FALSE,
);

$form['details_fieldset']['time'] = array(
    '#type' => 'textfield',
    '#size' => 10,
    '#title' => t('Preparation time'),
    '#description' => t('Recipe preparation time'),
);

$form['details_fieldset']['serving_size'] = array(
    '#type' => 'textfield',
    '#size' => 8,
    '#title' => t('Serving size'),
    '#description' => t('Recipe serving size'),
);

// Initialization of variables for ingredients
if(empty($form_state['ingredient_num'])) {
    // ingredient number f
    $form_state['ingredient_num'] = 1;
    // ingredient checker array stores all removed  ingredients
    $form_state['ingredient_check'] = array ();
    $form_state['ingredient_count'] = 1;
    $form_state['ingredient_check'][$form_state['ingredient_num']] = 1;
}
// Fieldset for ingredients
$form['ingredient_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Recipe ingredients'),
    '#prefix' => '<div id="recipe_ingredients">',
    '#suffix' => '</div>',

);
//For loop for dynamic fields for ingredients
for ($i=1; $i <= $form_state['ingredient_num']; $i++) {
    // check array = 1 render the field ( for rendering field in the bottom only )
    if($form_state['ingredient_check'][$i] == 1){
        $form['ingredient_fieldset']['ingredient'][$i]['field'] = array(
        '#type' => 'textfield',
        '#prefix' => '<div id = "ingredient_'. $i . '">',
        );

        if ($form_state['ingredient_count'] != 1) {
            $form['ingredient_fieldset']['ingredient'][$i]['remove_ingredient'] = array(
              '#type' => 'submit',
              '#value' => t('Remove'),
              '#submit' => array('remove_ingredient_list'), // function submit callback for removing ingredients
              '#suffix' => '</div>',
              '#name' => $i,
              '#ajax' => array(
                'callback' => 'ajax_remove_ingredient', // ajax callback function for removing ingredients
                'wrapper' => 'recipe_ingredients',
              ),
            );
        }
    }

}
// Add new ingredients button
$form['ingredient_fieldset']['add_ingredient'] = array(
    '#type' => 'submit',
    '#value' => t('add another ingredient'),
    '#submit' => array('add_ingredient_list'), // function submit callback for adding ingredients
            '#ajax' => array(
        'callback' => 'ajax_add_ingredient', // ajax callback function for adding ingredients
        'wrapper' => 'recipe_ingredients'
    ),
);
// Fieldset steps
$form['step_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Recipe steps'),
    '#prefix' => '<div id="recipe_steps">',
    '#suffix' => '</div>',

);
// Step variables initialization
if(empty($form_state['step_num'])) {
    $form_state['step_num'] = 1;
    $form_state['step_check'] = array ();
    $form_state['step_count'] = 1;
    $form_state['step_check'][$form_state['step_num']] = 1;
}
//For loop for dynamic fields for steps
for ($j=1 ; $j <= $form_state['step_num']; $j++) {

    if($form_state['step_check'][$j] == 1){
        // check array = 1 render the field ( for rendering field in the bottom only )
        $form['step_fieldset']['step'][$j]['field'] = array(
        '#type' => 'textfield',
        '#prefix' => '<div id = "step'. $j . '">',
        );

        if($form_state['step_count'] != 1){
            $form['step_fieldset']['step'][$j]['remove_step'] = array(
              '#type' => 'submit',
              '#value' => t('Remove'),
              '#submit' => array('remove_step_list'), // function submit callback for removing steps
              '#suffix' => '</div>',
              '#name' => $j,
              '#ajax' => array(
                'callback' => 'remove_step', // ajax callback function for removing steps
                'wrapper' => 'recipe_steps' ,
              ),
            );
        }
    }

}
// Add new steps button
$form['step_fieldset']['add_step'] = array(
    '#type' => 'submit',
    '#value' => t('add another step'),
    '#submit' => array('add_step_list'),
            '#ajax' => array(
        'callback' => 'add_step',
        'wrapper' => 'recipe_steps',
    ),
);

$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit recipe'),
);

return $form;
}

function add_ingredient_list($form, &$form_state){
$form_state['ingredient_num']++;
$check = $form_state['ingredient_num'];
$form_state['ingredient_count']++;
$form_state['ingredient_check'][$check] = 1;
$form_state['rebuild'] = TRUE;
}

function remove_ingredient_list($form, &$form_state) {
$key = $form_state['triggering_element']['#name'];
$form_state['ingredient_count']--;
$form_state['ingredient_check'][$key] = 2;
$form['ingredient_fieldset']['ingredient'][$key]['field']['#access'] =    FALSE;
$form['ingredient_fieldset']['ingredient'][$key]['remove_name']['#access'] = FALSE;
$form_state['rebuild'] = TRUE;
}
function ajax_add_ingredient($form, $form_state) {
return $form['ingredient_fieldset'];
}
function ajax_remove_ingredient($form, $form_state) {
return $form['ingredient_fieldset'];
}
function add_step_list($form, &$form_state){
$form_state['step_num']++;
$check = $form_state['step_num'];
$form_state['step_count']++;
$form_state['step_check'][$check] = 1;
$form_state['rebuild'] = TRUE;
}
function remove_step_list($form, &$form_state) {
$key = $form_state['triggering_element']['#name'];
$form_state['step_count']--;
$form_state['step_check'][$key] = 2;
$form['step_fieldset']['step'][$key]['field']['#access'] = FALSE;
$form['step_fieldset']['step'][$key]['remove_name']['#access'] = FALSE;
$form_state['rebuild'] = TRUE;
}
function add_step($form, $form_state) {
return $form['step_fieldset'];
}
function remove_step($form, $form_state) {
return $form['step_fieldset'];
}

```

# Answer
> 1 votes
I had the same issue recently, as it turns out it was calling the wrong callback because you need to have a unique '#name' for each of the buttons.

In your code you have the '#name' as $i and $j which represents a number but this means that the '#name' is not unique as both $i and $j can have the same number.

So for example, this:

```
'#name' => $i,

```

Should be something like:

```
'#name' => 'remove_ingredient_' . $i,

```

This differentiates the two so the right callback is used.

You then need to strip the text out of the '#name' to use the key:

```
function remove_ingredient_list($form, &$form_state) {
  $key = $form_state['triggering_element']['#name'];
  $key = str_replace('remove_ingredient_', '', $key);
  $form_state['ingredient_count']--;
  $form_state['ingredient_check'][$key] = 2;

```

I realise this is an old question but hopefully it helps anyone else having the same issue :-)

---
Tags: forms, ajax
---


# Question
Title: User field imported with Feeds but not showing in user edit page?
I'm using Feeds Importer to create users from a csv file, in my Drupal 7 site.

It works perfectly, except one case. I added some custom fields to user profile and I can set all them with my importer, except one (a simple text field, let's say 'foo').

The value for 'foo' is correctly imported: if I open the 'View' page for a user profile I can see it, listed as supposed. In the 'Edit' page of the user profile, however, the value of the field is showed empty. If I modify the value in this edit page and save, the value is stored AND showed in the edit page.

I tried even to create another custom field similar to 'foo' and it works perfectly in any case. (I can't delete foo and recreate it for it contains several data)

How could this be debugged? I checked the csv, the importer, even the database (in the table field\_data\_field\_foo the value is stored correctly), and all seems fine. No error in drupal log, neither in importer log.

# Answer
> 2 votes
> I can't delete foo and recreate it for it contains several data

Here is how I would try to fix this:

1. Backup your entire Drupal Database.
2. With phpmyadmin or some other database manager/viewer, find the field\_foo table and extract the table as a CSV file.
3. In Drupal, go to user manage fields and Delete field foo
4. Flush the cache (not necessary, but eh, just in case)
5. Add a new field, foo
6. Edit user 1 and put something for field foo. (This is just so we get the table structure on step 7)
7. Find field\_foo in DB and extract.
8. Open Original field foo .csv in excel and highlight all data and copy.
9. Open new field foo .csv and paste data and save
10. Import new field foo .csv to DB.
11. Flush/Clear the Cache
12. Try importing with feeds again and see what happens.

---
Tags: 7, feeds
---


# Question
Title: How to add an additional wrapper div within a Views row?
I have a Views page with a format of ‘unformatted list’. For a views row I’d like to add an additional div to act as an additional wrapper. The resulting mark-up would then look like

```
<div class=“views-row views-row-1”><div class=“myWrap”>

```

I’ve looked in the various views template files located in the views module folder within the view module but am not seeing a place to add such a div.

Does anyone know how this can be achieved?

I guess I could use an HTML list and make that work but I’d prefer what i just described above.

# Answer
This could be done in a couple of ways depending on your requirement.

1. If you want to add a wrapper div to a particular row: (**Note:** This will work if you are displaying fields in the view)
    * Click on that field.
    * Under style settings select the HTML element, and choose DIV.
    * You can also add the class to this div with the "Create a CSS class" option.
2. If you want to add a wrapper to all the rows: (**NOTE: This will only work for D7**)
    * The best way to do this is via a views template. Click on the "Advanced" section on the right hand side.
    * Click on the "Theme information"
    * Select "Views row style output"
    * Copy the template content.
    * Create a template with the name provided against "Row style output" link in the screenshot above. Paste the content into it.
    * Add an extra div element in the template directly.
    * **Note:** The template overrides are provided from "generic" to specific" if you go from left to right. E.g. `views-view-fields.tpl.php` would get applied to all the rows of *all* the views, and the specificity of the templates goes on increasing as you go right of the "Theme information".
> 3 votes

# Answer
**The solution below will wrap all your rows inside your class, as long as you are not using the `views-row view-row-1` classes for something specific, this will work too**

You can add a row class by clicking on the `Settings` link that its beside `Unformatted List`

This will output:

```
<div class=“views-row views-row-1 example”>

```

then doing `.example { border: solid red; }` will add red border to all your rows.
> 1 votes

---
Tags: views, theming
---


title: How do I remove page title/header?

text:
# Question
Title: How do I remove page title/header?
In Drupal 8, is there an easy way to configure a page so that its page header/title is not displayed on the page?

I have created a Basic Page, with /home as path alias, and *Home* as title. I set it as front page. However, it displays 'Home' at the top of the page, just below the navbar and breadcrumbs.

Is it necessary to create a subtheme of the 'Bootstrap' theme, and somehow add custom CSS?

# Answer
Drupal 8/9 places the page title in its own block (called Page title). You can control when and where that block displays on the block layout page: /admin/structure/block
> 33 votes

# Answer
You can do this entirely with CSS. You need to target that node which you are using as HOME page.

Now, Drupal-7 was generating specific class for each node. And this way it was easy to target each individual node and we were able to apply the specific CSS to that particular node.

But, in Drupal 8 this property is not available, hence we need to add this. follow following steps. I am showing this using Bartik theme as I do not have familiarity with Bootstrap theme. You can do with bootstrap theme also. It is pure CSS, so no sub-theming necessary.

**1. Add the function to bartik.theme file.**

> ```
> if ($node = \Drupal::request()->attributes->get('node')) {
>     $variables['attributes']['class'][] = 'page-node-' . $node->id();
>   }
>
> ```

in the section of,

```
function bartik_preprocess_html(&$variables) {

}

```

Why I am showing this way, because there is already other codes in `function bartik_preprocess_html(&$variables)`, so add this function as last line.

Clear cache,

**2. Get the CSS for that node**

Now, if you do `Inspect element` on that particular node. You can find the class in `<body></body>` section as `page-node-XX`.

**3. Go to core/themes/bartik/css/components/page-title.css,** and add following code in that,

> ```
> .page-node-XX .page-title {
>  display: none;
> }
>
> ```

Clear cache,

Now, this way you can target that particular node and you can do whatever CSS you want to apply.

**Credit for function code:** Link
> 2 votes

# Answer
you can also use this module for drupal 8 https://www.drupal.org/project/exclude\_node\_title

* This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers. It provides a checkbox on node-edit pages for easier exclusion. Also provides the option to hide all titles of a certain Content type. From the administrative interface you can select a content type to hide title for.
> 2 votes

---
Tags: 8, theming
---


title: Best way to create mobile menu?

text:
# Question
Title: Best way to create mobile menu?
I have a template that I am trying to convert into a custom theme and it contains a mobile menu that is a duplicate of the main menu.

What is the best way to tackle this with the least amount of duplication?

I tried to create a **menu--main.html.twig** file and repeated 2 menus in one file. It looked liked it worked at first until my menu contains submenus and then some weird behavior where it nested both menus into the below menu. I would like to avoid creating a separate mobile menu in the admin dashboard and manually adding new links if created, but if that is the best way then I can handle it. Just looking for other opinions.

Thanks

# Answer
Are you familiar with Boostrap or Zurb Foundation framework? I suggest you research either of these 2 frameworks and you will find that you can accomplish your goal using either one.

Here is a little background. Basically they are just a javascript file and css file. The javascript file has code for a ton of common/widely used features and built to be mobile responsive. All you have to do is assign your divs a specific class name and they will get a certain functionality. You can find the class names that you need to use on their documentation page.

In Drupal, you can use the Boostrap theme or Zurb Foundation theme to build on top off. These themes have done some of the work for you. Ex: assign all the buttons the proper button classes using a preprocess function.

Here are specific tutorials regarding your question:

Bootstrap 3 Tutorials - #2 - Responsive Collapsing Navbar

Zurb Foundation | Top-Bar Tutorial
> 2 votes

# Answer
If you are using Bootstrap Framework then take the Theme Aegan for example, In this theme it well handle the multi-level menu and also would support for mobile menu, Take it as inspiration it would help to create better menu for you.

And also see my blog it explain to create mobile multi-level menu in drupal 8
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Printing PHP variable in form element in buildForm function
I have a php variable like this

```
$opensslOut = preg_replace('/\n\r{0,1}/', '<br>', $str);

```

I need to print its value on a form element. I used the following code

```
$form['openssl'] = [
      '#title' => t('OpenSSL'),
      '#markup' => t('$opensslOut'),
    ];

```

But didn't worked? I am a newbie in Drupal, Please help me to figure out a solution.

# Answer
> 2 votes
It's just a silly error `'#markup' => t('$opensslOut')` needs to be without the `''` because $opensslOut is a variable and not a string.

So use

`'#markup' => t($opensslOut)`

# Answer
> 1 votes
The answer is simple.Just remove the quotes of $opensslOut.

$form\['openssl'\] = \[ '#title' =\> t('OpenSSL'), '#markup' =\> t($opensslOut), \];

---
Tags: forms, 8
---


# Question
Title: Composer, git and update core and modules
I started working with Drupal 8 and tried to find out the best way for developing and administrating projects. As Drupal 8 with all its dependencies is very big (more than 60 MB) I like the suggestion not to commit all the Drupal core, modules and dependencies into a git repository but to let Composer deal these things. The idea is to set everything (Drupal core version, installed modules with their versions) in the composer.json, commit this file to a GIT repository and when a remote colleague wants to work on the project he/she just checks out the composer.json from the repo locally, starts composer install and all the needed PHP files (Drupal core, modules and dependencies) get downloaded (as far as I understand).

For me this seems to be an interesting way to start new projects but I feel that this could be some kind of bottleneck for the everyday project management. For example when I define the modules and the core in composer.json usually it seems to be done in a more general way in terms of the version. Usually not the specific version seems to be defined in composer.json:

```
"drupal/core": "8.0.*"

```

When I start `composer install` locally earlier as my colleague he/she might get a newer version of Drupal which may lead to different behaviors of our working copies (although it should not with regards to versioning rules - I know). But if we define a specific version:

```
"drupal/core": "8.0.0"

```

so we can be sure that every remote colleague will have the exact same version we can not use `composer update` to update to newer versions automatically - we would need to look for the latest version and change the version in composer.json manually.

The same appears with contributed modules or themes.

To be honest, I never worked with Composer before; maybe someone with more composer experience could explain to me how to deal with these issues.

# Answer
> Is it correct that "composer install" does install the versions as defined in composer.lock which gets created after "composer install" is run the first time?

The composer.json file describes which versions can be installed, while the composer.lock module contains the version of the installed libraries.

For example, the composer.json file could contain the following, which would say that is only acceptable to install any version that is greater or equal to 1.0 but lower than 1.1.

```
"require": {
    "monolog/monolog": "1.0.*"
}

```

The composer.lock file could contain a `"monolog/monolog": "1.0.2"` line, since that is the higher version available of the Monolog library that respect the restrictions of the composer.json file.

So, simplifying:

* The composer.json file is used from `composer install`
* Both the composer.json and the composer.lock files are used from `composer update`

> When I start composer install locally earlier as my colleague he/she might get a newer version of Drupal which may lead to different behaviors of our working copies (although it should not with regards to versioning rules - I know).

Yes, that can happen, but it is not a problem, since you just need to run `composer update` to get the same versions your colleague has. That is, if both of you have the same composer.json file, and neither of you installed other libraries that could cause any conflict.
> 1 votes

---
Tags: updating, version-control, composer
---


# Question
Title: Why is 1 of 8 menu choices not displaying for anonymous users?
I have a migrated a Drupal 6 site to Drupal 8, but in order to update the content I remigrated it. In my Primary link menu I have 8 menus, but now one of then is shown only to the administrator user.

```
About Board of  Water  Construction Business Finance Community News &
 us   Directors Supply Facilities   Opps     Invest  Outreach  Publications

```

Anonymous users see the following.

```
About Water  Construction Business Finance Community News &
 us   Supply Facilities   Opps     Invest  Outreach  Publications

```

This is something that was not happening when I did my first migration.

I am using Superfish.

What happened? How can I fix this?

# Answer
Check the permission of whatever "Board of Directors" links to (a node, a view, something else?). To ensure anonymous have permission to access it (also).
> 1 votes

---
Tags: 8, navigation
---


title: Can't update header area in view

text:
# Question
Title: Can't update header area in view
When I'm updating the heasder area in my view and hit Apply (all displays), I get a page full of cryptic code like

```
[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"seven","theme_token":"nktojBAhwknIwX4rM0nJ0129z8flAy8_R7C7RpTZNUo","jquery_version":"1.8"},"ckeditor":{"input_formats":{"filtered_html":{"customConfig":"\/sites\/all\/modules\/ckeditor\/ckeditor.config.js?","defaultLanguage":"en","toolbar":"[\n    [\u0027Source\u0027],\n    [\u0027Cut\u0027,\u0027Copy\u0027,\u0027Paste\u0027,\u0027PasteText\u0027,\u0027PasteFromWord\u0027,\u0027-\u0027,\u0027SpellChecker\u0027,\u0027Scayt\u0027],\n    [\u0027Undo\u0027,\u0027Redo\u0027,\u0027Find\u0027,\u0027Replace\u0027,\u0027-\u0027,\u0027SelectAll\u0027,\u0027RemoveFormat\u0027],\n    [\u0027Image\u0027,\u0027Flash\u0027,\u0027Table\u0027,\u0027HorizontalRule\u0027,\u0027Smiley\u0027,\u0027SpecialChar\u0027,\u0027Iframe\u0027],\n    \u0027\/\u0027,\n    [\u0027Bold\u0027,\u0027Italic\u0027,\u0027Underline\u0027,\u0027Strike\u0027,\u0027-\u0027,\u0027Subscript\u0027,\u0027Superscript\u0027],\n    [\u0027NumberedList\u0027,\u0027BulletedList\u0027,\u0027-\u0027,\u0027Outdent\u0027,\u0027Indent\u0027,\u0027Blockquote\u0027,\u0027CreateDiv\u0027],\n    [\u0027JustifyLeft\u0027,\u0027JustifyCenter\u0027,\u0027JustifyRight\u0027,\u0027JustifyBlock\u0027,\u0027-\u0027,\u0027BidiRtl\u0027,\u0027BidiLtr\u0027],\n    [\u0027Link\u0027,\u0027Unlink\u0027,\u0027Anchor\u0027,\u0027Linkit\u0027,\u0027LinkToNode\u0027,\u0027LinkToMenu\u0027],\n    \u0027\/\u0027,\n    [\u0027Format\u0027,\u0027Font\u0027,\u0027FontSize\u0027],\n    [\u0027TextColor\u0027,\u0027BGColor\u0027],\n    [\u0027Maximize\u0027,\u0027ShowBlocks\u0027],\n    [\u0027DrupalBreak\u0027,\u0027DrupalPageBreak\u0027]\n]","enterMode":1,"shiftEnterMode":2,"toolbarStartupExpanded":true,"width":"100%","skin":"moono","format_tags":"p;div;pre;address;h1;h2;h3;h4;h5;h6","show_toggle":"t","default":"t","allowedContent":true,"ss":"2","loadPlugins":{"drupalbreaks":{"name":"drupalbreaks","desc":"Plugin for inserting Drupal teaser and page breaks.","path":"\/sites\/all\/modules\/ckeditor\/plugins\/drupalbreaks\/","buttons":{"DrupalBreak":{"label":"DrupalBreak","icon":"images\/drupalbreak.png"}},"default":"t"},"imce":{"name":"imce","desc":"Plugin for inserting files from IMCE without image dialog","path":"\/sites\/all\/modules\/ckeditor\/plugins\/imce\/","buttons":{"IMCE":{"label":"IMCE","icon":"images\/icon.png"}},"default":"f"}},"scayt_autoStartup":false,"filebrowserBrowseUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/ckfinder.html?id=Advanced","filebrowserImageBrowseUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/ckfinder.html?Type=Images\u0026id=Advanced","filebrowserFlashBrowseUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/ckfinder.html?Type=Flash\u0026id=Advanced","filebrowserUploadUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/core\/connector\/php\/connector.php?command=QuickUpload\u0026type=Files\u0026id=Advanced","filebrowserImageUploadUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/core\/connector\/php\/connector.php?command=QuickUpload\u0026type=Images\u0026id=Advanced","filebrowserFlashUploadUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/core\/connector\/php\/connector.php?command=QuickUpload\u0026type=Flash\u0026id=Advanced","stylesCombo_stylesSet":"drupal:\/sites\/all\/modules\/ckeditor\/ckeditor.styles.js","contentsCss":["\/sites\/all\/modules\/ckeditor\/css\/ckeditor.css?oahnlb","\/sites\/all\/libraries\/ckeditor\/contents.css?oahnlb"]},"full_html":{"customConfig":"\/sites\/all\/modules\/ckeditor\/ckeditor.config.js?","defaultLanguage":"en","toolbar":"[\n    [\u0027Source\u0027],\n    [\u0027Cut\u0027,\u0027Copy\u0027,\u0027Paste\u0027,\u0027PasteText\u0027,\u0027PasteFromWord\u0027,\u0027-\u0027,\u0027SpellChecker\u0027,\u0027Scayt\u0027],\n    [\u0027Undo\u0027,\u0027Redo\u0027,\u0027Find\u0027,\u0027Replace\u0027,\u0027-\u0027,\u0027SelectAll\u0027],\n    [\u0027Image\u0027,\u0027Flash\u0027,\u0027Table\u0027,\u0027HorizontalRule\u0027,\u0027Smiley\u0027,\u0027SpecialChar\u0027,\u0027Iframe\u0027],\n    \u0027\/\u0027,\n    [\u0027Bold\u0027,\u0027Italic\u0027,\u0027Underline\u0027,\u0027Strike\u0027,\u0027-\u0027,\u0027Subscript\u0027,\u0027Superscript\u0027,\u0027-\u0027,\u0027RemoveFormat\u0027],\n    [\u0027NumberedList\u0027,\u0027BulletedList\u0027,\u0027-\u0027,\u0027Outdent\u0027,\u0027Indent\u0027,\u0027Blockquote\u0027,\u0027CreateDiv\u0027],\n    [\u0027JustifyLeft\u0027,\u0027JustifyCenter\u0027,\u0027JustifyRight\u0027,\u0027JustifyBlock\u0027,\u0027-\u0027,\u0027BidiLtr\u0027,\u0027BidiRtl\u0027,\u0027-\u0027,\u0027Language\u0027],\n    [\u0027Link\u0027,\u0027Unlink\u0027,\u0027Anchor\u0027,\u0027Linkit\u0027,\u0027LinkToNode\u0027,\u0027LinkToMenu\u0027],\n    \u0027\/\u0027,\n    [\u0027Format\u0027,\u0027Font\u0027,\u0027FontSize\u0027],\n    [\u0027TextColor\u0027,\u0027BGColor\u0027],\n    [\u0027Maximize\u0027,\u0027ShowBlocks\u0027],\n    [\u0027DrupalBreak\u0027,\u0027DrupalPageBreak\u0027]\n]","enterMode":1,"shiftEnterMode":2,"toolbarStartupExpanded":true,"width":"100%","skin":"moono","format_tags":"p;div;pre;address;h1;h2;h3;h4;h5;h6","show_toggle":"t","default":"t","allowedContent":true,"ss":"2","loadPlugins":{"drupalbreaks":{"name":"drupalbreaks","desc":"Plugin for inserting Drupal teaser and page breaks.","path":"\/sites\/all\/modules\/ckeditor\/plugins\/drupalbreaks\/","buttons":{"DrupalBreak":{"label":"DrupalBreak","icon":"images\/drupalbreak.png"}},"default":"t"},"imce":{"name":"imce","desc":"Plugin for inserting files from IMCE without image dialog","path":"\/sites\/all\/modules\/ckeditor\/plugins\/imce\/","buttons":{"IMCE":{"label":"IMCE","icon":"images\/icon.png"}},"default":"f"}},"scayt_autoStartup":false,"filebrowserBrowseUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/ckfinder.html?id=Full","filebrowserImageBrowseUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/ckfinder.html?Type=Images\u0026id=Full","filebrowserFlashBrowseUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/ckfinder.html?Type=Flash\u0026id=Full","filebrowserUploadUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/core\/connector\/php\/connector.php?command=QuickUpload\u0026type=Files\u0026id=Full","filebrowserImageUploadUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/core\/connector\/php\/connector.php?command=QuickUpload\u0026type=Images\u0026id=Full","filebrowserFlashUploadUrl":"\/sites\/all\/modules\/ckeditor\/ckfinder\/core\/connector\/php\/connector.php?command=QuickUpload\u0026type=Flash\u0026id=Full","stylesCombo_stylesSet":"drupal:\/sites\/all\/modules\/ckeditor\/ckeditor.styles.js","contentsCss":["\/sites\/all\/modules\/ckeditor\/css\/ckeditor.css?oahnlb","\/sites\/all\/libraries\/ckeditor\/contents.css?oahnlb"]}},"plugins":[]},"CTools":{"dependent":{"edit-options-token-help":{"values":{"edit-options-tokenize":[1]},"num":1,"type":"hide"}}},"urlIsAjaxTrusted":{"\/admin\/structure\/views\/ajax\/config-item\/golf_feed\/page\/header\/area":true}},"merge":true},{"command":"viewsDismissForm"},{"command":"viewsShowButtons","changed":true},{"command":"viewsTriggerPreview"},{"command":"insert","method":"html","selector":"#views-tab-page","data":"\u003Cdiv id=\u0022edit-display-settings-details\u0022\u003E\u003Cdiv id=\u0022edit-display-settings-top\u0022 class=\u0022views-ui-display-tab-actions views-ui-display-tab-bucket clearfix\u0022\u003E\u003Cdiv class=\u0022ctools-no-js ctools-button ctools-dropbutton\u0022\u003E\u003Cdiv class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022 class=\u0022ctools-twisty ctools-text\u0022\u003Eopen\u003C\/a\u003E\u003C\/div\u003E\u003Cdiv class=\u0022ctools-content\u0022\u003E\u003Cul class=\u0022horizontal right actions\u0022\u003E\u003Cli class=\u0022view\u0022\u003E\u003Ca href=\u0022\/talking-rock-golf-course\u0022\u003Eview Page\u003C\/a\u003E\u003C\/li\u003E\u003Cli class=\u0022duplicate\u0022\u003E\u003Cinput type=\u0022submit\u0022 name=\u0022op\u0022 value=\u0022clone Page\u0022 class=\u0022form-submit\u0022 \/\u003E\u003C\/li\u003E\u003Cli class=\u0022delete\u0022\u003E\u003Cinput type=\u0022submit\u0022 name=\u0022op\u0022 value=\u0022delete Page\u0022 class=\u0022form-submit\u0022 \/\u003E\u003C\/li\u003E\u003Cli class=\u0022disable\u0022\u003E\u003Cinput type=\u0022submit\u0022 name=\u0022op\u0022 value=\u0022disable Page\u0022 class=\u0022form-submit\u0022 \/\u003E\u003C\/li\u003E\u003C\/ul\u003E\u003C\/div\u003E\u003C\/div\u003E\u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting odd clearfix\u0022 \u003E\n      \u003Cspan class=\u0022label\u0022\u003EDisplay name:\u003C\/span\u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/display_title\u0022 class=\u0022views-ajax-link \u0022 title=\u0022Page\u0022 id=\u0022views-page-display-title\u0022\u003EPage\u003C\/a\u003E  \u003C\/div\u003E\n\u003C\/div\u003E\u003Cdiv id=\u0022edit-display-settings-main\u0022 class=\u0022clearfix views-display-columns\u0022\u003E\u003Cdiv class=\u0022views-display-column first\u0022\u003E\u003Cdiv class=\u0022views-ui-display-tab-bucket title\u0022 \u003E\n          \u003Ch3\u003ETitle\u003C\/h3\u003E\n    \u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting defaulted even clearfix\u0022 \u003E\n      \u003Cspan class=\u0022label\u0022\u003ETitle:\u003C\/span\u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/title\u0022 class=\u0022views-ajax-link \u0022 title=\u0022Change the title that this display will use.\u0022 id=\u0022views-page-title\u0022\u003ETalking Rock Golf Course\u003C\/a\u003E  \u003C\/div\u003E\n\u003C\/div\u003E\n\u003Cdiv class=\u0022views-ui-display-tab-bucket format\u0022 \u003E\n          \u003Ch3\u003EFormat\u003C\/h3\u003E\n    \u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting defaulted odd clearfix\u0022 \u003E\n      \u003Cspan class=\u0022label\u0022\u003EFormat:\u003C\/span\u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/style_plugin\u0022 class=\u0022views-ajax-link \u0022 title=\u0022Change the way content is formatted.\u0022 id=\u0022views-page-style-plugin\u0022\u003EUnformatted list\u003C\/a\u003E\u003Cspan class=\u0022label\u0022\u003E\u0026nbsp;|\u0026nbsp;\u003C\/span\u003E\u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/style_options\u0022 class=\u0022views-ajax-link views-button-configure\u0022 title=\u0022Change settings for this format\u0022 id=\u0022views-page-style-options\u0022\u003E\u003Cspan\u003ESettings\u003C\/span\u003E\u003C\/a\u003E  \u003C\/div\u003E\n\u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting defaulted even clearfix\u0022 \u003E\n      \u003Cspan class=\u0022label\u0022\u003EShow:\u003C\/span\u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/row_plugin\u0022 class=\u0022views-ajax-link \u0022 title=\u0022Change the way each row in the view is styled.\u0022 id=\u0022views-page-row-plugin\u0022\u003EContent\u003C\/a\u003E\u003Cspan class=\u0022label\u0022\u003E\u0026nbsp;|\u0026nbsp;\u003C\/span\u003E\u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/row_options\u0022 class=\u0022views-ajax-link views-button-configure\u0022 title=\u0022Change settings for this style\u0022 id=\u0022views-page-row-options\u0022\u003E\u003Cspan\u003ETeaser\u003C\/span\u003E\u003C\/a\u003E  \u003C\/div\u003E\n\u003C\/div\u003E\n\u003Cdiv class=\u0022views-ui-display-tab-bucket fields\u0022 \u003E\n          \u003Ch3\u003EFields\u003C\/h3\u003E\n    \u003Cdiv class=\u0022views-display-setting\u0022\u003EThe selected style or row format does not utilize fields.\u003C\/div\u003E\u003C\/div\u003E\n\u003Cdiv class=\u0022views-ui-display-tab-bucket filter-criteria\u0022 \u003E\n        \u003Cdiv class=\u0022ctools-no-js ctools-dropbutton ctools-button views-ui-settings-bucket-operations\u0022 id=\u0022ctools-button-1\u0022\u003E\u003Cdiv class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022 class=\u0022ctools-twisty ctools-text\u0022\u003Eopen\u003C\/a\u003E\u003C\/div\u003E\u003Cdiv class=\u0022ctools-content\u0022\u003E\u003Cul class=\u0022actions horizontal right\u0022\u003E\u003Cli class=\u0022add first\u0022\u003E\u003Ca href=\u0022\/admin\/structure\/views\/nojs\/add-item\/golf_feed\/page\/filter\u0022 class=\u0022icon compact add views-ajax-link\u0022 title=\u0022Add\u0022 id=\u0022views-add-filter\u0022\u003EAdd\u003C\/a\u003E\u003C\/li\u003E\n\u003Cli class=\u0022rearrange last\u0022\u003E\u003Ca href=\u0022\/admin\/structure\/views\/nojs\/rearrange-filter\/golf_feed\/page\/filter\u0022 class=\u0022icon compact rearrange views-ajax-link\u0022 title=\u0022Rearrange\u0022 id=\u0022views-rearrange-filter\u0022\u003EAnd\/Or, Rearrange\u003C\/a\u003E\u003C\/li\u003E\n\u003C\/ul\u003E\u003C\/div\u003E\u003C\/div\u003E        \u003Ch3\u003EFilter criteria\u003C\/h3\u003E\n    \u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting page-filter-status odd clearfix\u0022 \u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/config-item\/golf_feed\/page\/filter\/status\u0022 class=\u0022views-ajax-link\u0022\u003EContent: Published (Yes)\u003C\/a\u003E  \u003C\/div\u003E\n\u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting page-filter-type even clearfix\u0022 \u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/config-item\/golf_feed\/page\/filter\/type\u0022 class=\u0022views-ajax-link\u0022\u003EContent: Type (= Golf Content)\u003C\/a\u003E  \u003C\/div\u003E\n\u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting page-filter-field-display-in-golf-news-feed-value odd clearfix\u0022 \u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/config-item\/golf_feed\/page\/filter\/field_display_in_golf_news_feed_value\u0022 class=\u0022views-ajax-link\u0022\u003EContent: Display in Golf news feed (= On)\u003C\/a\u003E  \u003C\/div\u003E\n\u003C\/div\u003E\n\u003Cdiv class=\u0022views-ui-display-tab-bucket sort-criteria\u0022 \u003E\n        \u003Cdiv class=\u0022ctools-no-js ctools-dropbutton ctools-button views-ui-settings-bucket-operations\u0022 id=\u0022ctools-button-2\u0022\u003E\u003Cdiv class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022 class=\u0022ctools-twisty ctools-text\u0022\u003Eopen\u003C\/a\u003E\u003C\/div\u003E\u003Cdiv class=\u0022ctools-content\u0022\u003E\u003Cul class=\u0022actions horizontal right\u0022\u003E\u003Cli class=\u0022add first\u0022\u003E\u003Ca href=\u0022\/admin\/structure\/views\/nojs\/add-item\/golf_feed\/page\/sort\u0022 class=\u0022icon compact add views-ajax-link\u0022 title=\u0022Add\u0022 id=\u0022views-add-sort\u0022\u003EAdd\u003C\/a\u003E\u003C\/li\u003E\n\u003Cli class=\u0022rearrange last\u0022\u003E\u003Ca href=\u0022\/admin\/structure\/views\/nojs\/rearrange\/golf_feed\/page\/sort\u0022 class=\u0022icon compact rearrange views-ajax-link\u0022 title=\u0022Rearrange\u0022 id=\u0022views-rearrange-sort\u0022\u003ERearrange\u003C\/a\u003E\u003C\/li\u003E\n\u003C\/ul\u003E\u003C\/div\u003E\u003C\/div\u003E        \u003Ch3\u003ESort criteria\u003C\/h3\u003E\n    \u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting page-sort-created even clearfix\u0022 \u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/config-item\/golf_feed\/page\/sort\/created\u0022 class=\u0022views-ajax-link\u0022\u003EContent: Post date (desc)\u003C\/a\u003E  \u003C\/div\u003E\n\u003C\/div\u003E\n\u003C\/div\u003E\u003Cdiv class=\u0022views-display-column second\u0022\u003E\u003Cdiv class=\u0022views-ui-display-tab-bucket page-settings\u0022 \u003E\n          \u003Ch3\u003EPage settings\u003C\/h3\u003E\n    \u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting odd clearfix\u0022 \u003E\n      \u003Cspan class=\u0022label\u0022\u003EPath:\u003C\/span\u003E\n        \u003Ca href=\u0022\/admin\/structure\/views\/nojs\/display\/golf_feed\/page\/path\u0022 class=\u0022views-ajax-link \u0022 title=\u0022\/talking-rock-golf-cours...\u0022 id=\u0022views-page-path\u0022\u003E\/talking-rock-golf-cours...\u003C\/a\u003E  \u003C\/div\u003E\n\u003Cdiv class=\u0022views-display-setting views-ui-display-tab-setting even clearfix\u0022 \u003E\n      \u003Cspan class=\u0022label\u0022\u003EMenu:\u003C\/span\u003E\n        \u003Ca ...

```

This even happens when I just add a strinf "test" to my existing header content. While the change seems to be saved, it won't apply to the actual view as I never get the chance to actually save & apply my changes. Any idea what's happening here? I'm on `Views: 7.x-3.14` and `core 7.50`

**EDIT1**
And I already have the `Jquery Update` module installed.

# Answer
I had this issue to and the problem for me was with JQuery. So take a look at what JQuery is being used. In my case I installed the 'Jquery Update' module and sorted it with that.

Hope this helps you too.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How can I change the search form placeholder value?
How can I change the search form placeholder value? I can change the value of it in my **.theme** file, but I want it to be also translatable.

What is the correct way of doing this?

# Answer
> 19 votes
You don't alter a `TranslatableMarkup` object: You replace it with another `TranslatableMarkup` object you obtain from `t('The new placeholder')`, `new TranslatableMarkup('The new placeholder')`, or a function/method that returns a `TranslatableMarkup` object.

```
function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['title'] = t('The new placeholder');
}

```

The result of this code is the following (on Google Chrome running on OSX "El Capitan").

>

What you are showing is not the placeholder, but the input title. To change the placeholder of a form element, you should use code similar to the following one.

```
function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

```

Using this code, you get the following result.

>

# Answer
> 2 votes
you can use form alter for this

```
 function yourtheme_form_search_block_form_alter(&$form, &$form_state) {
      $form['keys']['#attributes']['placeholder'][] = t('enter the terms you wish to search for');
    }

```

# Answer
> 2 votes
I think, we could alter the form details from hook\_form\_FORM\_ID\_alter, The following code would help to fix the issue :)

```
function my_module_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['keys']['#title'] = t('Your custom Title');
  $form['keys']['#attributes']['title'] = t('Your custom Placeholder');
}

```

The above code will change the title and placeholder for the search form.

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


# Question
Title: How to list 5 most view nodes without using the Statistic module?
I am trying to create a view/block of the most viewed node without using a module if possible.

If it's not possible, is it possible to do it without using the statistic module?

# Answer
The simple and best solution which work with views is node view count. Which works with views and play around it.
> 0 votes

# Answer
Apart from the Node view count modules (already mentioned in another answer), here are some other modules that might be a possible fit:

* Visitors (disclosure: I'm the maintainer of it).

Comes with a set of **Visitors Reports**, such as:

+ User activity report (hits, nodes, comments).
    + A *Visitor* tab that is added to each node, with details about Referrer, Date, User, IP address, User agent.
* Better Statistics, here's a quote from its project page:

> ... introduces a Statistics API, allowing developers and contributed modules a way to collect, limit, and route custom access statistics and data.
> 0 votes

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


# Question
Title: Migrating from Postgresql 9.1 (non drupal) to Percona Server 5.5
We decided to go from a perl website to Drupal 7 (PHP 5.5.23).

My big question is how do i migrate the DB which is PSQL 9.1 to mySQL. I've heard of the Migrate module, Drush, MySQL Workbench.

Can someone direct me on which steps to take after converting my postgresql schema to mysql?

# Answer
I end up using the feeds importers modules. You may have to change (rewrite/delete) your tables.

1. dump my table in a csv file (\*.csv) make sure to add the headers.
2. create a content type with the name of my table and have all the columns of my tables
3. create a feed importer make sure to map the sources (postgreql) and target (drupal mysql) columns
4. got the import link (homepage/import) to upload the file. this may take a few minutes depending on how big you DB is.
5. when you go to content you should see all the newly added rows

Hope it helps.
> 1 votes

# Answer
As an alternative to migrating such Postgress database, you may want to go for a co-existence approach (which eventually you can still migrate later on). To do so, have a look at the Forena module (disclosure: I'm a co-maintainer of it). It can be used to build reports and/or charts about data stored in your existing Postgress database. Here is a quote about Forena:

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

The advantage of this approach is that you get lots of Drupal features available, while the "backend-part" of your application continues to be the applicationn you already have (you don't loose the investements made in that).
> 0 votes

---
Tags: 7, database, migrations
---