How to restrict users of other roles from seeing the site administrator details? I have created a role called "Site Admin" and created a user with that role. When i log in with that username.  "People" menu is showing in toolbar only when we give "adminster user" permissions to site admin. But when we give adminster user permission site admin can see and edit users in the site. These includes our main administrative users. How can i give permission so that site admin can only see the users excluding administrator user?

That's kind of a "asking for a module to do X" question, which is not really allowed but I do think it is a very common task.

There are a few approaches/modules to this, we are using the combination of https://www.drupal.org/project/userprotect to prevent users from editing users that already have the administrator role, and https://www.drupal.org/project/roleassign to prevent them from giving the administrator role to a user that they are allowed to edit.

There is also https://www.drupal.org/project/administerusersbyrole, which in the 8.x-2.x branch attempts to solve this without requiring users to get the administer users permission, which is more safe, but it also requires core patches because a lot of things in core itself can't really deal with users being able to edit other users without that permission yet.


How to translate custom content block title? How do I properly translate custom content block titles?

Problem:
I've got a custom content block with just one CKeditor text field. I want to show the custom block title and the text field. When I place that block, the PLACED block title is copied from (but not referencing) the custom content block.

When a content translator later translates that custom content block, the PLACED block title is wrong/untranslated. Is there a way to reference the correctly translated, custom content block title in block placement? E.g. using tokens?

NOT allowed solution:
Giving translators access to block placement to translate the block placement is an absolute no-go. They are only allowed to use custom block library.

Unwanted workaround:
I know I could create an additional fake-title field and disable "Show title" in block placement. But I really hope I can avoid this, or I would have to modify all my existing block templates.

To use the title from the custom content block entity (not the title from the block placement config):

function mymodule_preprocess_block (&$variables) {
  if ($variables ['elements'] ['#base_plugin_id'] == 'block_content') {
    $variables ['label'] = $variables ['content'] ['#block_content'] ->label ();
  }
}

This also respects translations and does not require access to block placement for translators.


How do I schedule a PHP function every 2 month? I need, every 2 months, to execute some rule component programmatically, but I don't know how to do this.

If I use hook_cron(), I don't know how to check 2 months are passed from the last time it was executed.

I can check 'the 10th day of the month' + 'month number is even'.

If cron tasks run twice a day, I cannot send 2 identical emails to users.

How can I achieve this?

You can easly do this without having access to crontab/shell, by using following code in your cron_hook:

// check if current day is 10th and month is an even number
if (date('d')==10 && date('m') % 2 == 0) {
    // get todays-date (format: yyyymmdd)
    $today = date('Ymd');
    // get info about last run
    $last_run = variable_get('my_last_run', 0);
    // check last run was not today
    if ($last_run!=$today) {
        // set last run to today
        variable_set('my_last_run', $today);

        /* Place your code here */

    }
}

For more info on the modulo-operator (the % ) check:
http://www.php.net/manual/en/internals2.opcodes.mod.php


Sharing variables between node preprocess and page preprocess Both of my preprocess files use the $vars array. I assigned a new element to the $vars array in page preprocess but I can't access this variable in node preprocess. I tried doing it the other way around and had the same problem. How can I get around this?

The node object itself can be used to share information across these two functions. In your template_node_preprocess() override do something like:

$node = $variables['node'];
$node->my_data = my_data_function();
$variables['my_data'] = $node->my_data;

Then in template_preprocess_page() override write:

if (!empty($variables['node'])) {
  $variables['my_data'] = $variables['node']->my_data;
}


Drupal and apache rewrites I'm just migrating a site that has a proxy pass in the vhost config like the following.

ProxyPass /n/ http://xxx.xxx.xxx.xx:80/n/
ProxyPassReverse /n/ http://xxx.xxx.xxx.xx:80/n/

I need to replicate that in the drupal .htaccess file as I don't have direct access to the hosting as we're using a fully managed drupal solution. I have tried the following but it does not work, when I navigate to the drupal site /n I just get a 404.

RewriteRule /n/?$ http://xxx.xxx.xxx.xx:80/n/ [P]

Be aware that [P] requires mod_proxy to be enabled:

RewriteEngine on
RewriteRule /n/(.*)$ http://xxx.xxx.xxx.xx:80/n/$1 [P]


Autocomplete selection in Rules Component How do I create a rules component which lets you select or autocomplete a node from an existing list of nodes?

I have tried all the Data Type while creating a Rule Component. Each one of them requires a direct input rather than a Drop Down Select List or Autocomplete function.

Please advice

I'm assuming that your question is related to executing a Rules Component, and not creating it.

A possible approach might be to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of entities (such as nodes) that you want to be processed.
add a loop to perform a Rules Action, for each entity (such as a node) contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


drupal 7 PDOException error saying I'm missing a table or view mysite_drupal.cache_views The full warning message goes like this: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mysite_drupal.cache_views' doesn't exist: TRUNCATE {cache_views} ; Array ( ) in cache_clear_all() (line 165 of /home/user/mysite.com/includes/cache.inc).
should I try to manually create it?

Yes, if cache_views is missing and you have the Views module installed, you need to create it.

To do so, simply duplicate the standard cache table and rename it to cache_views; they share the same columns.

You might also need to re-create the cache_views_data table, also with the same columns.


Load a media entity/object from a fid? I have the file ID (fid), and the rest of the file object.

I need to get fields from the parent media entity, but I can't find anything about loading a media entity from a file object.

Drupal 8.4.0

Update

I asked this question in relation to another: Media name as link to file

As far as I could find Kevin's comment is correct.

Using the service file.uses you get the file media object:

Example:

$file is a loaded file object.
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

$result should now contain an array like so:

$result['file']['media']['4372'] = 2;

Where 4372 is the media id. and 2 the times the file is used.

From the docs of listUsage:

@return array
   *   A nested array with usage data. The first level is keyed by module name,
   *   the second by object type and the third by the object id. The value of
   *   the third level contains the usage count.


SFTP Can't upload module despite using owner's credentials I'm new to both Linux and Drupal, but I can see that the owner and group assigned to the drupal modules directory is one of my SU accounts on the server. When I log on to SFTP I use that same credential.

I tried to upload a module using Aptana studio and it tells me it can't create folders.

Do you feel that there's additional ownership info needed on the server side? Would my folder rights not be applicable when connecting via SFTP?

Using ssh you can log in to the system to check about directory permissions using the same credentials you use with sftp.

try..

ssh user@host

to login and then use a number of commands to check permissions

ls -l                      //Lists files with permissions for user, group and other
chmod 755 dir/file         //Change file/directory permission
chown user:group dir/file  //Change the user/group ownership of file(s)

scp command can also upload file from local (*nix) machine to server.

scp path/to/local/file user@host:/path/on/server


Popups & colorbox issues in Chrome Hoping for some guidance here. Sometime in the past few weeks, my inline modal popups stopped working in Chrome. I had Colorbox set up at the time, both hand coded inline links and views colorbox triggers. With views, the links now force a page refresh to the home page with the colorbox query appended:

i.e. ?width=500&height=500&inline=true#content

With hard links, the page refreshed on the existing page, with the same query string added.
After some investigation, I discovered that ONE page on the site still works, but it's part of a series of panel variants on a page. I've been through the variants with a fine toothed comb, but they're configured identically, so there's no clear reason why this one page should work when the others don't. I've also tested Chrome on two other (both older) laptops, with the same results.
I installed the Popup module to see if I could by-pass the issue, but the results are exactly the same. The popups work on the one rogue page but not on any of the others. So the problem isn't colorbox, but something else. Again, this is ONLY in Chrome. Firefox and IE both work fine.
I've tried creating solo links on basic pages, I've systematically turned off all the other components on all of the test pages ... nothing. I tried removing all of my custom jquery and disabled my custom modules. No dice.
Can anyone suggest another approach, or other possible conflict areas I can test?
Edit to add:
Looks like the working page is processing the link class as "colorbox-inline init-colorbox-inline-processed cboxElement", while the non-functioning pages are only rendering "colorbox-inline". It's the same block on all pages, so I'm not sure why it wouldn't be processed evenly.
The base colorbox inline code I'm using is adapted from the following:

Link to click

What ever content you want to display in a Colorbox.

Turned out to be a conflict with the Superfish menu module. Leaving this here because several other people have reported similar issues and this might help.


Post comment permission by content type and role I want to only allow users of a specific role to be able to comment on a specific content type. The only current solution for this is using the "Comment Permissions" module which unfortunately is only available for Drupal 6 and hasn't been updated for over a year.
I have seen some people saying that it's possible to do this by writing custom code however i haven't been able to find any examples of this. Does anyone here know how this could be done or at least point me in the right direction? I'm not good at php though i have some programming experience.

I was thinking that it would also be okay if i could allow users of a specific role to comment on nodes/content type where commenting has been closed if achieving it that way is simpler.

Any help is greatly appreciated.

These days there is a D7 version of Comment Permissions. Here is a quote about it (from the module's project page):

  ... enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.


twig template suggestion for comment reply form there is no template suggestion for a comment reply form in Drupal 8, how can i create one?
i am not talking about the reply form displayed in the node for which Drupal suggest a template :

field--node--comment--article.html.twig

I'am talking about the form in the redirection page after we click "reply" in a comment. there is no  template suggestion, only this template is suggested

form.html.twig

Can you please tell me how can i create a specific template in my .theme file of my theme.

It's a bit unclear what exactly you want to achieve. But you can easily add another template suggestion based on the form ID by implementing hook_theme_suggestions_HOOK_alter for forms. The form ID can be found in the $variables then. But no matter if you are on the node route or the reply route this will simply give you comment_comment_form.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  $form_id = $variables['element']['#form_id'];
  // Add template suggestion based on form ID.
  $suggestions[] = 'form__' . $form_id;
}

If you want to do something different on the reply route you could check the current path for the /reply and /comment arguments OR check if the route parameters contain a PID, which would be the parent comment ID.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  // Add template suggestion based on form ID.
  $suggestions[] = 'form__' . $variables['element']['#form_id'];
  // Add template suggestion based on form ID and parent comment ID.
  if ($pid = \Drupal::routeMatch()->getParameter('pid')) {
    $suggestions[] = 'form__' . $variables['element']['#form_id'] . '__reply';
    $suggestions[] = 'form__' . $variables['element']['#form_id'] . '__reply__' . $pid;
  }
}

Which will give you the following theme suggestions.

<!-- FILE NAME SUGGESTIONS:
   * form--comment-comment-form--reply--1.html.twig
   * form--comment-comment-form--reply.html.twig
   * form--comment-comment-form.html.twig
   x form.html.twig
-->


How can I use one of the pre-set email texts for user registration in a custom module At /admin/config/people/accounts, there are several stock email messages set.
How can I use one of these when I am sending emails from a custom module?
The text that's being used in "Welcome (new user created by administrator)" is all that I need, plus there's the bonus that our client can edit this email in the future if they want to.
I can send the message easily enough using:
$params = [
   'title' => "My Title",
   'subject' => "An Account Has Been Created for you",
   'message' => Html::escape("Some text here")
 ];

$result = $mailManager->mail($module, $key, $to, $language_code, $params, NULL, true);

Is there a variable somewhere to get the pre-entered text?

I guess this should be possible via configuration API. Look for the suitable entry where the message body is saved, call it via the service to put it into a variable. Then you can do additional coding with the string variable.
More information you can find here:
Configuration override system in the docs


Field Collection Data Deletion for particular Content type I have one senario where 2 for content type i have added field collection field.

Each content type has around 3k plus nodes data. each nodes has 50+ records of field collections. All content creation done through excel import functionality.

For second content type, the field collection records that i imported is wrong. i want delete all the fields collection items only for second content type.

How to do it? i can't manually since it has 3k+ nodes and 50+ records in each nodes.

Any module which handle these kind of scenario? or any coding documentation which help me here.

as i search i got few related links as below. but none of them completely fit my requirement.

Could anyone please let me know or help me achieve this.

Deleting field collection items : As mentioned on this page i can't play with DB.

Field Collection Value field is not deleting correctly(using programmatically) : looks like i can use it deletion of data. but how for particular content type.

And I have to give one interface on the site where a non-technical guy can handle this if the same mistake happens.

If anybody knows please help.

Thanks in Advance.

My suggestion is to do this using code. IF your using D7, try following code in any custom module or in a basic page.

//Use a query to get all nodes of your particular content type.

$results = db_query("SELECT nid FROM node WHERE type = 'your-content-type'");
$nids = array();
foreach($results as $result){
  $nids[] = $result->nid;
}

foreach($nids as $nid){ // use for loop for testing
  $node = node_load($nid);
  foreach ($node->field_international_activity[LANGUAGE_NONE] as $key => $value) {
   // Build array of field collection values.
   $field_collection_item_values[] = $value['value'];

   // Unset them.
   unset($node->field_international_activity[LANGUAGE_NONE][$key]);
  }

// Delete field collection items.
entity_delete_multiple('field_collection_item', $field_collection_item_values);
node_save($node);
}

For more details please refer link1, link2

This code is not tested, first just try for a single node by using a for loop instead of foreach.


How to add another field collection instances on Add Form page load programatically I have one field collection with unlimited values in Commerce Product Add form.

After performing some action, When user redirects to Add Product form, based on some predefined values in session, I want to display User a Field collection items pre-filled.

If I have 5 predefined values then 5 Field-collection items would be displayed to User and by clicking on save that product would be saved with that field collection item values.

By clicking on 'Add another item', User can add more as well. Above field collection items won't be saved until User clicks on Save form button.

I tried below code but it's not adding new items/instances :

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_product_ui_product_form') {
    if (isset($_SESSION['compatibilityInfo']) && $_SESSION['compatibilityInfo'] != '') {
      $compInfo = $_SESSION['compatibilityInfo'];
      $comp = explode('!c!', $compInfo);
      $cnt = count($comp);

        // Go one level up in the form, to the widgets container.
        $element = drupal_array_get_nested_value($form, array('field_part_details','und'));
        $field_name = $element['#field_name'];
        $langcode = $element['#language'];
        $parents = $element['#field_parents'];
        // Increment the items count.
        $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
        $field_state['items_count'] = $cnt;
        field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);

    }
  }
}

I had to do this recently on a product.  What I ended up doing is copying the instance of the field collection and then looping through and creating them.  If your session variable keys are numerical from 0 on then you dont need the $item_count.  In my case it was not so I could not simply use the foreach($value as $key => $val).

$my_loop = array(); // Array of items with your default values
$item_count = 0;
$field_collection_clone = $form['field_my_field_collection']['und'][0]; // Clone the field collection form element

//Loop through and create a new instance of the field collection form
foreach($my_loop as $loop){
 $form['field_my_field_collection']['und'][$item_count] = $field_item_base;
 $form['field_my_field_collection']['und'][$item_count]['field_my_field']['und'][0]['value']['#default_value'] = 'my default value';
$item_count++;
}


Why does drush en node_clone end up in a circle this pretty much says it all:

drush en node_clone
node_clone was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                             [ok]
node_clone
Would you like to download them? (y/n): y
Install location /xxx/sites/all/modules/node_clone already exists. Do you want to overwrite it? (y/n): y
Project node_clone (7.x-1.0) downloaded to /xxx/sites/all/modules/node_clone.                            [success]
Project node_clone contains a module named clone.
node_clone was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                             [ok]
node_clone
Would you like to download them? (y/n): y
Install location /xxx/sites/all/modules/node_clone already exists. Do you want to overwrite it? (y/n): n
Skip installation of node_clone to /xxx/sites/all/modules/node_clone.                                    [warning]
node_clone was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                             [ok]
node_clone
Would you like to download them? (y/n): n

Seems this has been well answered in drupal.org

Commands need to be

drush dl node_clone

but

drush en clone

Discussions about the 'naming standards' are here


Why does Git in Cygwin complain about info/refs not being found? I am learning to use git with Drupal. I'm using Cywgin (Windows-based Linux command line), and trying to follow Practicing patches. The documentation tells me to use the command:

git clone --branch master http://git.drupal.org/project/current_content.git

However, I appear to have an old version of Git, because it tells me that "--branch" is unknown. The Git troubleshoot page explains a work around:

git clone [project_url] [directory]
cd [directory]
git checkout --track origin/[existing_branch_name] -b [tracking_branch_name]

However, the first line tells me:

fatal: http://git.drupal.org/project/current_posts/current_posts.git/info/refs
 not found: did you run git update-server-info on the server?

Any suggestions on what I am doing wrong? I've got the last version of git via Cygwin.

From the error, it looks like your git clone line was incorrect (it complains about current_posts—which isn't a project—instead of current_content—which is). Try:

git clone http://git.drupal.org/project/current_content.git

You can also do:

git clone git@git.drupal.org:/project/current_content.git

Note that the master branch is the default branch: you don't need to specify it in the clone or afterwards: it'll automatically check it out.


Form submit to page with another Form I am trying to make a submission from one page that has a form to another dynamic page with a form. As you can see in my hook menu I'm using drupal_get_form as the callback and I would think this would normally work, since I am able to go to the 1st form just fine without any problems.

I do notice I get this error when I submit to the URL, the page is simply not rendering the 2nd form or the contents I have in the function that is suppose to display in the mark up of the 2nd form.

This is the error I get

Notice: Undefined index: listings_mini_form in drupal_retrieve_form() (line 764 of /home/domain/public_html/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'listings_mini_form' not found or invalid function name in drupal_retrieve_form() (line 799 of /home/domain/public_html/includes/form.inc)

This is not a multiform rather it is 2 different pages with their own forms.

Any suggestions?

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

    $items['site/listings'] = array(
        'title' => 'State Listings',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('listings_form'),
        'access arguments' => array('access content'),
    );

    $items['site/listings/%/%'] = array(
        'title' => 'Business Listings',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('listings_mini_form'),
        'access arguments' => array('access content')
    );

    return $items;

}

/*
 *  FIRST FORM
 */

function listings_form($form, &$form_state){

    $form['zipcode'] = array(
        '#title' => t('Zipcode'),
        '#type' => 'textfield',
        '#maxlength' => 5,
    );

    $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
        '#type' => 'submit',
        '#value' =>  t('Submit')
    );

    return $form;
}

/*
 *  FIRST FORM SUBMIT FUNCTION
 */

function listings_form_submit($form, &$form_state){

    $zipcode = $form_state['values']['zipcode'];

    $form_state['redirect'] = 'site/listings/'.strtolower(listings_db_state($zipcode)).'/'.strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
}

/*
 *  2ND FORM ON PAGE IM CALLING
 */

function listings_mini_form($form, &$form_state){

    $form['mini-form'] =  array(
        '#title' => t('Enter your Zip Code for more listings.'),
        '#type' => 'textfield',
        '#maxlength' => 5,
    );

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

    if(isset($form_state['values'])){
        $form['page_output'] = array(
            '#markup' => listings_list_view($form, $form_state)
        );
    }

}

/*
 *  2ND FORM SUBMIT FUNCTION
 */

function listings_mini_form_submit($form, &$form_state){

    $zipcode = $form_state['values']['zipcode'];

    $form_state['redirect'] = 'site/listings/'.strtolower(listings_db_state($zipcode)).'/'.strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
}

/*
 *  FUNCTION WITH LISTINGS INSIDE OF IT
 */

function listings_list_view($form, &$form_state){

    global $base_url;

    $zipcode = isset($form_state['values']['zipcode']);
     dpr($zipcode);

     #blah blah blah
}

Use this code, your missing $return $form in the second form

    /**
     * Implements hook_menu().
     */
    function listings_menu() {
        $items = array();
        $items['site/listings'] = array(
            'title' => 'State Listings',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('listings_form'),
            'access arguments' => array('access content'),
        );

        $items['site/listings/%/%'] = array(
            'title' => 'Business Listings',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('listings_mini_form'),
            'access arguments' => array('access content')
        );

        return $items;
    }

    /*
     *  FIRST FORM
     */

    function listings_form($form, &$form_state) {

        $form['zipcode'] = array(
            '#title' => t('Zipcode'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        return $form;
    }

    /*
     *  FIRST FORM SUBMIT FUNCTION
     */

    function listings_form_submit($form, &$form_state) {

        $zipcode = $form_state['values']['zipcode'];

        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  2ND FORM ON PAGE IM CALLING
     */

    function listings_mini_form($form, &$form_state) {

        $form['mini-form'] = array(
            '#title' => t('Enter your Zip Code for more listings.'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

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

        if (isset($form_state['values'])) {
            $form['page_output'] = array(
                '#markup' => listings_list_view($form, $form_state)
            );
        }
        return $form;
    }

    /*
     *  2ND FORM SUBMIT FUNCTION
     */

    function listings_mini_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  FUNCTION WITH LISTINGS INSIDE OF IT
     */

    function listings_list_view($form, &$form_state) {
        global $base_url;
        $zipcode = isset($form_state['values']['zipcode']);
        dpr($zipcode);
        #blah blah blah
    }

I got output using this code

    /*
     *  FIRST FORM
     */

    function listings_form($form, &$form_state) {
        $form['zipcode'] = array(
            '#title' => t('Zipcode'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        return $form;
    }

    /*
     *  FIRST FORM SUBMIT FUNCTION
     */

    function listings_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . $zipcode . '/' . $zipcode;
    }

    /*
     *  2ND FORM ON PAGE IM CALLING
     */

    function listings_mini_form($form, &$form_state) {
        $form = array();
        $form['mini-form'] = array(
            '#title' => t('Enter your Zip Code for more listings.'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

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

        if (isset($form_state['values'])) {
            $form['page_output'] = array(
                '#markup' => listings_list_view($form, $form_state)
            );
        }
        return $form;
    }

    /*
     *  2ND FORM SUBMIT FUNCTION
     */

    function listings_mini_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  FUNCTION WITH LISTINGS INSIDE OF IT
     */

    function listings_list_view($form, &$form_state) {
        $zipcode = isset($form_state['values']['zipcode']);
    }


How to create a node out of a webform submission? I'd like to be able to create a node out of a webform submission in Drupal 8. It can happen either on successful submission or as an additional task after the webform has been submitted. I've seen some info on creating content entities via REST/GET (https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities) and I know that you can post a webform submission to a URL with Webform (yamlform) using either x-www-form-urlencoded or JSON, but I'm not sure if this is even the right thing to be looking at.

The webform, submissions, and content type I'd like to use are all on the same site.

I know this question came up for Drupal 7 and the direction was to have them use a content type, but we're not able to allow the submitters to use content types at this time because of the way the site is setup.

The answer from @owenpm3 is great for adding this as an administrative duty.

In order to automate this and make it occur on a successful submission, I would create a custom WebformHandler that you add to your form in the configuration settings, the same way you configure your form to send an email upon a successful submission. So under your web forms Settings tab, under the sub-tab: Emails / Handlers.

To build this you would need to create a custom module, mymodule and place the custom webform handler in: mymodule/src/Plugin/WebformHandler/

I will call the WebformHandler MyWebformHandler.php. Aside from this you will need an info file and that should do it.

Code for MyWebformHandler.php as follows:

<?php

namespace Drupal\mymodule\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create a new Article node from a webform submission.
 *
 * @WebformHandler(
 *   id = "article_from_webform",
 *   label = @Translation("Create a node on submit"),
 *   category = @Translation("Content"),
 *   description = @Translation("Creates a new Article node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class MyWebformHandler extends WebformHandlerBase {

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

    // Get an array of form field values.
    $submission_array = $webform_submission->getData();

    // Dump the $submission_array to acquire the fields if you don't know what fields you're working with.

    // Prepare variables for use in the node.
    $title = $submission_array['subject'];
    $body = "
" . $submission_array['name'] . "
";
    $body .= $submission_array['email'] . "
";
    $body .= $submission_array['message'];

    // Create the node.
    $node = Node::create([
      'type' => 'article',
      'status' => FALSE,
      'title' => $title,

      'body' => [
        'value' => $body,
        'format' => 'basic_html',
      ],

    ]);

    // Save the node.
    $node->save();
  }
}


Views Bulk Operations with Field Collection Item tokens I am trying to modify the values of one field in all instances of a field collection type.
I have a view listing all field collection items, that I want and an operation field with modify entity. Setting value in the field works fine, but I can't use any tokens from the current item, only site tokens are available.

Can this be done with VBO? Are there any other easy ways to do it?

You can create a view of nodes, rather than field collections, then add the collection as a Relationship.

Your node tokens should now be available for application to the field collection fields.


Group search result by content type I am using apachesolr on my drupal 6 website for search. Now I wanted to use filter results by content type on search page.
At first I was using a panel page as search page. Here I tried to use the apachesolr filter by content type block. But this didnt work. I tried all other facets available with apachesolr module and all others worked fine. Now I thought maybe filter by content type doesnt work with panels quiet well so i removed the panel page and used the apachesolr default search psge. Still it doesnt work for me.

Can someone tell me some method for grouping my search results by content type.

I have used same thing in Drupal 7 . Please check if this can help

Function custom_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  $resultTypes = array();

  // Divide results
  foreach ($variables['results'] as $result) {
    $resultTypes[$result['bundle']][] = $result;
  }

  // Create fieldsets
  foreach ($resultTypes as $resultType => $resultTypeResults) {
    $value = '';

    foreach ($resultTypeResults as $result) {
      $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));

  $variables['search_results'] .= theme('fieldset', array('element' => array('#title' => $resultType, '#children' => $value));
  }
}


Render exposed filter without creating block Can we place/render exposed filter to some other region(sidebar second) without creating exposed filter in block because when we creating exposed filter with block its autosubmit functionality stopped working ,without creating exposed filter with block its autosubmit functionality working fine.

I am using better exposed filter module https://www.drupal.org/project/better_exposed_filters.

I found the solution. I created a custom block which uses the following code.
use Drupal\Core\Form\FormState;
use Drupal\views\Views;

$form = [];
$view_id = 'Your-view-id';
$display_id = 'your-display-id';
$view = Views::getView($view_id);
if ($view) {
  $view->setDisplay($display_id);
  $view->initHandlers();
  $form_state = (new FormState())->setStorage([
    'view' => $view,
    'display' => &$view->display_handler->display,
    'rerender' => TRUE,
  ])
    ->setMethod('get')
    ->setAlwaysProcess()
    ->disableRedirect();
  $form_state->set('rerender', NULL);
  $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
  print render($form);
}

You can create your own exposed filter in a block without requiring any third-party module.


how to create custom template for a product type in drupal 8 commerce I want to have separate twig templates for each product type in drupal 8 commerce to customize them.

is there any way to do that?

by default drupal 8 uses commerce-product.html.twig. you can find it from modules/contrib/commerce/modules/product/templates/ and copy and paste it to your template folder in your theme.

and to create separate template file for each product type you can add --product type at the end of file name. for example if you have shoes product type then you should create a file commerce-product--shoes.html.twig.

then drupal uses the new template for shoes product type only.


logging in after exiting website under maintenance i was installing updates for drupal website, while on maintenace mode. waited for updates to finish and then signed out. i've been trying a lot of things i'm reading online and it doesn't work. on another note, possibly related, when i've tried to do some editing on certain blocks i get the message that i don't have sufficient permission to edit. also, while googling online i found my website, though, with a different url that had the log-in ability, but my credientials didn't work. i believe my next attempt is to insert or edit code in the db..how can i do that? or whats the best solution? sorry to type so much, i've been doing a lot of research on this and i've become desperate.

Are you logging in as Admin (user 1) or a site administrator?  They are the only ones who have the rights to login while the site is in maintenance mode.  The URL should be http://www.example.com/user/login or http://www.example.com/index.php?q=user .

KMT


Displaying 5 decimals in shopping cart I'm developing a website that mostly sells electrical wire. Prices are per kilometer and imported into commerce with 2 decimal places. Order amounts are per meter though, so in a rule I divide the price by 1000 when calculating the unit price. I use the following module for formatting the price with 5 decimals after the decimal point: https://drupal.org/project/commerce_price_decimals_formatter . In the display node this renders the price per meter correctly.

In the shopping cart view, I can also choose to format the price with 5 decimals, but the extra decimals are not shown, and simply show zeros.

So if I have a cable that's priced at

€ 124.44 / km, it shows
€ 0.12444 / m in the product display node, but
€ 0.12000 / m in the shopping cart

The totals in the shopping cart are correct. I'm guessing views is only getting the unit price up to 2 decimals out of commerce. What can be done to fix this?

Prices are always going to be rounded when saved unless you've updated the definition of the currency itself to support storage to the 5th decimal place. It sounds like that module is simply offering part of the solution, while the whole solution will involve hooking into the currency info array and then updating whatever prices you've already entered to be saved with the new precision.


Generate google search result for my website like that of flipkart I have my website which i can search in google and it comes up. But if i see flipkart search result on google, it is structured very well. Is there any module to do that in drupal?

I believe this technique is call Rich Snippets and this might be a cool module for you: https://www.drupal.org/project/schemaorg


Schema not getting installed I'm working the SchemaAPI but can't get it to create the tables. This is the content of my schema_test.install which is mostly copied form the examples modules.

<?php
function schema_test_install() {
  drupal_install_schema('schema_test');
}
function schema_test_schema() {
  $schema['schema_test_one'] = array(
    'description' => 'Stores example person entries for demonstration purposes.',
    'fields' => array(
      'pid'  => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique person ID.',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "Creator user's {users}.uid",
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the person.',
      ),
      'surname' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Surname of the person.',
      ),
      'age' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'The age of the person in years.',
      )
    ),
    'primary key' => array('pid'),
    'indexes' => array(
      'name'    => array('name'),
      'surname' => array('surname'),
      'age'     => array('age'),
    ),
  );
  return $schema;
}
/* vim: set ts=8 sw=2 tw=79 cc=80 ft=php:*/

I also have the Schema Module enabled and it lists this schema under "Missing". So it's recognized but never installed when the module is being enabled. What am I missing here?

I got caught out in Drupal 7 by the fact that you don't need to call drupal_install_schema.  Also, hook_install should now be used to perform actions on your tables, rather than set them up.

Drupal 7 sees your schema and installs it automatically when your module is activated, so because you're calling it manually, it's trying to install the schema twice.

This might help explain it a bit.

Also, try checking in your database to see if the tables already exist.  If it's installed incorrectly, Drupal might be seeing the tables and thinking they're correct when actually they're not.


drupal_add_js not work in form validation failed I add js file with drupal_add_js in hook_form_alter, it is ok and I see it in list of js loaded in page, but when I submit form and form not validate and return to that form (after validation failed) I don't see js files that added to form, why this happened? and how can add my js file in that form after validation failed ?

some part of my code

function mymodle_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'news_node_form') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js'); //, array('scope' => 'footer','weight' => 10));
  }
}

code work correctly in add and edit form, but when form submit and validation failed it show validation error but my js file not loaded in page (I checked html source and check firebug script files), but there is not my js file,

Javascripts are lost when the form is rebuilt when using drupal_add_js(). Use $form['#attached'] instead. Also, it's better to use hook_form_FORM_ID_alter() instead of a general hook_form_alter(). hook_form_alter() will run for every form on the page. Try using the below:

function mymodule_form_news_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js',
  );
}


Remove or Redirect Users who go to www.domain.com to domain.com My drupal site is apparently accessible as both 'www.domain.com' and just 'domain.com'. Does anyone know of a way to remove the 'www' accessibility, or at least redirect users who go there to the 'domain.com' domain?

I've installed Global Redirect module but am not seeing options that solve this problem. Does Global Redirect module solve this problem or is this a stackoverflow question?

If you're using Apache with your setup, this is built into the .htaccess file that comes with the distribution of Drupal. Look for the following code and follow the instructions in the comments:

  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment and adapt the following:
  # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
  # RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

You'll have to replace example.com with your own site's domain.


Comments sorted by oldest first I've set my comments display order to be oldest first. When there are more comments than the number allowed per page, the comments are spread across 2 pages and a pager is provided.

My issue is that when you first come to the node to see the comments, you see the older comments. You then have to click to the 2nd page to see the latest comments.

I understand from a logical perspective why it works this way, but I don't think its the best for usability. How can I make it so when you arrive at a node you see the last page of comments by default? Do I need to use a views override?
Thanks

Note, in case its of interest this point has been raised by the drupal experts lullabot:
http://www.lullabot.com/articles/drupal-usability-comment-configuration

  While shorter pages are generally more usable, setting the number of
  comments per page to a low number comes in conflict with my
  recommendation of setting the display order to oldest first. With a
  small number, it is very possible that the latest comments will not be
  listed on the initial page and will require several clicks and
  scrolling to get to them. This is bad. A better solution is to set the
  comments per page as high as possible. Users will intuitively scroll
  down to find the latest stuff.

you could do this with a view. I was about to post you a long detailed post on how to get this done, but found this post on the subject that explains it in great detail.

Basically, you create a view and from there you have sort options available for your comment fields.

Credits to DAO Design for the blog post, hope that helps, cheers!


Installation error in Ubuntu - The settings.php file does not exist I've installed Drupal 6\7\8 in WAMP environments for about a hundred times, but I don't recall ever having the following instllation error, which I encountered only in Ubuntu desktop 15.10, Apache2 (2.4.12), Drupal 8:

  The Settings file does not exist.

  The Drupal installer requires that
  you create a ./sites/default/settings.php as part of the installation
  process. Copy the ./sites/default/default.settings.php file to
  ./sites/default/settings.php. More details about installing Drupal are
  available in INSTALL.txt.

As the error suggest, I've tried to create it myself from the default.settings.php as the install error suggests and there was no change. I could surly import it from another Drupal 8 site in my WAMP environment, but I would thank any Drupal developer who would shed some light on why this would even happen?

Maybe it happened due to the fact that in the first time there was an install attempt, the folders permissions were not 777 (now they are - changed recursively for the site's folder only and at least temporarily).

Will thank you for your help,

Update

go to the folder where you installed drupal. Ex:

cd /var/www/drupal

then

sudo chown www-data -R sites

Now try installing again.


how to apply .active class to only one menu item that uses optional filters I have an exposed a filter to a page like so in drupal: http:example.com/user?profile=12 There is a menu entry for this specific link in a block in the sidebar. Is there a way drupal can add the .active class to the link with this specific url. Currently the active class is applied to links with this pattern: http://example.com/user?profile*

Which happen to be all links in that block.

A page with optional filters set in the url is not treated as a new different page, hence the .active class is applied on all pages with the same pattern. Use of a contextual filter such that the path changes to something like:

  http://example.com/user/1

will fix this problem, since each new url will be pointing to a new page.


Print message only if checkbox field is alter using form alter I have created a checkbox in user edit using form alter and based checkbox state I want to print the message. For this I used below code

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

  $form['account']['checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => 'Test check',
   );
   $form['#submit'][] = 'module_simplenews_unsubscribe';
}

//~ //Submit handler for Subscribe/unsubscribe newsletter.
function module_simplenews_unsubscribe($form, &$form_state) {

  if ($form['account']['checkbox']['#value'] == 0) {
    drupal_set_message(t("You are checked"));
  }
 if ($form['account']['checkbox']['#value'] == 1) {

    drupal_set_message(t("You are unchecked"));
  }
}

It works fine. When checkbox is checked/unchecked and user saves the profile it prints respective message. But when user doesn't modify this checkbox field and modify some other field and saves, again it prints message based on checkbox state.

I want to display the message only when checkbox field is modified. How can I achieve this?

You can use form_state instead of form in your submit handler and use default_value of check box in your form alter

$form['account']['checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => 'Test check',
    '#default_value' => 0,
   );

and then your submit handler will go like this

function module_simplenews_unsubscribe($form, &$form_state) {

  if ($form_state['values']['checkbox'] == 0) {
    drupal_set_message(t("You are checked"));
  }
 if ($form_state['values']['checkbox'] == 1) {

    drupal_set_message(t("You are unchecked"));
  }

Use debug tools for proper index of form_state for checkbox.


Calculate percentage between two entity fields in Drupal using Computed Field Module I am trying to calculate a % of two entity fields in Drupal 7 using Computed Field module.

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_accounts_payable_bs'))) /
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_customer_deposits_bs')));

Display:

$display_output = number_format($entity_field_item['value'] , 1 , '.' , ',');

Current the value I get is ".20" But I want it "20.0"

First print_r($data) in your Output code text area so you can see what you can work with. Depending on what you have, your Output code is going to look something like this:

$percent = 100 * $data->field_accounts_payable_bs['0']['raw']['value'] / $data->field_customer_deposits_bs['0']['raw']['value'];

print(number_format($percent, 1, '.', ','));


Checking two databases when logging in a user with a custom module I am trying to create a module that will check for two databases when logging in a user to Drupal. If drupal's native login is a success but the external application does not have that account, then the module will create an account on the external application. If the account is not on drupal but is on the external application then drupal will create a local account. If the user does not exist on either database then the login will fail. Which hook(s) would I need to implement this in a module?

Never tried, but you can basicaly:

try hook_user() but you may not catch the case where the user doesn't exists in drupal but your other site.
create your own login form & callback and:

check if user exists in drupal with user_external_load()
if user exists on your external site either login or register on drupal using user_external_login_register()

You may find some interesting code in the openid_authentication().


Is there a way to call "access callback" with parameters? I have:

function hook_menu()  {
    $items = array();
    $items['experiment-2'] = array(
        'title' => 'Experiment 2',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('experiment_form'),
        'access callback' => 'user_can_access_experiment',
        'file' => 'includes/experiment-2.form.inc',
        'type' => MENU_NORMAL_ITEM,
      );

    ...

This will call:

function user_can_access_experiment() { }

But I want to be able to call it something like:

function user_can_access_experiment($experimentID) { }

And then somehow let hook_menu call the function as user_can_access_experiment(1) or user_can_access_experiment(2) or whatever.

Is this possible?

If I understand your query right the access callback needs to accept a parameter based on which it decides whether or not to return TRUE for the menu path. This should be achievable using access arguments, like

'access arguments' => array($experimentID),

quoting from the hook_menu API documentation

  "access arguments": An array of arguments to pass to the access
  callback function, with path component substitution as described
  above. If the access callback is inherited (see above), the access
  arguments will be inherited with it, unless overridden in the child
  menu item.

The passed argument, in your case the $experimentID could be either from any custom computation like a value from the user object or even a part of your query parameters.


Why don't we hack core? I couldn't believe that this question hasn't already been answered on this site, but I didn't find it when I searched, so...

Why is it such a bad idea crime against nature to hack core?

Is it really that great to be able to upgrade your core version? Most of my sites end up having horribly out of date cores anyway, so why bother?
Even if it is so bad for site owners, why does the community care so much? Why is it referred to as "killing kittens"? Isn't that rather hyperbolic?
Hacking core is so easy, don't we like taking the easier route to a problems' solution?
Aren't there problems that can only be solved by hacking core? What then?

I could write a massive answer here, but I'm just gonna post this link: Never hack core!

The main reason I guess is that if you hack core to do something you need, and then update it...BANG!  Your changes are gone. Lost. You could then try and roll back the code from your VCS, but seeing as you can't roll back database upgrades from Drupal core - you're looking at restoring all code from VCS, and then restoring databases from your backups. All the time you're trying to roll back your code, you'll probably then notice that your last pre-update database backup failed, and you'll swear more than you've ever sworn before.

Also - most importantly - if you hack core, then Dries and Webchick both kill a kitten :-o


Send user's password in mail I want to send a reminder email to the users to log in to my website with their username and password. My mail script is ready with the login ID, but I don't know how to decrypt the user's password.

Can anyone tell me how should I get the password associated with a user account?

You cannot get the user's password from what Drupal saves in the database. Drupal doesn't encrypt the password and saves it in the database, but it saves in database the hash of the password, which is the value returned from a one-way function; this means that is not possible to calculate the value that originated the hash.
That is the reason why hashes are saved instead of the passwords: If somebody access the database used by a Drupal site, it is not possible to retrieve the passwords, and access that site as one of the users registered in that site. (It could still possible to find a word with the exact same hash; so far, collision attacks are shown possible in short time only with MD5.)

Drupal is able to send an email to reset a user's password, which is not what you are asking for, but it could be helpful if you want the users to reset their password after X months. In this case, you could be interested to the code used by _user_mail_notify().

  // By default, we always notify except for canceled and blocked.
  $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
  $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
  if ($notify) {
    $params['account'] = $account;
    $language = $language ? $language : user_preferred_language($account);
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
    if ($op == 'register_pending_approval') {
      // If a user registered requiring admin approval, notify the admin, too.
      // We use the site default language for this.
      drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
    }
  }


Views Contextual Filter - Full Month display I created a View and it is working perfectly. There is only an issue with how it's formatting the dropdown list for Month filtering. Right now it's displaying the months in abbreviated format (ex. Jan, Feb, Mar, Apr). I'd like it to display the months in full format (ex. January, February, March, April).

Is there a way to override this behavior?

Thanks for any help.

function your_module_name_date_select_process_alter(&$element, &$form_state, $context) {
  $element['month']['#options'] = array
  (
    '' => t('Month'),
    1  => t('January'),
    2  => t('February'),
    3  => t('March'),
    4  => t('April'),
    5  => t('May'),
    6  => t('June'),
    7  => t('July'),
    8  => t('August'),
    9  => t('September'),
    10 => t('October'),
    11 => t('November'),
    12 => t('December')
  );
}


Module for floating vertical and customizable image menu I'm looking alternative module to ShareBar (but not for social network buttons).

The features should include:

floating image menu items/buttons (like: Menu Icons) on the side linking to pre-defined paths/URLs
ability to add new menu elements
visible to standard user (including anonymous), not like Quickbar which is for used for admin

Something like having Back To Top or SnapEngage floating button, but with multiple menu items grouped together which are customizable.

Which modules can provide such features? Or how this can be achieved?

In summary, like this:

Image source: Floating Social Share for Drupal

but beyond social buttons (so any button/menu item with any image/link can be added).

You can use Floating block module

Floating Block Module page says

  The Floating block module allows you to keep html blocks, selected
  using jquery selectors in a fixed position on the page as you scroll.
  It works in a similar way the table header fixer in Drupal Core. This
  means that when the user scrolls their browser selected parts of the
  page can stay in the users view.


How to translate a custom Constraint message? I have a custom constraint in the Allow a content type only once (Only One) module that is working and is defined as:

<?php

namespace Drupal\onlyone\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that Only One node of locked languages exists.
 *
 * @Constraint(
 *   id = "LockedLanguages",
 *   label = @Translation("Locked Languages Constraint", context = "Validation"),
 *   type = { "entity" }
 * )
 */
class LockedLanguagesConstraint extends Constraint {

  /**
   * Message shown when a node of a locked language exists on a content type.
   *
   * @var string
   */
  public $nodeExists = "The content type %content_type is configured to have Only One node per language but the node @title exists for the %language language.";

}

And I want to be able to translate the message, the problem is that you can't use the t() function in the property definition. How can I accomplish this?

The constraint system is one of the few places where string literals aren't directly wrapped in t(). One reason for this is probably because the variables which form the "context" and string replacements for the messages aren't directly available when defining the constraint. @see \Drupal\Core\Validation\DrupalTranslator.

So the answer is: core does this for you. You can see exactly where this happens in: \Drupal\Core\TypedData\Validation\ExecutionContext::addViolation.


Loading Video Files via Ajax and Views I am looking for a way to implement a gallery style selection for a content type containing multiple videos.  I am using Drupal 7.

I have a content type called roles which has a title, banner image, description, videos and video thumbnails.

The videos and video thumbnails are file fields which can accept multiple files (the idea being that you can upload the videos then the thumbnail for each video in the same sequence).

At the moment to display videos on the site I am using mediaelement - however for this page layout I need to be able to show the video thumbnails then let the user select and have it load the video via an ajax call.

I have tried using views filters exposed to the user based on the videos file id, however this seems to break the videos.

Is there another way to accomplish this in views? Or is there another way to accomplish what I am trying to do?

I slightly changed the way I handled this after following the excellent tutorial
Creating a Simple AJAX Interface with Views

All is up and working now.


Batch API error: ResponseText: {"errors":[{"message":"Not acceptable format: json"}]} When running a batch process on Drupal 8, the following error is returned:

ResponseText: {"errors":[{"message":"Not acceptable format: json"}]}

The HTTP response is HTTP POST / 406

I can see the route is defined ok for the batch callback with the JSON support there:

select * from router where name like '%system.batch_page%' \G;
*************************** 1. row ***************************
           name: system.batch_page.html
           path: /batch
pattern_outline: /batch
            fit: 1
          route: C:31:"Symfony\Component\Routing\Route":970:{a:9:{s:4:"path";s:6:"/batch";s:4:"host";s:0:"";s:8:"defaults";a:2:{s:11:"_controller";s:52:"\Drupal\system\Controller\BatchController::batchPage";s:15:"_title_callback";s:57:"\Drupal\system\Controller\BatchController::batchPageTitle";}s:12:"requirements";a:2:{s:7:"_access";s:4:"TRUE";s:7:"_format";s:4:"html";}s:7:"options";a:4:{s:14:"compiler_class";s:34:"\Drupal\Core\Routing\RouteCompiler";s:12:"_admin_route";b:1;s:12:"_no_big_pipe";b:1;s:14:"_access_checks";a:1:{i:0;s:20:"access_check.default";}}s:7:"schemes";a:0:{}s:7:"methods";a:2:{i:0;s:3:"GET";i:1;s:4:"POST";}s:9:"condition";s:0:"";s:8:"compiled";C:33:"Drupal\Core\Routing\CompiledRoute":312:{a:11:{s:4:"vars";a:0:{}s:11:"path_prefix";s:0:"";s:10:"path_regex";s:12:"#^/batch$#sD";s:11:"path_tokens";a:1:{i:0;a:2:{i:0;s:4:"text";i:1;s:6:"/batch";}}s:9:"path_vars";a:0:{}s:10:"host_regex";N;s:11:"host_tokens";a:0:{}s:9:"host_vars";a:0:{}s:3:"fit";i:1;s:14:"patternOutline";s:6:"/batch";s:8:"numParts";i:1;}}}}
   number_parts: 1
*************************** 2. row ***************************
           name: system.batch_page.json
           path: /batch
pattern_outline: /batch
            fit: 1
          route: C:31:"Symfony\Component\Routing\Route":858:{a:9:{s:4:"path";s:6:"/batch";s:4:"host";s:0:"";s:8:"defaults";a:1:{s:11:"_controller";s:52:"\Drupal\system\Controller\BatchController::batchPage";}s:12:"requirements";a:2:{s:7:"_access";s:4:"TRUE";s:7:"_format";s:4:"json";}s:7:"options";a:3:{s:14:"compiler_class";s:34:"\Drupal\Core\Routing\RouteCompiler";s:12:"_admin_route";b:1;s:14:"_access_checks";a:1:{i:0;s:20:"access_check.default";}}s:7:"schemes";a:0:{}s:7:"methods";a:2:{i:0;s:3:"GET";i:1;s:4:"POST";}s:9:"condition";s:0:"";s:8:"compiled";C:33:"Drupal\Core\Routing\CompiledRoute":312:{a:11:{s:4:"vars";a:0:{}s:11:"path_prefix";s:0:"";s:10:"path_regex";s:12:"#^/batch$#sD";s:11:"path_tokens";a:1:{i:0;a:2:{i:0;s:4:"text";i:1;s:6:"/batch";}}s:9:"path_vars";a:0:{}s:10:"host_regex";N;s:11:"host_tokens";a:0:{}s:9:"host_vars";a:0:{}s:3:"fit";i:1;s:14:"patternOutline";s:6:"/batch";s:8:"numParts";i:1;}}}}
   number_parts: 1
2 rows in set (0.00 sec)

Just wondering if anyone else has encountered this error for the Batch API processing and may have some suggestions on it.

In our case, we had to turn off Cloudflare's Query String Sort option. See here --> https://support.acquia.com/hc/en-us/articles/360022037774-Resolving-Not-acceptable-format-json-error-HTTP-code-406-in-batch-operations

Here is the drupal issue too --> https://www.drupal.org/project/drupal/issues/2879023


Modify the page title of view and set custom title for it I am using views and drupal 7 . I pass arguments in the URL and i want this as view page title. This is possible by using override title check-box. But i want to modify this title. i.e do some formatting and some trim of the content and show only what i require as title. how can i do it.

Found one that works

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'menu') {
    $view->build_info['title'] = "TEST TITLE";
  }
}


how to hide the adminblog link in the teaser how to remove admin`s blog in footer of teasers i can remove the add comment link with this code :

function  mytheme_node_view_alter(&$build){
if ($build['#view_mode'] == 'teaser')
{
    // remove "add comment" link from node teaser mode display
    unset($build['links']['comment']['#links']['comment-add']);

    // and if logged out this will cause another list item to appear, so let's get rid of that
    unset($build['links']['comment']['#links']['comment_forbidden']);
}

but i cant remove admins blog what can i do ?!

Try to use something like the below code to hide admin's blog from teaser's view in your theme's template.php, hope it will work for you:

function THEME_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'teaser') {
        if ($variables['type'] == 'blog' && (arg(0) != 'blog' || arg(1) != $variables['uid'])) {
          unset($variables['content']['links']['blog']['#links']['blog_usernames_blog']);
          unset($variables['content']['links']['node']['#links']['node-readmore']);
        }
      }
    }


Views Grid Display Images Thumbnail Sequently using jQuery I am trying to make an image catalog using views grid. This is what I have done so far.

Created a views grid and gave the test class to each .

tr class="row-1 row-first">

Then I added my custom Javascript to my .info module file. This works since I can confirm it by viewing the page source.

These are the contents of my custom.js :

(function($){
var lis = $('.test').hide(),    i = 0;

(function displayImages() {
        lis.eq(i++).fadeIn(200, displayImages);
})();
})(jQuery);

When I open Mozilla Firefox there is no Javascript error and the effects are not working.

Please guide me to solve this problem. I am following this great tutorial.

Regards,

mbahlol

UPDATE

aha i found it. this is what i do, based on stackoverflow

(function ($) {
$(function(){
var lis = $('.test').hide(), i = 0;
(function displayImages() {
    lis.eq(i++).fadeIn(800, displayImages);
})();
})
})(jQuery);

First check if your jQuery file is properly called, if its called than you can add jQuery.noConflict(); first and than replace $ sign with jQuery.


Change pathauto generated URL of node Does anybody know where/how to change the pathauto-URL of a node (that comes out of the db table "url_alias")?

Background (Example):

I have a page with list of nodes (A, B, C)

A -> links to "clean-URL/A.html"
B -> links to "clean-URL/B.html"
C -> should not link to "clean-URL/C.html" but to "clean-URL/A.html" (C has a field that says it should link to A)

So, I want that everywhere there is a link to C, the link should be changed to A. For example in search results or in views.

Unfortunately I can't find a pathauto hook that does something like "render_pathauto_link_of_node"...

I found what I needed. It is the function hook_url_outbound_alter...

function myModule_crawler_url_outbound_alter(&$path, &$options = FALSE, $original_path){
    $mother_nid = $options['entity']->field_mother_series_nid["und"][0]["value"];
        if( $mother_nid > 0 ){
            $path = "CLEAN-URL/".$mother_nid;
            $options['alias'] = "CLEAN-URL/".$mother_nid;
        }
}

Thanks for helping!!!


(nginx) File field upload progress not working, but upload progress in FileField Sources works Drupal 7.14, FileField Sources 1.4, Nginx, php cgi. File upload limit 1000MB. Using Chrome as browser

Everything has been configured fine.

I've tested using FileField Sources, upload about 700MB through Remote URL. Everything including the progress bar works without problem, even it takes too long time up be uploaded.

But when upload from my computer;

If upload small file, the upload progress is visible, but not showing any progress even the file uploaded as usual.

If upload large file, it will be same as above. But it will timeout (timeout after 30 seconds if using Chrome) (if using Opera, the timeout sometime after 17 seconds, sometime after 5 seconds).

The timeout error in Opera:

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /file/ajax/field_hcuba/und/0/form-j39oCcFwF3Y4J8hBu8A1HHms9oDs3xuhYIgLoZ0MQ2Q
StatusText: n/a
ResponseText: 413 Request Entity Too Large
nginx
ReadyState: undefined

The timeout error in Chrome:

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /file/ajax/field_hcuba/und/0/form-1smxhyxT7Xw1F6zjZul2gRxkMI7DNF8pkPRTUyW35SU
StatusText: n/a
ResponseText:
ReadyState: undefined

This only happen in Nginx server. In Apache, all works without problem.

Nginx doesn't support upload progress in core, you will need to install - http://wiki.nginx.org/HttpUploadProgressModule

To show upload progress a webserver should implement - RFC1867


point a subdomain to a page without using domain module I want to add a subdomain to my site (mysite.local) so it is, x.mysite.local and I want that to land on a custom page, i.e. a node, a view. I do not want to use the domain module because it has way more stuff that I need. Is there an easy way to do that in a custom module?

I tried doing something like this in settings.php but that does not seem to work:

// Get the subdomain:
$sub = explode('.',  $_SERVER['HTTP_HOST'])[0];
if ($sub == 'test') {
  $config['system.site']['page']['front'] = "node/12664";
}

I'm going to assume 1) you already have the proper DNS records set up and 2) you want a redirect (tells the browser to go to URL node/12664) and not a proxy rewrite (i.e. serve the page at node/12664).

Your best option would be to handle this in your .htaccess with mod_rewrite:

# Handle request for subdomain
RewriteCond %{HTTP_HOST} ^test\.mysite\.local$ [NC]
RewriteRule (.*) https://mysite.local/node/12664 [L,R]

If you do want to try to handle this as a redirect in your settings.php you could try something like this:

if ($_SERVER["HTTP_HOST"] == 'test.mysite.local') {
    // Tell the browser to redirect to the HTTPS URL.
    header("Location: https://mysite.local/node/12664");
    exit;
}

If you want to serve a page from a different subdomain/host, without changing the URL, you'll have to delve into the hell of Apache ProxyPassReverse


Referencing "type" in nodes returned by loadMultiple(); I know there are easier ways to sort nodes by type, using views, or using:

$query->loadByProperties(['type' => 'my_content_type']);

... but what I really want to do is return ALL nodes and then do different things based on the type field, like so:

$result = \Drupal::entityQuery('node')->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

foreach ( $nodes as $node ) {
  if ( $node->type == "my_content_type" ) {

    // do something...

  } else {

    // do something else...

  }
}

However, my condition is never getting met, so I can only conclude that I am referencing the node type incorrectly. What am I doing wrong?

Thanks @berramou the solution is to use:

if ( $node->bundle() == "my_content_type" ) { ... }

Solved!


Categorizing content types I have a lot of views that need a content type filter which I should select about 20 content types for each of them.
Is there any module to categorize content types(not contents)? For example adding a taxonomy term named news to content types news, image news,.. so instead of selecting content types I will add the filter content typs has tag news.

You can't add fields to the content type in regular old Drupal.

Also, the thing is that the view itself is pulling fields from the actual entities you're trying to list, so even if you manage to somehow add tags/fields that relate to the content type (through a custom or contrib module), your views wouldn't be able to just access those special fields by default.  After all, your views are actually pulling entities themselves and accessing their fields.  You know?

The simplest way to do this, I think, is to hard-code which content types you want listed in your views as filters:

In your views' 'Filter Criteria' section, simply add the filter 'Content: Type' and select all the content types to include.  So, if you wanted a view that applies to 'news' category types, just filter to include all those content types (news, image news, etc).  Of course, if you ever add a new content type or want to change your categorization, you'd have to edit your views by hand to match the new way of doing things...

The above is better, in my opinion, then adding a 'content category' vocabulary that is included in each of your content types as a field.  Even if a 'category' vocabulary has a default, which allows content editors to create nodes and not have to set a category, the problem is that tagging each node (versus filtering by the content types as above), would make 'switching' your categories or removing/adding categories to your content types harder.  If you decide to change them later, what do you do about all the nodes you've created in the meantime that have been tagged a certain way already?  :-)


Multiple template pages when creating new pages new to Drupal 7. I can kind of get the result I want through "hacky" methods but was wondering what best practice was.

I am creating a drupal 7 bootstrap subtheme.

The main content area of the site needs to come in two basic verities.

A single column content area
A two column content area

I want my end users to be able to select which of the two page layouts to use should they need to create a new page.

I can create the effect to some extent by having the two areas defined as regions in my theme and then having them populated - or not - with blocks.
The issue with this solution is I don't want my end users to be able to add blocks to both layouts. I want them to be forced to select one or the other.

is there an accepted "drupal" way to do something like this?

Option 1:

The simplest "core" way to do this, is to create two separate content types.  For this example, let's call one One Column and the other Two Column

You can now create two different node template files:

node--one-column.tpl.php
node--two-column.tpl.php

Now you can customize those two template files to display the content however you wish, and it would depend on what you want to accomplish with each of these.

Option 1a:

If you decide to go with option 1, using Paragraphs to allow your users to add multiple fields into the columns could be well suited to your needs.

Option 2:

Another option is to use Display Suite which has the similar idea of creating multiple template files, but here you can choose the display method on a per node basis (via Display Suite Extras)  Also since you are using Bootstrap, there is a nice add-on called Display Suite Bootstrap Layouts that provides layouts for you to use.

Option 3:

Panalizer allows you to use "Panels" on a per node basis, which could help you solve this problem. There is also a Panels Bootstrap Layouts module as an add-on.

Option 4:

I believe Panopoly can do this as well.

Summary:

There are many different ways to do this, but you will have to try them out to see which works best for you.  The options above are probably the most common so I'd start there.  If you need anything more specific for your needs, there is always a way.


Future editable select list option? I am building a car directory with 500+ car models x 10 years. Every car listing will have many computed fields calculating various aspects of car model like fuel cost, maintenance, insurance, model depreciation, price after 5 year etc.

Now in depreciation computed field it takes the set value from depreciation rate field (which is different for every car) while adding the car. This Depreciation is region specific and I might have to change or tweak few values as we progress based on people feedback, updated research etc. I need some solution, with which i can change the depreciation rate field and republish the nodes to take effect the new values. In current select list option i can't change any value once that value is in use.

I have tried Views batch update (as a tweak), and that's my last option if I can't get this functionality somehow.

Instead of using the list field type, I'd suggest you to use taxonomy and term reference field. That way you can always update the referenced term independently, add new terms, delete terms etc.

Create a vocabulary for the field, for example, depreciation
Add as many terms as you want to have in the select list
Add a new field in your content type, and as field type select Term reference; as widget select Select list
In the field options you should assign the newly created vocabulary (e.g. depreciation) to that field

UPDATE:

I assume that you have

a content type called 'car'
a vocabulary called 'model'

You should create a new vocabulary for each list field that you need to make future editable/expandable. If I understood correctly, you want to have the 'depraciation rate' editable, so you should create a new vocabulary called depreciation_rate

Go to admin/structure/taxonomy/add
Name it 'Depreciation Rate' or whatever you like
Add as many terms as you want to have in your 'select list' field. The terms will be listed as options in that field.

Then, you need to create a field to reference this vocabulary on the car content type if depreciation rate is different for every car (or on the model vocabulary if the depreciation rate is different for every model).

Go to admin/structure/types/manage/car/fields
Add new field, name it 'Depraciation Rate' with the machine name 'field_depreciation_name', or whatever you like.
As field type select 'Term reference' and as widget 'Select list'
On the field settings, assign the vocabulary you created.


Prepend custom block body text I have a custom block with text in the body field. I need to prepend some text to this body field, either using php in a theme_hook function or in a twig file. How can I get just the text of the body field of a custom block so that I can alter it?

Here are three possible approaches to achieve your desired effect.

1. Hardcoding into a twig template for the custom block

If you don't need to modify the actual content defined within the body field of the custom block, and just want to hardcode the prepended text before the body content, creating a custom twig template for the block itself is probably easier for maintaining in the long run. This way it's easy to find and modify without the need to do any theme_hook function editing.

In your theme's template folder, add a block--[machinename-with-hyphens].html.twig template.
Copy the contents of the block.html.twig template that already exists in your theme or from a theme included with Drupal Core such as Bartik or Classy (/core/themes/classy).
Then in the template, add your markup and desired text before the {% block content %} section.  If your custom block has more than a body field, you can also render just the body field data using {{ content.body }}, and the other fields as {{ content.[field_machinename] }}

2. Hardcoding the text into a theme hook preprocess function

If you would rather avoid setting up a custom one-off twig template for the block and just want to hardcode the prepended text using a preprocess hook, you could:

Add a [custom_theme]_preprocess_block function. If your function doesn't explicitly inlcude the block's machine name in the function name, be sure to check the block machine name before prepending text and setting the content.
Create a variable for your custom markup/formatted text.
Concatenate that with the existing block content.
Set the 'content' variable in the preprocess function

See Drupal.org documentation for template_preprocess_block or hook_preprocess_block

3. Recommended Approach: no template or preprocess code required.

The easiest method to approach this might be to just add a custom field to the custom block type with the default value reflecting the prepended text. To do this:

Go to Structure > Block Layout
Select the Custom Block Library tab
Select Block Types
Choose Edit next to your existing custom block type or Add custom block to add a new custom block type.
In the Manage Fields section, add a field for the predefined text (or markup) to prepend.
In the Manage Display section, set the desired order for the fields to render.


Call node information when rendering links Alright, this one is a bit tricky. I'm using the theme() function and theme_links__system_main_menu to render the main menu in a specific way on the front page. All the menu items link too basic pages.

The idea is that when hovering over a menu item, a pop-up appears with the content of a field called 'Preview' that's on the basic page of which the menu item is linked to. The pop-up itself is a simple CSS thing, so what I'm looking for is a way to access the information of the node in question.

I know $variables contains the link to the node, is there perhaps a function that gives you node information by link?

Assuming that you need to access to $node to populate the preview:

You will need to load the node object for access to $node. So lets say you extract the href from $variables, you wont be able to load node based on the url, atleast I dont know any function that does it. You will need to extract (php explode etc) node nid and then use node_load($nid) to load the $node object and then you can populate the preview based on a field of $node.

Where to write the code?

You can either override the theme function or use the preprocess, the preprocess for this should be (though not sure) yourtheme_preprocess_links__system_main_menu(&$vars) and theme override will be yourtheme_links__system_main_menu. I hope you understand the difference between theme function override and preprocess. I'd suggest preprocess to add preview in $variables and then overriding theme function to use that value. OR, you can build the preview and add it as an attribute to the link.

Hope that helps.


How to create a view with group by node title and no grouping on nid I want to create a view that shows nodes with duplicate titles. I am using Views 7.x-3.7 and Drupal 7.24

To do this I created a view with 2 fields: nid and title.

I turned on Use aggregation and for the node title field set it to group results together, and for the nid field selected count.

The query generated was:

SELECT node.title AS node_title, node.nid AS nid, COUNT(node.nid) AS nid_1
FROM
{node} node
GROUP BY node_title, nid
LIMIT 10 OFFSET 0

Clearly this won't work - we can't count nids if we are grouping by the nid.

How would I change my view so the query outputted was:

SELECT node.title AS node_title, COUNT(node.nid) AS nid_count
FROM
{node} node
GROUP BY node_title
LIMIT 10 OFFSET 0

Is this even possible? And if not why not? I would ideally like to achieve this without hook_query_alter if possible.

Exported view:

$view = new view();
$view->name = 'duplicated_page_titles';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Duplicated Page Titles';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Duplicated Page Titles';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: COUNT(Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'duplicated-page-titles';

If you display nodetitle as a link it won't show as a duplicate. Uncheck 'display as a link' in fieldsettings of title and you should be good to go.

I imported your view, made this change, created a duplicate titled page and my view showed duplicate results immediately grouped by title, displaying the nodecount of that title.


Build a dynamic form based on user input I am looking on how to build a dynamic form in Drupal 6.
Users enter the number of people attended the meeting, and the form should present a text box for each of the people attending the meeting, and containing the contact information. I would love to use webforms to do this.

What would you suggest as best way to do this?

If I understand well, one user need to enter informations for X persons who has to attend to your future meeting right?

To do it, I think the better way is to create a content type and use CCK with multiple field. If you need a group of fields, you can install CCK 3.X that include multiple_group module. It's a module very useful that allow you create a group of fields and the user can multiple it at infinite or as you wish.


Added items to registration form and get "Notice: Undefined property: stdClass" I added 2 items to the user registration form Phone Number and Carrier. When I register a user or edit one i get the following error.
Notice: Undefined property: stdClass::$phone in user_account_form() (line 1066 of /var/www/capaug/modules/user/user.module).
Notice: Undefined property: stdClass::$carrier in user_account_form() (line 1076 of /var/www/capaug/modules/user/user.module).

Here is the code for the user registration:

function user_account_form(&$form, &$form_state) {
  global $user;

  $account = $form['#user'];
  $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

  $admin = user_access('administer users');

  $form['#validate'][] = 'user_account_form_validate';

  // Account information.
  $form['account'] = array(
    '#type'   => 'container',
    '#weight' => -10,
  );
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array('class' => array('username')),
    '#default_value' => (!$register ? $account->name : ''),
    '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
    '#weight' => -10,
  );

  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

  //Phone Number Entry
  $form['account']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#maxlength' => PHONE_MAX_LENGTH,
    '#description' => t('A valid Telephone number. Numbers only, no parentheses or dashes.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->phone : ''),
  );

  //Carrier Selection
  $form['account']['carrier'] = array(
    '#type' => 'select',
    '#title' => t('Carrier'),
    '#options' => array(t('--- NONE ---'), t('AT&T'), t('NTelos'), t('Sprint'), t('Straight-    Talk'), t('T-Mobile'), t('Tracfone'), t('Verizon'), t('Virgin Mobile')),
    '#description' => t('Your phone service provider. Select "None" for home phones.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->carrier : ''),
  );

Where do I have to define those variables to get them to work?

Thank you all!

Never, ever patch core like that. This is not how Drupal works. That said, you didn't specify whether you are using Drupal 7 or not; I presume you do. Instead of doing this, use the field UI module to add the relevant fields to users under Administer > Configuration > People > Profiles.


Conditionally hide the node comments via preprocess function I have learned how to hide the display of the author and the creation date of a node, depending on the content of a taxonomy field.
Is it going to hide the comment on the same way?

function mytheme_preprocess_node(&$variables) {

  // check if this is the right content type where the field exists
  if ($variables['node']->getType() != 'article') {
    return;
  }

  // taxonomy field
  $field = $variables['node']->field_where_to_publish;

  if (!$field->isEmpty() && $field->entity->label() == 'public') {

    // How to hide the comment for this entity label?
  }

}

$variables['content']['comment']['#access'] = FALSE;

That should work, assuming you use the default comment field named "comment", otherwise whatever you named it. Comments are just a field, nothing special about them.

You can also check it directly in twig and not print it there.


How to alter $form_state before render a form? I want to render a Custom Form from a Controller class. So i've written the code like this

class MyController extends ControllerBase {

  public function content() {

    $form = \Drupal::formBuilder()->getForm('Drupal\MyModule\Form\CustomForm');
    return $form;
  }
}

but i want to put some values in $form_state i.e. set #default_values.But here $form is a renderable array, not an object so there is no $form_state object. So, what to set default values ?

An edit form for what exactly?

getForm() accepts arguments. All additional arguments are passed to the buildForm() method of your form. So you pass whatever you are editing in, and when building the form, you get the current value and set it as #default_value of the form elements.

If you are editing entities, then you should consider using an entity form. I'm maintaining the _entityform_block module, which has the following build() method in it's block, you could do something similar in a controller:

$values = array();
// Specify selected bundle if the entity has bundles.
if (\Drupal::entityTypeManager()->getDefinition($this->configuration['entity_type'])->hasKey('bundle')) {
  $bundle_key = \Drupal::entityTypeManager()->getDefinition($this->configuration['entity_type'])->getKey('bundle');
  $values = array($bundle_key => $this->configuration['bundle']);
}

$entity = \Drupal::entityTypeManager()
  ->getStorage($this->configuration['entity_type'])
  ->create($values);

if ($entity instanceof EntityOwnerInterface) {
  $entity->setOwnerId(\Drupal::currentUser()->id());
}

$form = \Drupal::entityTypeManager()
  ->getFormObject($this->configuration['entity_type'], 'default')
  ->setEntity($entity);
return \Drupal::formBuilder()->getForm($form);


What is the equivalent of user_set_authmaps()? I need the equivalent function for user_set_authmaps(), in Drupal 8.

What function/method replaced it?

As reported in {authmap} deprecation, the authmap database table has been removed from Drupal 8; at the same time, the functions using that database table (such as user_set_authmaps()) has been removed.

The suggested alternatives are:

Write your own solution for managing user external authentication and storing remote identities
Use the External Authentication module


Rehash Drupal 7 passwords into SHA1 I need to sync my user database with another user database; the other user database uses SHA1 as hash with USERNAME:PASSWORD as algorithm.
Is there a way to rehash it that I can store it in the database?

Do you have any idea?

It should be possible to edit the user/*/edit form and hash the password on my own and save it afterwards, or am I wrong? If it can work, can you give me any tip on how?

I did a bit reasearch about editing the user_profile_form (for example: Making a username/password syncronization scheme - D7) where I read that $form_state['values']['pass'] could give me the password in plain text to hash it on my own and insert it into my database.
Afterwards I directly tried to investigate more and tried to displa me the password with dpm($form_state['values']['pass']);, but I noticed (controlled with dpm($form, '$form info for $form_id '.$form_id);) that theres no values.

How can I get the plain text password in user_profile_form or is it impossible and only possible in user_register_form (as stated in topic above).
In my user_registe_form is no password entered, because I use the method to get a link with E-Mail were you can login one time and change the password with user_profile_form.

Thank you!

There are a couple of ways to do this.

You need to look into the function user_authenticate.

In that function, you will see there is a call to variable_set() that sets the path to the variable password_inc. So, basically you could overide the path of this file, change it so it points to your custom password.inc, in a custom module out of core code.  In that file you would redefine the same functions with your own logic.

There could well be a simpler way of doing this.  I know single-sign on can also be easily done with Drupal 7 as there are functions that make this easily available out of the box. Maybe look at OpenID code or other contrib modules if you choose to use that path.

Good-luck!