title: Best way to render a form on a node?

text:
# Question
Title: Best way to render a form on a node?
I am trying to add a textfield to the bottom of a node (for a specific cck type), that once (an authenticated user) submits, stores the value as a term in a taxonomy vocabulary.

What is the best way to do so?

I have tried adding the form to my subtheme's node.tpl.php file for a custom cck type.

I am having trouble with form validation. I'm able to submit the form properly, but get the red borders around the field that needs to be validated, instead of the message; Until I resubmit and the cached error message then shows. I get why it's happening - code executing prior to node.tpl.php load. See - How do I use form\_set\_error() the right way?.

If Form Builders are not supposed to be called from within a template file, how else can I add a form to a page? I'm sort of working off this form example tutorial

I started with this - Embed form inside a block \- and since added this to my node.tpl - https://gist.github.com/1847060.

I'm still trying to wrap my head around using the forms api, so thanks for any advice.

# Answer
From what I've read and tried it seems like if you want the messages to appear correctly the form needs to be built latest in the template\_preprocess\_page() function. Doing it in template\_preprocess\_node() or in the theme template files is too late with Drupal 7. To put this into the code you could declare a variable that holds the form for your node template in your theme's template.php file:

```
function mytheme_preprocess_page(&$variables) {
  // For node templates.
  $variables['node']->my_form = drupal_get_form('form_name');
  // For page templates.
  // $variables['my_form'] = drupal_get_form('form_name');
}

```

Then you can render the form in your template file:

```
<?php print render($my_form); ?>

```

This way the messages appear when they should not one page call too late.
> 3 votes

# Answer
You want to avoid putting this into your node template. Generally you want to keep "business logic" (any php functions other than print) out of template files. You might be better served by creating this as a block and placing it below or above the node because it is more reuseable. If you don't want to use a block you can use hook\_node\_view() and add an additional element to $node-\>content as in the linked example.
> 5 votes

# Answer
```
/**
 * Implements hook_node_view()
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {
  // prepare the form
  $form = drupal_get_form('a_very_simple_form');
  // append a new field to the content
  $node->content['a_new_field'] = array(
    '#markup' => drupal_render($form), // and render the form there
    '#weight' => 10,
  );
}

function a_very_simple_form($form, &$form_state) {
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

```

See `hook_node_view()` for more information.
> 1 votes

# Answer
The Webform module has an "Available as block" option, which can be placed on whichever pages using the Block UI, Context or Panels (if you're into that sort of thing, but I don't recommend it).

I found this over at How to embed a webform in a node in drupal 7. This was also mentioned over at Embedding a webform inside a node content and Add webform to content type.
> 0 votes

---
Tags: forms
---


# Question
Title: Programmatically get the list of fields of a custom content
I want to programmatically create a custom content (custom content created via the admin UI). Before the creation, I want to check the types of fields of my custom content.

My custom content contains a field "body" (type text), a field "description" (type text), an int field (type int), an attached file field (type fid ?).

I tested several ways; this is my last try.

```
// I get the entity object "my_custom_content"
$entity_object = NodeType::load("my_custom_content");
dpm($entity_object); //Work perfectly

$test = \Drupal::getContainer()->get("entity_field.manager")->getFieldDefinitions("my_custom_content",$entity_object->bundle())

```

The code returns an error:

> The *my\_custom\_content* entity type does not exist.

With this `$entity_object`, how can I get the list of the fields of my custom content? I see the `EntityFieldManager` class, the `FieldItemList` class, but I still do not understand how to play with Drupal 8.

# Answer
> 12 votes
You're mixing up entity types/node (content) types/bundles. Common mistake :)

Especially since the UI naming is... very unfortunate.

What is called Content in the UI is actually the entity type `node`. And Content types are node types (you figured out that much), which are bundles of the node entity type.

getFieldDefinitions() expects an entity\_type ID and a bundle. In your case, that is:

```
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

```

Note that this will also return base field definitions like nid, vid, title, status and so on.

Tipp: Once you have a node object, you can get the same definition from that object and other useful information too:

```
$node = Node::create(['type' => 'my_custom_content']);
$node->getFieldDefinitions();
$node->getFieldDefinition('body');
$node->hasField('body');

```

So if you want to dynamically do something like this, it can simplify your code a lot if you first create the node with the information that's always enable and then work with the methods on your entity object.

Default recommendation when working with entities in 8.x: http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

---
Tags: nodes, entities, 8
---


# Question
Title: Backup and Migrate exclusion recommendations?
When doing database backup using Backup and Migrate, what is the reasonable table exclusion strategy?

My first guess was:

* **Exclude the following tables altogether** \- leave that listbox with no selection
* **Exclude the data from the following tables** \- select all tables that include "cache" word, such as `cache_block` or `ctools_css_cache`.

Any comments, any considerations, any recommendations?

# Answer
I have following tables to exclude data (**not** to exclude the table altogether):

* all cache\_\* tables
* ctools\_views\_cache
* ctools\_object\_cache
* flood
* history
* queue
* semaphore
* watchdog
* search\_index

Usually search\_index saves a lot of database size.
> 5 votes

# Answer
As discussed by Charlie S, Artur and MPD above, the recommended settings are good but you need to watch for additional cache tables from added modules while accidental clicks can, a) lead to needless extra sized or huge mysql files that prevent full fileset/data backups (especially on shared servers); or b) totally useless backups; or c) backups that seem good on restore but are actually total disaster worse than useless because one of the many tables or missing data from a table is missing but not evident until a later time.

That being said, Drupal **default Seven** theme or other layout/style/css for BaM profiles page is **decent** and usable, **BUT AWKWARD and this can lead to mis-clicks** (been there 20 times) or time wasted scrolling up and down, up and down, trying to ensure there is no mis-click. The developers are kind enough to offer toggle between select box and check box but still scrolls up and down in the default theme UI may lead to issues from human error.

To **improve the backup Migrate UI** when adding or making a profile I use Context module based on path `admin/config/system/backup_migrate/settings/profile/add` and `admin/config/system/backup_migrate/settings/profile/edit/*`to get rid of theme sidebars and CSS Injector to **"exclude tables" and "exclude data" SIDE BY SIDE** with css for HEIGHT as tall as possible and FLOAT right. Side by side human readability are therefore reliability of backup configurations are much easy that way.

The real point in respect to "exclusion table strategy" is that not all BaM Profiles are full backups, and aside cache table exclusion, when creating profiles for table sets for certain purposes, say nodes and fields, just field sets, locations and maps, rules and flags, filters and fonts, etc etc **a BETTER INTERFACE** for a GOOD SYSTEM means better protection.
> -1 votes

---
Tags: database, backups
---


# Question
Title: Change the permissions needed in a service to get info from a module?
I'm adding Services integrations to the Room Reservations module. A service I need to expose is the times when reservations can be made. I found a function inside room\_reservations.inc (the function is \_room\_reservations\_facility\_hours()) and created a action type of service pointing to that function.

The problem here is that only the administrator user can have access to the output of this web service, whenever another user (even with the Administrator role) consumes the service I receive a 403 error. Is there a way I can solve this?

The Service declaration

```
$room_service = array(
    'room_reservations'=>array(
    'actions'=>array(
    'get_times'=>array(
      'help'=>'Gets the hours and the days reservations can be made',
      'file'=>array(
        'type'=>'inc',
        'module'=>'room_reservations',
        'name'=>'includes/room_reservations.service'
        ),
      'callback'=>'_room_reservations_service_get_open_hours',
      ),
  ),
),

```

The callback function (which connects to \_room\_reservations\_facility\_hours())

```
function _room_reservations_service_get_open_hours(){
  $dates = _room_reservations_facility_hours(TRUE);
  $i=0;
  $realDates = array();
      foreach ($dates as $key => $value) {
      //array_push($realDates, $dates[$key]);
        //$realDates[$key]=$dates[$key];
        if ($i<8) {
          $realDates[$key]=$dates[$key];
          $i++;
        }

    }
  //$standarized[] = $dates;
  $standarized[] = $realDates;
  return $standarized;
}

```

Edit: I'm already using the CSRF Token as a header when consuming the service

# Answer
Sounds like an authentication issues - have you read up on tokens? There's a couple of modules out there, one pretty recent, plus some doc:

https://www.drupal.org/project/services\_token\_access https://www.drupal.org/project/services\_token https://www.drupal.org/node/2424977
> 0 votes

# Answer
Trying using `access callback` and `access callback file` instead:

```
          'access callback' => 'INSERT CALLBACK FUNCTION NAME HERE',
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'room_reservations',
            'name' => 'includes/room_reservations.service',
          ),

```
> 0 votes

---
Tags: 7, users, services
---


# Question
Title: A menu link that points to specfic place on a page (I can't use anchors)
I have some embedded pdfs on my site using PDF Reader module, which is working great. But my boss wants a link to a specific place in one of those pdfs. Thus I need some way to add a link to the main menu, that will take the user to the page with the embedded pdf, and then automatically scroll down to the proper spot in the multi-page pdf.

I've looked at both the jquery.scrollTo module and the jquery.scrollTo script, but I can't see how to use these without using #anchors, which I cannot put into the middle of my embedded pdfs.

Is jquery.scrollTo the right way to go? Something else?

Thanks in advance, Peace Corps Volunteer, In Way Over His Head

# Answer
> 1 votes
I know it's been a while, but I found this forum post and thought it might help you:

http://forums.adobe.com/thread/13098

# Answer
> 0 votes
Its simple! You just create a link and go to page content edit option through Drupal admin. In the bottom of edit content page you will get a URL path settings, there is url alias field on there. You just put path in your field.

---
Tags: files, navigation
---


# Question
Title: Replace the file on disk while running the migration
I am changing the migration code (not written by me) to not create new files on migration but to re-use (or rewrite) the existing files.

The migration code looks like the following:

Source part:

```
$url = url('filename.json', array('absolute' => TRUE));
$this->source = new MigrateSourceJSON(new MultiListJSON($url), 'name', $fields);
$this->destination = new MigrateDestinationFieldCollection(
  'field_product_documents',
  array('host_entity_type' => 'node')
);
$this->map = new MigrateSQLMap($this->machineName,
  array(
    'name' => array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
    ),
  ),
 MigrateDestinationFile::getKeySchema()
);

```

Destination part:

```
$this->destination = new MigrateDestinationFile('file', 'MigrateFileBlob');
$this->addFieldMapping('value', 'blob');
$this->addFieldMapping('destination_file', 'name');
$this->addFieldMapping('filename', 'name');
$this->addFieldMapping('destination_dir' ,'dest_dir')
  ->defaultValue('private://');

```

This migration is only responsible for creating of the file entities from the `blob` which comes from a third party service.
There is another migration that is executed after this migration and is responsible for associating the file ids of the files created by this migration.

Following the documentation of the MigrateDestinationFile, the following code could be used to replace the file on the directory:

```
<?php
    $this->addFieldMapping('field_my_image:file_replace')
         ->defaultValue(FILE_EXISTS_REPLACE);
?>

```

But, during the file migration I am not associating it with any field. Hence, it could not be used. Or I am not sure of the exact way to use it.

My main concern is (let's say) if I have a file `ABC.pdf` on disk (might not be associated with any entity), the migration should not create a new `ABC_0.pdf`.

Any pointers would be highly appreciated!

# Answer
> 1 votes
As a temporary fix I have implemented the following in the `prepareRow` function.

```
function prepareRow($row) {
  // Delete the file if already present.
  $file_path = drupal_realpath($row->dest_dir . '/' . $row->name);
  if (file_exists($file_path)) {
    unlink($file_path);
  }
}

```

However, I am still not sure about the way it is recommended in the Migrate module.

---
Tags: 7, migrations
---


title: Multistep form submission fails

text:
# Question
Title: Multistep form submission fails
I'm trying to add multistep form functionality to a node creation form via a form alter. My (abbreviated) code follows:

```
function mymodule_form_FORM_ID_alter($form, &$form_state)
{
        if (!isset($form_state['storage']['step']))
        {
            $form['actions']['submit']['#submit'][] = 'my_form_submit';
        } elseif (isset($form_state['storage']['step']) && $form_state['storage']['step'] == 'step-two')
        {
            $form['foo'] = array(
                '#type' => 'textfield',
                '#title' => 'Add foo',
            );
            $form['actions']['#type'] = 'actions';
            $form['actions']['submit'] = array(
                '#type' => 'submit',
                '#value' => 'Register',
                '#submit' => 'step_two_form_submit',
            );
        }
}

function my_form_submit($form, &$form_state)
{
    if (!isset($form_state['storage']['step']))
    {
        $form_state['storage']['step'] = 'step-two';
        $form_state['rebuild'] = TRUE;
    }
    //so far so good
}

function step_two_form_submit($form, &$form_state)
{
    //This code never runs
    drupal_goto('/');
    dd('step two ran');
    //etc
}

```

The second step of the form loads as I would expect along with a submit function. The submit callback, however, is never called. Am I making a mistake by nuking the entire $form array? (The $form\_state array, which is what I really need to hold onto, remains intact.) I feel like I'm very close but am missing something substantial.

# Answer
> 1 votes
This is actually easier than it looks! :)

Use the one submit callback and in it use a switch or if statement to execute different actions depdending on what step you're on.

```
function my_form_submit($form, &$form_state) {
  if (!isset($form_state['storage']['step'])) {
    $form_state['storage']['step'] = 'step-two';
    $form_state['rebuild'] = TRUE;
  }
  else if ($form_state['storage']['step'] === 'step-two') {
    // do something awesome for step-two
  }
}

```

**UPDATED**

The following is working code I have running in Drupal 6:

```
  // multistep form
  if (!isset($form_state['storage']['page']) || $form_state['storage']['page'] < 4) {
    $form_state['rebuild'] = TRUE;
    $page = $form_state['storage']['page'];
    $form_state['storage'][$page]['values'] = $form_state['values'];
    $form_state['storage']['page']++;
  }
  // process submit
  else {
    // grab submitted values for each step from storage array
  }

```

It runs in the only submit handler of a multistep form.

I realize this is Drupal 6 but its close enough, can you try this?

# Answer
> 0 votes
For multistep forms you can use Ctool multistep wizard.

Following are the useful links for the same:

http://www.grasmash.com/article/building-multistep-registration-form-drupal-7-using-ctools

http://www.webomelette.com/ctools-object-cache-multi-step-form

---
Tags: 7, forms
---


# Question
Title: Strange behavior with flexslider: Uncaught TypeError: $(...).flexslider is not a function
When I logged into a dev version of my site flexslider was broken. Rather than a slide show, I have the slideshow images repeating down the page in a single column . I get a js error in the console that reads `Uncaught TypeError: $(...).flexslider is not a function` in the jquery.min script.

I'm baffled because I don't recall changing anything, and another dev version of the site doesn't have the issue. The only thing I've done recently is zip the sites folder to move it to a test server which doesn't exhibit the issue.

From googling this is a jquery issue, but I'm at a loss to diagnose how to fix this.

Any help appreciated

EDIT: Not an issue of jquery versioning. Both versions of the dev site (on my local machine) and the live site are all using jquery version 1.5.

EDIT 2: Noticed an issue with my drupal install, specifically flexslider library wasn't there. So, I copied the library to the libraries folder, flushed caches, and still nothing.

# Answer
> 1 votes
Flex slider library was missing. Pretty hard to diagnose by itself without the drupal system warning. I looked over the issues more carefully, and there it flagged that the flexslider library was missing. I'd been moving around a lot of files, and I suppose it must not have copied.

# Answer
> 1 votes
Try this: Install jQuery Update module. Seems like your jQuery version is out of date.

---
Tags: javascript
---


# Question
Title: $is_front is not available in all templates
As far as I know $is\_front is a global template variable in Drupal 7 and therefore the variable is available in all templates.

Now for Drupal 8 it seems that this is no longer true. I tried to call for `$is_front` in page-title.html.twig and realized that `$is_front` was not available here.

Using `template_preprocess_page_title(&$variables)` I could add `$is_front` to the template.

\*Why is Drupal 8 not providing `$is_front` in the same style as Drupal 7? And what would be the way to check for frontpage in a template where `$is_front` is not available?\**

It also seems that drupal\_is\_front\_page() is not available anymore.

Should I go like:

```
  try {
$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();

 }

      catch (Exception $e) {
        // If the database is not yet available, set default values for these
        // variables.
        $variables['is_front'] = FALSE;
        $variables['db_is_active'] = FALSE;
      }

```

(taken from template\_preprocess\_page)

# Answer
You almost answered the question yourself, you can add the variable to all templates with this code:

```
function theme_preprocess(&$variables, $hook) {
  try {
    $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  }
  catch (Exception $e) {
    $variables['is_front'] = FALSE;
  }
  // Ensure the cache varies correctly (new in Drupal 8.3).
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

```

For performance reason you can make a condition on $hook to only add the variable to the templates you need, and to avoid that the code is run twice for page.

Edit:

New in Drupal 8.3: Cache context for determining the Front Page
> 12 votes

---
Tags: 8, theming
---


# Question
Title: Why node object loses data after using workbench_moderation_moderate?
I'm using Workbench Moderation module because it matches my needs. I have a front-end form that initiate the node with some fields. Editor should review the node and fill all the required fields remaining.

So, I need to make sure that all fields are now filled with data then the state should be changed to Needs Review.

I implemented hook\_workbench\_moderation\_transition to trigger the state change. If the next state was Needs Review, then I would make sure that all required fields were filled with data otherwise I would change the state back to the previous one and redirect to the node edit form.

What I've done so far

```
    function workflow_handler_workbench_moderation_transition($node, $previous_state, $new_state){
        if ($new_state == 'needs review'){
          //check if node was not reviewed before , then redirect to form
          $instatnces = field_info_instances('node',$node->type);
          //should check first if conditional_fields module is existed
          $CFS = conditional_fields_load_dependencies('node',$node->type);
          foreach ($instatnces as $key => $field_options) {
            $field = field_get_items('node', $node, $key);
            if ($field_options['required'] && !$field && !array_key_exists($key, $CFS['dependents'])) {
               //set workbench state to previous one
               workbench_moderation_moderate($node, $previous_state);
               drupal_set_message(t('Please make sure that all required fields has been reviewed'),'error');
               $url = url("node/$node->nid/edit");
               header("Location:$url");
               drupal_exit();
            }
         }
      }
   }

```

Problem exists when using workbench\_moderation\_moderate in the context above. For some reason, when I got redirected to the form to edit, and after saving, my edits were not saved on the node object and so if I opened the edit form again, I couldn't find my edits. Any ideas?

# Answer
> 0 votes
The Problem was that workbench\_moderation\_moderate() calls internally hook\_workbench\_moderation\_transition() so I decided to do it with another technique that should cover the two ways that workbench moderation uses to change the state

First way to be covered, the links that exist in workbench moderation back end views. I implemented hook\_menu\_alter to intercept the request from those links to add my custom logic.

```
function my_custom_logic($node, $state){
   //add your logic here
}

/**
* Implements hook_menu_alter()
*/
function workflow_handler_menu_alter(&$items){
  $items["node/%node/moderation/%/change-state/%"] = array(
    'page callback' => 'workflow_handler_moderate_callback',
    'title' => 'Change moderation state',
    'page arguments' => array(1, 5),
    'load arguments' => array(3),
    'access callback' => 'workflow_handler_moderate_access',
    'access arguments' => array(1, 5),
    'type' => MENU_CALLBACK,
  );
}

function ei_workflow_handler_moderate_access($node, $state){
  return _workbench_moderation_moderate_access($node, $state);
}

function workflow_handler_moderate_callback($node, $state){
  my_custom_logic($node, $state);
  workbench_moderation_moderate_callback($node, $state);
}

```

Second way to be handled, the form that workbench adds in every node details page. I implemented hook\_form\_alter to add my submit handler before workbench moderation one and I added my logic again there.

```
/**
* Implements hook_form_alter()
*/
function ei_workflow_handler_form_alter(&$form, &$form_state,$form_id){
    if($form_id == 'workbench_moderation_moderate_form'){
      $form['submit']['#submit'][] ='my_custom_logic_handler';
    }
}

function my_custom_logic_handler ($form, &$form_state) {
  my_custom_logic($form_state['values']['node'], $form_state['values']['state']);
}

```

Hopefully this helps anyone who encounter that issue in the future.

---
Tags: nodes, hooks, workbench
---


title: How to debug weird and random behavior

text:
# Question
Title: How to debug weird and random behavior
I'm trying to figure out how to debug the following behavior and would appreciate some ideas on how to track down the source of the problem.

I run a website were some users have privileges to create and edit nodes and taxonomy terms.

Upon creating content or taxonomy terms, users report that, on occasion, content is created 3 times, for both entity types.

What steps can I take to find the culprit for this behavior knowing that...?

1. I have made sure users only click the submit button once, but that hasn't made any difference.
2. Both Drupal and PHP error logs are clean. I can see 3 logged messages confirming content has been triplicated but nothing else.
3. It only happens in live environment. I haven't been able to reproduce it in development environment
4. It happens randomly. Users have reported this only happens ocasionally.
5. When this happens, any rules that react to the condition 'After saving node ...' or 'After updating node...' are also fired 3 times

# Answer
Treat it like any bug:

1. Find a way to reliably reproduce the problem (this is essential to debugging any code issue for obvious reasons; the question "how do I debug this problem I can't reproduce?" doesn't have an answer, let alone a Drupal-specific one). You may need to set up a clone of your production environment as the issue might not be related to Drupal (e.g. you could have a rogue process duplicating MySQL records that Drupal doesn't get involved with)
2. Fire up XDebug or your debugger of choice.
3. Step through every single line of the code that gets involved in the problem you're seeing, keeping an eye on what parameters are being passed to methods, and if they contain the expected data. Basically run through an entire bootstrap for the page(s) you're having problems with, starting at index.php, narrowing down your target search area as you go.
4. Fix when you've identified the problem (you're not done yet though...)
5. To help for next time, write a test that fails before you implement your fix, and passes afterwards. Make it part of your deployment workflow to run this test after every change you make. Consider adding tests for other major pieces of functionality as you decide which are the most important, to help avoid this sort of situation in future.
> 1 votes

---
Tags: nodes, taxonomy-terms, rules, hooks
---


title: Removing external CSS files with hook?

text:
# Question
Title: Removing external CSS files with hook?
My theme is adding the following CSS below. How can I remove it? I know that with Drupal 6 you can do `stylesheets[all][] =` in the .info file but what about Drupal 7? Can `hook_css_alter()` be used on an external file?

```
<link type="text/css" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" media="all" />

```

# Answer
You can use the following code to remove your external css

```
function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css['path of you external css']);
}

```
> 1 votes

# Answer
Yes, `hook_css_alter` can be used with external CSS.
> 1 votes

# Answer
Use function hook\_css\_alter you can unset css

```
function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
}

```
> 1 votes

# Answer
You can use function hook\_css\_alter. This hook function will alter CSS files before they are output on the page.

```
//This hook function will unset css.
function hook_css_alter(&$css) {
    // Remove defaults.css file.
    unset($css['CSS FILE PATH']);
}

```

In additionally, you want to remove core css then follow below code:

```
function hook_css_alter(&$css) {
    $exclude = array(
        'misc/vertical-tabs.css' => FALSE
    );
    $css = array_diff_key($css, $exclude);
}

```

just add `$exclude` to your info to remove a CSS file. This is simple way to remove css file.

Let me know if there is any doubt/query from this.
> 0 votes

---
Tags: 7, theming
---


title: Import the data

text:
# Question
Title: Import the data
I have excel sheet where in I want to import all data into my Drupal site so for this I am using feed module, so while importing the data only the text fields are importing its not importing the entity reference field to drupal site its retaining empty for all those please can anyone tell me why is this strange ?

# Answer
> 1 votes
Use Entity Reference feeds module. If you want to have multiple value field separated by a comma or something then use feed tamper module

---
Tags: importing-exporting, nodes
---


# Question
Title: D8 render a contact form from theme preprocess
I want to render a form in a node view. I made an entity reference to a contact form, then in the preprocess\_node I'm trying to get the render array of the contact form.

```
function mysupertheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->getType() == 'mynodetype') {
    if (!empty($node->field_mynodetype_form->referencedEntities())) {
      $contact_form = $node->field_mynodetype_form->referencedEntities()[0];
      $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $contact_form->id(),
      ));

      //$form = \Drupal::entityFormBuilder()->getForm($message);
    };
  }
}

```

I don't know how to call entityFormBuilder in preprocess. Is this the right way to do this ? How can I display a choosen contact form in a node ?

Thanks

# Answer
Your code will work when this patch is implemented:

Add a view builder for contact\_form
> 2 votes

---
Tags: 8, theming, emails
---


# Question
Title: Does node_load() function prevent multiple loading of the same node?
In some cases, for example page where a lot of block are loading the same current node in one request it could be useful to load node just once for every block. Once I read somewhere this is default functionality for node\_load() function.

Is it really true, or do I have to workaround that by myslef (store node as global variable or something like that)? Documentation says nothing about that.

# Answer
Yes, node data is statically cached per request, if the requests are for *un-revisioned* nodes. No, you don't need to do the caching yourself.

The cache read/write happens in `NodeController::load()` if you're interested in what's going on behind the scenes.
> 0 votes

---
Tags: nodes
---


# Question
Title: What URL do I use to view an OG membership entity?
I see one can edit a membership entity by going to:

```
group/node/204/admin/people/edit-membership/32

```

What is the URL to view the entity?

I see the membership entity has a display mode that allows you to rearrange the fields but there is no view link in the OG membership (people) admin area.

# Answer
> 7 votes
I don't think that there is a page you can view the membership. I've just skimmed the code of OG module and didn't found any relating part which displays a membership in a separate page.

However, since memberships are entities, it should be possible that you can setup a view which takes a membership id as contextual filter and display it in a selected view mode.

Here is how you do that with views:

1. Create a new view visiting `admin/structure/views/add`
    * Give your view a name like **View Membership**
    * Set it to **Show** *OG Membership*
    * Set a **Path** with a placeholder like `view-membership/%`
    * **Display format** *Unformatted list* **of** *Rendered entity*
    * **Items to display** *1*, uncheck **Use a pager**
    * **Continue & Edit**
2. Under **Advanced** section, add a contextual filter **OG membership: Og membership ID**
    * **WHEN THE FILTER VALUE IS NOT IN THE URL**: *Show "Page not found"*
3. Save
4. Visit the page `view-membership/<membership_id>` and you'll see the membership entity.

# Answer
> 4 votes
**There is no view link because it does not exist.**

As you've already mentioned: a membership is an entity. Entities, by default, don't have display pages. You use a custom entity if the data does not necessary has to be publicly displayed on its own. Otherwise, you could use nodes (which are nothing more than extended entities).

In this case, the entity `og_membership` is used to store data about which users and nodes are connected. In addition, OG Groups provides some views which generate lists with these memberships. Of course, you can also create your own views.

The fields you attach to the `og_membership` entity can be displayed in these views.

---
Tags: organic-groups
---


# Question
Title: Views Load More for products listing page in ajax
For my **ecommerce website** i am using `View Infinite Scroll` module which is for Products listing page lazy loading,

Lazy loading works fine for my products listing view, but my requirement is when i click **View More** button then only it gets to load more products.

Is there options to call View More button or anyother modules supports for my requirement, please tell me if anyone have any idea means.

# Answer
> 0 votes
You can use views load more module. It provides a button. Clicking that button lists more contents only. The pager should be defined in your views settings.

# Answer
> 0 votes
It's actually really easy to do with standard Views and jQuery.autopager in your theme.

The most important part is using the correct classes, I can't find my working example at the moment, but it should look something like:

```
$.autopager({
  // where contents would be appended.
  // use "appendTo" or "insertBefore"
  appendTo: '.views-content',

  // a selector that matches a element of next page link
  link: '.pagination .next a:first',

  // a selector that matches page contents
  content: '.views-row',
});

```

# Answer
> 0 votes
In views, there is option for

> Use AJAX

from advanced settings, there we can select **Yes**, then it will work Ajax view more

---
Tags: views
---


# Question
Title: How to remove a theme's default menu class from a specific menu?
I bought a Drupal 7 premium theme and thus my menus use the theme's default menu class.

How do I remove this class from one of the menus so that it would be a simple HTML list or use the native Drupal menu class?

# Answer
> 2 votes
You can remove all unwanted classes and add your own classes using the code below, Its for a rough idea, use dpm or any debugger to locate exact tool

```
function THEME_menu_link(array $variables) {
  //unset all the classes
  unset($variables['element']['#attributes']['class']);

  $element = $variables['element'];

  if($variables['element']['#attributes'])

  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

---
Tags: 7, theming
---


# Question
Title: How to revoke edit access to the node's author after publishing a node?
I am trying to build a new rule on Drupal 7 with both the Rules and Content Access modules (and its sub module Content Access Rules integration). Thus, I get new actions like "grant or revoke an access" for specific role.

An authenticated user can add a content on the website but it is unpublished by default (like a draft).

When the user is ready, he/she can publish the content (different modules can do that, Save Draft, Publish content).

After the content is published (which event?), I need to revoke the modification access for the node author.

I have tried to build the rule as this tutorial shows but without Flag.

It does not work, the author can still edit the content after publication and no modifications have been made on access control for this node (I have checked the "Per content node access control settings" box in the content type settings).

I guess the problem is the non-published state of my node and thus the lack of access settings, since Content Access needs published nodes to operate. Then, I ask Rules to modify content access that does not exist ...

A custom module is available here but I would rather use the Rules module since, theoretically, it could be done.

Here is an export of my rule code :

```
{ "rules_revoke_edit_access_after_publication" : {
    "LABEL" : "Revoke edit access after publication",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "content_access_rules" ],
    "ON" : { "node_update--manuscript_submission" : { "bundle" : "manuscript_submission" } },
    "IF" : [ { "data_is" : { "data" : [ "node:status" ], "value" : "1" } } ],
    "DO" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node" ],
          "permissions" : { "value" : [
              "view:3",
              "view_own:3",
              "update:3",
              "update_own:2",
              "update_own:3",
              "delete:3",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }
}

```

Default access for authenticated user : view/modify own content (+ view any unpublished content (of the content type needed) thanks to the View unpublished module)

Access needed after publication : view own content only.

# Answer
> 1 votes
# Approach 1:

Here is the rule (in Rules export format) that I think is what you are looking for:

```
{ "rules_disallow_edit_own_content_after_node_is_published" : {
    "LABEL" : "Disallow edit own content after node is published",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "content_access_rules" ],
    "ON" : { "node_update--manuscript_submission" : { "bundle" : "manuscript_submission" } },
    "IF" : [
      { "data_is" : { "data" : [ "node-unchanged:status" ], "value" : "0" } },
      { "data_is" : { "data" : [ "node:status" ], "value" : "1" } }
    ],
    "DO" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node" ],
          "permissions" : { "value" : [
              "view:3",
              "view_own:3",
              "update:3",
              "update_own:2",
              "update_own:3",
              "delete:3",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }
}

```

Just import this rule in your own environment to review/qa-test it.

Some more details about the "clue" (magic?) of this rule:

* The **Rules Event** is related to "Updating a node of content type `manuscript_submission`.
* The **Rules Condition** is to ensure that the Rules Action is only triggered the moment that the node changes from unpublished to published.
* The **Rules Action** simply REMOVES the permission for the author of the node (cfr. "own" in Content Access terminology) to edit that node for rome "authenticated user".

**Note**: The above rule is "tuned" to content type with machine name `manuscript_submission`. Change that machine name to any other content type (eg: `article`). Make sure to perform such change before you actually import this rule (because the Rules UI do not allow you to change that "event" after importing anymore).

# Approach 2:

You can also use a work-around to implement "*... revoke the modification access for the node author...*" that you are asking for, as detailed below.

Have a look at my answer to the question about "How to specify a Rules condition like 'Before creating new content'?". Here is a quote from it, which I also recommend in your case here:

> Try using Rules (System) event "Drupal is initializing" (= init), which is actually BEFORE your edit form is shown.

With that, you actually don't (have to) "revoke access", instead you just the Rules module to capture the Rules event that somebody is about to start an edit session of a node. And then, depending on the extra Rules conditions you want to check (in your case: 'is the current user the author of this node?' AND 'is the status of this node published?'), you just use a Rules action to redirect a user to "somewhere else" (instead of showing them the edit form they asked for).

**Note**: If you want to use my proto-type Rules example in my answer I mentioned above, it's obvious that you'll have to adapt the Rules conditions and/or Rules actions to make it fit for you case (like the URL of your edit form?).

---
Tags: 7, nodes, rules, users
---


title: How do I unset a block?

text:
# Question
Title: How do I unset a block?
I just started creating a Drupal 8 theme.

For example in Drupal 7 if I want to remove the breadcrumb, I just need to remove this line of code `<?php if ($breadcrumb) print $breadcrumb; ?>` from the `page.tpl.php`.

In Drupal 8 I removed `{{ page.breadcrumb }}` from the `page.html.twig` and I still seeing the breadcrumb. So not sure how to remove or unset these kind of blocks in Drupal 8.

# Answer
Yes, what you are seeing is the render cache. If you are developing a theme, you likely want to disable render caching and enable twig debug. See sites/example.settings.local.php for instructions on how to do that.

That said, breadcrumbs, like almost everything else, is a block now. Blocks are configuration. If you don't want a block, just remove that block in the UI. If you just remove it in the template, Drupal still needs to load and prepare that block for rendering as it cannot know the template doesn't print it.

And if you don't display the region (you always display regions with 0-N blocks, not directly blocks in page template), you should also not define it as an available region so that the user/site admin knows that he can't place blocks there.
> 5 votes

# Answer
I did the same in bartik theme, removed the breadcrumb line, even removed the page.content line but no effect. I went on and cleared the cache and back to the page and the changes were made. So you need to clear your cache.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to prepare directories in private file system?
I've configured private file system. Using it from UI works well. I want to generate dump site content via devel\_generate with custom modifications. So I'm hooking into Node API for assigning sample PDF files to nodes.

Inside private directory I want to create directory structure:

```
  $dir = sprintf('private://org%d/%d/person%d', $this->getOrganization()->nid,
                    date('Y'), $this->getEmployee()->uid);

  if (!file_prepare_directory($dir)) {
    throw new Exception('Cannot create document file directory or it\'s not writable');
  }

```

But exception is thrown.

How to set proper directory permissions? Content is generated via drush command - drush genc.

# Answer
Ok, I solved it by passing proper flag (for UI):

```
file_prepare_directory($dir, FILE_CREATE_DIRECTORY);

```

For using drush command still don't know and failing.
> 0 votes

---
Tags: 7, files
---


title: Search Api custom field type

text:
# Question
Title: Search Api custom field type
I have a field that concatenates multiple taxonomomy terms into a single text field. I have altered the existing module concat\_field.

This all works fine but I cannot get search API to recognize the field (it worked with an older version of search api)

I have added this to the module:

```
function concat_field_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];

  $property['type'] ='text'; //tried concat_field as well which is the type in concat_field_field_info
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  $property['label'] = 'Concat field';
  $property['description'] = 'concatenated field';
  unset($property['query callback']);
}

```

Any clue what i am doing wrong?

# Answer
Ok, I should have looked better at contrib modules, If anyone needs to achieve something similar, look into the computed field module. I just made a small custom module that creates a computed concatenated field. I used taxonomy terms, but you can concatenate any field.

My code:

```
 /**
computed_address is field name used by computed_field module, you can use any field that is created with computed_field module
*/

function computed_field_field_computed_address_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {

  $taxonomyterms = array('field_province', 'field_city', 'field_street'); //fields machinenames to concatenate
  $result = array();

  foreach ($taxonomyterms as $taxonomyterm) {

      $field_myterms = field_get_items($entity_type, $entity, $taxonomyterm);

            if (!empty($field_myterms)) {
                $term = taxonomy_term_load($field_myterms[0]['tid']);
            }

      $result[] = $term->name;
    }

    $entity_field[0]['value'] = implode(', ', $result);
}

function computed_field_computed_address_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
  return $entity_field_item['value'];
}

```

Maybe this will help anyone else...
> 0 votes

# Answer
I think you need to follow following approach:

```
 /**
 * Implements hook_entity_property_info_alter().
 */
function modulename_property_info_alter(&$info) {
  $info['node']['properties']['concat_field'] = array(
    'type' => 'text',
    'label' => t('Concatenated form of all the taxonomies that has been added to the node'),
    'sanitized' => TRUE,
    'getter callback' => 'modulename_search_api_property_concat_field_callback',
  );
}

/**
 * Getter callback for concatenate terms field.
 */
function modulename_search_api_property_concat_field_callback($item) {
  /** Do all your processing/functionality here. **/
  return <resultant concatenated value>;
}

```
> 0 votes

# Answer
I actually tried that, I also found in the search.api.php that its possible to register a new type.

As described here:

```
 *** Define new data types for indexed properties.

 function concat_field_search_api_data_type_info() {
     return array(
       'concat_field' => array(
       'name' => t('Concat Field'),
       'fallback' => 'string',
       ),
   );
 }

```

However still no luck, and it really seems that that is the way?
> 0 votes

---
Tags: search
---


# Question
Title: Purpose of the .htaccess files in the Drupal files directory?
Besides the *.htaccess* file in the Drupal site main folder, I've found a .htaccess file in the `sites\default\files` folder, and further such files some sub-folders of `sites\default\files` folder (for example, in `sites\default\files\private`).

My question can actually be broken down into two separate questions:

1. How would you define in simple words the purpose of both the main *.htaccess* files, and the others under `sites\default\files` (I assume there aren't anymore *.htaccess* files?).
2. Is the only reason for splitting the *Python syntax* to different *.htaccess* files is to not make a single huge file? Or there are other reasons?

Thanks,

# Answer
> 5 votes
The first .htaccess file in the root directory is for routing and to override any PHP related settings.

The second .htaccess file under sites/default/files is for security purpose, to avoid any file injection. This folder is Drupal's main upload folder.

The upload folder can be moved in different places, or in a multi site setup you could have more than one folder. That is why they provided a separate .htaccess instead of putting everything in one place.

---
Tags: .htaccess
---


# Question
Title: Overriding a page content in a custom module
After looking at a bunch of modules I am still confused as to how I can take a content piece I've created (a Server), make my own custom module (servers) and do some logic so I can pass that on to a servers-template.

servers.info.yml

```
name: Servers Module
description: Creates a Servers Module
package: Servers
type: module
core: 8.x

```

servers.module

```
<?php
  function servers_theme(){
   $theme['server_page'] = [
      'variables' =>['name' => NULL],
      'template' => 'server',
    ];
    return $theme;
  }

```

And I am not sure if this is correct, but my servers.routing.yml

```
servers.server:          #Pretty sure this part doesn't matter
  path: '/node/{server}' #I'd like to have /server/{server/ but my content's url is /node/xx
  defaults:
    _title: 'Servers'
    _controller: '\Drupal\servers\Controller\Servers::getServersImplementation'
    entity_type: 'server' #Not sure if this is correct
  requirements:
    _permission: 'access content' #Do I need this?

```

Controller

```
#located in servers/src/controller/Servers.php
namespace Drupal\Servers\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller for js_example pages.
 *
 * @ingroup js_example
 */
class Servers extends ControllerBase {
  /**
   * Accordion page implementation.
   *
   * We're allowing a twig template to define our content in this case,
   * which isn't normally how things work, but it's easier to demonstrate
   * the JavaScript this way.
   *
   * @return array
   *   A renderable array.
   */
  public function getServersImplementation($name)
  {
    return[
      '#theme'=>'server_page',
      '#name'=>$name,
    ];
  }
}

```

Absolutely nothing shows up when I've enabled the module. I know it's enabled because I can change the routing path to a node id /node/93 and that node will give me a page not found error, when without the routing I can get the content.

No errors are present in the error.log, or recent log messages. I am quite confused with this in D8, but once I can get this concept I know I will be able to understand all I need to complete my modules.

Thanks in advance.

# Answer
Try removing the entity line, it might be breaking your routing - I'm not sure what you intended with that but if you want to declare the passed variables' entity type you need to use Options.

```
route_with_two_nodes:
  path: '/foo/{node1}/{node2}
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::foo'
  options:
    parameters:
      node1:
        type: entity:node
      node2:
        type: entity:node

```

https://www.drupal.org/node/2310425
> 0 votes

# Answer
I think, you don't want to declare a new entity type. You are generating a custom page. This is not connected to entities and nodes. Don't use `/node/{id}`, because this is already in use. The path `/server/{server}` is fine, where {server} is the parameter for the controller. You have to use identical names:

```
path: '/server/{server}'

public function getServersImplementation($server)

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How can I attach a view for each row of another view?
I may not have the correct terminology here but please allow me to explain what I am trying to do.

I have a view that shows pictures that users have uploaded and that require approval. I am handling approval through the Flag module (administrators flag a node to approve it).

I have created a view that shows all the unflagged nodes containing pictures that are awaiting approval.

Now, on this view, for each picture that a user has uploaded, I would like to show all the other pictures that the author has uploaded (Users are limited to uploading five pictures, so this can't get too crazy. Each picture is its own node.)

To do this, I tried creating a view display **attachment** that shows all the pictures uploaded by a user (limited by a **Contextual filter** of *author: uid*). I then attached this to my main view, but the contextual filter's value is not added per row. I may be misunderstanding how views attachments work; I've never used them before.

Am I configuring this wrong? Is there a different approach that I should be taking?

In short, this is what I am trying to achieve:

* The main view shows each picture (stored as an individual node) that needs to be approved.
* Next to each picture that is pending approval, I would like to show all the pictures uploaded by that user (stored as individual nodes) that have already been approved.

# Answer
> 2 votes
1) **Viewfield** is a good solution.

Views attachment attach to a views display (Page, Block etc) not to each row.

So, first remove the Contextual filter uid.

Then add one more field, the flag of the node. Then you will have User\_Name, Node Image, Flag and each row will represent a node.

2) Another option is to use the Views\_Merge\_Rows. In the Merge Rows settings you have to set the Merge Options for the User Name field as "Use the values of this field as filter" and uncheck the "Exclude this field from display". For the other fields select the "Use the first value of this field".

3) If you don't want to use a contributed module use the "*Group results together*" on the Format display settings. Group by user name and then *Exclude from display* the User Name field.

# Answer
> 2 votes
You can also use Views Field View in order to add a field that represents another View. Each row will have that field.

In order to achieve what you want, you will have to add the new field and specify which contextual filter you want to pass to the other View. You will be able to select tokens from other fields of the same row.

That another view, which will be a Block display with the appropiate contextual filter, will receive the token and display the correct fields (pictures in your case).

Take into account that embedded views may produce a slow performance. So you may also want to use views caching. Different modules provide Views caching (e.g. Views Content cache and Cache Actions).

---
Tags: views
---


# Question
Title: Search Api, fulltext and string for search bar and facets
I'm trying to figure out how to make and indexed field (City) play nice with fulltext search exposed filter and a facet term.

As of right now, a fulltext option works with the search bar, but splits 2 word cities into separate facets. And string combines multi-word cities into one facet, but then breaks the search bar.

What setting will work for both?

# Answer
> 1 votes
I had an issue similar to this with 2 separate fields, Country and City. Country was a taxonomy term while City was a textfield. I wanted to use both for fulltext search and as facets. In my Search API Index I added related fields for my Taxonomy (Country) and used the name (Country:name) as a fulltext field for my search bar. The thing is that the City when indexed as a fulltext didn't work in combination with the Country facet, and when I changed it to string it didn't work with the search bar.

Solution:

* Leave your field (City) as a string field
* Go to your Search API Index
* Click on "Filters"
* Check "Aggregated Fields"
* Add new field and select your desired field, for example "City" and aggregation type "fulltext"
* Go to your view, where you use the fulltext search, click on it and in the Searched fields you will see the aggregated field you had added before.

It should work fine now. If not, try re-indexing the items, clear your cache, double check that the field is set to be indexed, etc.

---
Tags: views, search
---


# Question
Title: Drupal login using other subdomain user account with certain role
I'm having a main site and few subdomain sites for different countries:

* www.mydomain.com (for U.S users)
* newzealand.mydomain.com
* singapore.mydomain.com
* australia.mydomain.com

For each site, there are roles of anonymous user, authenticated user, member.
Rules module is used to add "member" role if this is an active user, and remove "member" role if this is not an active user.

I'm going to have another subdomain, **members.mydomain.com**.

Only those users with "member" role in those subdomains are able to access to members.mydomain.com.

In members.mydomain.com, how am I going to retrieve the user login info and user role from different subdomain?

# Answer
Are you using different databases for all sites? or the Domain Access module? https://www.drupal.org/project/domain

If you are using different databases for each site and if they are on the same server I would consider to let the sites share the users + users\_roles table. In that way all users exist on all of the sites with the same password and have the same role everywhere. You can then assign different permissions to different roles per site.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Hook on product page view in Drupal commerce
I want to run page view event from tracking with Google Analytics/piwik on Drupal commerce using my own Module.

Which hook can i use in Drupal commerce to run my own code? I just need to find the best hook that is called when page view is fired for the product.

# Answer
> 1 votes
Since product displays are nodes, `hook_node_view()` is what you're looking for.

---
Tags: commerce, google-analytics
---


# Question
Title: Register Drupal Commerce user before checkout completes
The default behavior for Drupal Commerce is that an anonymous user get's registered only after the checkout process completes and an order is paid in full. I am trying to create a new checkout rule to register an user just after he/she enters his/her e-mail address, but failing to find the right rule on admin/config/workflow/rules/reaction/manage/rules\_sd/add/event.

I have modified my checkout flow, so that a user can enter his/her e-mail at the first step like shown in the screenshot:

Unfortunately, there is no rule something like "After entering an e-mail". Does anyone have a suggestion how to overcome this problem?

On /admin/commerce/config/checkout/rules it says:

> When a customer advances to the checkout completion page, rules reacting on the Completing the checkout process are evaluated. Default rules handle standard tasks like updating the order status, sending order e-mails, and creating accounts for anonymous users. You can edit these or add additional rules to customize your checkout workflow.

Does this mean I can't trigger any actions until checkout completes? Not very much convenient if so.

Edit: I've also found this somewhat similar discussion: How to force account creation before commerce checkout is complete?

# Answer
> 0 votes
If you are wanting to do something *during* the checkout process, your best bet is to use a `hook_form_alter()` on the checkout forms and add your own submit handler. In this case you're looking at the `commerce_order_account_pane`. Remember that panes are fieldsets within a per-page form, so you'll want to look for the router page form and put your submit handler there.

---
Tags: commerce
---


title: Load Module on Node ID

text:
# Question
Title: Load Module on Node ID
My programming skills are really not up there.

I'm trying to load a module, and whatever instructions in there, only when a node ID is viewed.

I think I need to use hook node\_load.

In other words, if Node ID of type webform is being viewed, load the following instructions from enabled custom module.

# Answer
> 0 votes
I think it is best to create a `hook_preprocess_node` in your custom module. There, you can check the node id and call the required functions.

---
Tags: nodes, webforms
---


# Question
Title: How to add help text to tabs in admin/structure/types/manage/{node-type}
I maintain a module (http://www.drupal.org/project/csm) that adds two tabs to the node type settings form at admin/structure/types/manage/{node-type}. I'd like to add some help text to these tabs. In the picture below, there is help text set for the top four tabs, but not for the last three tabs.

I've had a look at the Drupal core code to see if I can work out how to set this help text, but have had no joy so far. How can I set it?

For the record, the code used to generate the last tab in the form is as follows:

```
$form['cnpt'] = array(
  '#type' => 'fieldset',
  '#title' => t('Node creation page title and status message'),
  '#access' => user_access('change ' . $form['#node_type']->type . ' creation page title'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  //'#tree' => TRUE,
  '#weight' => 101,
  '#attributes' => array('class' => array('csm-form')),
  );

```

# Answer
The summaries are dynamic so they're controlled by JS. It should be something as simple as this:

```
(function($) {
  Drupal.behaviors.csmFieldsetSummaries = {
    attach: function (context) {
      $('fieldset.csm-form', context).drupalSetSummary(function (context) {
        // Make a decision about what summary to display based on your tab's current value.
        var summary = $('input.foo', context).is(':checked') ? 'Input checked' : 'Input not checked';

        // Or static strings are fine too.
        summary = 'Static summary';

        return Drupal.t(summary);
      });

      $('fieldset.another-csm-form', context).drupalSetSummary(function (context) {
        // ...
      });
    }
  };
})(jQuery);

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Omega 4 php warnings with node_modules folder with gulp install
So, I have been happily using Omega 4 with SASS for a while. For workflow and performance reasons, I went with a Gulp/Ruby SASS set up. Recently, I've had a bunch of warnings pop up related to errors in the file.inc file in the includes folder. At this stage, I don't really know what's causing the errors. I sometimes get them at top of the page above my content (where sass warnings usually go) as well as in the pink/orange php warnings block. This seems to happen when it's not happy with something in my sass formatting, but again I'm not sure.

Any insight into what is causing this would be appreciated.

```
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie,sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): The system cannot find the path specified. (code: 3) in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): failed to open dir: No such file or directory in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie,sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): The system cannot find the path specified. (code: 3) in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): failed to open dir: No such file or directory in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie,sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): The system cannot find the path specified. (code: 3) in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): failed to open dir: No such file or directory in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie,sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): The system cannot find the path specified. (code: 3) in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).
Warning: opendir(sites/all/themes/postomega/node_modules/gulp-util/node_modules/dateformat/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/load-json-file/node_modules/pinkie-promise/node_modules/pinkie): failed to open dir: No such file or directory in file_scan_directory() (line 2118 of C:\Users\Nick\Sites\devdesktop\postcatlocal\includes\file.inc).

```

# Answer
It appears that you're using Windows, there has been a long term issue with NPM in which the nesting structure of node\_module dependencies breaks windows. The issue is that the folders nest so far that they create a file path longer than windows can accommodate.

For a long time it appeared that they did not want to correct this, and there were various ways to get around it that didn't always work, but it seems that they have finally added an option in NPM3 that allows you to flatten dependencies.

If you upgrade to NPM3, delete your `node_modules` folder and rerun `npm install` you shouldn't have this issue any more.
> 2 votes

---
Tags: theming
---


title: Enable "parent":[] in REST export view

text:
# Question
Title: Enable "parent":[] in REST export view
I have multi level taxonomy with 2 levels, but when I run REST export on it, "parent":\[\], always stays blank - no matter how many levels there is.

How can I expose relations within taxonomy via restful?

# Answer
This is a bug in core, see https://www.drupal.org/node/2543726 In the meantime, you could write a new normalizer service that is only for terms.
> 2 votes

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


title: Custom code inside <body>

text:
# Question
Title: Custom code inside <body>
Is there any way to output code from **module** controller class inside `<body>` in front page ? I need output a javascript code which will look like, lets say:

```
$phpvariable = variable_get('mymodulename_companyid', false);

<script type="text/javascript">
    alert("'.$phpvariable.'");
</script>

```

In Drupal 7 I was doing this in file `mymodulename.module` like this.:

```
function mymodulename_init()
{
    $phpvariable = variable_get('mymodulename_companyid', false);

    if($phpvariable){
        drupal_add_js('alert("'.$phpvariable.'");', array(
            'scope' => 'footer',
            'type' => 'inline',
        ));
    }
}

```

Ofcourse now It doesn't work and I cant find the proper method for this problem.

# Answer
> 1 votes
1. Create a libraries file in your module/theme (foo.libraries.yml in this example).
2. Add a library declaration in your libraries file.
3. In your library declaration point to a javascript file that will contain your logic (foo.js in this example)
4. Attach your library in hook\_page\_attachments or in a specific render array.
5. Attach your variable to the drupalSettings object.

---

### foo.libraries.yml

```
baz:
  version: VERSION
  js:
    js/foo.js: {}
  dependencies:
    - core/drupalSettings

```

---

### foo.js

```
(function (drupalSettings) {
  alert(drupalSettings.bar.message);
})(drupalSettings);

```

---

### foo.module

```
foo_page_attachments(array &$page) {
  $page['#attached']['library'][] = 'foo/baz';
  $page['#attached']['drupalSettings']['bar']['message'] = 'Hello World';
}

```

# Answer
> 2 votes
I think you could go with hook\_page\_attachments instead of hook\_init. Of course you would also need to add the javascript in a different way in D8, read here https://www.drupal.org/node/2274843

# Answer
> 1 votes
You can either use the already mentioned hook\_page\_attachments() together with #type html\_head to create arbitrary elements in .

If it really must be in the body, you can use `hook_page_top` and put anything using #markup, #type inline\_template or a real template. See `toolbar_page_top` for an example.

# Answer
> -3 votes
For all those who in the future will face the same problem. The solution turned out to be trivial.

In module folder create a file `modulename.module`. Inside this file simply add (ofcourse with `<?php` at the begining of file) :

```
/**
 * Implements hook_page_top().
 *
 * Description
 */
function mymodulename_page_top(array &$page_top) {
    $val = \Drupal::state()->get('phpvariable');

    if($val)
    {
        echo '<script>alert("'.$val.'");</script>';
    }
}

```

---
Tags: 8
---


# Question
Title: access denied error on user registration module
I created a custom registration form using the code I show below. It works on my test site, but on my live site, it returns an access denied error. I am not sure what the problem is.

```
function medical_reg_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'medical_register';
  $form['actions']['submit']['#value'] = t('Next');
}

```

The setup is the same so I am rather perplexed. The test site is local. Are there some configurations which make a big difference?

# Answer
> 1 votes
You will get a 403 on user/register if you are already logged in.

# Answer
> 0 votes
It is because you are logged in, my suggest is you first logout user and ten redirect him/his to `/user/register` page So what you do to is in your custom module

```
// Implementation of hook_init

function yourmodule_init(){
global $user;
if(current_path=='user/register' && $user->uid){ // if user is logged in and the current path is user/register
drupal_goto('user/logout?destination=user/register');
 }
}

```

Also (if you familiar with rules modules) you can handle it by Rules

---
Tags: users
---


title: How to create .install custom file

text:
# Question
Title: How to create .install custom file
How do I create and add an .install file for Drupal 8 custom form data storage?

My file is *custom\_form.install*, but my custom module doesn't load this file.

```
/**
 * Implementation of hook_schema().
 */
function custom_form_schema() {
  $schema=array();
  $schema['custom_form'] = array(
    'description' => 'An example form table',
    'fields' => array(
      'fe_id' => array(
        'description' => 'The primary identifier for a form.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'firstName' => array(
        'description' => 'A field storing text',
        'type' => 'text',
        'length' => 50,
        'not null' => TRUE,
      ),
      'lastName' => array(
        'description' => 'A field storing text',
        'type' => 'text',
        'length' => 50,
        'not null' => TRUE,
      ),
      'emailId' => array(
        'type' => 'varchar',
        'length' => 50,
        'not null' => TRUE,
      ),
      'pass' => array(
        'type' => 'varchar',
        'length' => 50,
        'not null' => TRUE,
      ),
      'likes' => array(
        'description' => 'A field storing Likes',
        'type' => 'text',
        'length' => 200,
        'not null' => TRUE,
      ),
      'gender' => array(
        'description' => 'A field storing Gender',
        'type' => 'text',
        'length' => 50,
        'not null' => TRUE,
      ),
      'description' => array(
        'description' => 'A field storing Description',
        'type' => 'text',
        'length' => 255,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('fe_id'),
  );

  return $schema;
}

```

# Answer
You need to create the schema using the following code

```
$schema = Database::getConnection()->schema();
$schema->createTable('custom_form', $spec);

```

For further details visit here
> 0 votes

# Answer
This should just work. But it only works when you install the module. If you have your module already installed on a site, you either need to re-install it or write an update function that creates the table too.

You also might want to consider defining a content entity type instead, then you can let it build a form for you using field widgets and it also takes care of storing the data for you.
> 0 votes

---
Tags: 8, database
---


# Question
Title: How would I be able to get the full URL from an image field?
In a node template, how would I be able to get the URL from an image field? Like if it were something like this:

> {{ content.field\_image.URL }}

Or if there is a similar alternative perhaps?

# Answer
> 0 votes
Have you seen the answer of this question?

# Answer
> 0 votes
`{{ content.field_image[0]['#item'].target_id }}` would return the file entity id.

`{{ content.field_image[0]['#item'].getUploadLocation() }}` would return the file upload location uri (public://image-1)

It is better to use a preprocess function for this kind of logic and pass the result as a variable.

# Answer
> 0 votes
Getting the URL in a way that is actually a URL is not so easy and I think can currently only be done in preprocess. You need something like this:

`enter code here`file\_create\_url($variables\['node'\]-\>field\_image-\>entity-\>getFileUrl())

---
Tags: 8
---


title: Confirmation pop up on login submit

text:
# Question
Title: Confirmation pop up on login submit
I have built a site using drupal 7.41. I have added the login form by adding this line in my page.tpl.php "print render($page\['login\_container'\]);".

When user click on the login button I want to show a popup with options "yes" and "no". only when the user choose "yes" he/she should be logged in. I need change the style of this pop up, that's why I cannot use jquery window.confirm function.

I went through drupal documentations and found about the function confirm\_form. this is what I am trying to do, but not able to.

I created a hook menu and then called the confirm\_form fucntion. But I am not able to call this from the login submit button.

# Answer
Sounds like some simple Javascript. E.g. by the help of JQuery you could bind a click/submit function on the login-form, show a confirm-window ("Would you really like to log in?") and if this is confirmed, submit login-data (or not).

Such a function could(!) look similar to this:

```
$('#user-login-form').submit(function(){
 var r = confirm("Would you really like to login?");

 if (r == true) {
    return true; // submit form-data
 } else {
    return false; // stay on page
 }
});

```
> 0 votes

---
Tags: 7, javascript
---


title: Drush Site-Aliases won't work

text:
# Question
Title: Drush Site-Aliases won't work
I've been trying to set up some Drush aliases. However, when I try to run any command, it will echo the contents of all aliases files, and `drush sa` simply returns the contents of those files twice, and then the `@none`, `@self` and `@default` aliases (since I'm in the folder of a Drupal installation). When trying to run any command with an alias, e.g. `drush @local status`, I once again get a dump of those files, and finally a `Could not find the alias @local` error.

I've tried putting the aliases in `~/.drush/aliases.drushrc.php` and in `~/.drush/local.aliases.drushrc.php`. In the latter case, I tried two formats:

```
$aliases['local'] = array(
    'root' => '/home/user/subdomain/public_html',
    'uri' => 'subdomain.domain.com'
);

```

and

```
@code
    $options['uri'] = 'subdomain.domain.com';
    $options['root'] = '/home/user/subdomain/public_html';
@endcode

```

both without any different effect, apart from different contents being dumped. No other errors are thrown, it seems. I've also done a `drush cache-clear all` after each attempt.

Any thoughts as to what might cause this?

# Answer
Your error was quite simple; you forgot to put `<?php` at the top of your alias file.
> 6 votes

---
Tags: drush
---


# Question
Title: Entityform send email to entity referenced node email
I have a content type "Business" which has a field "Business Email".

I have an entity form with an Entity Reference field that allows a user to select mutliple businesses, leave a message and click send.

I need to send an email to the "Business Email" field of all referenced Businsess in the submission.

I have set up a Rule to react "After saving a new entityform submission" which checks "Enity has field:Business Email", and then sets up a send mail, but I am having trouble actually getting the value for business email and looping through it. Has anyone achieved something like that that can lend a hand?

# Answer
Your rule should first use condition "Entity has field" on your entity reference field from the form -\> the field where user selects businesses. In this case your form submission is the primary entity that your rule will target.

And then you'll have to loop through selected businesses and extract business email from each business that was selected by user in that form submission.

You can use components for getting email field out of your business entity or you can install "Conditional Rules" module (CR), which will allow you to write all the logic in rule's "actions" section without using components.

So your rule (if you installed CR) would be as follows:

**Events:** After saving a new entityform submission

**Conditions:** 1) Entity has field \[entityform:field-select-business\]

**Actions:** Your actions will look something like this.  **Loop:** here you loop through your Entity Reference field - \[entityform:field-select-business\]. You cannot loop through your Email field directly - every email is taken from refernced entity.

**IF** \- here you will select conditional "Entity has field" Entity: \[list-item\], Field: \[field\_business\_email\] \<- your email field. This brings email field into the rule's scope, otherwise your rule can't see the email field. This part is not possible to achieve in Actions section of a rule without "Conditional Rules" module.

And in the end - nest "Send Email" action under IF condition and you should be good to go.
> 1 votes

# Answer
The real issue was that my field\_business was not being recognised as a multiple value field. Once I selected the correct data selector "entityform" instead of "entityform:type" the field was allowed to be added as a loop.

Once I fixed that stupid mistake the rest was simple!

```
{ "rules_pinboard_emails" : {
    "LABEL" : "Pinboard Emails",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entityform" ],
    "ON" : { "entityform_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_businesses" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "entityform:field-businesses" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "[list-item:field-business-e-mail]",
                "subject" : "New Enquiry",
                "message" : "You have received a new enquiry, please login to your account to view.",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```
> 0 votes

---
Tags: rules, entities
---


# Question
Title: calculate sum of user's orders in drupal commerce
Is there a solution of calculating a sum of user's orders in drupal commerce (7.41 core) and display them in views? I tried to create a table in view which couldn't show anything except total number of orders but had not user filter. What should I do in order to combine "user" and "drupal commerce"?

# Answer
> 3 votes
You can use the view **Commerce Backoffice: User orders**.

1. Clone the display users orders.
2. IN advanced settings, set use aggregation : YES
3. remove All fields from the display except **order Total**
4. In order total field aggregation settings, set type = SUM, group a column = Amount

That's it.

Alternatively, if you don't use Commerce Backoffice module, you can create a view from scratch if you have no user's orders view (I don't remember which default views are provided with Commerce) :

1. Create a view of orders
2. Add a contextual filter Commerce Order:UID
3. Add a field total and repeat steps above

This should be enough. Remain formatting details...

# Answer
> 0 votes
I believe the commerce "Cart" submodule provides this out of the box with the "Shopping Cart" block. Make sure that module is enabled, then visit the views page for that block (/admin/structure/views/view/commerce\_cart\_block/edit/default) I believe initially they provide the sum in the footer of the view. I changed my view to display the count of the number of products and I got rid of everything else except the view cart and checkout links. I was able to get the count of products by turning on aggregation for the view ( Advanced \> Other \> Use aggregation:Yes ) and then putting a count on the "(Line items referenced by commerce\_line\_items)" field and then adding sort with a count "(Line items referenced by commerce\_line\_items)"

Depending on what you're trying to sum, you make be able to get it via aggregation in Views.

---
Tags: views, entities, commerce
---


# Question
Title: How to make an existing content type a product in Ubercart 3 and Drupal 7?
This is a follow up to this question. If I go to admin/store/products/classes, then I can only create new content types:

The problem is, I have another content type, called "product", which I need to set as an UberCart product. And I create this class in ubercart that has now resulted in a new content typed called "Basic Product". When all I really want is for the existing product to be considered as an actual product.

When I edit the "product" content type, I can see it doesn't have the same options as the "basic product" content type:

So the question is: how do I make my EXISTING "product" content type an Uber Cart product? I checked under classes and that only seems to work if you want to create a NEW content type.

# Answer
Have you simply tried to ***put the machine name of your existing content type*** in Class ID, and its human name in NAME ?

I've had such problem 3 years ago, and I solved it so. More, for tests purpose I've just created a *foo* content type. Then I added the Class ID *foo*, and it has been mapped with *foo* content type.
> 1 votes

---
Tags: ubercart
---


title: db_or() returns a SelectQuery-object

text:
# Question
Title: db_or() returns a SelectQuery-object
In my module, I was trying to make use of db\_or() in this way...

```
$filterSparten = db_select($this->tbl_hat_sparte, 'hs')
  ->fields('hs', array('hat_AID'));

$or = db_or();

foreach($_GET['tags'] as $tag) {
  $or->condition('hat_KID', $tag);
 }

 $filterSparten->condition($or)
  ->execute()
  ->fetchAssoc();

```

...which, unfortunately, only returns a SelectQuery-object:

```
SelectQuery Object
(
    [fields:protected] => Array
        (
            [hat_AID] => Array
                (...

```

Why doesn't my code return a fetched results-object? I have compared it several times with the examples on the Drupal-pages, but I can't help myself with it.

# Answer
> 0 votes
Assuming an unchanged core codebase, and assuming you mean that your *final* line is returning a `SelectQuery` (not the `db_or()`, which returns a `DatabaseCondition`), the only way you could be seeing a `SelectQuery` is if you're inspecting the wrong variable, i.e. `$filterSparten`. The query will remain a query, you need to assign the *results* to something else:

```
$results = $filterSparten->condition($or)
  ->execute()
  ->fetchAssoc();

```

Inspecting `$results` should give you what you're expecting.

---
Tags: database
---


# Question
Title: How to programmatically create forum topics using entity api?
I used this post and this post to get started but I was trying to use only the entity API.

Here is my code. So far the node creation works but I'm not able to save the node under the correct tid.

```
global $user;
$properties = array(
'type' => 'forum',
'uid' => $user->uid,
'status' => 0
);
$entity = entity_create('node', $properties);
$wrapper = entity_metadata_wrapper('node', $entity);
$wrapper->title = "My new forum topic";
$terms =  taxonomy_get_term_by_name ('General discussion','forums');

//$wrapper->taxonomy = $terms; //Doesnt work
//$wrapper->forum_tid = $terms->tid; //Doesnt work
//$wrapper->taxonomy_forums = $terms->tid; //Doesnt work

$wrapper->save();

```

# Answer
> 1 votes
`$wrapper->taxonomy_forums = reset($terms)->tid;` works!! `taxonomy_get_term_by_name()` returns an array of objects keyed with extra dimension (I think its keyed by the tid). The wrapper's save method will call `forum_node_presave($node)` but will look in the wrong dimension for the tid if you don't get rid of it.

---
Tags: entities, nodes
---


title: Embedded Youtube Block Thumbnail

text:
# Question
Title: Embedded Youtube Block Thumbnail
I seem to be having an issue with the auto generated Thumbnail of a you tube video that shows in a block as a teaser on my frontpage.

When viewing the front page using Firefox the thumbnails are shown. But when viewing on IE11 I just get the alternative text description without the thumbnail.

I am using Drupal 7

# Answer
> -1 votes
Try using the `/watch?v= parameter` (i.e. `www.youtube.com/watch?v=Y9eXzmVzDR8`) instead of `www.youtube.com/embed/Y9eXzmVzDR8` when adding content to the field.

---
Tags: files
---


# Question
Title: What other PHP memory_limit restrictions could there be besides php.ini?
I have been facing some weird memory limit issues on a managed dedicated server and spent alot of time trying to fix this other with the server admin. phpinfo() is showing the correct overridden memory\_limit values. Everything is cool, except when I use drush to do `drush en module` or Views Bulk Operation execution. If anyone has experienced this before, I will really appreciate if you can share with us the steps needed to fix this.

In my php.ini :`memory_limit = 256M ;`

In sites/default/settings.php: `ini_set('memory_limit', '256M');`

The WSOD message after executing a Views Bulkd Operations on ONE entry: `Fatal error: Out of memory (allocated 131334144) (tried to allocate 5 bytes) in /public_html/includes/cache.inc on line 401
Memory used at: devel_boot()=5.02 MB, devel_shutdown()=82.06 MB, PHP peak=82.25 MB.`

In SSH, using drush cli. After running `drush en languageassign`: `The following extensions will be enabled: languageassign
Do you really want to continue? (y/n): y`

`Fatal error: Out of memory (allocated 76021760) (tried to allocate 72 bytes) in /public_html/sites/all/modules/views/includes/base.inc on line 84`

`Drush command terminated abnormally due to an unrecoverable error. [error]`

`Error: Out of memory (allocated 76021760) (tried to allocate 72 bytes) in
/public_html/sites/all/modules/views/includes/base.inc, line 84`

# Answer
> 2 votes
Try including "RLimitMem 128000000" in your .htacess file.

# Answer
> 1 votes
Another place where the memory\_limit could be set is your .htaccess file. For drush also check out the cli php.ini file, usually found at /etc/php5/cli/php.ini

To check if you correctly set memory\_limit try this:

When running drupal from the webserver you can do this by going to admin/reports/status/php

For drush you can check your php settings by running this command: `php -i | grep memory_limit`

# Answer
> 0 votes
are you sure init\_set is enabled and you can modify your settings to that value?

most shared/dedicated servers have a limit for some settings or ignore ini\_set commands

# Answer
> 0 votes
Set memory limit in setting. php file using **ini\_set('memory\_limit' '256M')**. Also you need to check your php execution time because vbo need more time to executive the operation.

---
Tags: 7, drush
---


# Question
Title: Why does core update result in 'The requested page could not be found'?
I have Drupal 8 rc-3 and I unzip 8.0.0 version files cause need to update. Site works fine and all external site pages shows but when I go to update.php and push Run database updates it goes to update.php/selection and displays the error:

**The requested page could not be found.**

Also this error appears in /admin/modules and /admin/appearance/settings and may be others don't know.

I run Drupal 8 on Nginx and think my config is wrong. What I need in this case? My config files you can read here tlito.ru/node/253

# Answer
> 1 votes
i found nginx drupal 8 host config here https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/

my config is this

```
server {
server_name www.EXAMPLE.COM .EXAMPLE.COM;
root /var/www/EXAMPLE.COM/www;

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
    allow 192.168.0.0/16;
    deny all;
}

location ~ \..*/.*\.php$ {
    return 403;
}

location ~ ^/sites/.*/private/ {
    return 403;
}

# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
    return 403;
}

location / {
    # try_files $uri @rewrite; # For Drupal <= 6
    try_files $uri /index.php?$query_string; # For Drupal >= 7
}

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ '\.php$|^/update.php' {
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

    include             /etc/nginx/conf.d/fastcgi_params.conf;

    fastcgi_param       SCRIPT_FILENAME     /var/www/EXAMPLE.COM/www$fastcgi_script_name;
    fastcgi_param       DOCUMENT_ROOT       /var/www/EXAMPLE.COM/www;

    fastcgi_param       PHP_ADMIN_VALUE     upload_tmp_dir=/var/www/EXAMPLE.COM/tmp/upload;
    fastcgi_param       PHP_ADMIN_VALUE     session.save_path=/var/www/EXAMPLE.COM/tmp/sessions;
}

# Fighting with Styles? This little gem is amazing.
# location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
location ~ ^/sites/.*/files/styles/ { # For Drpal >= 7
    try_files $uri @rewrite;
}

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires max;
    log_not_found off;
}
}

```

AND the problem disappears.

---
Tags: 8, updating
---


# Question
Title: Changing Column width of a table view (Drupal 7 Views 3)
I have a view with 4 columns. The first column, which contains a majority of the text is taking about about 80% of the width of the form and forcing the 2nd, 3rd, and 4th rows to wrap. Problem is those columns have content that should not really be wrapped for exmaple Tues 3pm - 5pm ends up looking like

Tues

3pm -

5pm

So rather than the columns adjust based on content, I'd like to manually set the width of the first column so that it leaves enough space for the others. Or if need be manually set all the column widths.

Please understand I am totally lost in drupal and only have a small amount of css/php knowledge so please be as absolutely descriptive as possible. I've found a bunch of examples in other areas but people have left out huge chunks of the code, or where it's supposed to go etc. One place kept says "make changes to the css", not sure if it's normal but I have about 25 different css files in my drupal install, I had no idea WHAT css to make the change in.

Thanks in advance for any help! This is a great community and I'm happy I went with Drupal because of it.

# Answer
> 10 votes
A more general approach than useful answers from @Michael Greisman @Neograph734 is to create some utility CSS classes that can be deployed on any View. That means if this requirement comes up when creating a new View, you already have a solution ready to deploy.

This is something that has been really helpful on a site where I have configuration responsibility but all template / CSS work is done by a contracted developer (who suggested this approach).

1. Create some CSS classes that can be used to fix column widths. In our case, using % values worked best, but do whatever makes sense for your site. Example:

```
.fix-width-20 {
width: 20%;
}
.fix-width-40 {
width: 40%;
}
.fix-width-50 {
width: 50%;
}

```
2. On a view with the table format, go to the 'Style settings' for the Field that is populating the column (or columns) where you want precise control of column width. Add the name of the CSS class that fixes the width. Example:

# Answer
> 1 votes
Oke, you will need to do two things. First thing is to find out what name was given to the first column. Views will name (almost) everything it creates.

Open the page with the table, and then right click the table and choose 'inspect element' (this migth depend on your webbrowser, you can also view the source code).

You will find some HTML like below:

```
<table class="views-table cols-4">
 <thead>
  <tbody>
   <tr class="odd views-row-first">
    <td class="views-field views-field-title">
    <td class="views-field views-field-uid">
    <td class="views-field views-field-body">
    <td class="views-field views-field-custom">
   </tr>
   <tr class="even">
    <td class="views-field views-field-title">
    <td class="views-field views-field-uid">
    ...

```

As you can see, each first field is called `views-field-title` (basically the name of the first field).

In your css, you can set a width by writing something like this:

```
.views-field-title {
  width: 60%;
}

```

The best place to put this, is a difficult question. The best way would be to write a custom module that uses drupal\_add\_css function to add a css file to the page. However it is quite a hard way for 3 lines of code.

For this case I think adding it to the bottom of your theme's css will work just as good (if you update your theme, you might have to add it again though). Also if you have users who can choose different themes, make sure to add it to all of them.

# Answer
> 1 votes
@TheMad-Hatter, the earlier advice you got was correct; this is a styling issue, to be fixed using CSS. There are (of course) several ways to go about it, but the easiest is to change the style sheet for your theme.

If you can't tell which stylesheet to correct, change `style.css`. If that gets overridden by other style rules (that is, you know you did it right, you've cleared the caches, but still don't see the change)... then I'm sorry to be blunt, but you're going to have to learn enough CSS to deal with it. However, it's guaranteed to be worth the time.

* The quick way is to change the style.css file in your theme.
* The more correct way is to make a child theme (if you don't already have one)
and change the style.css file in that. That way, you can apply updates to your parent theme without losing this addition.

## CSS solutions:

You can style the width of the first column, perhaps like this:

```
.this-view table td:first-child {
  width: 55%;
}

```

However, that won't necessarily protect columns 2-4 from wrapping, so you might want to use this instead:

```
.this-view table td {
  /* initially set all columns to not wrap */
  white-space: nowrap;
}
.this-view table td:first-child {
  /* then set the first column to wrap normally */
  white-space: normal;
}

```

Oh, and the 25 stylesheets are normal. That is a whole different set of headaches.

# Answer
> 0 votes
```
white-space: nowrap;

```

/\* Adding the white-space:nowrap worked like a charm for the tables, did not need to add the width options.

Thanks Michael Greisman

# Answer
> -1 votes
* Simple solution;
    + go to your CSS folder located under your subthemme
    + find a file called tables.css
    + locate code table.cols-4 {..... width: 200px; } CHANGE width: 200px; for width: 100%;
    + flush css caches.

---
Tags: views, theming
---


# Question
Title: Commerce price attributes doesn't work when I use commerce discount for products
I used commerce pricing attributes in order to add extra fee based on a select box field. For example if user select black from color attributes, price increases 10$ and if user select white, price increases 5$ today, I have installed commerce discount module and defined a discount for all products.

But it seems price attributes doesn't work when discount is defined for product. Because by changing color in no change happened for price.

what is your suggestion to solve this problem?

# Answer
> 0 votes
I found the solution of this problem. In order to avoid this error, you must set order for your discount.

for the field order (with description : Discounts will be sorted by this value to be evaluated in that order.) set the discount on 1 (or the lowest amount in the select box)

this will fix the problem.

---
Tags: commerce
---