# Question
Title: Calculate distance using Geolocation module
I'm using the drupal/Geolocation module to assign a location field to a specific content-type.

I have created a View (REST Export display) to return all the content-type entries with all the fields and it's working fine.

I'd like to calculate the distance between a sent lat/lng point and the location of each entry and sort them by distance (and also include it in the resulting JSON).

I'm already applying some changes to the JSON output using the `views_post_render` hook (and changing the `$output` variable), but I don't think in that hook I can access a query string (sent via Ajax request).

What would be the best way to pass the user's location from the website frontend to the view? Right now my bet would be sending the query parameter via an Ajax request, adding something like `?location=-17.000,19.000` to the URL.

And where could I access that data (the user's lat/lng location) and calculate the distance to pass it again to the frontend?

# Answer
> 0 votes
I've found a solution.

### Getting the user location

I'm using the Browser API to get the user location in the frontend and then pass those parameters as query strings to my view, like `?latitude=xxxx&longitude=xxxx`.

```
if (navigator.geolocation) {
    var options = {
        enableHighAccuracy: true,
        maximumAge: 0
    };

    function success(pos) {
        var crd = pos.coords;
        // Send ajax request with crd.latitude and crd.longitude in query strings
    };

    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    };

    navigator.geolocation.getCurrentPosition(success, error, options);
} else {
    console.warn('Geolocation not available.')
}

```

### Using the location to calculate distances with Drupal hook

Then, using the `THEME_views_post_render(\Drupal\views\ViewExecutable $view, &$output)` hook I check that `$view->id()` is the view in which I want to make the calculations and I get the data from the URL using the Drupal function `\Drupal::request()->query->get('latitude');` (and longitude).

From that point, I decode the JSON variable `$output['#markup']` and change the JSON objects the way I need to fulfill my requirements.

```
if ($view->id() == 'farmacias_perto') {
        $user_latitude = \Drupal::request()->query->get('latitude');
        $user_longitude = \Drupal::request()->query->get('longitude');
        $json_result = json_decode($output['#markup']->jsonSerialize());

        foreach ($json_result as $pharmacy) {
            $latlong = explode(',', $pharmacy->field_geolocation);
            $pharmacy_latitude = $latlong[0];
            $pharmacy_longitude = $latlong[1];
            $distance = distance($pharmacy_latitude, $pharmacy_longitude, $user_latitude, $user_longitude);
            $pharmacy->distance = round($distance);
        }

        $output['#markup'] = json_encode($json_result);
}

```

I used the distance function explained here.

---
Tags: views, 8
---


# Question
Title: User referencing another user causes unexpected error
I have a Drupal 7 site with a bunch of users. Some are clients and others are sellers (role). I put an entity reference field `field_seller` on the user account form which filters users with the seller role.

Now, when applying a seller to a client and the client logs in, he gets an error

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

The following error is shown in the log:

> Recoverable fatal error: Object of class stdClass could not be converted to string in \_theme\_table\_cell() (row 2418 of /mysite.com/includes/theme.inc).

Any idea why this happens?

# Answer
I think, that the user entity will be rendered at the profile page. So you should check the settings here: `admin/config/people/accounts/display`

Also you check if the role client is able to access user profiles, if the seller will be rendered on the clients profile page
> 0 votes

---
Tags: 7, entities, users
---


# Question
Title: 8 - How to run jQuery to show a div, after register form is submitted?
I've looked at this question, but I want a `div` to be displayed rather than a Drupal Message

After a user successfully submits the `user_register_form`, I want to call a jQuery function like this:

```
function showMessage(){
  $('#message-overlay').fadeIn();
}

```

This is so I can show users that they have to confirm their email address in order to login.

I tried using hook\_form\_alter like this to display a custom message, but even this does not work...

```
function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
    $form['#submit'][] = 'submitForm';
  }
}

function submitForm(array &$form, FormStateInterface $form_state) {
  drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

```

Please advice!

# Answer
> 1 votes
I used like below and it works for me:

```
function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
      foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_message_submit';
        }
      }
  }
}
function _message_submit(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  drupal_set_message(t('The user @name account has been created successfully.', ['@name' => $values['name']]));
}

```

---
Tags: 8, forms, users, javascript
---


# Question
Title: Show progress of code executed on form submit
I have a form in my site (custom module) where the user chooses some options and depending on those options, some code is executed.

The code basically executes shell commands on a remote server and at the moment, all the **drupal\_set\_message** commands are only shown after all commands are executed.

Is there any way that I can show those messages as soon as each part of the code is executed?

```
function mymodule_connect() {
    $host = '<my ip address>';
    $username = '<my username>';
    $password = '<my password>';

    $connection = ssh2_connect($host, 22);
    ssh2_auth_password($connection, $username, $password);

    return $connection;
}

function mymodule_form_submit(&$form, &$form_state) {

    $delete_load = $form_state['values']['delete_load'];
    $change_load = $form_state['values']['change_load'];
    $load_number = $form_state['values']['check_load'];

    if($change_load == 1) {
        # DELETE
        # perform some command

        # LOAD
        # perform other command

        drupal_set_message('Deleting. Please wait...', 'error');
        drupal_set_message('Changing load. Please wait...', 'warning');
    } elseif ($delete_load == 1 && $change_load == 0) {
        # DELETE
        drupal_set_message('Deleting. Please wait...', 'error');

        $command = "<some shell script command to send>";

        $connection = mymodule_connect();

        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);

        ssh2_exec($connection, 'exit');
        unset($connection);

    } else {
        # do nothing
    }

    # OTHER DIFFERENT SET OF COMMANDS TO SEND
    drupal_set_message('Configuring. Please wait...', 'status');

    $commands = array(
        "<some shell script command to send>",
        "<some shell script command to send>",
        "<some shell script command to send>",
    );

    $connection = mymodule_connect();

    foreach ($commands as $command) {
        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);
    };

    ssh2_exec($connection, 'exit');
    unset($connection);

    return t('Success');
}

```

# Answer
> 1 votes
As Mohammed Gomma mentioned you need to use Batch API to achieve the same. The implementation of batch api may look something like code given below:

1. Create Batch array
2. Create function to execute commands and call them using batch operation
3. set context message in the function created
4. create finish callback

function mymodule\_form\_submit(&$form, &$form\_state) {

```
      $delete_load = $form_state['values']['delete_load'];
      $change_load = $form_state['values']['change_load'];
      $load_number = $form_state['values']['check_load'];

      if ($change_load == 1) {
        # DELETE
        # perform some command
        # LOAD
        # perform other command

        drupal_set_message('Deleting. Please wait...', 'error');
        drupal_set_message('Changing load. Please wait...', 'warning');
      }
      elseif ($delete_load == 1 && $change_load == 0) {
        # DELETE
        drupal_set_message('Deleting. Please wait...', 'error');

        $command = "<some shell script command to send>";

        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);

        ssh2_exec($connection, 'exit');
        unset($connection);
      }
      else {
        # do nothing
      }

      # OTHER DIFFERENT SET OF COMMANDS TO SEND
      drupal_set_message('Configuring. Please wait...', 'status');

      $commands = array(
        "<some shell script command to send>",
        "<some shell script command to send>",
        "<some shell script command to send>",
      );

      $batch = array(
        'finished' => 'batch_example_finished',
        'title' => t('Processing Example Batch'),
        'init_message' => t('Example Batch is starting.'),
        'progress_message' => t('Processed @current out of @total.'),
        'error_message' => t('Example Batch has encountered an error.'),
      );
      foreach ($commands as $command) {
        $batch['operations'][] = array('_batch_execute_command', array($command));
      };

      batch_set($batch);

      return t('Success');
    }

    function _batch_execute_command($command, &$context) {
      $connection = mymodule_connect();
      $stream = ssh2_exec($connection, $command);
      stream_set_blocking($stream, true);
      $output = stream_get_contents($stream);
      dpm($output);
      ssh2_exec($connection, 'exit');
      unset($connection);
      $context['message'] = t('Now processing %command', array('%command' => $command));
      if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
      }
    }

    /**
     * Batch 'finished' callback
     */
    function batch_example_finished($success, $results, $operations) {
      if ($success) {
        // Here we do something meaningful with the results.
        $message = t('@count items successfully processed:', array('@count' => count($results)));
        // $message .= theme('item_list', $results);  // D6 syntax
        $message .= theme('item_list', array('items' => $results));
        drupal_set_message($message);
      }
      else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
        drupal_set_message($message, 'error');
      }
    }

```

**Nested batch example:**

```
function gamify_batch_form($form, $form_state) {
  return array(
    'submit' => array(
      '#type' => 'submit',
      '#title' => 'submit',
      '#value' => 'submit',
    ),
  );
}

function gamify_batch_form_submit($form, $form_state) {
  $batch = array(
    'finished' => 'batch_example_finished',
    'title' => t('Processing Example Batch'),
    'init_message' => t('Example Batch is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Example Batch has encountered an error.'),
  );
  $commands = array(
    'hi',
    'hello',
    'world',
    'dear',
    'world',
  );
  foreach ($commands as $command) {
    $batch['operations'][] = array('_batch_execute_command', array($command));
  };

  batch_set($batch);
}

function _batch_execute_command($command, &$context) {
  file_get_contents("https://drupal.stackexchange.com/questions/246767/show-progress-of-code-executed-on-form-submit/247718?noredirect=1#comment303466_247718");
  if($command == 'world'){
    $batch = array(
      'finished' => 'batch_example_finished',
      'title' => t('Processing Example Batch'),
      'init_message' => t('Example Batch is starting.'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('Example Batch has encountered an error.'),
    );
    $commands = array(
      'hi 1',
      'hello 2',
      'dear 3',
    );
    foreach ($commands as $innercommand) {
      $batch['operations'][] = array('_batch_execute_command', array($innercommand));
    };

    batch_set($batch);
  }
  $context['message'] = t('Now processing %command', array('%command' => $command));
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * Batch 'finished' callback
 */
function batch_example_finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = t('@count items successfully processed:', array('@count' => count($results)));
    // $message .= theme('item_list', $results);  // D6 syntax
    $message .= theme('item_list', array('items' => $results));
    drupal_set_message($message);
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
    drupal_set_message($message, 'error');
  }
}

```

# Answer
> 4 votes
Surely you need to implement Batch API to achieve what you need, and keep the user notified for what's happening in the background.

Very similar question that will help you more. Read it carefully.

These modules will help you:

1. Progerss This is an attempt to implement a generic framework for keeping track of any progress
2. Background progress takes over the existing Batch API and runs batch jobs in a background process

---
Tags: forms
---


# Question
Title: Redirect user to previous page after registration
I'd like users registering on my website are redirected to the page where they clicked the "create account" button which is in a modal.

First, I tried to redirect to an absolute url I tried

```
$form_state->setRedirect($myUrl);

```

I tried

```
$_REQUEST['destination'] = '<front>';

```

I tried this too :

```
$response = new \Drupal\Core\Routing\TrustedRedirectResponse('http://www.google.be');
$form_state->setResponse($response);

```

I'm always redirected to /user/\[uid\]/edit

# Answer
You could use Rules module to achieve that..
> 0 votes

# Answer
You can accomplish this with the Rules Link module, and using the php variable php variables %server\[HTTP\_REFERER\]

Or, without having to enable php in rules, you can use a custom 'previous page' token, explained in this drupal.org issue.

Create a rule that triggers when the link is clicked, stores the previous page a a variable, do some other actions you want and at the end a redirect action to that previous page variable.
> 0 votes

---
Tags: 8, users, redirection
---


title: Import/export views

text:
# Question
Title: Import/export views
I am currently migrating a Drupal 6 website to Drupal 8. There is no single way to import views. It seems there is no import path in Drupal 8 as in Drupal 6 to do this one by one.

What's the way to achieve this?

# Answer
> 3 votes
There is currently (D8.4 october 2017) no migrate update path for views (D6 or D7) to D8. It doubful if this will ever happen because of the complexity of views. I.e. missing views handlers, changed base tables, etc More info here: https://www.drupal.org/node/2500547

Some work was done on a contrib module for this d.o/project/migrate\_views , but it is doubtful if this will ever be finished.

There is basically no other solution than to rebuild your views in the new D8 site. Luckily this is a lot easier than building them on D6 was.

Issues with migration page ( https://www.drupal.org/docs/8/upgrade/known-issues-when-upgrading-from-drupal-6-or-7-to-drupal-8) also states:

> Views are not yet migrated.

---
Tags: views, 8, importing-exporting
---


# Question
Title: hook_node_insert PDOException exception issue
I am attempting to programmatically insert some field data when a new node is being created using the following code:

```
function mymodule_node_insert($node) {

    $dialects = array('en-AU', 'en-NZ', 'en-US');

    node_object_prepare($node);
    foreach ($dialects as $dialect) {
        $node->translations->data[$dialect]['entity_id'] = $node->nid;
        $node->translations->data[$dialect]['entity_type'] = 'node';
        $node->translations->data[$dialect]['revision_id'] = 3;
        $node->translations->data[$dialect]['language'] = $dialect;
        $node->translations->data[$dialect]['source'] = 'en';
        $node->translations->data[$dialect]['uid'] = 1;
        $node->translations->data[$dialect]['status'] = 1;
        $node->translations->data[$dialect]['translate'] = 0;
        $node->translations->data[$dialect]['created'] = time();
        $node->translations->data[$dialect]['changed'] = time();

        $node->field_page_body[$dialect] = $node->field_page_body['en'];
    }
    node_save($node);
}

```

However, I recieve the following error:

**I understand it's complaining about the same node ID being saved twice but I'm not sure how to avoid this exception and update my new node with the programmatically set data?**

It's important I execute my code at hook\_node\_insert because there are hundreds of nodes to be imported later and they all need the same treatment.

The same code works when tested in `mymodule_init()`.

# Answer
I found the work around to this issue here.

Use `field_attach_update('node', $node);`

instead of:

`node_save($node);`
> 0 votes

# Answer
You cannot call `node_save($node)` during `hook_node_insert($node)`.

According to the documentation, that hook is invoked during the middle of the database transaction, so the node isn't committed to the database yet. So when you invoke node\_save, the old node you're attempting to update doesn't exist yet, and it will attempt to create a new node (with the same ID). Thus, the collision.
> 0 votes

---
Tags: 7, nodes, database, hooks
---


# Question
Title: Access Value of variable content in twig template
I'm new in a Drupal 8 and using Devel `kint()` function for debugging. In my twig template `menu--main.html.twig`, I have looped for the menu items like this:-

`{% for item in items %}
 {{kint(item.url)}}`

The output like this:-

What I should write to print the URI, I've tried `{{item.url.uri}}` but not working

# Answer
You can try `{{item.url.getUri}}`.

You can change to tab **Available methods** to see other method. Example isExternal. :D
> 1 votes

---
Tags: theming, 8, debugging
---


# Question
Title: About the drupal hook_theme_registry_alter
I have a query:--

I have installed a module imgix which implements like this:--

It implements hook\_theme\_registry\_alter;

```
function imgix_theme_registry_alter(&$theme_registry) {
  // Overrides theme_image().

   unset($theme_registry['image']['preprocess functions']);

   if (isset($theme_registry['image'])) {
       $theme_registry['image']['function'] = 'imgix_theme_image';
       $theme_registry['image']['theme path'] = drupal_get_path('module','imgix');
       $path_module = drupal_get_path('module','imgix');
       $theme_registry['image']['file'] = 'imgix.module';
       $theme_registry['image']['includes'] = array($path_module."/imgix.inc");
  }

 return $theme_registry;
}

```

I have now installed a new module called lazyloader.

which is also using same hook and overriding the image tag.

How can I call both of the function one after the another from different modules and overriding the same image theme.( I have tried. I changed the weight of module .The module having higher weight executed successfully. and the other one does not.)

So How to solve the above problem ?

# Answer
This will never work as the later hook just overrides the previous. You can implement your own module, with `hook_theme_registry_alter` and point `$theme_registry['image']['function']` to your custom theme function.

Then you will need to re-implement `imgix_theme_image` and `lazyloader_image` (they are very similar and doing the same: assigning attributes to img tag) in your custom theme function.

This is a basic explanation, you will probably need to take care of other `$theme_registry['image']` parameters to get it to work.
> 0 votes

---
Tags: hooks
---


title: drush migrate-status command not found

text:
# Question
Title: drush migrate-status command not found
I've installed both version of drush using composer, and trying to list migration within my newer drup8 installation, in order to migrate an older drupal 7 website .. then I feel really stucked because I can't follow the next commands to execute ..

```
composer global require drush/drush:dev-master --> migrate-status not found
composer global require drush/drush:7.* --> won't work with drupal8

```

Any ideas or enlightment would be greatly appreciated.

# Answer
> 2 votes
If you're using Drush 9, you need to apply the patch from Drush 9 port of commands since Drush 9 is implementing drush commands in a new way. Otherwise downgrade to Drush 8.x.

If you're already using Drush 8.x, run:

```
drush en migrate_tools
drush cc drush

```

# Answer
> 1 votes
Try `drush status` and `drush help` to see if Drush is working with your Drupal 8 site. Presumably, `drush help` will confirm that the migrate-status command is not available. Try enabling the migrate module on your Drupal 8 site.

# Answer
> 1 votes
The drush support for Migrate isn't in core itself, but you can easily install it by installing the Migrate Tools module. If you enable migrate\_tools, you will get everything you need to use drush with your migrations:

```
$ drush en migrate_tools
The following extensions will be enabled: migrate_tools, migrate, migrate_plus
Do you really want to continue? (y/n): y
migrate was enabled successfully.                                                                                [ok]
migrate_plus was enabled successfully.                                                                                [ok]
migrate_tools was enabled successfully.                                                                                [ok]
migrate_tools defines the following permissions: administer migrations

$ drush help | grep migrate
All commands in migrate_tools: (migrate_tools)
 migrate-import (mi)   Perform one or more migration processes.
 migrate-manifest      Execute the migrations as specified in a manifest file.
 migrate-messages      View any messages associated with a migration.
 migrate-reset-status  Reset a active migration's status to idle.
 migrate-rollback      Rollback one or more migrations.
 migrate-status (ms)   List all migrations with current status.
 migrate-stop (mst)    Stop an active migration operation.

```

---
Tags: drush
---


# Question
Title: How to uninstall a text format created by a D8 module?
My module creates its own text format upon installation by having a file named `config/install/filter.format.{format}.yml`.

However, I can't uninstall and reinstall the module, because the format persists and will then cause a conflict. ("... already exists in active configuration.")

This looks like a bug in the filter API, but maybe there is some explicit way to delete the format when the module is removed? It's really annoying to have to manually delete the config key every time.

# Answer
You need to add a dependency in your filter format to the module. Then when the module is uninstalled, the format should get deleted
> 0 votes

# Answer
Text formats are undeletable.

@see this 8.0.x-dev issue: Change the disable user interface with formats. Make it remove.

### Berdir's answer:

> It is called disable because it's not deleted, it stays there as a format is undeletable, you'll just never be able to get it back ;)
>
> There have been endless and insane discussions and issues around this before the release of 7.x. Headache-causing discussions ;)

### Wim Leers' answer:

> To clarify Berdir's points: text formats may not be deleted because almost always there's \>0 pieces of content using it, which must still be renderable, which means that the text formats they use must remain available. Hence text formats can only be disabled.

---

Maybe in the future there'll at least be the option to re-enable them.

@see this 8.5.x-dev issue: Disabled text formats can't be seen in the GUI.
> 0 votes

---
Tags: 8, input-formats
---


title: How does AccessResult::neutral() work?

text:
# Question
Title: How does AccessResult::neutral() work?
I have seen in code:

```
AccessResult::neutral()
AccessResult::allowed()
AccessResult::forbidden()

```

`allowed()` and `forbidden()` are pretty obvious, but how does `neutral()` work?

I have been debugging and sometimes `neutral()` allow access and sometimes it doesn't.

# Answer
> 12 votes
“Neutral” basically means “I don’t care” in this context.

Returning it means you’re saying that your code has no opinion on whether access should be granted or not, and that other methods/modules should make the decision.

---
Tags: 8
---


title: Load disabled items in a menu

text:
# Question
Title: Load disabled items in a menu
I load my main menu programmatically with the following code :

```
    $menuTree = \Drupal::menuTree();
    $menuTreeParameters = $menuTree->getCurrentRouteMenuTreeParameters($name);
    $menuTreeParameters
        ->setMinDepth($minLevel)
        ->setMaxDepth($maxLevel);

    $tree = $menuTree->load($name, $menuTreeParameters);
    $tree = $menuTree->transform($tree, $this->getDefaultManipulators());

    return render($menuTree->build($tree));

```

I would like to get all my menu items, included thoses which are disabled. When I inspect $tree variable, I have all my menu items.

I don't know why but after the call to the build method, I get only my enabled items.

# Answer
Check this line in `buildItems()` which is called by `$menuTree->build($tree)`, in *\Drupal\Core\Menu\MenuLinkTree.php*:

```
  // Generally we only deal with visible links, but just in case.
  if (!$link->isEnabled()) {
    continue;
  }

```

It's designed to exclude links that are not enabled. I played around with something like this to get them all showing:

```
foreach ($tree as $id => $treeItem) {
    // Get the link definition.
    $definition = $tree[$id]->link->getPluginDefinition();

    // Skip links that are already enabled.
    if ($definition['enabled'] == 1) {
        continue;
    }

    // Change definition and enable link.
    $definition['enabled'] = 1;

    // Recreate the link.
    // I'm not 100% sure about the correctness of this part.
    // This is my first time playing with this stuff. Hopefully someone can fill in this blank.
    $pluginContainer = \Drupal::getContainer();
    $conf = [];
    $newLink = \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent::create($pluginContainer, $conf, $id, $definition);
    $tree[$id]->link = $newLink;
}

```
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: How can I allow anonymous visitors to submit content?
I am working on a website that displays a list of historical events. Most of the events have been added by a small group of users that manage the site. However, I would also like to add the ability for anonymous visitors to suggest events to be added to the site.

I could make the node/add form available to anonymous visitors however this isn't ideal for several reasons:

* the standard submission form is quite complex and I would like to simplify this for anonymous visitors e.g. some fields aren't relevant I want to hide these.
* anonymous visitors should be able to submit partial information about the events and for an editor to add more details later.
* anonymous submissions need to be moderated before being published.
* I would like to guard against spam submissions.

How would you suggest I do this?

Is it possible to have two forms to add a new event, a more complex one for site users and a simpler one for anonymous visitors?

# Answer
> 4 votes
Create another content type, say "*Event Suggestion*", which contains only those fields you want anonymous users to submit suggestions for. Do not include the fields you consider as not relevant (and which you want to 'hide' for such anonymous users).

When creating such extra content type, for its fields just use the same fields as for the content type that you already have, say "*Event*". So the fields for this new content type (*Event Suggestion*) will be a subset of the fields that you already have for the content type already being used by your "small group of users" (= Event).

Related to permissions: allow anonymous users to create an *Event suggestion*, but do not allow *Event* to be created by anonymous users.

For spam reduction/prevention, use modules such as Honeypot, Mollom, Captcha, reCaptcha, etc.

Use the Rules module to finetune your workflow related to nodes of type *Event suggestions* being created (saved). To just mention a few options (the list is virtually unlimited):

* Unpublish such nodes (so that spam submissions that are not caught by spam prevention modules, never get shown without reviewing them first).
* Send an eMail msg to your small group of users who manage your site (something like "a new Event suggestion is waiting your approval".
* Set some kind of "confirmation message" when an Event suggestion is beiing submitted (like "Thank you for your Event suggestion, it will be reviewed soon ...").

When your small group of users who manage your site then review such *Event suggestion*, they should use the Node Convert module to convert an *Event Suggestion* into an *Event*. Using the Rules module you could then automatically "publish" such event also. After such node got converted, your small group of users who manage your site could then complete what you described as "add more details later on".

Other modules like Flag and/or Content Access might further enhance the various features / functionality you might be looking for. E.g. as an alternative to working wirth "unpublished" content, you could work with content that is published, but can only be accessed by authorized users.

**Bottom line**: Rules and Node Convert could get you pretty close, possibly further enhanced with Flag and Content Access.

**Note**: Adding the View unpublished module seems like an interesting improvement also, i.e. to grant access for specific user roles (such as editors or reviewers) to view unpublished nodes of a specific type.

# Answer
> 2 votes
**Simple Interface for Anonymous User**

Create custom form submit of what will call node\_save() with values from form fields. Custom form will be simple and will have only limited fields to be shown to anonymous user.

**Content Moderation by Editor.**

In order to have moderation on content you can install workbench\_moderation module. With help of this module you can setup different moderation states on any content type, also it will give dashboard to users with permissions so if in your case you have Editor as role to publish nodes created by anonymous user, you can setup draft as the intermediate moderation state before it gets published, now when anonymous user submits the custom form, a node is created programmatically and is in draft state, Editor role will have permission to access Draft dashboard which will be coming out of workbench\_moderation module and will list all nodes in draft state, all you need is to give permission to editor role to move nodes from draft to publish.

**Spam Protection**

In order to avoid spam you can have captcha on your custom form, install recaptcha module. Your custom form will have field like

```
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);

```

Reference - How do I add reCaptcha to a custom form?

# Answer
> 1 votes
I see two simple options:

1) create a completely different content type for the submission, and use something like Node Block

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

to display the submission over an edit form of the final content, so the moderators can simply copy and paste from the top of the screen to the bottom, and then make changes as they like

OR

2) Use Field Permissions

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> Features
>
> Enable field permissions on any entity, not just nodes. Role-based field permissions allowing different viewing patterned based on what access the user has. Author-level permissions allow viewing and editing of fields based on who the entity owner is. Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

and restrict the view and edit of the fields you don't want anonymous users to access.

Either way you could then create a flag system: a boolean value only moderators can see and change (again using Field Permissions) which tells the system if the submission has been accepted or not (for either content type)

With the Flag system you can use Views

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

To display a list of pending submissions to moderators, based on the flag value

For the Anonymous content creation, you will want to look at some form of spam control, be it captcha, or form edit timing - but there are lots of resources available for determining what's best for your situation elsewhere.

# Answer
> 0 votes
For Drupal 8, we developed subtonode (https://github.com/owenmorrill/subtonode) to push a webform submission to a node of a specific content type (ours was "bulletin").

Permissions are such that we can't let submitters edit their submissions at this time. Once the node is created with subtonode, anonymous users have no backend/edit access to it.

# Answer
> -1 votes
You can use anonymous\_posting module https://www.drupal.org/project/anonymous\_posting

---
Tags: nodes, forms, users, advertising
---


title: How to hide not translated menu items

text:
# Question
Title: How to hide not translated menu items
I have a multilanguage site. Now i'm running in the issue that some pages don't have translations. So i would like to hide that from the navigation.

I already tried to manipulate it with that hook:

`mytheme_preprocess_menu_local_task`

But it seems that it does not have an affect. I also don't find any other hook which i could use for that.

Any suggestion?

# Answer
Use `hook_node_access()` to deny access to the not translated nodes and this will automatically hide the corresponding menu items:

*mymodule.module:*

```
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;

  /**
   * Implements hook_node_access().
   */
  function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if (!$node->hasTranslation($langcode)) {
      $access = AccessResult::forbidden();
    }
    else {
      $access = AccessResult::neutral();
    }
    $access->addCacheableDependency($node);
    return $access;
  }

```

You can be more specific, hide not translated nodes of specific content types. Or for specific user roles, which you probably need to do if other users than the admin wants to edit the nodes. Or you have to be specific about the operation $op. And test this with different user roles, as admin you won't see a difference, because this account passes all access checks.
> 5 votes

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


# Question
Title: What happens when multiple context conditions match?
I have a multi-site setup using multiple contexts:

```
Context A
  Conditions:
    - Path:  <front>
  Reactions:
    - Block: sidebar-left

Context B
  Conditions:
    - Domain:  Domain1.com
    - Path:  <front>
  Reactions:
    - Block: sidebar-left

Context C
  Conditions:
    - Domain:  Domain2.com
    - Path:  <front>
  Reactions:
    - Block: sidebar-right

```

My goal is for the more specific contexts to match first (B,C), and for the general context (A) to match all other domains.

My problem is that Context A is always being matched first for Domain2. Is there a way to define the "weight" of each context, and force Context C to evaluate before Context A?

# Answer
> 2 votes
Context starts from top and moves downward on all your created contexts and will stop on the first one to trigger it. This is why your context A is being displayed.

You have a few options...

1. Set a required condition to your context A as "Default Context" this way it will only trigger if no other contexts were found.
2. Make a few MAIN contexts that apply to many different cases for example, cache 1day, cache 5 days, cache 2hours, etc. The tag you can start with z\_caches or something like that and put no conditions to these cache contexts, only the reactions. Note this will move them all the way down and you may think they will never apply... wait... now go to a main context for example, article\_type and there you add a condition of "context (any or all)" and add the cache context you already created to that list. That way all article content types will automagically first add the context cache you want applied within this context. This way the page will stop on only one context, yet that one context contains multiple contexts within it. This is perhaps the best solution in most cases that need to apply multiple contexts or share conditions. Seeing your example, you can also create a "Domain" context like we did cache and apply it to whatever contexts you want and easily edit any of the included contexts without having to create so many different contexts since you are sharing some contexts that you know will be common. Cache, Http headers, delta (for theme layouts), domains, language, etc. These are all possible conditions that people may see themselves repeating on multiple contexts, but if you ever need to edit any of these, you have to go one by one to every context you added them and edit that field. However, if you use this method of sharing or including/excluding other contexts within your context, you only have to edit that one particular context that was included and will apply to all contexts referencing it.
3. Reorder your contexts in the order you want them triggered from top to bottom. The easy way to do this is by using the "clone" link when viewing all your contexts. Simply clone it and change the "tag" field (second field above the description) and you can start all your tags with numbers (like weights) and that will get the contexts in the order you need.

\*NOTE: For point #2, you can use the "context all" or "context any" conditions to display or not display (not display using ~) any other contexts or the "context\_disable\_context" module which will allow you to select which contexts to omit.

In summary, using context is similar to using Path Breadcrumbs for example, in the sense that you have to plan ahead the hierarchy of importance from top to bottom of anything you create and know it will stop on the first item if true.

See your example, and you will see that in fact domain B and C when seeing context A, are in fact true, that is why it stops there (both domain B and C have a page). If however, you follow my option #3 and reorder A to the bottom (B,C,A) and make all conditions of B & C required, any pages that do not specify the domain B or C will in fact trigger A.

The main difference between path breadcrumbs and context is that with path breadcrumbs you can drag and drop their weight order making things much easier. Here, you must find a way around that by altering your orders based on any of the methods i mention above. Not all will work in every case so i guess you just have to see which one works in your situation. I for example always have my path contexts above my content type contexts to ensure that the path if triggered has precedence over the content types and i use any conditions that are shared across multiple contexts by using method #2 i explain above.

I hope i made sense since i have not slept in over a day. At least it may be a good starting point :)

---
Tags: multi-sites, 7
---


title: Test if a value exists in $form_state

text:
# Question
Title: Test if a value exists in $form_state
If I wanted to rebuild a form in Drupal 7, conditional on the state of the form, I would do something like this:

```
if (isset($form_state['values']['foo'])) {
  $form['...
}

```

Now, `$form_state` is an object in Drupal 8. What would be the best equivalent?

# Answer
> 1 votes
Pretty much `$form_state->getValue('foo');`.

See the docs page for getValue.

# Answer
> 1 votes
I belive that the equivalent to `isset()` is

```
if ($form_state->hasValue('foo')) {
  ...
}

```

---
Tags: 8
---


# Question
Title: Can we write javascript code in twig template?
Can we write javascript code in twig template?

Its needed to write javascript code in twig template.

When we are writting the same code in custom.js file that particular code is not working in it.

How to write javascript code directly into the twig template?

# Answer
Yes, you can write JS code in a twig template. I can't think of any syntax crossovers so you should be able to literally write it as-is.

Indeed this works fine in html.twig.html:

```
<script>
  (function(val) {
    console.log(val);
  })('test');
</script>

```

If you're having syntax trouble, you can always escape it with `raw`, but it should be unnecessary:

```
{% raw %}
<script>
  (function(val) {
    console.log(val);
  })('test');
</script>
{% endraw %}

```
> 11 votes

---
Tags: 8
---


title: From template.php to tpl.php

text:
# Question
Title: From template.php to tpl.php
I define variables in `template.php` file `preprocess_page` but it come undefined in `tpl.php` files. What can be a problem? Here is code

template.php file

```
$user_profile = profile2_load_by_user($uid, 'user_profile');
$vars['user_profile'] = $user_profile;

```

tpl.php file

```
print_r($user_profile);

```

# Answer
> 1 votes
Firstly, check to see that `profile2_load_by_user` is a function available via a .module file and not something you will need to load via `module_load_include()` \- which will load other files, such as .inc files.

Second, check the argument list for the preprocess hook. Did you define it as `&$variables` and mistakenly assign it to `$vars` which would mean nothing in this context? Did you forget to pass by reference via `&` which makes the array modifiable?

Third, if you just added this code, clear your site caches so the changes are picked up.

Fourth, the function name isn't `preprocess_page`. It should be `MYTHEME_preprocess_page`.

# Answer
> 1 votes
Solution is write not one preprocess\_page but, many preprocesses depend on page... Say you have user\_page page, preprocess should be `theme_name_preprocess_user_page` or use `['theme_hook_suggestion'][] = 'tpl.php - name';`

---
Tags: theming, users, entities
---


# Question
Title: Limit the number of discount per product to 1, Commerce Discount
I'm trying to make a one time discount for each product of a certain type per customer. If the user buy a product he will have a discount on it, but he cannot have it a second time.

How can I do that.

So far I couldn't figure out how to limit it for the product itself. Maximum usage determines how many times a discount may be applied across all customers or to a single customer's orders, which in my case should be empty (unlimited).

Where is the setting to limit the number of use per product to 1?

Is it a rule I need to code?

Cheers

# Answer
> 3 votes
You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag each product by the customer, after such discount was applied (for the first time). To actually flag such products by the customer, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

Any time a customer buys a product, you can verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no flagged this product already (by the flag you created for this purpose)".

If you're not familiar with the Flag module, checkout either of these:

---
Tags: commerce
---


# Question
Title: Unit price showing in purchased entity (Item) field
Commerce2.x admin/structure/views/view/commerce\_cart\_form

Field: (order\_items: Order Item) Order item: Unit price (price) admin/structure/views/nojs/handler/commerce\_cart\_form/default/field/unit\_price\__number

Showing in

Field: (order\_items: Order Item) Order item: Purchased entity (item) admin/structure/views/nojs/handler/commerce\_cart\_form/default/field/purchased\_entity

Is this a bug or configuration problem?

d8.4 Commerce2 updated

# Answer
> 0 votes
Workaround fix: In structure/views/view/commerce\_cart\_form Change to hidden field: (order\_items: Order Item) Order item: Purchased entity (Item) \[hidden\]

Add field (order\_items: Order Item) Order item: Title (Item) for line item display.

Still researching Purchased entity problem.

---
Tags: commerce
---


# Question
Title: Whats best practices for handling Drupal 8 core file paths for vendor package.json
I use drupal-vm when setting up my dev environment and have heard that setting up Drupal core files in the document root is a security issue and should be set in a different way.

So I have set my composer.json to:

```
 "merge-plugin": {
        "include": [
            "docroot/core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    },
    "installer-paths": {
        "docroot/core": ["type:drupal-core"],
        "docroot/modules/contrib/{$name}": ["type:drupal-module"],
        "docroot/profiles/contrib/{$name}": ["type:drupal-profile"],
        "docroot/themes/contrib/{$name}": ["type:drupal-theme"],
        "docroot/drush/contrib/{$name}": ["type:drupal-drush"],
        "docroot/modules/custom/{$name}": ["type:drupal-custom-module"],
        "docroot/themes/custom/{$name}": ["type:drupal-custom-theme"]
    }

```

I get issues with the autoload not being able to find the vendor/autoload:

```
Warning: require(/var/www/site/docroot/vendor/autoload.php): failed to open stream: No such file or directory in /var/www/site/docroot/autoload.php on line 14

```

Whats is the best practice for placement of Drupal 8 core files?

# Answer
> 2 votes
I think this is a slight misinterpretation of the security risk.

The core/ directory needs to be in your DOCROOT; it has assets that the webserver needs to serve up (JS, CSS, and images).

The vendor/ directory should (mostly) be outside of your DOCROOT; some packages have files that shouldn't really be accessed by the webserver directly and have been the focus of recent SAs.

The exception to this are dependencies that need to be served up or be in the proper place, hence why people use the `installer-paths` to place modules, themes, and JS libraries in the right place.

While not universal, I would say that drupal-composer/drupal-project is a growing best practice, at least for starting points for websites. This will place vendor/ outside of DOCROOT, take care of the autoloader and scaffold files, and set up a sane set of `installer-paths`. Even if I am not using this directly, I look to its composer.json for inspiration.

---
Tags: 8, composer
---


# Question
Title: How can I change the selectable years in a date field?
I have a date field, `birthday`, created with the Date module. By default, the selectable years are 1900-2050. This makes no sense for birthdays so I want to change it to only show years from `1900-(current year-18)`.

How can I do this?

There is a solution for Drupal 7 but that code does not work in Drupal 8 because form\_process\_date() does not exist in Drupal 8.

This is the full error:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'form_process_date' not found or invalid function name in Drupal\Core\Form\FormBuilder->doBuildForm() (line 993 of core/lib/Drupal/Core/Form/FormBuilder.php).

```

Here is the code I'm using:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['birthday']['#process'] = array('form_process_date', 'mymodule_fix_year_range');

```

# Answer
You shouldn't need to add a `#process` to this.

The **Select List** widget is based around the `Datelist` element.

Per the docs (and I don't know why the are on that method and not `::getInfo()`. You should be able to form alter this, and change the '#date\_year\_range' key. This is a string value, which defaults to '1900:2050' (min-year:max-year). You would just need to have some logic to build it up in the proper format.
> 2 votes

# Answer
@mpdonadio♦'s answer provides the explanation. Here is the actual code I used:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_birthday']['widget'][0]['value']['#date_year_range'] = '1950:2005';

```
> 5 votes

---
Tags: 8, datetime
---


# Question
Title: How to get referring items from a Entityreference field in the opposing item list? (back reference)
Using an Entityreference field in a content type A makes it possible to reference multiple items from another content type B to it. On node teaser pages or any other Views lists you can list them additionally on each row of content item from the content type A as a sub-list of referenced items. But how can I list the reference sources the other way around automatically without using another Entityreference field on the content type B (needless double-edit)?

Example: A car (content type A) has been repaired in 3 different car service stations (content type B). So the content type "car" gets a Entityreference field to add them (items from B). When I build a list of service stations (B), I would like to see a list of the cars (A) being repared in them automatically without an additional back reference field or additional modules like CER, making things needlessly complicated in the database.

NOTE: Basically it's the behaviour we would expect from Taxonomy terms, which are also Entityreferences in Drupal 8, but they seem to have some more build in functionality to work from both sides in item lists.

# Answer
> 4 votes
At the moment I only see 2 (edit: 3) options to solve the backreferencing issue without creating SQL request duplicates:

1. Using Views Field View for nesting a list of type A nodes referencing node type B via contextual filters in the second view to filter for each items nid (possible performance issue).
2. Syncing 2 Entityreference fields from both content types and maybe automate them with Rules and using the second Entityreference field for the back reference list in Views.
3. Using the CER module (I know you said no but), I think after testing that this module is the best option at the moment if you know that you want this connection synced "fix" and not individually changed.

First would have a huge performance impact if the lists and nested lists are long. And the caching modules required to compensate it are not ready yet for D8.

Second can have other issues sinces Rules not always work flawlessly and I am not 100% sure if Rules supports the needed triggers for this approach.

EDIT: Third is my recommendation. After testing around I was quite impressed about its simpleness and working warranty. It's not as flexible as using rules, but as I sad, rules is a story of ots own. So maybe you give it another try (CER).

---
Tags: 8, entities, views
---


# Question
Title: Why `GROUP BY` in hook_views_query_alter() doesn't work?
I'm using Views 7.x-3.6 and I tried altering the `GROUP BY` clause with `hook_views_query_alter()` as below:

```
function mymodule_views_query_alter(&$view, &$query) {
    if ($view->name == "view_name"){
      $query->add_groupby('field_name');
      dpm($query);
    }
}

```

When I look in `$query`, **the `groupby` clause is correctly enabled** but **the SQL query is not affected**: the `GROUP BY` clause doesn't appear:

What I eventually did is using a Drupal core hook (`hook_query_alter()`) and it worked fine: the SQL is now affected.

```
function mymodule_query_alter(QueryAlterableInterface $query) {
  $view_name = 'view_name';
  if ($query->hasTag('views_' . $view_name)) {
    $query->groupBy('field_name');
  }
}

```

Any reason why my `hook_views_query_alter()` doesn't work? I'm wondering if there's a cleaner way to do it and.

# Answer
Use `add_field()` with `array('function' => 'groupby')` parameter.

```
$query->add_field('node', 'nid', 'node_nid', array('function' => 'groupby'));
$query->add_groupby('node.nid');

```

**Aditional information:**

After using `add_groupby` you might see the next code after `GROUP BY`:

```
GROUP BY node.nid, nid

```

See the next issue: https://drupal.org/node/1578808

To avoid unnecessary GROUP BY conditions add:

```
$query->distinct = TRUE;

```
> 12 votes

# Answer
If you look are the documentation of hook\_views\_query\_alter, I believe the query is already prepared to run. Eg, replacements have been made by the database API and its about to be sent over the wire to MySQL. Another example of hook\_views\_query\_alter usage can be seen the BTMash blog.

This being the case you no longer have a DB Query Object but the pieces of the SQL statement with expressions, variables, etc as an Array.

I dont have a query in front of me but something like the following untested code is what you want:

```
$query->groupby[0]['field'] = 'field_name';

```
> 1 votes

# Answer
This is the way it is done in views\_query\_alter; the node\_access part is not necessary.

```
function xdas_target_audience_views_query_alter(&$view, &$query) {
  $controlled_views = variable_get('xdas_target_audience_views', array(
    'landing_products',
    'promotions',
    'landing_coupons',
    'landing_coupons_belvita',
    'landing_coupons_lulu',
    'related_coupon',
    'cuponazo',
    'banner',
    'brands',
  ));
  if (in_array($view->name, $controlled_views) && $view->base_table == 'node') {
    //add node_access to views so we can control access.
    $query->add_tag('node_access');
    $join = new views_join();
    $join->construct('xdas_target_audience_boost', 'node', 'nid', 'nid');
    $query->add_relationship('xdas_target_audience_boost', $join, 'node');
    $query->add_field('xdas_target_audience_boost', 'score', 'score' , array('function' => 'max'));
    $query->add_orderby(NULL, NULL, 'DESC', 'score');
    $query->add_groupby('nid');
  }
}

```
> 1 votes

# Answer
Late to the party but this might help someone else.

In my case I was providing a list of users (using additional module Profile2) with a Taxonomy Term field (https://drupal.org/node/1808320). I was seeing multiple results I could not get rid of through the Views 3 API.

In my custom module I added:

```
/**
    Implementation of hook_views_query_alter()
**/
function MYMODULE_views_query_alter(&$view, &$query) {

  if($view->name == "provider_results_list" && $view->current_display == "page_1") {

    $query->distinct = TRUE;

    // User the provider uid to make the results distinct: using a taxonomy field for
    // keyword searches brings up multiple results.
    $query->add_field('profile', 'uid', 'provider_uid', array('function' => 'groupby'));

  }
}

```

The parameters for add\_field are

```
add_field(TABLE_NAME, FIELD, FIELD_ALIAS, array('function' => 'groupby'))

```
> 1 votes

# Answer
If you are still facing with unnecessary GROUP BY statements added to query, you could remove them in `hook_query_alter()`. I solved the issue with ordering comments by most commented parent comments for example.

So in `hook_views_query_alter()` I have:

```
/**
 * Implements hook_views_query_alter().
 */
function MODULENAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'reviews' && $query->orderby[0]['field'] == 'comment_thread') {
    $join = new views_join;
    $join->construct('comment', 'comment', 'cid', 'pid', NULL, 'LEFT');
    $query->add_relationship('c1', $join, 'comment');
    $query->add_field('comment', 'pid', 'c1_pid', array('function' => 'groupby'));
    $query->add_groupby('c1.pid');
    $query->add_orderby(NULL, 'COUNT(c1.cid)', 'DESC', 'comments_count');
    $query->distinct = TRUE;
    $query->orderby[0] = $query->orderby[count($query->orderby) - 1];
    unset($query->orderby[count($query->orderby) - 1]);
  }
}

```

I got error related to inability to group by

> comments\_count

field that is actually a result of SQL `COUNT()` function.

I ended up with this:

```
/**
 * Implements hook_query_alter().
 */
function MODULENAME_query_alter(QueryAlterableInterface $query) {
  if (isset($query->alterMetaData['view']->name) && $query->alterMetaData['view']->name == 'reviews') {
    $fields =& $query->getGroupBy();
    foreach (array_keys($fields) as $key) {
      // Remove group by statements from generated query which were actually not set in view query.
      if (!in_array($key, $query->alterMetaData['view']->query->groupby)) {
        unset($fields[$key]);
      }
    }
  }
}

```
> 1 votes

# Answer
I wondered that no one provided a real solution that just works. There is one such method that I've found here, many thanks to @b-ravanbakhsh:

```
/**
 * Implements hook_query_alter().
 */
function MODULENAME_query_alter(QueryAlterableInterface $query) {
  if (isset($query->alterMetaData['view'])) {
    if($query->alterMetaData['view']->name == 'YOUR_VIEW_NAME'){
      // also you can unset other group by critera by using, unset($query->getGroupBy());
      $query->groupBy('users.uid');
    }
  }
}

```
> 1 votes

# Answer
In Drupal 8 and thanks to graceman9 approach, it will be :

```
use Drupal\Core\Database\Query\AlterableInterface;

function MYMODULE_query_alter(AlterableInterface $query) {
  if (isset($query->alterMetaData['view'])) {
    if($query->alterMetaData['view']->id() == 'replace_by_view_machine_name') {
      // Group by UID to remove duplicates from View results
      $query->groupBy('users_field_data.uid');
      // If multilingual site, you should add the following
      // $query->groupBy('users_field_data.langcode');
    }
  }
}

```
> 1 votes

---
Tags: 7, database, views
---


# Question
Title: How to get the value of a custom field in hook_node_presave?
Using hook\_form\_alter I have added a custom field in my node creation form

```
function custom_assignments_form_alter(&$form, $form_state, $form_id) {
//print_r($form_id);exit;
if($form_id == 'node_assignment_form'){

    $lecture_options = array();
    $lecture_values = db_query("SELECT nid, title FROM `node_field_data` WHERE nid IN (SELECT entity_id FROM
                        `node__field_module` WHERE bundle='lectures' AND field_module_target_id=:tid)",
                        array(':tid' => $selectedWeek))->fetchAll();
    foreach($lecture_values AS $key => $value){
        $lecture_options[$value->nid] = $value->title;
    }
    //print("<pre>");print_r($lecture_options);exit;

    $form['field_after_lecture']['#access'] = FALSE;
    $form['field_after_lecture_tmp'] = array(
            '#title' => t('After Lecture'),
            '#required' => true,
            '#type' => 'select',
            '#options' => $lecture_options,
            //'#default_value' => print_r($form_state->getBuildInfo()['args']);exit;,
            '#weight' => 100,
            '#prefix' => '<div id="custom">',
            '#suffix' => '</div>'
    );
}}

```

How to get the value of field\_after\_lecture\_tmp in hook\_node\_presave I printed the node fields using `$node->toArray()` function. But this field is not there. In Drupal 7 I was able to access it.

# Answer
You can't get the value in the hook\_node\_presave() because this is not a node field, as you says is a custom field that you create altering the form.

In this case you need to add a custom submit handler to use the value, something like this inside the hook implementation:

```
function custom_assignments_form_alter(&$form, $form_state, $form_id) {
// ...
  if (isset($form['actions']['save_continue']['#submit'])) {
    array_unshift($form['actions']['save_continue']['#submit'], '_node_revision_delete_form_node_type_submit');
  }
// ...
}

```

And in the function you can access to the value and perform your actions

```
function _node_revision_delete_form_node_type_submit(array &$form, FormStateInterface $form_state) {
// Getting the form values.
  $field_after_lecture_tmp = $form_state->getValue('field_after_lecture_tmp');
}

```
> 2 votes

---
Tags: 8, forms, hooks
---


# Question
Title: Is there any way to tell when a user's password was changed?
A user tried to log on today and discovered that his password had mysteriously been changed. All I can assume is that he left his computer unattended and someone changed it.

Is there any way to tell *when* this happened, so as to narrow down who might have done it? I suspect the answer is "no" - I don't see a watchdog entry, and in `/var/log/mysql` all there is is an error log, not a log of queries.

Is there another place where DB queries might be logged or is there somewhere else in Drupal I could check?

# Answer
It is not possible to tell from the database it-self when user changed his password.

The user password in Drupal 7 is stored in `users` table with the following columns of interest:

* `pass` \- User's password (hashed).
* `access` \- Timestamp for previous time user accessed the site.
* `login` \- Column which tells you timestamp for user's last login.

However there are few workarounds:

* If you've got logging enabled (*dblog* or *syslog*), Drupal logs when particular user has logged in. This should point you to the IP address (whether it's different as usual).
* On live environments, periodical backups of database should be a must. Depending how often you do the backups, compare different dumps focusing on particular user and his password, for example:

```
gzcat db-dump-2017*.sql.gz | grep -w users | grep -w pass | grep specific_user

```

Note: Above command attempts to stream compressed dump of database in order to find value of `pass` column from `users` table for the given user.

Then check which database dump has the new changed password. From there you can check the logs (e.g. from `watchdog` table) for this user. Especially check IP addresses, requested URLs and authorization attempts (whether successful or failures).
> 0 votes

---
Tags: 7, users, log-messages
---


# Question
Title: How to get the vocabulary ID of a taxonomy term?
I need to get vocabulary ID by term object.Please see attched screenshot for term object.

# Answer
> 15 votes
You should be able to use the `getVocabularyId()` function on the term object like:

```
$vocabulary_id = $term->getVocabularyId();

```

See https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/function/Term%3A%3AgetVocabularyId/8.2.x.

# Answer
> 15 votes
I think we're supposed to use EntityInterface::bundle now as Term::getVocabularyId is deprecated:

> Scheduled for removal before Drupal 9.0.0. Use TermInterface::bundle() instead.

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


# Question
Title: How can I hide the "day" in a date field?
I have a date field, but I only want to collect the year and month, not the day. How can I hide the day part?

There are instructions for Drupal 7, but I am using Drupal 8.

# Answer
> 4 votes
Note that the day is required.

This means there are some difficulties:

* You need to set the value for the day field (otherwise the form will fail validation). In this example, we will set it to the 15th of the month.
* You can't use `unset()` or `#access: FALSE` because this will cause the form to have no value and fail validation.

You can do this in an `#after_build` callback.

```
function MYMODULE_form_MYFORM_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] = 'MYMODULE_date_remove_day_after_build';
}

function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#value'] = '15';
  $form['field_MYFIELD']['widget'][0]['value']['day']['#attributes']['class'][] = 'element-hidden';
  return $form;
}

```

And then in your theme .css, add this class:

```
.element-hidden {
  display: none !important;
}

```

# Answer
> 0 votes
Not sure exactly but if I understand your question correctly...

One approach might be through templating. In your template file try printing this:

**{{ content.field\_name.0.value | date('F j - h:i a') }}**

I am not sure what this would actually be, use **{{ dump(content | keys) }}** in your template file to see what array keys are available.

This method, you are able to apply the date filter to the field time value which allows you to use php date formatting... you can then render the timecode any way you want.

---
Tags: 8, forms, datetime
---


title: Programmatically use token filter

text:
# Question
Title: Programmatically use token filter
I'm attempting to use the token filter programmatically inside a .theme file like so.

```
function mytheme_preprocess_block(&$vars){
  $token = Drupal::token();
  $vars['label'] = $token->replace('[node:title]');
}

```

I looked at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21Token.php/function/Token%3A%3Areplace/8.2.x for information. However when I output $vars\['label'\] all it produces is \[node:title\] as if no replacement occurred at all. How would I programmatically initiate the token filter?

UPDATE: As a test I attempted using another method of token to make sure anything was happening at all by using `$token->scan('[node:title]');` and it did spit out

> array(1) { \["node"\]=\> array(1) { \["title"\]=\> string(12) "\[node:title\]" } }

So I know I invoked the token class properly at least

UPDATE: It appears that the token replace was working it just didn't recognize \[node:title\]. Using \[site:name\] did produce the expected result. How would I be able to get \[node:title\] to work? Do I need to supply it with that data?

# Answer
> 4 votes
Data about the node needed to be supplied as a parameter to the replace method. It worked once I used

```
$node = \Drupal::routeMatch()->getParameter('node');
$vars['label'] = $token->replace($vars['label'],['node' => $node]);

```

---
Tags: 8, tokens
---


# Question
Title: What is the cause for this Symfony exception after upgrading core to 8.4.0?
I have upgraded to Drupal 8.4.0 (from 8.3.7) with composer, using webflo/drupal-core-strict to maintain the proper core dependencies.

When I run drush updb (with drush 8.1.15) to update the database, I get the following error:

```
Symfony\Component\DependencyInjection\Exception\RuntimeException: Constructing service "validation.constraint" from a parent definition is not supported at build time. in /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php on line 847 #0 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(451): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\DefinitionDecorator), 'validation.cons...')
#1 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(957): Symfony\Component\DependencyInjection\ContainerBuilder->get('validation.cons...', 1)
#2 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(954): Symfony\Component\DependencyInjection\ContainerBuilder->resolveServices(Object(Symfony\Component\DependencyInjection\Reference))
#3 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(1145): Symfony\Component\DependencyInjection\ContainerBuilder->resolveServices(Array)
#4 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(918): Symfony\Component\DependencyInjection\ContainerBuilder->callMethod(Object(Drupal\Core\Config\TypedConfigManager), Array)
#5 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(451): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), 'config.typed')
#6 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(957): Symfony\Component\DependencyInjection\ContainerBuilder->get('config.typed', 1)
#7 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(954): Symfony\Component\DependencyInjection\ContainerBuilder->resolveServices(Object(Symfony\Component\DependencyInjection\Reference))
#8 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(879): Symfony\Component\DependencyInjection\ContainerBuilder->resolveServices(Array)
#9 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(451): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), 'config.factory')
#10 /var/www/docroot/modules/contrib/libraries/src/LibrariesServiceProvider.php(29): Symfony\Component\DependencyInjection\ContainerBuilder->get('config.factory')
#11 /var/www/docroot/core/lib/Drupal/Core/DependencyInjection/Compiler/ModifyServiceDefinitionsPass.php(30): Drupal\libraries\LibrariesServiceProvider->alter(Object(Drupal\Core\DependencyInjection\ContainerBuilder))
#12 /var/www/vendor/symfony/dependency-injection/Compiler/Compiler.php(120): Drupal\Core\DependencyInjection\Compiler\ModifyServiceDefinitionsPass->process(Object(Drupal\Core\DependencyInjection\ContainerBuilder))
#13 /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php(573): Symfony\Component\DependencyInjection\Compiler\Compiler->compile(Object(Drupal\Core\DependencyInjection\ContainerBuilder))
#14 /var/www/docroot/core/lib/Drupal/Core/DrupalKernel.php(1307): Symfony\Component\DependencyInjection\ContainerBuilder->compile()
#15 /var/www/docroot/core/lib/Drupal/Core/DrupalKernel.php(884): Drupal\Core\DrupalKernel->compileContainer()
#16 /var/www/vendor/drush/drush/lib/Drush/Drupal/DrupalKernel.php(61): Drupal\Core\DrupalKernel->initializeContainer()
#17 /var/www/docroot/core/lib/Drupal/Core/DrupalKernel.php(466): Drush\Drupal\DrupalKernel->initializeContainer()
#18 /var/www/vendor/drush/drush/lib/Drush/Boot/DrupalBoot8.php(146): Drupal\Core\DrupalKernel->boot()
#19 /var/www/vendor/drush/drush/includes/bootstrap.inc(354): Drush\Boot\DrupalBoot8->bootstrap_drupal_full()
#20 /var/www/vendor/drush/drush/includes/bootstrap.inc(473): drush_bootstrap(5, 6)
#21 /var/www/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(59): drush_bootstrap_to_phase(6)
#22 /var/www/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#23 /var/www/vendor/drush/drush/drush.php(12): drush_main()
#24 {main}
Drush command terminated abnormally due to an unrecoverable error.   [error]
Symfony\Component\DependencyInjection\Exception\RuntimeException: Constructing service "validation.constraint" from a parent definition is not supported at build time. in Symfony\Component\DependencyInjection\ContainerBuilder->createService() (line 847 of /var/www/vendor/symfony/dependency-injection/ContainerBuilder.php).

```

Could anyone point me in the right direction to track down this error?

# Answer
About Drush 8 the release notes of Drupal 8.4.0 are a bit misleading. Drupal 8.4 + Drush 8 (8.1.12 or higher) work only globally, but you are using Drush locally (in the vendor directory), so you need Drush 9:

```
composer require drush/drush:~9.0

```

BTW using Drush 9 is the recommend way. Despite that it is not stable yet, it's nonetheless the more stable solution, because it uses the same Symfony version as D8.4, while Drush 8 still has the old Symfony version of D8.3 to maintain backward compatibility.
> 2 votes

# Answer
I am experiencing the same problem, and opened an issue on drupal.org here: https://www.drupal.org/node/2915332

As my comment (#4) on drupal.org suggests, I think this is a Drupal (or contrib) bug that has nothing to do with Drush. I believe it will need to be fixed by the Drupal developers, but you can test my workaround below (please note the WARNING):

## Environment

my site is running on Pantheon with PHP 7.0.

## Background

I initiated the site update via Pantheon's interface, which I believe is running Drush on the back end to handle this operation. Once I ran into this issue after trying to update, any/all drush commands (including cache clearing) result in the same error. The problem is that the application is unable to bootstrap itself and spin up, thus it cannot fulfill any requests (web, Drush, or otherwise). As far as I can tell, the system is failing to spin up because it is choking on the core Drupal configuration in `core/core.services.yml` that I referenced at the end of my issue.

When the Kernel is booting, it is instantiating the `config.typed` configuration, which in turn calls the `validation.constraint` which is configured with a `parent` attribute, making it a configuration instance of `DefinitionDecorator` instead of `Definition`. Consequently, the `createService()` method on `ContainerBuilder` is choking right off the bat with:

```
if ($definition instanceof DefinitionDecorator) {
    throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id));
}

```

As the message suggests: `Constructing a service from a parent definition is not supported at build time.`

The problem was introduced in this commit when `@validation.constraint` became a dependency of `config.typed` via the `calls` attribute added in the commit:

```
config.typed:
    class: Drupal\Core\Config\TypedConfigManager
    arguments: ['@config.storage', '@config.storage.schema', '@cache.discovery', '@module_handler', '@class_resolver']
    tags:
      - { name: plugin_manager_cache_clear }
    calls:
      - [setValidationConstraintManager, ['@validation.constraint']]

```

## Workaround TEST

Edit `core/core.services.yml` and comment out the calls attribute for the `config.typed` block as follows:

```
config.typed:
    class: Drupal\Core\Config\TypedConfigManager
    arguments: ['@config.storage', '@config.storage.schema', '@cache.discovery', '@module_handler', '@class_resolver']
    tags:
      - { name: plugin_manager_cache_clear }
    #calls:
    #  - [setValidationConstraintManager, ['@validation.constraint']]

```

Now go to `[your_url]/update.php` in a browser. There will be pending database updates that need to run. That's it.

# WARNING

I have no idea what the repercussions of the configuration change above are. **I don't suggest anyone do this in production**. It's just a demonstration of what is causing the problem and how to hack around it. As far as I can tell, this is a Drupal bug stemming from an improper usage of the new Symfony configuration standard. I have no idea why/how this wasn't caught in QA before `8.4.0` was released, but I am guessing it is because only a certain set of circumstances cause the bootstrap process to instantiate `config.typed`, otherwise everyone who updated to `8.4.0` would be experiencing this problem, and no QA would have passed because all `8.4.0` instances would be choking in this way. I will look into what circumstances in my environment trigger `config.typed` and report back if I find anything.

# EDIT: More Info Below

My testing indicated that my boot strapping process is instantiating configured serviced in this order:

1. `config.factory`
2. `config.typed`
3. `validation.constraint`

Some further inspection of the stack trace suggests that `config.factory` is being instantiated in `code/modules/libraries/src/LibrariesServiceProvider.php`. That's coming from the Libraries module, and it looks like **@Em D** is experiencing the same call (from OP's stack trace):

```
#10 /var/www/docroot/modules/contrib/libraries/src/LibrariesServiceProvider.php(29): Symfony\Component\DependencyInjection\ContainerBuilder->get('config.factory')

```

There is a working but not "official" Drupal 8 release. I have it installed because I am using Juicebox module, which requires it.

I've tested putting the original `core/core.services.yml` file back in place, disabling Juicebox, disabling Libraries, then executing a drush cache clear, and the problem no longer occurs. So, this update problem doesn't affect all systems but does affect those with Libraries module installed.

The question now is, is this really the fault of Libraries module, or is there still an inherent problem with the new `config.typed` configurations use of validation.constraint in its new calls attribute?

## How to Reproduce This Error

If you are on a version below `3.4.0`:

1. install Libraries module
2. initiate update to `3.4.0` using Drush or whatever method you choose

If you are already on version `3.4.0`:

1. install Libraries module

## Workaround/Solution:

Disable Libraries module. This is only a "solution" if you aren't actually dependent on that module. If you downloaded it at some point just to test it, never used it, and forgot to delete it, then disabling it should resolve your problem. If, however, you, like me, are dependent on the Libraries module (or one of your other dependencies is), then uninstalling Libraries and/or the dependent parent module may delete views and other configurations/records/data. You should be sent to a warning page after clicking "Uninstall" if this is the case.

# UPDATE

As it turns out, this might only be a problem with Libraries release 8.x-3.x-dev (2016-Nov-13), not the current 8.x-3.x-dev release. Digging more into it now. OP, you could try updating Libraries to the latest 8.x-3.x-dev release before running the 8.4.0 update.

# FINAL UPDATE

My Solution:

1. restore backup
2. update Libraries Module from 8.x-3.x-dev (2016-Nov-13) to latest 8.x-3.x-dev
3. Get Pantheon support to restart my webstie container to get around Fatal Error cause by step above (more)
4. run update.php for good measure
5. update core to 8.4.0
> 1 votes

---
Tags: composer
---


# Question
Title: Cannot import Paragraph based Feature into new site
Perhaps someone with a bit more Features expertise can help me here.

I have a Drupal site with 25 or so Paragraph types that I would like to export (one by one) to its own contained Feature.

I installed the latest version of Features, and created a new bundle called Paragraphs. In this new bundle, I enabled Paragraphs as a Base Type so they are an exportable option.

I go back to the main Features admin, and click "Create new feature". I fill out the basic info here, the name of the feature, then I select the Paragraph Type I want to export and wait for all of the required dependencies to auto populate. I finish the export by clicking on "Write" which produces the module folder.

In the new Drupal site I want to import it to, I see it in the list of Features. When I go to enable the module, I get an error like:

> Error importing field.field.paragraph.text\_editor.field\_rich\_text : Attempt to create a field field\_rich\_text that does not exist on entity type paragraph.

Except... this Feature should be introducing this field into the application and install it. The Paragraph just has a long text field for CKEditor, and there is no `field.storage.paragraph.field_rich_text.yml` file that is exported. Yet, `field.storage.paragraph.field_rich_text` is listed as a config dependency in the same said Feature.

Did I miss a step here? I basically want to export my Paragraph types as if they were Node types. I want to install them into a new Drupal installation without wiring them to any reference fields or Node types - I want to do that later.

Why am I getting errors like `Attempt to create a field field_rich_text that does not exist on entity type paragraph.`? I get a similar error for each Paragraph I try to enable, which are all made up of basic fields and nothing special.

Note: it *looks* like the auto detection doesn't quite work. For example, if I pick one of the Paragraphs from the list of non-exported Features on the overview page, the field storage definitions that are marked as a dependency in the output are NOT selected for being exported here.

I started over and removed all the exported Features, and created a new Feature. This time, when I picked the paragraph type, it still did not include the field storage definition for the field that is being bundled. When I selected it, exported it, this time it enabled on the new site, no error.

What is the proper way to do this? Do I have to go through one by one and simply ensure the field storage(s) are exported myself?

# Answer
> 0 votes
My best answer to this question is: Features is awesome but a little buggy, or seemingly so, due to field and field storage dependencies. The best solution I have found in Drupal using features and all these export issues is to create a content type where you create ALL your field base instances. I always call mine xxxFields. Then in all other content types, always add an "existing" field. really all this is doing is helping with user error. I have used features from 7 and now into 8, and I find that most issues arise through configuration of numerous content types which share fields, which creates dependency issues when trying to export features modules.

I believe your specific issue may be that that module is trying to create itself but has a dependency for a field base and field storage configuration that was created in another content type.

---
Tags: 8, features, paragraphs
---


title: get images URL in a twig template

text:
# Question
Title: get images URL in a twig template
I have two content types, the first is **Homepage** and the second is **SLider**. The **Slider** content type has multiple fields like title, ink, and image. In the **homepage** content type, I have an entity reference field referring to the **slider** content type with multiple selections. I've created a template in my custom theme as `node--home-page.html` and want to get the sliders fields values, All is okay with me except the image. I cannot get the image URL. My code:-

```
{% for slide in node.field_hoeme_slideshows %}
        {{ kint(slide.entity.field_home_slide_cta.uri) }} {# This is working #}
        {{ kint(slide.entity.title.value) }} {# This is working #}
        {{ kint(slide.entity.field_home_slide_snippet.value) }} {# This is working #}
        {{ kint(slide.entity.field_home_slide_image) }} {# ****** This is not working *****#}
{% endfor %}

```

# Answer
> 1 votes
As an alternative configuration using Field Collections. Instead of using two content types and a field reference...

```
{% for item in content.field_slide %}
<a href="{{ item.getFieldCollectionItem().field_link.0.url }}">
    <figure class="my-class {% if loop.first %}{{ 'first-class' }}{% endif %}  {% if loop.last %}{{ 'last-class' }}{% endif %}">

        <div class="my-image-wrapper">

            <img src="{{ file_url(item.getFieldCollectionItem().field_slide_image.0.entity.uri.0.value) }}" alt="{{ item.getFieldCollectionItem().field_slide_image.0.alt }}" title="{{ item.getFieldCollectionItem().field_slide_image.0.title }}" />

        </div>

        <h2>{{ item.getFieldCollectionItem().field_h2.0.value }}</h2>
        <figcaption>{{ item.getFieldCollectionItem().field_p.0.value }}</figcaption>

    </figure>
</a>
{% endfor %}

```

This is off the top of my head so double check the code.

Then you just create a field collection field on the home page content type called slide. Go to field collections, select "slide" and add the fields: link, slide\_image, h2, and p.

# Answer
> 0 votes
```
{{ file_url(content.field_image['#items'].entity.uri.value }}

{{ file_url(content.field_image['#items'].entity.uri.value | image_style('1440px')) }}

```

Im not sure of your current setup.... but you might need to try something like "item in node.field\_home\_slideshows\['#items'\]"

(note: you spelled home, hoeme)

inside do...

```
file_url(item.entity.uri.value)

```

This is twig valid:

```
{% for item in content.field_image['#items'] %}
 {{ file_url(item.entity.uri.value }},
{% endfor %}

```

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


title: One Page User Profile

text:
# Question
Title: One Page User Profile
How do I make a one-page user profile? I want to include wishlist, cardonfile and addressbook from commerce, and render all the data already inserted into the profile, and edit/create forms on the individual user page.

Thanks!

# Answer
To keep this convo going even though I do not have a definitive answer...

I feel that is a pretty big question with a fair bit of config and templating even... So my short answer would be Views and/or Blocks. Depending on your needs maybe you could do just a views page with filters and relationships as you need populated with commerce entities and content types. Maybe you need views blocks, blocks, and content types with template files to render everything on the same page. My gut just tells me that's the pace to start. Views is Drupal cores way of bringing many things together.
> 0 votes

---
Tags: commerce
---


# Question
Title: What is the best procedure to upload sites folder from Locahost to live server?
I've had problems on and off with executing this task, using D7.

I create sites on localhost , then I ftp the files to live server.

FTPing the whole sites folder doesn't work, sometimes causes errors, how should I upload the sites folder properly?

So what I have done is upload the sites/all and sites/default/files separately, and I take out the .htacess file from the sites/default/files folder and keep the original one in there...

But that's a pain in the ass, shouldn't it simply be delete the complete sites folder on the server and FTP the one from locahost?

# Answer
> 2 votes
Instead of using FTP, consider using Git over SSH. Drupal.org has documentation on using Git with Drupal 6, 7, and 8. Note that for this, your webhost will need to support SSH, which some of the cheapest do not.

If you're using Drupal 8, consider using Git with Composer.

If you need some help figuring out how all this works, consider making a test site and a free account on one of the Drupal-dedicated hosts like Pantheon or Acquia. (Disclaimer: I have sites on Pantheon, but here I'm just recommending trying a free account to see how the Git flow works.)

# Answer
> 2 votes
I personally prefer rsync for transferring files other than code between local and live servers or between the servers themselves. the advantage is that rsync checks if the file already exists and does not repeat the transfer if it exists.

Git is good if you are transferring code based files and it should be part of your development and deployment strategy for all code.

---
Tags: files
---


# Question
Title: How to ensure emails are sent only once to users in a Views Block Operations (VBO) list?
I created a view which is a list of comments made by users to a particular node.

I then created a rule which triggers upon event "when a new comment is saved" The action is to load the view i created, loop through the list and then send an email to all the users who have previously posted comments.

My challenge is that it sends emails to the users based on the number of times they appear in the list. So for example a user who has made 3 comments to the node will get three (3) emails each time a new comment is saved.

I have tried using the Distinct query. It did not work. I also installed the Views distinct module and selected the filter option. This filtered the list to one value each, but mails were still sent multiple times to people who had commented more than once.

Please is there a way to ensure emails are sent only once irrespective of times user has commented to the node/appears on the list?

# Answer
You can adapt my answer with a "trick filed" on your content type in this (last) answer. Update "trick field" when your mail is sent the first time. Why is my rule that reacts on event "After updating an existing user account" firing twice? Then hide "trick field" modifying your "form-id" and field name with this solution (2nd answer) Is there a way to prevent a user from seeing a field on their user profile page?
> 0 votes

# Answer
I suggest you rework this part of the Rules logic you tried:

> I then created a rule which triggers upon event "when a new comment is saved" The action is to load the view i created, loop through the list and then send an email to all the users who have previously posted comments.

Here is a blueprint to actually do so:

* Create a new variable, which you define as a "list of users" (so that you can use this list later on to "*loop through the list*", as in the quoted text above).
* Replace that "send an eMail" (within your existing Rules loop) by an action to "**Add an item to a list**" (using the list you created via that new variable). When doing so, you make sure to set "ENFORCE UNIQUENESS" to `true`, so that you "*only add the item to the list if it is not yet contained*" (see where I'm going?).
* After the Rules loop is finished, the value of the new variable will contain a list of *unique* users. So just add another Rules loop at the end, to iterate of each of the users in that list. And guess what you can then do in this additional Rules loop ... indeed: send an email to each of those users, similar to what you already have in the rule you tried. The difference being that now each user is only contained 1 time in that list, so they will only receive 1 eMail.

***Easy, no***?
> 0 votes

---
Tags: 7, views, rules, emails
---


# Question
Title: How to replace url of taxonomy label link?
I want to alter url of a field and his display. The field is a taxonomy label with link to the entity. The default url is : `taxonomy/term/{tid}`

I wanto to chage with : `my_specific_page?technologie={tid}` (used to prepopulate exposed filter)

I tried with :

```
function MYTHEME_preprocess_field__field_technologie(&$variables, $hook){
  $element = $variables['element'];

  foreach ($variables['items'] as $item) {

    $route_name = 'entity.node.canonical';
    $params     = 39;

    $options = [
      'query' => ['technologie' => 27],
    ];
    $url = Url::fromRoute($route_name, array('node' => $params), $options);

    $item['content']['#url'] = $url;
  }
}

```

I think i need to replace routeName attribut, but how ?

Content type : "manage field"  Content type : "manage display"  Kint result $variables\['element'\] \[\]

# Answer
I found solution :

```
function MYTHEME_preprocess_field__field_technologie(&$variables, $hook){
  $element = $variables['element'];

  foreach ($variables['items'] as $index => $item) {

    $route_name = 'entity.node.canonical';
    $params     = 39;
    $tid = $item['content']['#options']['entity']->id();

    $options = [
      'query' => ['technologie' => $tid],
    ];

    $url = Url::fromRoute($route_name, array('node' => $params), $options);
    $variables['items'][$index]['content']['#url'] = $url;
  }
}

```
> 3 votes

---
Tags: 8
---


title: Alter field inside fieldset

text:
# Question
Title: Alter field inside fieldset
I have created form using Drupal 8 Webform.I have created fieldset and fields.But i couldn't add or alter fields inside fieldset using hook\_form\_alter.I can add fields outside of fieldset using form alter.How can i alter fields inside fieldset?

# Answer
> 0 votes
Finally i got the answer. In order to alter Drupal 8 webform we can use code like this

```
$form['elements']['field_name']['#title'] = t('Your Name');

```

I think same method can follow to alter other field attribute.

---
Tags: webforms
---


title: How do I change language for a page?

text:
# Question
Title: How do I change language for a page?
How do I change language from `<html lang="en">` to `<html lang="en-GB">`?

# Answer
Change default language to English on this page `/admin/config/regional/language`
> 2 votes

---
Tags: 8
---


# Question
Title: Why do I get a "Unauthorized" error even though the user is logged-in?
I am trying to programmatically log in a user in a custom module.

The code I am using in mymodule.module is the following.

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#validate'] = array('user_login_name_validate', 'mymodule_login_validate', 'user_login_final_validate');
  }
}

function mymodule_login_validate($form, &$form_state) {
  global $user;
  $username = $form_state['values']['name'];
  $password = $form_state['values']['pass'];

  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL, "http://localhost/MYAPI/oauth/authenticate");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS,"username=" . $username . "&grant_type=password");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Basic xxxxxxxxxxxxxxx"));

  // receive server response ...
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $server_output = curl_exec ($ch);
  curl_close ($ch);
  $postData = drupal_json_decode($server_output);
  $count = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' =>$username))->fetchField();

  if ($count == 0) {
    if (!empty($postData['access_token'])) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,"http://localhost/MYAPI/rest/user/1/get_user_details");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Bearer ".$postData['access_token']));

       // receive server response ...
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       $server_output = curl_exec($ch);
       curl_close($ch);
       $postData = drupal_json_decode($server_output);
       $resRoleArr = $postData['userDetail']['role'];
       $resMail = $postData['userDetail']['email'];
       $roleArr = user_roles();
       $common_roles = array_intersect($resRoleArr,$roleArr);

       if (count($common_roles) > 0) {
         user_external_login_register($username, 'mymodule');
         $user_fields = [
           'pass' => $password,
           'status' => 1,
           'mail' => $resMail,
           'init' => $resMail,
           'roles' => [DRUPAL_AUTHENTICATED_RID => 'authenticated user'],
         ];

         user_save((object) ['uid' => $user->uid], (array) $user_fields);
         $account = user_external_load($username);
         $form_state['uid'] = $account->uid;
         if ($role = user_role_load_by_name($common_roles)) {
           user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
         }
       }
     }
   }
   else {
     user_login_authenticate_validate($form,$form_state);
   }
 }

```

As you can see I am trying to login an user externally where it's credentials coming from a REST API.

Before to externally log in, I check if the user already exists in the database. if it doesn't exist, I use `user_external_login_register($username, 'mymodule')`; if it exists, I use `user_login_authenticate_validate($form,$form_state)`.

Though I am able to successfully log in the user in both the cases, I am getting an *Unauthorized* error.

What could the issue be?

I am using Drupal 7.56.

# Answer
> 0 votes
Below code might help you login-in with current user:

```
function mymodule_user_login_cred($username, $password)
{
  if(user_authenticate($username, $password))
  {
    $user_obj = user_load_by_name($username);
    $form_state = array();
    $form_state['uid'] = $user_obj->uid;
    user_login_submit(array(), $form_state);
    return true;
  }
  else
  {
    return false;
  }
}

```

---
Tags: forms, users
---