# Question
Title: Users are getting spontaneously logged out
Every so often, my users get logged out, and are unable to log back in without doing the "forgot your password" thing (which works fine). I've put some watchdog statements into core to try to see what's going on, and, while I'm hardly expert in the ins and outs of the Drupal login process, I can tell that, in `_password_crypt()`, down in password.inc, things make it all the way through to the comparison of the hashed entered and stored passwords, where it fails. This is perhaps because, in checking the database, the users' values for PASS have changed relative to what I saw there when the users were able to log in successfully.

Some other details:

* Yes, I'm up to date on patches (Drupal 7.15, and up-to-date versions of contrib)
* System and browser caches have been cleared multiple times.
* The site is under apache-level password control, and I've confirmed from the log files that nobody from the outside world is sneaking in. So there's no funny business there.
* There don't seem to be any exact time aspects to this, but I can typically run, stay logged-in for a day or so before getting logged out.
* I'm running the Twitter Bootstrap theme, and I am also using the Less module for CSS generation. Both seem to work fine.
* I've experimented with setting `$base_url` and `$cookie_domain` in the settings file; neither seem to have much effect on the problem, either set or unset.
* Because of the watchdog statements I added (see above), I've been able to see that `_password_crypt()` is running at times when I wouldn't have expected it to be running (like, not in response to a user's logging in). Checking `user->pass` in the database, I found that at least one of the users' entries was no longer what it was after the user set the password after getting logged in through the login link. When this happened, that user was still logged into a browser, and he was still able to function as that logged-in user. However, once he logged out, he couldn't log back in without requesting a new password. More system tracing is underway.

This is seriously killing me; I've worked with Drupal a lot, and have never seen anything like this. Can anybody offer some thoughts on this?

# Answer
> 1 votes
OK, I think I've got this figured out:

As part of the siteI need to be able to programmatically set user field values -- what used to be called "profile values" in Drupal 6. I looked around for some ways of doing that, and found a possible solution at http://drupal.org/node/1047600#comment-4094988, which recommends something like this:

```
$existing = user_load($uid);
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($existing, $edit);

```

The instrumentation I did showed user\_save was the guy calling \_password\_crypt(). My belief is that, somewhere along the way (either the method itself or the way I was using it), my call to user\_save() was trashing/regenerating user-\>pass, leaving me in my unfortunate state.

So: I'm now doing the field-saving stuff in a way that doesn't involve user\_save (some day I'll figure out this new entities stuff, but, in the meantime, I'm just bashing values into the database) and, so far, I'm staying logged in. Hopefully this will solve the problem; thanks to all for your attention.

# Answer
> 1 votes
## TL;DR

The solution is to unset the `pass` array element. Added the necessary extra line to your code:

```
$existing = user_load($uid);
$edit = (array) $existing;
unset($edit['pass']); // added line
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($existing, $edit);

```

## Explanation / Justification

The Drupal(7) API for `user_save()` (function user\_save (Drupal 7.x)) starts off with the following code :

```
if (isset($edit['pass']) && strlen(trim($edit['pass'])) > 0) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}
else {
  // Avoid overwriting an existing password with a blank password.
  unset($edit['pass']);
}

```

This part show clearly what the necessary solution is : **`if (isset($edit['pass'])`** (the rest of the code is interesting to see at least once, fyi :).

Neograph734 had the correct answer in his comment, but because of the conflicting answers posted I felt this needed a decent explanation and justification.

## Extra info

The reason why the answer by aaronbauman is not correct is that the `original` object property serves mainly as comparison to see what fields have been updated. If `original` is not set by the user in his custom code, the `user_save()` function will set this value :

```
// Load the stored entity, if any.
if (!empty($account->uid) && !isset($account->original)) {
  $account->original = entity_load_unchanged('user', $account->uid);
}

```

If you want to change the password, the new value will be hashed at the start of the `user_save()` function with the code shown above. The new hash will be different from the hash contained in the `original`, triggering the following code later in the same function :

```
  // If the password changed, delete all open sessions and recreate
  // the current one.
  if ($account->pass != $account->original->pass) {
    drupal_session_destroy_uid($account->uid);
    if ($account->uid == $GLOBALS['user']->uid) {
      drupal_session_regenerate();
    }
  }

```

# Answer
> 0 votes
Is this happening when viewing a particular page? If so, check any function using `$user` for storing any data other than the global `$user`.

# Answer
> 0 votes
See lines 546 - 551 of user.module:

```
// If the password changed, delete all open sessions and recreate
// the current one.
if ($account->pass != $account->original->pass) {
  drupal_session_destroy_uid($account->uid);
  if ($account->uid == $GLOBALS['user']->uid) {
    drupal_session_regenerate();
  }
}

```

So, setting $account-\>original before calling user\_save() should fix this for you:

```
$existing = user_load($uid);
// LINE ADDED:
$existing->original = $existing;
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($existing, $edit);

```

For me this was happening when i called user\_save during cron.

---
Tags: users
---


# Question
Title: How to count entity references from same field in different entity types?
I have three entity types:

* Company
* Team (has field\_company which is an entity reference to Company)
* Employee (also has field\_company, and field\_team which is an
optional entity reference to Team)

The idea is that all Employees are at least part of a Company, and possibly part of a Team within that Company. Using the Reference Field Option Limit module I have limited the options shown for field\_team to only show Teams for the selected Company.

So far so good.

Now I want to create a table view with the following columns:

* Company Name
* Team Count
* Employee Count

I have created two relationships to referencing entities for field\_company, and created a type filter for their types (Employee and Team). The problem is that Companies with no Teams, or no Employees are filtered out.

Any help with solving this deceivingly simple problem would be greatly appreciated!

# Answer
> 1 votes
Firstly, create a users view of the format: table with aggregation options with the following fields: \- Company ref. \- Team ref. \- User name. Then go into the table's settings and add a **group and compress** function to the first field, and **count** to the others. Optionally you can use the **tally members** function and you'll get team names with counts displayed between parenthesis.

Secondly,.. well this is simple but depends on how much you are comfortable with php.

1. Create a views\_preprocess\_view (either that or \_views\_pre\_render) function in your theme or in a custom module.
2. Install and enable devel and use dsm() in your function to print the resulting array of your view.
3. Use entity field query to get a list of your companies.
4. Compare your views results array with the entity field query results to figure out what is missing from the list.
5. Add it to the view with 0 or dashes for counts.

# Answer
> 0 votes
You should use **Aggregation** in your view and no filter. Use columns *nid* only and aggregate the fields. Then **group results** by company first, then team. Tell me if you need further precisions.

# Answer
> 0 votes
There is only one field at play here, Company Reference. And you want the count per node type of items using that field to reference a company.

Very simple if the field for referencing the company were called different things e.g `employee_company_reference` and `team_company_reference` but not easy when they are the same as you can't filter for node type per column.

There is however ( as always ) a module for Drupal that counts the incoming references and they can be filtered by node type (with applied patch) then you just create a view of all companies and add the two reference count fields, one for company ref filtered by teams, one for company ref filtered by employee.

So either use separate fields for your references and create a normal aggregations -\> count view. OR install and patch this module : https://www.drupal.org/node/2035601

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


# Question
Title: Code to take quiz again on the next day after user is failed
In drupal 6, I had a requirement to enable the users to take the quiz on the next day if they failed and from somewhere I got the following code to make that work. They added one more variables, `time_end` and used `strtotime('today')`

But now I upgraded to Drupal 7 and code for the same a little bit changed and I couldn't make that work. I am looking forward to getting help to achieve it. I am using quiz quiz-7.x-4.0-rc1

***Drupal 6 Original lines***

```
// Check to see if this user is allowed to take the quiz again:
  if ($quiz->takes > 0) {
//   $query = "SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = %d AND nid = %d";
//   $taken = db_result(db_query($query, $user->uid, $quiz->nid));

```

***Drupal 6 Changed lines*** (only first two lines. after that code remains the same except drupal\_set\_message.)

```
     $query = "SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = %d AND nid = %d AND time_end > %d";
        $taken = db_result(db_query($query, $user->uid, $quiz->nid, strtotime('today')));

    $allowed_times = format_plural($quiz->takes, '1 time', '@count times');
    $taken_times   = format_plural($taken, '1 time', '@count times');

```

***Drupal 7 Original lines.***

```
  // Check to see if this user is allowed to take the quiz again:
  if ($quiz->takes > 0) {
    $taken = db_query("SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $quiz->nid))->fetchField();
    $allowed_times = format_plural($quiz->takes, '1 time', '@count times');
    $taken_times   = format_plural($taken, '1 time', '@count times');

```

Full drupal 7 code is available here DrupalContrib

# Answer
> 0 votes
I could find a solution. It's actually pretty simple. But I don't know whether this is the right way doing it. Just change `$taken` like below. Then anybody can retake the test on the next day. Thanks to all for the support.

```
$taken = db_query("SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = :uid AND nid = :nid AND time_end > :time_end", array(':uid' => $user->uid, ':nid' => $quiz->nid, ':time_end' => strtotime('today')))->fetchField();

```

---
Tags: 7, quiz
---


title: SSL errors - .well-known

text:
# Question
Title: SSL errors - .well-known
I am seeing lot of SSL errors after enabling SSL for my site. Following is the common error related to the SSL configuration:

```
AH01797: client denied by server configuration: /var/www/xxxxxx/.well-known

```

Is this something related to any settings in our Drupal folder like creating "**.well-known**" folder or adjusting .htaccess settings or is it related to the Apache settings?

# Answer
> 1 votes
That folder is needed by LetsEncrypt and is nothing to do with Drupal. For some details elsewhere on the SO network see https://serverfault.com/questions/796745/letsencrypt-do-i-need-to-keep-well-known-accessible-for-certificate-renewal

---
Tags: 7, .htaccess, ssl
---


# Question
Title: Implementing a secure confirmation page for an entity form (D8)
I have a custom entity that is used for user submissions. Anonymous users will be able to submit confidential information using the entity add form. After submission I want to show some kind of confirmation page (Thank you for submitting etc.), but I'm not sure what is the best way to achieve this. The user should also receive a similar confirmation by email.

I was thinking of simply adding a view mode `confirmation` to the entity and have the form redirect to that page on submit, but I am concerned about access control here: visitors would be able to view other user's submissions, if they simply try random entity ids. Is there a way to restrict access to visitors who just submitted the form?

# Answer
In drupal there are several way to do the same thing. What I suggest in this case (certainly different for another person) use a small custom module with Cookies or Session.

1. Create a custom module.
2. Add an extra submitter.

* Save the new USER ID on session, cookie ...
    * Redirect to the page (Ex : `$form_state->setRedirect('your.module.route.name');`)
3. Create a small dynamic custom page (Like : http://www.drupal8.ovh/en/tutoriels/5/create-a-simple-module-for-drupal-8-step-2-create-simple-page)

* Get the USER ID from session, cookie ...

You can change the confirmation mail template from back office.
> 2 votes

---
Tags: forms, 8, entities, users
---


# Question
Title: Override display of content type using Views
How can I use the Views module to override the output of a content type's display?

So that when a user visits a page/node created with this content type, it renders a view instead

# Answer
> 2 votes
Use Panels instead, are designed for this very reason, and more.

Alternatively do this: Create a new node display (`admin/structure/types/manage/node_type/display`) with all fields you want and in Views, below "Format" there is a "Show" option, change it to "Rendered entity" and choose the node view you have created. The downside of this method is that all views advantages like: "Rewrite results", "Style settings" etc are not available, ds or preprocess functions should lift this weight if need it.

---
Tags: views
---


# Question
Title: How to add web app icon png to root document folder?
> To specify an icon for the entire website (every page on the website), place an icon file in PNG format in the root document folder called `apple-touch-icon.png`

Exactly how do I do this in Drupal 8?

Yes, my site adds lots of different touch icons to the `html.html.twig` template in an assortment of different sizes for Android, Apple, and MS Tiles but all this does not have precisely the effect I want for my web app. For further info see Apple docs here.

# Answer
> place an icon file in PNG format in the root document folder called apple-touch-icon.png

Literally that - put a file called apple-touch-icon.png in your web root. Drupal doesn't affect static files, it won't interfere.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: From time to time, the system does not find a file that exists
From time to time (1 in 20 pages or so), I receive the following Drupal error:

```
Warning: file_get_contents(/sites/all/themes/MYTEMPLATE/lightGallery/dist/js/lightgallery.js):
failed to open stream: No such file or directory in _locale_parse_js_file()
 (line 1488 of /home/[MACHINE_NAME]/domains/[DOMAIN_URL]/public_html/includes/locale.inc).

```

The folder has permissions, it works perfectly, but the error message is persistent. I don't know why it happens and how to avoid it.

# Answer
The problem was traced back to a call to `drupal_add_js` with relative URLs. I have added a prefix of **drupal\_get\_path** and the problem has disappeared for ever; it seems sometimes Drupal did not find the file because it thought it was in another location, but later it found it. This is why clearing the cache reproduced the problem. With the absolute path, problem is vanished.
> 0 votes

---
Tags: 7, files
---


# Question
Title: Import CSS stylesheet only for specific content type?
I want to use `materializeCSS` for my `Blog` content type. Problem is, when I import the stylesheet (I have set up my content type to process all HTML tags), it does not affect only the area of content of that content type, but it "leaks" to the rest of the theme, and changing overall theme look where CSS classes overlap (like default styling of H2 element in Materialize changes the whole look of the theme). Is there a way/module to have imported CSS stylesheet only affect the content it is imported to, but not the rest of the theme? I tried several modules that deal with context and CSS on sites, but neither of them works.

# Answer
> 0 votes
You can add your css only on Blog node pages so it does not impact site wide. Sample code

```
function MYTHEME_preprocess_node($vars) {
  if ($vars['#node']->type == 'blog') {
    drupal_add_css(drupal_get_path('module', 'mymodulename') . "/css/materializeCSS.css");
  }
}

```

---
Tags: theming
---


title: View a permanent warning

text:
# Question
Title: View a permanent warning
How to display a warning message on all pages of the site, using rules. When I created a rule with the action "Display a message on the site," it appears that a single time. I hope it will display permanence and on all my pages.

# Answer
> 2 votes
It depends on what event you have subscribe your rule for.

If you choose event as 'Drupal is initialised' and then choose action as 'Show message on site',the message will be showed on every page request, only thing you would like to make sure is disabled the repeat behavior of message, so that message does not stack up on every page request.

Here goes the export of such rule, that might give you a good starting point.

```
{ "rules_system_wide_message" : {
    "LABEL" : "System Wide Message",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "Site wide message", "repeat" : "0" } }
    ]
  }
}

```

---
Tags: 7, rules
---


title: #Ajax change the input wrapper

text:
# Question
Title: #Ajax change the input wrapper
i've made a form which update the price of a product. The user just need to select a duration by a select-list and it update the price by an Ajax callback. It update well the price but it change the structure of my select and then the select when is changed again does nothing...

The form inputs :

```
$key = array('field_friterie_suggest', 'MY-PRODUCT-SKU');

$form['content']['deals'][$key[0]]['purchase']['value'] = array(
            '#type' => 'select',
            '#name' => 'update-price-'.$key[0],
            '#options' => array(
                5 => t('- None -'),
                0 => t('1 month'),
                1 => t('3 month'),
                2 => t('6 month'),
                3 => t('1 year'),
            ),
            '#default_value' => $default_purchase_value,
            '#ajax' => array(
                'callback' => 'fritr_commerce_update_pricing_callback',
                'wrapper' => 'pricing-'.$key[0],
            ),
            '#attributes' => array(
                'data-update' => array(
                    'pricing-'.$key[0],
                ),
                'data-type' => array(
                    $key[1],
                ),
            ),
        );
        $form['content']['deals'][$key[0]]['purchase']['pricing'] = array (
            '#prefix' => '<div class="pricing" id="pricing-'.$key[0].'">',
            '#suffix' => '$</div>',
            '#markup' => 0,
        );

```

And my callback :

```
$month = $form_state['triggering_element']['#value'];
    $price = 0;
    if ($mont != 5) {
        $month_definition = array(1,3,6,12);
        // get the product by his SKU
        $product = commerce_product_load_by_sku($form_state['triggering_element']['#attributes']['data-type'][0]);
        // get the product price and reduction
        $product_base_price = ($product->commerce_price[LANGUAGE_NONE][0]['amount'] / 100) * $month_definition[$month];
        $reduction = $product->field_commerce_reductions[LANGUAGE_NONE][$month]['value'];
        // set the new price
        $price = $product_base_price - ($product_base_price * ($reduction/100));
    }
    return array (
        '#prefix' => '<div class="pricing" id="'.$form_state['triggering_element']['#attributes']['data-update'][0].'">',
        '#suffix' => '€</div>',
        '#markup' => $price,
    );

```

So my input become :

```
<select data-update="pricing-field_friterie_suggest" data-type="MY-PRODUCT-SKU" class="form-control form-select ajax-processed" id="edit-content-deals-field-friterie-suggest-purchase-value" name="update-price-field_friterie_suggest"></select>

```

to :

```
<div class="form-item form-item-update-price-field-friterie-suggest form-type-select form-group">
    <div class="input-group">
        <select data-update="pricing-field_friterie_suggest" data-type="MISE-EN-AVANT-SITE" class="form-control form-select ajax-processed" id="edit-content-deals-field-friterie-suggest-purchase-value" name="update-price-field_friterie_suggest"></select>
        <span class="input-group-addon"></span>
    </div>
</div>

```

Then when i change the value of the select, it does nothing. Can you help me please ?

# Answer
The solution proposed by Jaypan works well. The solution was to not put the modifications of my field in the callback but in the form definition and set the value here by checking the $form\_state fields.
> 1 votes

---
Tags: 7, forms, ajax
---


# Question
Title: how can add pagination in custom module?
i have a custom module file and i want to add the pagination but nothing is appear, might be i did it wrong way. please suggest the right direction. here is my file. **form-list** is the url.

```
<?php
function form_example_permission() {
  return array(
    'submit form_example' => array(
      'title' => t('Submit form_example'),
      'description' => t('Submit the form_example form'),
    ),
    'access form_example submissions' => array(
      'title' => t('Access form_example submissions'),
      'description' => t('Access the form_example submissions'),
    ),
     'access form_example search' => array(
      'title' => t('Access form_example search'),
      'description' => t('Access the form_example search'),
    ),
  );
}
function form_example_menu() {
  $items = array();

  $items['form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Employess Entry Form', //page title
    'description' => "A form to submit the employee's data.",
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit form_example'),
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'),

      );

 $items['form-submissions'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_submissions',
    'access callback' => TRUE,
    'access arguments' => array('access form_example submissions'),
    'type' => MENU_CALLBACK,
  );

  $items['form-list'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_list',
    'access callback' => TRUE,
    'access arguments' => array('access form_example search'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['empemail'] = array(
  '#weight' => '2',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Email'),
);
$form['empdesignation'] = array(
  '#weight' => '3',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Designation'),
);
$form['file'] = array(
  '#weight' => '4',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
 $form['submit'] = array(
     '#weight' => '5',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('<pre>'.print_r($form_state['values'],1).'</pre>');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function form_example_form_submit($form, &$form_state) {
   $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
 // drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));

 $fe_id = db_insert('form_example')
        ->fields(array(

          'empcode' => $form_state['values']['empcode'],
          'empname' => $form_state['values']['empname'],
          'empemail' => $form_state['values']['empemail'],
          'empdesignation' => $form_state['values']['empdesignation'],
          'empphoto' => $file->filename,
        ))
        ->execute();
        drupal_set_message(t('Successfully added'));

}
function form_example_theme($existing, $type, $theme, $path) {
  return array(
    'form_example_function' => array(
      'variables' => array('rows' => NULL),
    ),
    'form_example_template' => array(
      'variables' => array('rows' => NULL),
      'template' => 'form_example_template',
    ),

  );
}

/* view the form submissions*/
function form_example_submissions()
{
  $results =  db_query("Select * from {form_example}");
   $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
        $result->empname,
        $result->empphoto,
        $result->empemail,
         $result->empdesignation,
      );

  }
  return theme('form_example_function',array('rows' => $rows));
}
/*function theme_form_example_function($variables)
{
  print_r($variables);
//$output ="<h2>".print_r$variables."</pre></h2>";
/*  foreach ($variables as $result)
  {

    $output = "<h2><pre>".print_r($result)."</pre></h2>";
  }
return $output;
 $output = '';

    foreach($variables['rows'] as $row) {
        foreach($row as $values) {

          print_r($values);
         $output .= "Empcode: " . $values . "</br> ";
         // $output .= "EmpName: " . $values[1] . " </br>";
        //$output .= "Emphot: " . $values[2] . "\n";
        }
    }
    return $output;

}*/
function theme_form_example_function($variables)
{
    $output = '';
   $search_form =drupal_get_form('form_example_search_form');
    $output = '<div class="block" >'.drupal_render($search_form).'</div>';
    $output .= '<div style="clear:both" ></div>';

   //print_r($variables);
    foreach($variables['rows'] as $row) {
      //  echo $path;
      // $output .= "Empcode: " . (isset($row[1]) ? $row[1] : "--") . " ";
      //  $output .= "EmpName: " . (isset($row[2]) ? $row[2] : "--") . " ";
      //  $output .= "Emphot: " . (isset($row[3]) ? $row[3] : "--") . "<br>";

$img_url = 'public://'.(isset($row[3]) ? $row[3] : "--");  // the orig image uri
$style = 'medium';  // or any other custom image style you've created via /admin/config/media/image-styles

     $output .= '<div class="views-row"><div class="do_featured">
  <div style="position: relative;" class="do_image">
            <div class="field field-name-field-thumb-image field-type-image field-label-hidden"><div class="field-items"><div class="field-item "><img  src="'.image_style_url($style, $img_url).'" ></div></div></div></div>
  <div class="do_title">
    <span>    <div class="field"><div class="field-items"><b>'.(isset($row[2]) ? $row[2] : "--") .'</b></div></div>
 <div class="field"><div class="field-items">Emp Code:  </div><div class="field-items">'.(isset($row[1]) ? $row[1] : "--") .'</div></div>
 <div class="field"><div class="field-items">'.(isset($row[4]) ? $row[4] : "--") .'</div></div>
 <div class="field"><div class="field-items">'.(isset($row[5]) ? $row[5] : "--") .'</div></div>

      </span>
   </div></div></div>';

    }

    return $output;
}
function form_example_list(){
    $search_form =drupal_get_form('form_example_search_form');
    $content = '<div class="block" >'.drupal_render($search_form).'</div>';
    $content .= '<div style="clear:both" ></div>';

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empname']) && $_GET['empname'] != ''){
        $query->condition('pd.empname', '%' . db_like($_GET['empname']). '%','LIKE');
    }
    if(!empty($_GET['empcode'])){
        $query->condition('pd.empcode', '%' . db_like($_GET['empcode']). '%','LIKE');
    }
    if(isset($_GET['empdesignation']) && $_GET['empdesignation'] != ''){
        $query->condition('pd.empdesignation', '%' . db_like($_GET['empdesignation']). '%','LIKE');
    }
    $query->fields('pd');
     $query->extend('PagerDefault')->limit(1);
   //$query->limit(10);
    //$table_sort = $query->extend('TableSort')->orderByHeader($header);
    //$pager = $table_sort->extend('PagerDefault')->limit(10);

    $results = $query->execute();
   $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
        $result->empname,
        $result->empphoto,
        $result->empemail,
         $result->empdesignation,
      );

  }
  $limit =1;
  pager_default_initialize(count($results), $limit, $element = 0);
$pager = theme('pager',array("quantity"=>5));
return theme("form_example_function",array("rows"=>$rows ,"pager"=>$pager));
//  return theme('form_example_function',array('rows' => $rows));
 //return $content;
}
function form_example_search_form($form, &$form_state){

    $form['#method'] = 'get';
    $form['#token'] = FALSE;
    $form['#form_build_id'] = FALSE;
    $form['#form_id'] = FALSE;
    $form['empname'] = array(
        '#type' => 'textfield',
        '#title' => t('empname'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '<div class="form-inline views-exposed-form"> <div class="views-exposed-widget">',
        '#suffix' => '</div>',
        '#default_value' => isset($_GET['empname'])?$_GET['empname']:'',
    );
    $form['empcode'] = array(
        '#type' => 'textfield',
        '#title' => t('empcode'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '<div class="form-inline views-exposed-form"> <div class="views-exposed-widget">',
        '#suffix' => '</div>',
        '#default_value' => isset($_GET['empcode'])?$_GET['empcode']:'',
    );
    $form['empdesignation'] = array(
        '#type' => 'textfield',
        '#title' => t('empdesignation'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '<div class="form-inline views-exposed-form"> <div class="views-exposed-widget">',
        '#suffix' => '</div>',
        '#default_value' => isset($_GET['empdesignation'])?$_GET['empdesignation']:'',
    );
    //views-exposed-widget

    $form['submit'] = array(
        '#type' => 'submit',
        '#attributes' => array( 'name' => ''),
        '#prefix' => '<div class="views-exposed-widget">',
        '#suffix' => '</div></div>',
        '#value' => 'Apply',
     );

    return $form;
}
?>

```

# Answer
Issue seems to be that you are not attaching your global pager output with rest of content.

Checkout the following code, slightly different but covers up the way to print the pager for a custom menu page by querying certain table from database.

```
/**
 * Implements hook_menu().
 */
function test_dev_menu() {
  $items = array();

  $items['test-dev-1'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_list',
    'access callback' => TRUE,
    'access arguments' => array('access form_example search'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Menu callback.
 */
function form_example_list() {
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->fields('n', array('nid', 'title'))
      ->limit(1)
      ->addTag('node_access')
      ->groupBy('n.nid');
  $results = $query->execute()->fetchAllKeyed(0, 1);
  $pager = theme('pager', array("quantity" => 5));
  $output = theme('item_list', array('items' => $results));
  $output = $output . $pager;
  return $output;
}

```

Instead of sending the pager as argument to your theme function, just concatenate the output of theme\_pager and your custom theme function(in above example I am using theme\_item\_list).

```
  $output = $output . $pager;

```
> 2 votes

# Answer
```
$query = db_select('form_example', 'fe')->extend('PagerDefault');
$query->limit(5); // adjust to the number to show per page
$query->fields('fe', array('fe_id', 'empcode', 'empname', 'empphoto', 'empmail', 'empdesignation'));
$results = $query->execute();

```

After this you can output the pager wherever you want with:

```
theme('pager');

```

Or as part of a render array:

```
$element['pager'] = array
(
  '#theme' => 'pager',
);

```
> 0 votes

---
Tags: 7, paging
---


# Question
Title: Load a user object via login form name field
I'm trying to check if a user account has been disabled for LDAP before the user completes the login process using a custom form validator.

What has me stuck is how I would use user\_load to load the user object of the person logging in via the login form. I'm not sure how I would structure the form array within the user\_load function.

What I currently have is:

```
$account = user_load($form_state['values']->name);

```

Thank you for your time.

# Answer
For user\_load function in D6 you have to use pass the $user\_info array like ,

```
 $account = user_load(array('name' => $form_state['values']->name))

```
> 0 votes

# Answer
$user = user\_load(array('name'=\>'username'));
> 0 votes

---
Tags: 6, users, authentication-authorization
---


title: Display textfield as clickable link

text:
# Question
Title: Display textfield as clickable link
I am trying to make textfields clickable so it would appear as link. What would be the best solution for this? I tried **Link** module, but it is not what I am looking for. This is how I got my textfield written:

```
$form['element4']['link4'] = array(
        '#type' => 'textfield',
        '#title' => t('link for 4th div'),
        '#description' => t('your link'),
    );

```

I need for it to stay textfield as user can input his value, but I want it to be displayed lets say in blue color and so that you could click on it. How could I do this in the most simple way?

# Answer
> 1 votes
What you need is the #ajax property of the Form API. Have a look at this page to find the answer to your question:

https://www.drupal.org/node/1256510

---
Tags: 7, navigation
---


title: drupalgap webapp setup into subdomain

text:
# Question
Title: drupalgap webapp setup into subdomain
My main website is www.example.com. And I have 3 types content like: book,food,tutorial.

Now I want to serve all Book item from **book.example.com** subdomain. Is it possible to develop it with drupalgap using example.com node/content and same authentication?

\[After installing drupalgap module, I download web-app drupalgap zip file, and set it to **book.example.com** but, CORS problem detected.\]

anyone help please.

# Answer
> 1 votes
solving cors problem I just add configuration into my .conf file.

```
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token"

```

# Answer
> 0 votes
Sounds like you simply need to set the cookie domain in your settings.php to "example.com".

---
Tags: javascript
---


# Question
Title: rendered entity usage in "add node" form for an entity ref field
In one of my "add node" form, I would like to display the 'name' field of referenced content type rather than the title.

Let's say, Content type 'Car' contains a field called 'owner' which is entity ref to content type 'person'. 'person' has a unique title but also has a field called 'name'.

While displaying to the user '/node/add/car' form, I like to give the user a 'select list' for the field 'owner'. I want to populate this field with the names of the 'person' nodes in the system and not their 'title'.

So in 'manage form display' of the content type 'car', I used 'select list' and in the 'manage display', selected for the 'owner' field, format of "rendered entity". But this displays only the title in the dropdown list in 'add/node/car'.

When that did not work, I tried using the new d8 feature,'display mode'. I created a display mode called "nameview" and created a "nameview" display for content type 'person' which displays only the field 'name'. I then used that view mode in the "manage display" for 'Car'. Still I get only the titles in 'add/node/car'.

What am I doing wrong? or is this a bug in d8?

# Answer
What you configure in Manage display has nothing to do with what is shown in the form. That's not how it works.

You can do this using a view. In field settings, configure it to use a view show possible values and then configure that view to show the values you want to see.
> 1 votes

# Answer
This is actually not possible with Entity Reference views in Drupal 8, but will be soon. See View output is not used for autocomplete display.
> 0 votes

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


title: How do I auto-reset exposed filters?

text:
# Question
Title: How do I auto-reset exposed filters?
I am using views along with solr search api to display search results. Within results I need to add filters so I have used views exposed filter for the indexed fields. Now that I have exposed filter I am trying to reset all views exposed filters every time when someone tries to search something in the search field.

How do I achieve this?

I am using **Search: Fulltext search (exposed)** exposed filter to search for keywords using views.

# Answer
In exposed form settings enable reset button and give label save it you will get reset button
> 0 votes

---
Tags: 7, views, search
---


# Question
Title: Create a menu block with images in Drupal 8 & keep menu order
On the 1st level pages from our main menu I would like to list all the 2nd level child page titles from that page and corresponding images from those children pages' content fields. I would like them ordered the same as they are in the menu. I am using the path-auto pattern of \[parent-url\]/\[page-title\]. I'm open to any suggestions on how to do this.

I've looked into trying to create this with a view block or even a view REST feed but it appears I cannot get attributes from a menu in views in Drupal 8 to use to sort or filter the items. I tried to do this with a menu block but it appears I cannot add fields such as an image to show.

# Answer
> 1 votes
I finally had time to come back to this, so I'll answer my own question as I believe the following solves it. This code could for sure use some refactoring & cleaning up. I'm very new to Drupal 8 & I'm fairly new to Drupal in general. Feel free to suggest improvements.

```
<?php
/**
 * @file
 * Displays children pages as a block
 */

namespace Drupal\child_pages_display\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;
use Drupal\Core\Path;
use Drupal\Core\Menu;
/**
 * Provides a 'Next Previous' block.
 *
 * @Block(
 *   id = "child_page_block",
 *   admin_label = @Translation("Child Page Block"),
 *   category = @Translation("Blocks")
 * )
 */
class ChildPageBlock extends BlockBase {
  public function build(){
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $expandedParents = $parameters->expandedParents;
    reset($expandedParents);
    $root = current($expandedParents);
    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $parameters->setRoot($root);
    $parameters->setMaxDepth(3);
    $parameters->setMinDepth(1);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree->load($menu_name, $parameters);

    //Set Cache for block
    $cache['max-age'] = 3600;
    $cache['contexts'][] = 'url.path';
    $cache['tags'][] = $root;

    //Get node IDs from menu
    $nids = array();
    foreach($tree as $item){
      $nids[] = $item->link->getUrlObject()->getRouteParameters()['node'];
    }

    //Load nodes & generate content from nodes
    $nodes = (!empty($nids)) ? entity_load_multiple('node', $nids) : array();
    if (!empty($nodes) && is_array($nodes)){
      foreach($nodes as $key=>$val) {
        $nodeContent = array(
          '#prefix' => '<div class="block-child-page-menu">',
          '#suffix' => '</div>'
        );
        $url = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$key);

        //Get image thumbnail from content & use specified image style
        if(null !== $val->get('field_thumbnail')->entity){
          $imgPath = ($val->get('field_thumbnail')->entity->uri->value);
          $imgCroppedPath = \Drupal\image\Entity\ImageStyle::load('basic_page_thumbnail')->buildUrl($imgPath);
          $img = ($imgPath != '') ? '<img src="' . $imgCroppedPath . '" />' : '';
        }else{
          $img = "";
        }
        $nodeContent['#markup'] = '<a href="'.$url.'">' .
            '<h2>' . $val->getTitle() . '</h2>' .
            $img .
          '</a>';
        $content[] = $nodeContent;
      }
    }else{
      //Menu has no nodes
      $content['#markup'] = '';
    }
    //Add cache & css library to block
    $content['#cache'] = $cache;
    $content["#attached"] = array('library' => array('child_pages_display/child_pages_display_css'));
    return $content;
  }
}

```

---
Tags: views, 8, blocks, media, navigation
---


# Question
Title: How to display value in View global text field if another field has specific value
In my scenario I'm trying to display a flag (Font Awesome icon) in Views Global Text Field if another field in the same row of a type "Date" has a value of, say, a week from now. I tried Views Table Highlighter but it has some bugs with filters I'm using, so I thought that using the above approach would be better.

# Answer
> 2 votes
You can use views conditional module.

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views

---
Tags: views
---


title: Display random view result every x rows

text:
# Question
Title: Display random view result every x rows
I'm trying to display an ad every six rows of a view. I'm thinking of using another view that contains all the ads and displaying a random result of that every 6 rows of the main view.

Drupal 7 & Views 3.14

I have tried to do this but gotten stuck on the displaying something every 6 rows. Here is my code:

```
...code irrelevant, unedited coded copied from the template file in views module folder...
  <tbody>
    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <?php foreach ($row as $field => $content): ?>
          <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
            <?php print $content; ?>
          </td>
        <?php endforeach; ?>
      </tr>
      <?php if ((($row_count % 6) == 0 && $row_count !== 0): ?><tr>This is the row after every 6th multiple</tr><?php endif; ?>
    <?php endforeach; ?>
  </tbody>
</table>

```

UPDATE: I figured out a way to print a random result. Just add randomize as the only sort in the view. However, I still can't get the printed view result to be in the appropriate location.

# Answer
> 1 votes
Okay, I solved it by using by using an unformatted list instead of a table.

Here is my code in the end:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php
  $numRows = 6; /* Which row do you want the view to appear? E.g. 6 means that rows 6, 12, 18, etc. will have the view */
  if ((($id - ($numRows - 2) ) % ($numRows - 1)) == 0 && $id !== 0):
?>
    <div class="ads views-row"><?php print views_embed_view('VIEW_MACHINE_NAME', 'DISPLAY_ID',''); ?></div>
  <?php endif; ?>
<?php endforeach; ?>

```

---
Tags: views, theming
---


# Question
Title: "Read more" button references the front page
I manually created a view page with 3 fields: image, title, and body.

The body field has a *Read more* link which, instead of pointing to the specific node listed in the blog, it redirects to the front page.

I didn't track anything that would cause it. Maybe I'm missing something.

>

I also tried to use the *\[node:nid\]* token, but it didn't help.

# Answer
The problem here is 2 issues:

1. You're missing a field on your view to reference. In order to reference the Node ID in your view you'll need to add the field *Content: ID* so that it can be referenced in replacement patterns. It will also need to be ***ordered before your body field*** so that its value can referenced. You can use the **Exclude from display option** if you do not want it appearing in your view.
2. The format for token replacement has changed with D8. It's now Twig-like: `{{ field_name }}`. By default the *Content: ID* field should use the field name `nid` so your **More link path** value should be `/node/{{ nid }}`.
> 3 votes

---
Tags: views, 8
---


# Question
Title: How to import context module export -drupal 7
I have created a Context using the Context module for use with a custom module.

Is it possible to export a context and then import it with my custom module? And if so, where does the data from the export need to go in my module?

# Answer
**Way1: Using Features module**

I would recommend you to use features module to export your configurations like context, it will automatically pull the context configurations in code.

**Way2: Using custom module**

If for some reasons you want to do it in custom code then
> 1 votes

---
Tags: 7
---


title: Force login through mysql

text:
# Question
Title: Force login through mysql
I have a local install of a Drupal 7 site that will only display admin pages over https such as login and admin type pages. I was unable to disable them before downloading the database. In settings.php I have set secure pages to 0. However when i attempt to login the page simply refreshes and the form is displayed again and i am unable to visit any admin pages. Is there a way to login using mysql instead of having to go through Drupal?

EDIT:

finally got drush running correctly and used drush cc all after attempting to sign in i got the error message: Warning: Cannot modify header information - headers already sent in \_drupal\_bootstrap\_page\_cache() Warning: Cannot modify header information - headers already sent in drupal\_send\_headers()

the latter is repeated 7 times, the page simply refreshed again.

I ended up creating a temporary sign-in using drush command: drush user-login

# Answer
Sounds like you need to do the following:

1. Set the `securepages_enable` to 0 in settings.php
2. Open a MySQL Client, like HeidiSQL or SQL Pro
3. Truncate the `cache_` tables
4. Reload local site in browser

This should rebuild the variables and then your runtime value will be respected.

Also, check the `.htaccess` file to see that you are not being redirected to HTTPS.
> 1 votes

---
Tags: 7, users, ssl
---


title: Render whole entity inside a controller

text:
# Question
Title: Render whole entity inside a controller
I am trying to print an entity reference field (from paragraphs module) into a controller.
I learned from this ticket that you can use
`{{ teacher.field_classrooms.entity.field_in_paragraph.value }}` to get the value of one field from the entity, but what I really need is to print the whole entity not just one field from the entity.

I was hoping to do something like `{{ teacher.field_classrooms.entity }}` rather than `{{ teacher.field_classrooms.entity.field_in_paragraph.value }}
{{ teacher.field_classrooms.entity.field_different_in_paragraph.value }}`.

# Answer
You can do that by setting a variable in your controller or in template\_preprocess\_teacher in your .theme file, like:

```
function template_preprocess_teacher(array &$variables) {
  $classrooms = $variables['elements'][0]->get('field_classrooms')->referencedEntities(); //probably a bit different for paragraphs ..

  foreach($classrooms as $classroom) {
    $variables['classrooms'][] = \Drupal::entityTypeManager()->getViewBuilder($classroom->getEntityTypeId())->view($classroom, 'optional-view-mode');
  }
}

```

And then access it in twig like this:

```
{{ classrooms }}

```

If you're looking for a twig only solution use the twig\_tweak module, then it comes down to this:

```
{% for field_in_paragraph in teacher.field_classrooms.entity %}
  {{ drupal_entity('classroom', field_in_paragraph.value, 'optional-view-mode') }}
{% endfor %}

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Need to create a RedHen Contact for each Drupal User
I'm wanting to upgrade a current site to use the RedHen CRM module to track contact engagement (etc.) but first need to create RedHen contacts (redhen\_contact module) for each of the users. I'm familiar with Drush scripts so would be fine writing up a script but I'm unfamiliar with the internals of how RedHen works in Drupal. Is there anybody who knows it already who might be able to help point the way?

**Note**: This is not a third-party api. It's a CRM built within Drupal as a Drupal module. What I'm asking is the proper form to utilize the Entity API to create contacts within the RedHen CRM module programmatically.

# Answer
> 1 votes
Rules might be the quickest way to achieve this.

You could have one that on user create, generate a new contact for that user, and a separate rule that after a user updates their information update their contact.

According to RedHen documentation, they have direct rules support so this seems like an easy addition.

---
Tags: users
---


title: Creating a custom page

text:
# Question
Title: Creating a custom page
I am new to drupal 8 however, I have experience in MVC pattern and used Django earlier. I want to create a page that points to `localhost/home` where I would like to show a slideshow from `view slideshow` module as well as some static contents like images, links, etc. If I were on django, I would simple redirect the parameters to display directly on template i.e something like `HttpResponse(template.render(context, request))`.

How do I do such thing is drupal 8? I have looked at lots of places and still cannot find anything. The solution that I have found till now is to create separate module for each page i.e `home`, `about-us`, etc. and route a Controller function. Is this the only approach? Please help. Thanks.

# Answer
Pages in Drupal are largely composed of content types with fields attached to them, and sometimes, blocks (which can be created from Views).

You do not need to create custom routes and controllers for them, the core Node module takes care of this for you.

The core Path module will allow for custom aliases, and Pathauto will let you create automatic aliasing rules.

It would be a fairly rare thing to need to implement a route and controller just to display basic content in Drupal. 99% of the time it can be achieved with content types, Views, or panels.

You will probably want to review some of the material on Drupalize.me to learn Drupal content management.
> 0 votes

# Answer
For a front page you could use a template suggestion, or blocks and visibility settings.

You can place static content in the layout using a custom block with a text field, or add more fields for specific things like links (if you want them in seperate fields etc).

E.g. lets say you create a `page--front.html.twig` template suggestion in your theme, then add a region for a Views Slideshow block. Static content could be hard coded into this page--front template, or perhaps using custom blocks, nodes or whatever suits your purpose. For example if that content is in nodes you could create a View and display that in another region.

Alternatively you might create a module has blocks that hold the static content and place them programmatically or via the UI. Is this what you are really driving at?

Hovers, animations etc is a style/behaviour level thing that does not seem relevant to the original question.
> 0 votes

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


# Question
Title: Customizing the register form with a new class: Why do I get this error?
I'm trying to customize the register form. A user has a reference field to content of type A. However, I only want to allow values of A which satisfy a certain condition. To achieve this, I based my code on https://www.foreach.be/blog/how-manipulate-forms-drupal-8.

I created a module with the following services.

```
services:
  travels.route_subscriber:
    class: Drupal\travels\Routing\RouteSubscriber
    tags:
      - {name: event_subscriber }

```

I defined a `RouteSubscriber` class.

```
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
     if ($route = $collection->get('user.register')) {
        $route->setDefault('_form', '\Drupal\travels\ExtendedRegisterForm');
     }

   }
}

```

I also have an `ExtendedRegisterForm` class defined as follows.

```
class ExtendedRegisterForm extends RegisterForm {
     public function buildForm(array $form, FormStateInterface $form_state) {
         $form['test'] = [
            '#type' => 'email',
            '#default_value' => 'test'
          ];
         return $form;
      }
}

```

If I load the page to register a new user, I get the following error:

> Fatal error: Call to a member function getEntityTypeId() on null in xxxx\core\lib\Drupal\Core\Entity\EntityForm.php on line 77

I'm assuming no entity was given because the Entity still needs to be created (after the registration). Does anyone have a suggestion of what I might still need to do to get this working?

# Answer
The error you get is because you are overriding `EntityForm::buildForm()` without invoking it. In fact, it contains the following code.

```
  // During the initial form build, add this form object to the form state and
  // allow for initial preparation before form building and processing.
  if (!$form_state->has('entity_form_initialized')) {
    $this->init($form_state);
  }

```

It is then `EntityForm::init()` to initialize the entity object.

Truly, you are overriding the wrong method: It's `form()` that you need to implement, in the same way the `RegisterForm` class does overriding `AccountForm::form()`.

As for implementing `hook_form_alter()` or implementing the code as you did, the first is preferable when you need to just add some fields, or change any of them. If you are going to alter the logic behind the registration form, then the code you implemented is probably better. Keep in mind that another module could do the same, but if both the modules need to *heavily* change the logic behind the registration form, it is also probable they are not compatible with each other.
> 0 votes

# Answer
It seems like you could reduce complexity with hook\_form\_alter, and manipulate the options on the reference field.
> 0 votes

---
Tags: users, 8, event-subscribers
---


title: Unprocessed in wordpress migrate

text:
# Question
Title: Unprocessed in wordpress migrate
I migrated Wordpress to Drupal 7 using wordpress migrate

What does this mean unprocessed -444?

Is that I have 444 articles are failed imported to Drupal?

# Answer
Yes, as you guested *unprocessed* show the number of items that this module detected but couldn't import .
> 1 votes

---
Tags: 7, migrations
---


# Question
Title: How do i get the all the regions available in the current theme programatically?
I want the list of the names of all regions available in the current theme in drupal 8. How to do this ?
And is it possible to get the list of the blocks placed on that region ?

# Answer
Active ADMIN theme & active SYSTEM theme might be different.(By default active admin theme is **seven** & active system theme is **bartik**)
**Get the current theme used by the below code**(if you are in admin section it will return seven, else bartik)

```
$theme = \Drupal::theme()->getActiveTheme()->getName();

```

**As we need the system theme, below code will do the job**

```
$theme = \Drupal::config('system.theme')->get('default');

```

**And pass the theme name to get all the regions**

```
$system_region = system_region_list($theme, $show = REGIONS_ALL);

```

**This will give you all the regions in array format**

```
$region_list =  json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);

```

**Second part of the question**

Get the blocks in particular region . Below is the code snippet which can get the blocks placed in pre-content region:

```
  $blocks = \Drupal::entityManager()
      ->getStorage('block')
      ->loadByProperties(array('theme' =>  \Drupal::config('system.theme')->get('default'),'region'=>'pre_content'));

```
> 8 votes

# Answer
I don't know is it possible to get the blocks list in one line, but you can do it like that:

```
$blocks = \Drupal\block\Entity\Block::loadMultiple();
$region_name = 'content';
$block_ids = [];
foreach($blocks as $block){
  if($block->getRegion() === $region_name){
    $block_ids[] = $block->id();
  }
}

```
> 1 votes

# Answer
**This worked for me a couple of times already, looking how the core does it:**

In case of "/admin/structure/block" contains all the regions, you only have to look up how it's implemented in the core.

1. Get the link where you saw the functionality (/admin/structure/block in our case)
2. If you use IDE "find in path" on the core directory and paste it.
3. You are looking for a "\*.routing.yml", which will tell you which controller handles the request
4. Now you are on your own to find it, but it's really not that hard.

As mentioned above you will need this:

```
system_region_list($theme, $show)

```

But also I suggest you to take a look at `BlockListBuilder.php`, in core/modules/block!
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How do I give the following responsive information in the .info file?
I have the below lines in the info file for a Drupal 7 theme.

```
stylesheets[all and (min-width: 980px)][] = css/960.css
stylesheets[all and (min-width: 760px) and (max-width: 980px)][] = css/720.css
stylesheets[all and (max-width: 760px)][] = css/mobile.css
stylesheets[all][] = style.css
stylesheets[all][] = color/colors.css

```

How do I map these in Drupal 8?

# Answer
Your D7 declarations have the effect of placing the media query in the markup, and I think you want to replicate that method. You can do this in the library declarations, e.g.

```
stylesheets[all and (max-width: 760px)][] = css/mobile.css

```

Becomes:

```
mobile:
  version: 8.x-1.0
  css:
    layout:
      css/mobile.css: { media: all and (max-width: 760px) }

```

Note I am assuming this is for layout, hence my use of the "layout" SMACCS category for this library.

Personally I don't really bother with such things and write the media queries in the CSS, if you have many media queries you're going to have a lot of extra http requests if you're always splitting files based solely on breakpoint.
> 1 votes

# Answer
In Drupal 8 create `theme-name.libraries.yml` file inside that you can add your CSS and js files.

```
global-styling:
  version: VERSION
  css:
   theme:
    css/bootstrap.min.css: {}
    css/style.css: {}
    css/animate.css: {}

    css/font-awesome.min.css: {}

    css/slick.css: {}
    css/owl-carousel.css: {}
    #~ css/theme-red.css: {}
    #~ css/theme.css: {}
  js:
    js/bootstrap.min.js: {}
    js/wow.min.js: {}
    js/custom.js: {}
    js/slick.min.js: {}

```

You can refer this https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

I think you can achieve it using breakpoints. To create new Breakpoints, you need to add a `[theme-name]` or `[module-name]` .breakpoints.yml in the root folder of your theme or module

We’ll take the classy.breakpoints.yml to show you an example of the content of the breakpoint file.

```
  classy.mobile:
    label: mobile
    mediaQuery: '(min-width: 0px)'
    weight: 0
    multipliers:
    - 1x
  classy.narrow:
    label: narrow
    mediaQuery: 'all and (min-width: 560px) and (max-width: 850px)'
    weight: 1
    multipliers:
    - 1x
  classy.wide:
    label: wide
    mediaQuery: 'all and (min-width: 851px)'
    weight: 2
    multipliers:
    - 1x

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: variable_del wildcard when uninstalling a module
I have lot of variables created in a module. Is there any wildcard when deleting variables using `variable_del`.

```
Ex1: variable_del($key . '_campaign_text_*');
Ex2: variable_del($key . '_campaign_text_%');

```

Will any of these workout?

# Answer
> 5 votes
You can try db\_delete but handle with caution.

Example :

```
db_delete('variable')
->condition('name', '_campaign_text_%','LIKE')
->execute();
cache_clear_all('variables', 'cache_bootstrap');

```

---
Tags: 7, configuration
---


# Question
Title: Multiple fields that are generated dynamically in forms
In a particular section of my form, some of fields are iterated over n number of times whenever we click add button n times.

I want to add below details of each student by click add button and remove the details by remove button.

Help would be greatly appreciated :) Drupal version is 8.

```
  $form['reg']= array(
          '#type' => 'textfield',
          '#title' => 'Registration Number',
          '#validated' => TRUE,
      );
 $form['fname']= array(
          '#type' => 'textfield',
          '#title' => 'First Name',
          '#validated' => TRUE,
 );
  $form['lname']= array(
          '#type' => 'textfield',
          '#title' => 'last Name',
          '#validated' => TRUE,
  );
 $form['email'] = array(
       '#type' => 'textfield',
       '#title' => 'Email',
       '#validated' => TRUE
 );

```

# Answer
You can use session to store your data like:

```
$session = new \Symfony\Component\HttpFoundation\Session\Session();
$session->set('counter', $session->get('counter',0) + 1);
$counter =$session->get('counter');

$form['counter'] = array(
   '#type' => 'hidden',
   '#value' => $counter
);

```

Tuto : http://www.drupal8.ovh/en/tutoriels/25/save-user-temporary-data-on-session
> 1 votes

---
Tags: forms, 8
---


title: Module for HR and vacancies

text:
# Question
Title: Module for HR and vacancies
Is there a module for Drupal that can be used for job postings, with specific access limited to people from HR / system admin?

# Answer
> 1 votes
You can achieve your all requirements by installing Recruiter Drupal distribution.

> Recruiter is a Drupal distribution for building Drupal based e-recruitment platforms. Users can register either as recruiter and post job classifieds or they can register as applicants and fill out their resume. A faceted search helps users to find jobs and possible job candidates.

---
Tags: 7
---


# Question
Title: Disable price field when checkbox is checked (node add form)
I would like to disable 2 price fields when a checkbox is checked. This could be easier with webform by I want to implement that on the node add form (admin).

Thank you in advance.

# Answer
> 0 votes
For D7 you can go for

Conditional Fields

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

Field Conditional States

The Field Conditional State module can be used when:

> you have a text field you only want to be enabled when a certain checkbox is checked
>
> you want to show a different set of fields depending on the value(s) selected in a certain select list

---
Tags: nodes
---


# Question
Title: Is there any other way to store values in DB other than 'system_settings_form'?
On change(using AJAX) of Job title the text area will show and admin will enter text in admin form. By using `system_settings_form` I am storing values in DB using Variables.

**PROBLEM:**

1. I have more than 20 values in the dropdown.
2. For this I need to store the textarea values in a variable.
3. This leads to huge values stored in `variable` table.

Is there any other way rather than using this, or is this the best way of using?

***I am just checking all the possibilities.***

Any Ideas will be much appreciated, Thanks.

# Answer
You can store your data wherever you like, in whatever format you like, and you can manage it in any way that php allows; Drupal doesn't have an opinion on the matter.

If you're asking whether Drupal has another variable API you can use for this slightly different requirement, then no it doesn't.

So to answer your question directly

> Is there any other way to store values in DB other than 'system\_settings\_form'

Yes, just use the database API in whatever way you think is appropriate for the data you're storing/retrieving. Various modules provide data layers, e.g. ctools has a data API as Jimmy mentioned in the comments. There's also the core entity API, but that's going to be overkill for your needs.

All that said, you might want to actually profile your code to see if 20 values serialised into a single row is going to cause you any real problems. Yours and MySQL's definition of "huge" might be quite different.
> 1 votes

---
Tags: 7
---


title: How can I add an article to a region?

text:
# Question
Title: How can I add an article to a region?
How can I add a content (let's say content of Article type)' to ANY region (not only in content region), or how to add a region to a node view page?

# Answer
> 1 votes
By default drupal don't let you do this , you should achieve it with this two solution

1. use nodeblock

> 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.
>
> We advice you to use this module together with Node Level Blocks or Block Reference module.
>
> It is very handy to create a simple block content type and enable this content type for blocks and use these in place of the normal 'add block' functionality.

2. Achieve it by views block,I mean create a view, get result of it with what you want ,then save it as block ( I mean create block view), then put the block in the region you want.

---
Tags: 7, theming
---


# Question
Title: Services Module Unable To Update User Fields
I am using the Services module configured with a REST endpoint. I can update all other fields on the user account but when I attempt to update the mail field (user e-mail field) it doesn't appear to change.

I think this has to do with the "current\_pass" field. Am I supposed to validate the password somehow?

I am testing this but any "hey, silly guy, did you try this?" would be helpful.

# Answer
> 1 votes
**Way 1:**

Yes, you need to send the current password to update the user email that is default Drupal user account configuration, and the default user update enpoint exposed by services programmtically submit the same user profile form, which triggers all the validation your form has. In order to send the current password your request load may look like

```
{
    "current_pass": "onso",
    "mail": "test@example.com"
}

```

**Way 2:**

If you don't want to provide current password, you can consider using No Current Password module, but remember that it will remove the current password field from the form UI as well.

**Way 3:**

Expose custom endpoint to update user email. Make sure you have authentication on your endpoint.

---
Tags: users, services
---


title: Cannot create simplenews content

text:
# Question
Title: Cannot create simplenews content
I have simplenews module installed on drupal 7.50

When accessing **#overlay=node/add/simplenews**

I get a NOT FOUND, so I cannot create any newsletter content. Tried to flush cache but didn't work. Any ideas?

# Answer
I have tested on Drupal vanilla installation 7.50 and simplenews version 7.x-1.1 stable release, the link works perfect to add simplenews nodes.

I would recommend you

```
 -  Re install simplenews module
 -  Check if you see simplenews content type under structure>>content types
 -  Check if you see any error in your error logs.
 -  Check if you are using dev version of simplenews module

```
> 0 votes

---
Tags: 7, emails
---


title: Default value for Price field

text:
# Question
Title: Default value for Price field
I'd like to know if there's a way to assign a default value in the Price field in Drupal Commerce. Currently, there are no field settings available.

# Answer
> 1 votes
It is not possible for the default price field, because Drupal locks down the field / widget settings for "locked" fields. This is a general Drupal issue, but you could work around it by using an alternate price field that you add custom to your product type paired with a product pricing rule that swaps that price in at the start of the pricing process. You'd have to do a form alter or something to hide the default price field from your product forms.

# Answer
> 0 votes
You can temporarily unlock the field, set the default price and lock it again. The PHP code is as follows:

```
$field = field_read_field('commerce_price');
$field['locked'] = 0;  // 0: unlock; 1: lock.
field_update_field($field);

```

You could run it using drush eval (use backslash to escape the $ and put it all on one line) or the php block from the devel module. Credit: http://atlantic-canary.net/en/how-to-lockunlock-a-field-in-drupal.

Don't forget to lock it again after to make the field safe again.

# Answer
> 0 votes
Instill devel module Enable the devel module either by drush en or from admin/build/modules. It will generate several blocks and look for the one named ‘Execute PHP’ enable it by setting it to a preferred region . Write the code you want to check on the text area for example and then press execute to see the result.

so here we will use this code

`$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);`

note: this line $field\_name = 'field\_name'; you have to add your filed name for example like this $field\_name = commerce\_price;

if you got any error such as displayed as messages “Notice: Undefined index” or “Notice: Undefined variable” and your logs will grow insanely…

the solution is to add in your settings.php the line

`ini_set('error_reporting', 'E_ALL ^ E_NOTICE');`

---
Tags: commerce
---


title: Lock a Field Instance

text:
# Question
Title: Lock a Field Instance
Is there a way to lock a field instance?

I want to prevent users from editing or deleting a given instance, but allow the field to be customizable elsewhere by the user. If I lock the field, it will do the former, but prevent the latter.

According to this Field API documentation, fields can be locked by setting `locked = TRUE` in the field definition, but there is no corresponding `locked` key for the instance definition.

I experimented by adding `locked = TRUE` to my field instance definition, and while that removed the edit and delete links from the bundle types view, I can still edit and delete by visiting the appropriate url.

# Answer
> 0 votes
I was able to use a snippet from dropbucket to lock and unlock fields. I used the snippet in the devel execute php window but it could certainly be coded into a function instead:

```
/*
# You can use Devel Module to unlock/lock a existing field where you would otherwise get an error like "The field xxxx is locked and cannot be edited."
# Change the 'xxx' on line 1 with the machine readable name of your field.
*/
$field_name = 'xxx';
$field = field_read_field($field_name);
$field['locked'] = 1; //change this to 0 to unlock a field
field_update_field($field);

```

# Answer
> 0 votes
```
Instill devel module Enable the devel module either by drush en or from admin/build/modules.

```

It will generate several blocks and look for the one named ‘Execute PHP’ enable it by setting it to a preferred region . Write the code you want to check on the text area for example and then press execute to see the result.

so here we will use this code

```
$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);

```

note: this line

```
$field_name = 'field_name';

```

you have to add your filed name for example like this

```
$field_name = commerce_price;

```

if you got any error such as displayed as messages

```
Notice: Undefined index”

```

or

```
“Notice: Undefined variable”

```

and your logs will grow insanely…

the solution is to add in your settings.php the line

```
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');

```

---
Tags: entities
---


title: Drush installation issue

text:
# Question
Title: Drush installation issue
I am trying to install the most uptodate version of Drush as I begin working on Drupal 8.

Apt-get only installs Drush version 5.10.0. So, I'm attempting to install Drush via composer with the following effect:

```
sisko@li184-76:~$ composer global require drush/drush:dev-master
Changed current directory to /home/sisko/.composer
The "fxp/composer-asset-plugin" plugin was skipped because it requires a Plugin API version ("1.0.0") that does not match your Composer installation ("1.1.0"). You may need to run composer update with the "--no-plugins" option.
./composer.json has been updated
The "fxp/composer-asset-plugin" plugin was skipped because it requires a Plugin API version ("1.0.0") that does not match your Composer installation ("1.1.0"). You may need to run composer update with the "--no-plugins" option.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - drush/drush dev-master requires consolidation/robo dev-master -> satisfiable by consolidation/robo[dev-master] but these conflict with your requirements or minimum-stability.
  Problem 2
    - fxp/composer-asset-plugin v1.0.0 requires composer-plugin-api 1.0.0 -> no matching package found.
    - fxp/composer-asset-plugin v1.0.0 requires composer-plugin-api 1.0.0 -> no matching package found.
    - fxp/composer-asset-plugin v1.0.0 requires composer-plugin-api 1.0.0 -> no matching package found.
    - Installation request for fxp/composer-asset-plugin 1.0.0 -> satisfiable by fxp/composer-asset-plugin[v1.0.0].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.
sisko@li184-76:~$ drush status
The program 'drush' is currently not installed. You can install it by typing:
sudo apt-get install drush
sisko@li184-76:~$

```

Can anyone please help me out?

# Answer
> 1 votes
If you want to install Drush via `composer require` rather than `git clone` followed by `composer install` (which is slightly easier), then I would recommend:

1. Use the stable version of Drush, ~8
2. Install with cgr

# Answer
> 0 votes
I also had this headache

for me the best option was:

1. login als root
2. `~$ php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush`
3. `~$ php drush core-status`
4. `~$ chmod +x drush`
5. `sudo mv drush /usr/local/bin`

# Answer
> 0 votes
I installed drush following this tuto http://www.drupal8.ovh/en/tutoriels/138/install-and-update-drush-on-linux

```
php -r "readfile('http://files.drush.org/drush.phar');" > drush
chmod +x drush
sudo mv drush /usr/local/bin
drush init

```

# Answer
> 0 votes
> You may need to run composer update with the "--no-plugins" option.

As per above warning suggestion, try:

```
composer update --no-plugins

```

and try again as your composer could be out of date. You can also add `--no-plugins` to `composer global require` command to see if that will help.

---
Tags: drush, composer
---


title: Add image at form submit

text:
# Question
Title: Add image at form submit
I have created a form that has a submit button.

```
$form['products_submit'] = array(
    '#type' => 'submit',
    "#id"  => "submit_first",
    '#value' => t('Submit'),
    '#ajax' => array(
                'callback' => 'products_submit_driven_callback',
                'method' => 'replace',
                'effect' => 'fade',
                'progress' => array('type' => 'none'),
            ),
            '#prefix' => '<div class="button-logged-in">',
        '#suffix' => '</div>'
    );

  return $form;

```

And I want to add an image inside the button, at the left of 'Submit' text. I tried to add the img tag inside the t function but it just showed the code and not the image. Does anyone know how can I manage this?

# Answer
You can handle this from CSS.

Like :

```
.button-logged-in.input{
    background-image: url(/images/buttons/submit.png);
}

```

Example : https://stackoverflow.com/questions/2920076/html-css-how-to-add-image-icon-to-input-type-button
> -1 votes

---
Tags: 7, forms, media
---


# Question
Title: Print a list of checked form options in TWIG
I need to print out a list of checked form options in a TWIG template in Drupal 8.

I'm using Better Exposed Filters, and editing the `views-exposed-form.html.twig` template.

# Answer
Iterate over the form options, returning the # value of each item:

`{% for choice in form.filter['#value'] %}`

Then Print out the title value of each one of those options:

`{{ form.filter[choice]['#title'] }}`

**All together it looks like this:**

```
{% for choice in form.filter['#value'] %} {# Find each checked option #}
  {{ form.filter[choice]['#title'] }} {# Print the Title #}
{% endfor %}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How do I keep multiple sites in sync using drupal-composer/drupal-project
What is the correct process to keep local and production sites in sync when using drupal-composer/drupal-project. Most of the solutions online only discuss updating one site and not dev, staging and production properties.

This is the current process I am using

1. put live site in maintenance mode
2. run **composer update drupal/core --with-dependencies -vvv**

* I run this on both local and production servers
    * I noticed that this does not sync alpha and beta contributed modules
    * I noticed that running **'composer update'** from the root of the project updates core and all contrib modules
3. run **drush updb**

* I run this on both local and production servers
4. I then commit changes to git from the local site

I just want to find out what otheres are doing to keep multiple sites in sync

# Answer
> 1 votes
There are a number of different options that are all viable here; this is what I would suggest:

1. On your dev site, run `composer update` with options to suit what you want to update.
2. Run `drush updb` on your dev site.
3. Test thoroughly; then commit composer.json and composer.lock and push to your repository.
4. On your test site, pull your repository and run `composer install`. This will put all of your dependencies into the exact same state they were in on your dev site, so you will get exactly what you tested.
5. Run `drush updb` on your test site.
6. Test thoroughly again.
7. When you are ready to deploy to your live site, put it in maitenance mode and use a file copy program (e.g. rsync) to move the exact files from the test site to live. Alternately, you can use `composer install` again.
8. Run `drush updb` on your live site.
9. Confirm that all is okay and take your site out of maintenance mode.

---
Tags: drush, composer
---


title: Add field to a form with AJAX

text:
# Question
Title: Add field to a form with AJAX
I try to add dynamically some field on a form when I click on a button "Add a sponsee". I search on internet how to do that with the form API but unfortunatly whitout succes. Here is my form class :

```
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#tree'] = true; //Make the form fields a hierachical array*

    $form['#prefix'] = '<div id="sponsorship-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['sponsor'] = [
        '#type' => 'fieldset',
        '#title' => $this->t('You (sponsor)'),
    ];
    $form['sponsor']['civility'] = [
        '#type' => 'select',
        '#title' => $this->t('Civility'),
        '#options' => array('Miss' => $this->t('Miss'), 'Mister' => $this->t('Mister')),
        '#size' => 1,
    /* .......... */
    $form['sponsor']['submit'] = [
        '#type' => 'submit',
        '#value' => t('Send'),
    ];

    $form['sponsee'] = [
        '#type' => 'fieldset',
        '#title' => $this->t('Your sponsee'),
        '#prefix' => '<div id="sponsees-fieldset-wrapper">',
        '#suffix' => '</div>',
    ];

    //Default value of nb_sponsees to 1
    if ($form_state->getValue('nb_sponsee') == null) {
        $form_state->setValue('nb_sponsee', 1);
    }

    for ($i = 0; $i < $form_state->getValue('nb_sponsee'); $i++) {
        $form['sponsee'][$i]['civility'] = [
            '#type' => 'select',
            '#title' => $this->t('Civility'),
            '#options' => array('Miss' => $this->t('Miss'), 'Mister' => $this->t('Mister')),
            '#size' => 1,
        ];
        $form['sponsee'][$i]['firstname'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Firstname'),
            '#maxlength' => 64,
            '#size' => 64,
        ];
        $form['sponsee'][$i]['name'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Name'),
            '#maxlength' => 64,
            '#size' => 64,
        ];
        $form['sponsee'][$i]['phone'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Phone'),
            '#maxlength' => 64,
            '#size' => 64,
        ];
        $form['sponsee'][$i]['e_mail'] = [
            '#type' => 'email',
            '#title' => $this->t('E-mail'),
        ];
    }

    //If less of 3 sponsee we add the button
    if ($form_state->getValue('nb_sponsee') < 3) {
        $form['sponsee']['add_sponsee'] = [
            '#type' => 'submit',
            '#name' => 'add_sponsee',
            '#submit' => [$this, 'ajaxHandleSponseesSubmit'],
            '#value' => t('Add a sponsee'),
            '#ajax' => array(
                'callback' => [$this, 'ajaxHandleSponseesCallback'],
                'wrapper' => 'sponsees-fieldset-wrapper',
                'event' => 'click',
                'effect' => 'fade',
                'progress' => array('message' => '', 'type' => 'throbber'),
            ),
        ];
    }

    return $form;
}

/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
}

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    foreach ($form_state->getValues() as $key => $value) {
        drupal_set_message($key . ': ' . $value);
    }
}

/*
 * Custom Submit to increment nb_sponsees
 */
function ajaxHandleSponseesSubmit(array &$form, FormStateInterface &$form_state) {
    $form_state->setValue('nb_sponsee', $form_state->getValue('nb_sponsee') + 1);
    $form_state->setRebuild(true);
}

/**
 * Ajax submit handler that will return the form structure
 */
public function ajaxHandleSponseesCallback(array &$form, FormStateInterface &$form_state) {
    return $form['sponsee'];
}

```

As you can see, when I clic on $form\['sponsee'\]\['add\_sponsee'\], I increment the nb\_sponsees in the $form\_state and rebuild the form. Then, in my AJAX callback, I return the fieldset part of the form. I've turn this in many way without success. This way seams to work with lot of situation, but not in mine. Am I missing something ?

---

Here's my form working with the help of examples modules :

```
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#theme'] = 'sponsorship_form';
    $form['#tree'] = true; //Make the form fields a hierachical array*

    $form['#prefix'] = '<div id="sponsorship-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['sponsor'] = [
        '#type' => 'fieldset',
        '#title' => $this->t('You (sponsor)'),
        '#prefix' => '<div class="quick-contact__form col-xs-12 col-md-6">',
        '#suffix' => '</div>',
    ];

    / ** Some fields... */

    $form['sponsor']['submit'] = [
        '#type' => 'submit',
        '#value' => t('Send'),
        '#attributes' => [
            'class' => ['btn btn-full']
        ],
        '#ajax' => array(
            'wrapper' => 'sponsorship-form-wrapper',
            'callback' => '::ajaxRebuildForm',
            'effect' => 'fade',
            'progress' => array('message' => '', 'type' => 'throbber'),
        ),
    ];

    $nb_sponsee = $form_state->get('nb_sponsee');
    $form['sponsees'] = [
        '#type' => 'container',
        '#prefix' => '<div id="sponsees-fieldset-wrapper" class="quick-contact__form col-xs-12 col-md-6">',
        '#suffix' => '</div>',
    ];

    if (empty($nb_sponsee)) {
        $nb_sponsee = 1;
        $form_state->set('nb_sponsee', $nb_sponsee);
    }

    for ($i = 0; $i < $nb_sponsee; $i++) {

        $form['sponsees'][$i]['sponsee'] = [
            '#type' => 'fieldset',
            '#title' => $this->t('Your sponsee'),
        ];

        $form['sponsees'][$i]['sponsee']['civility'] = [
            '#prefix' => '<div class="formdetails-containHead">',
            '#type' => 'select',
            '#title' => $this->t('Civility'),
            '#options' => array(1 => $this->t('Mr'), 2 => $this->t('Miss')),
            '#size' => 1,
            '#title_display' => 'invisible',
            '#attributes' => [
                'class' => ['formDetails--civility']
            ]
        ];
        $form['sponsees'][$i]['sponsee']['firstname'] = [
            '#suffix' => '</div>',
            '#type' => 'textfield',
            '#title' => $this->t('Firstname'),
            '#placeholder' => $this->t('Firstname'),
            '#maxlength' => 64,
            '#size' => 64,
            '#title_display' => 'invisible',
        ];
        $form['sponsees'][$i]['sponsee']['name'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Name'),
            '#placeholder' => $this->t('Name'),
            '#maxlength' => 64,
            '#size' => 64,
            '#title_display' => 'invisible',
        ];
        $form['sponsees'][$i]['sponsee']['phone'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Phone'),
            '#placeholder' => $this->t('Phone'),
            '#maxlength' => 64,
            '#size' => 64,
            '#title_display' => 'invisible',
        ];
        $form['sponsees'][$i]['sponsee']['e_mail'] = [
            '#type' => 'email',
            '#title' => $this->t('E-mail'),
            '#placeholder' => $this->t('E-mail'),
            '#title_display' => 'invisible',
        ];
    }

    //If less of 3 sponsee we add the button
    if ($nb_sponsee < 3) {
        $form['sponsees']['add_sponsee'] = [
            '#type' => 'submit',
            '#prefix' => '<span class="containPlus">+</span>',
            '#attributes' => [
                'class' => ['btn-add-sponsee']
            ],
            '#value' => t('Add a sponsee'),
            '#submit' => array('::addSponcee'),
            '#ajax' => [
                'callback' => '::addSponceeCallback',
                'wrapper' => 'sponsees-fieldset-wrapper',
            ],
        ];
    }

    return $form;
}

/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
}

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->set('nb_sponsee', 1);
    // Display result.
    foreach ($form_state->getValues() as $key => $value) {
        drupal_set_message($key . ': ' . $value);
    }
}

/**
 * Ajax submit handler that will return the whole form structure.
 *  = callback of the complete submit of the form
 *
 * @param array $form
 *   An associative array containing the structure of the form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 *
 * @return array
 *   The form structure.
 */
public function ajaxRebuildForm(array &$form, FormStateInterface $form_state) {
    return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
public function addSponceeCallback(array &$form, FormStateInterface $form_state) {
    return $form['sponsees'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
public function addSponcee(array &$form, FormStateInterface $form_state) {
    $form_state->set('nb_sponsee', $form_state->get('nb_sponsee') + 1);
    $form_state->setRebuild();
}

```

# Answer
> 6 votes
You can make use of examples module where you can find many ajax examples. One of the ajax example is of add and remove button which can help you . I feel the add and remove button example i find is relevant to the problem you are asking solution for .

# Answer
> 1 votes
Try to change like :

```
'#ajax' => array(
    'callback' => '::ajaxHandleSponseesCallback',
)

function ajaxHandleSponseesCallback($form, FormStateInterface $form_state) {
$value = $form_state->getValue('nb_sponsee') + 1;
$form['sponsee']['#value'] = $value;
$form['sponsee']['#default_value'] = $value;
return $form['sponsee'];
}

```

You have more examples:

http://www.drupal8.ovh/en/tutoriels/26/ajax-form

http://www.drupal8.ovh/en/tutoriels/139/add-remove-fields-dynamically-using-form-api-and-ajax

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


# Question
Title: Use getclicky to have most views nodes on home page
I have installed the getclicky module and I can see the stats most views content.
How can I add that info in a view on my home page and list the top 10 nodes?
I cannot use the Statistics module.

# Answer
> 0 votes
I end up using google analytics reports. and added the top page view in my homepage.

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


# Question
Title: How can I get the saved value in the variable table to show on a form?
I have a form that gets values set in the variable table if any have been submitted. All of the fields work as expected except a radios field, which always shows the default. Here's the relevant code

```
$one = variable_get('one', array());

$form['one']['visibility'] = array(
 '#type' => 'radios',
 '#title' => t('The title'),
 '#options' => array(0 => t('Yes'), 1 => t('No')),
 '#default_value' => (!empty($one['visibility']))
 ? $one['visibility']
 : 1,
);

```

I had thought that keying the options array with strings would solve this but it doesn't. I'm still Googling, but I'm wondering if there's something easy I'm missing.

# Answer
You'll have to refer to the Form API docs for radios for tips.

Second, it might make things easier to reason about if you do:

```
$one = variable_get('one', array('visibility' => 0));
$is_visible = $one['visibility'];

$form['one']['visibility'] = array(
 '#type' => 'radios',
 '#title' => t('The title'),
 '#options' => array(0 => t('Yes'), 1 => t('No')),
 '#default_value' => $is_visible,
);

```
> 1 votes

# Answer
I have another field of radios in the form that works correctly, the difference is that the keys are strings, so I tried this again in the above code, this time using strings like "yes" and "no" for keys as well as values and it worked. For some reason, using 1 and 2, or "1" and "2" for array keys will not work as expected in this case.
> 0 votes

---
Tags: forms
---


title: Submission hook: What am I doing wrong?

text:
# Question
Title: Submission hook: What am I doing wrong?
**EDIT:** Still need some help with this. It seems the value of "$form\_id" is nothing related to "webform\_client...". When I echo the value of $form\_id in the mywebform\_extra\_form\_alter() function it outputs a value of: "search\_form\_block".. nothing indicating a webform.

Can I ask for some more assistance with this?

I've created a module for a webform submission hook to open and modify a CSV with the submitted values:

```
function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
    // Add validation for a particular Webform node:
    if ($form_id == 'webform_client_form_213') {
    // Add the submit handler after the existing Webform submit handler,
    // but before the second Webform handler. Pop off the first one and add
// ours second.
    $first = array_shift($form['#submit']);
    array_unshift($form['#submit'], $first, 'mywebform_extra_submit_213');
  }
}

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

    global $user;

    // Changes can be made to the Webform node settings by modifying this variable:
    $form['#node']->webform;

    $name = $form_state['values']['your_name'];
    $email = $form_state['values']['your_e_mail_address'];
    $zip_code = $form_state['values']['zip_code'];
    $date = date('m/d/Y');

    $handle = fopen("pledge_submissions.csv", "a");
    $line = array($name,$email,$zip_code,$date);
    fputcsv($handle, $line);
    fclose($handle);

}

```

It seems these functions are firing but when I open the CSV, no data has been added.

Is `$form_state['values']['field_name_here']` the correct way to target the webform field values? When I try to alert things inside that function the form errors out after submission.

# Answer
> 0 votes
Two things:

Check your argument to `fopen` for validity, and two, the `$form_state` in Webform is missing a key. Example:

```
  $data = array(
    'full_name' => $form_state['values']['submitted']['full_name'],
    'company' => $form_state['values']['submitted']['company'],
    'phone' => $form_state['values']['submitted']['phone'],
    'email_address' => $form_state['values']['submitted']['email_address'],
    'areas_of_interest' => array(),
    'comments' => $form_state['values']['submitted']['comments'],
  );

```

You are missing `['submitted']`.

---
Tags: 7, hooks, webforms
---


# Question
Title: "Did not meet requirements; missing migrations" error
In a custom D6-\>D8 migration module, how does one selectively migrate specific content-types, vocabs and blocks, etc, without receiving the error: 'XXX did not meet requirements. Missing migrations XXX'

I can already selective limit via migrate\_prepare\_row(), but anytime I do so content related to anything not migrated makes MI throw this error and fail.

Is there any core process plugin that addresses this type of scenario per row?

# Answer
> 1 votes
You don't describe precisely how you're doing your custom migration, but the key to missing requirements on migrations you are omitting is to remove the dependencies. The migration that is complaining will have in its configuration something like

```
migration_dependencies:
  required:
    - d6_user
    - d6_node_type
    - d6_node_settings
    - d6_filter_format
  optional:
    - d6_field_instance_widget_settings
    - d6_field_formatter_settings
    - d6_upload_field_instance

```

Simply remove references to migrations which you are not running.

---
Tags: 8, migrations
---