How to restrict creation of content based on unique field values? I'm not entirely sure how to title this question.  I want to restrict the creation of a particular content type to one entry per user per the value of a particular field.  So essentially what I'm saying is you should be unable to create a second piece of content of a particular type if the value of a particular field is identical to the value of the same field but in another piece of content created by the same user.

Is there anyway to accomplish this?

I'm not aware of an existing module with that functionality, but it wouldn't be too hard to code your own custom module to do the job.

This is an example using the 'article' node type:

function MYMODULE_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  if (empty($form['nid']['#value'])) {
    $form['#validate'][] = 'MYMODULE_article_node_form_validate';
  }
}

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

  // See if this user has already created a piece of content of this type.
  $args = array(':uid' => $user->uid, ':type' => 'article');
  $count = db_query('SELECT COUNT(nid) FROM {node} WHERE uid = :uid AND type = :type', $args)->fetchField();

  // If they have, check for another node created by the user with the same field value
  if ($count > 0) {
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('uid', $user->uid)
      ->fieldCondition('field_some_field', 'value', $form_state['values']['field_some_field'][LANGUAGE_NONE][0]['value']);

    $results = $query->execute();

    // If we have a result, invalidate the form.
    if (!empty($results['node'])) {
      form_set_error('field_some_field', t('Error message here'));
    }
  }
}

That'll need a bit of massaging to match your exact situation, but it should be a good place to start.


Pop-up for view bulk operation? Normally View Bulk Operation (VBO) will lead to separate page for asking details and performing actions.

Is there any module readily available to show pop-up for views bulk operations. Searches did not help.

You may check my post answer. You can apply your condition. I think this may help you to solve your query.


how to rename file before/after upload I want to rename an up-loaded file. I have the following code. I have defined a submit handler to do so.

function example_form_submit(&$form, FormStateInterface $form_state) {
    if ($form_state->hasFileElement()) {

        $video_file_file_array = $form_state->getValue('field_video_file');
        if (is_array($video_file_file_array)) {
            if (isset($video_file_file_array[0])) {
                $video_file_file_id = $video_file_file_array[0]['fids'][0];
                if($video_file_file_id){
                    $file = \Drupal\file\Entity\File::load($video_file_file_id);
                    $file->set('filename', 'something');
                    $file->save();

                }
            }
        }
    }
}

This is not working. Is there any other way.

Renaming file entity in Drupal 8 can be achieved like this:

    $file = File::load($file_target_id);
    $new_filename = "filename.png";
    $stream_wrapper = \Drupal::service('file_system')->uriScheme($file->getFileUri());
    $new_filename_uri = "{$stream_wrapper}://{$new_filename}";
    file_move($file, $new_filename_uri);

As you can see in this example Drupal file_move function is used here which takes care of everything. You only need to know file target_id which is the file fid.


Change function view_unformatted to work with format HTML list I have function in template.php which check if image fields exists (has content) and it adds classes if image exists (has_field) and if image does not exist (has_no_field).

This function now works with Unformatted format, but I need it to work with HTML list format. I already tried it with function theme_views_pre_render(&$view) but could not get it to work.

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image) || !empty($row->field_field_image_2) || !empty($row->field_field_image_3)) {
      $vars['classes_array'][$id] .= ' has_field';
    }
    else {
      $vars['classes_array'][$id] .= ' has_no_field';
    }
  }

}

How to make this work with HTML list format?

I think the hook name you are looking for is template_preprocess_views_view_list that applies to HTML list views.


Managing Drupal Core in Git for Aegir Platforms We've started developing a platform to deploy sites with using Drupal 7.2. The platform is managed in git. However, as we do not touch core, what is the best place to managed core?

Should core also be in git on its own repo? Or should the dev team update core as they develop the platforms, and push core with the platform?

Thanks!

Our current (simplified) practice at work:

Pull down the drupal core git repo http://drupalcode.org/project/drupal.git/
Add upstream to your local project that tracks the above repo
When a new version of drupal is released, fetch the drupal repo and merge the appropriate tag

e.g.

cd /var/www/your-platform/
git fetch upstream
git merge 7.7


How can I create a menu link that shows only to authenticated users? How can I create an user account menu link that shows up only to registered/authenticated users in Drupal 8? I do not want anonymous users to see it.

For example, I want to have "add node" menu link.

( When anonymous users come to drupal sites they just see "login" on user account menu . When register users come to drupal sites they see "my account" and "logout" . I want show anonymous just "login" and for register users "my account","add node" and " logout .  )

Long story short, you create 2 different Menu versions and give each version different visibility rules.

All you gotta do is configure your menu link block

Then in Roles, check mark ☑ Authenticated users and  you may want to also ☑ Administrator

Now create another Menu (/admin/structure/menu) which does not have the "add node" link. Then go to blocks (/admin/structure/block) in Primary Menu (Assuming you're using Bartik, may have a different name if you're using a custom theme) click add, and add the Menu you just created and configure it.

This time for Roles, only check mark ☑ Anonymous

  PS: In pages you can restrict so it only shows up in certain pages.


Customize admin menu item "Content" Is there a way to change this link to only a #. In the backend it's not possible to change this..

I want this only to be a activator for a dropdown and not a link to the content page because this page is not going to be used.

Just make sure your user does not have access to 'Access the content overview page' or any super admin permissions.


GTM container in block appears as regular text even though set to be Full-HTML I have opened a block at the header of my site and have putted the GTM-container code inside while at Full HTML input-format.

Yet, the container code appears as regular text (<p>&<a>) in this block.

I could solve it by giving "Display:none;" to it's region with CSS, but I would prefer to find the root cause of this problem rather than using CSS.

If there is any module that deals with this service I would prefer not to use it since I'm looking for a none-modular why of doing it.

I've discovered that CKeditor made the code <p> so I tried to replace the <p> tag of the input to  but it didn't help, so as alternative I tried to format the input as with PHP text-foramt, But this also didn't help.

Working solutions would be:

Putting the code somewhere (at the first row for example) of you page.tpl.php.
Installing the module.

If you plan to change your sites theme and going to change some themes in the near future, better pick option 2 --- It will save you from copying the code time and again to each new page.tpl.php.


Redirect to default node url I have an question about drupal's redirect.

Well I implemented hook_menu for the path: "node/%node/boost".

And I set all callbacks from default node path: "node/%node".

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['node/%node/boost'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );

  return $items;
}

So I would get the node from my custom URL

but I got the redirect to default node URL like "node/123".

Any idea how can I load nodes from the my custom URL?

Thanks

UPD

If I change "page callback" function to the my custom function "my_module_page_view", for example:

/**
 * Callback.
 */
function my_module_page_view($node) {
  return 'Hello Drupal!';
}

I will see the text "Hello Drupal!" on the page with URL "/node/1/boost".

But if I use the next code:

/**
 * Callback.
 */
function my_module_page_view($node) {
  return node_view($node);
}

I will get redirect from "/node/1/boost" to "/node/1"

Well It was a monkey's code in the one custom module: It implements hook_node_view() and, if the path  was similar to node/1/bla-bla, it redirected users to node/1.


Parameters in the HTTP request I am trying to render a block depending on the parameter(entity) present in the requested page. Suppose if I am on a url like this: http://localhost/drupal8/user/1 then a block with label user is created. Same thing I am trying to achieve for other urls like http://localhost/drupal8/node/1, http://localhost/drupal8/comment/1. I am using this piece of code:

if ($this->request->attributes->has($entity_type)) {
   return code for rendering block
 }

(here $entity_type will be replaced by user,comment,node) to check whether requested page has a particular key. This piece of code works for checking keys like node and user when I am on page http://localhost/drupal8/node/1 and http://localhost/drupal8/user/1 respectively but when I am on page like http://localhost/drupal8/comment/1 and check for key: 'comment' then it returns FALSE because it is not defined. Is this an expected behaviour, if yes then what should I do to solve my problem. Thanks.

Instead of inspecting the request object directly, the current_route_match service is the preferred object to consult for request parameters. It provides both the raw and upcast values of parameters. Additionally, using \Drupal\Core\Routing\StackedRouteMatchInterface you can retrieve values from the master request.

The reason you are having trouble with /comment/{comment} is because that route is special: it performs a subrequest to view the entity the comment belongs to. This explains why you only have the node entity available when viewing a comment on a node.

To work around this, consult the master request:

$comment = \Drupal::routeMatch()->getMasterRouteMatch()->getParameter('comment');


PHP to show if content has new comments in taxonomy-term.tpl.php? Is it possible to add some PHP to taxonomy-term.tpl.php that will look and see if any content tagged with the term has new comments, and if so print something in the html?

Yes you can but it will it performance without proper caching. Don't do that in tpl because you can cache it, even with page cache.
Code look something like that using drupal api.

<?php
$has_comment = false;
$nids taxonomy_select_nodes($term->tid);
foreach($nids as $nid){
$node = node_load();
  if($node->comment_count > 0){
    $has_comment = true;
  }
}


D7 Execute javascript on views exposed filters AJAX submit (Dropkick) I need a tutorial on how to run a piece of javascript after the AJAX form of a views exposed filter group submits.

The problem is with using the Dropkick javascript plugin to style some dropdowns. The Drupal Dropkick seems to do a half-decent job of implementing this on the initial form, but after AJAX submit the dropdowns lose their styling.

If it helps, here's a copy of the Drupal Dropkick module js:

(function($) {
  Drupal.behaviors.dropkick = {
    attach: function(context) {
      $(Drupal.settings.dropkick.selector, context)
        .not('#field-ui-field-overview-form select, #field-ui-display-overview-form select') //disable dropkick on field ui
        .each(function() {
          $(this).addClass('dk-active').dropkick({
            change: function(value, label){
                $(this).change();
            }
          });
      });

      //add clearfix to parent .form-item to fix floats
      $('.dk_container').parents('.form-item').addClass('clearfix');
    }
  }
})(jQuery);

Any thoughts?

You need to use ajaxcomplete function of jquery to perform any script after the ajax call. I have not worked on "Dropkick" module, but I have implemented "Selectbox" jquery plugin in my site to format the dropdown.

May be it will help you.

$(document).ajaxComplete(function(e, xhr, settings) {

  if (settings.url == Drupal.settings.basePath + "?q=views/ajax" || settings.url == Drupal.settings.basePath + "views/ajax" || settings.url == Drupal.settings.basePath + "?q=system/ajax" ||  settings.url == Drupal.settings.basePath + "system/ajax") {
 // enable selectBox jQuery plugin for all <select> elements
    $("SELECT").selectBox();
    //Drupal.attachbehaviours();

  }
});


Streaming video integration I'm looking for a solution for streaming video in Drupal 6. Ideally, I'd like to be able to have users upload video via a content type, convert and encode it, then have the published version be linked to a streaming server (like DSS). I want to host the streaming server myself and ideally I'd like it to be free.

I've never heard of it, but it seems there is also something called Kaltura that might work.

Anyone have experience in this realm? Know of something simple I could integrate?

The best I option I can see so far seems to be to display the video via jw player and write something custom to upload videos to the streaming server from those that are uploaded via drupal.

I have used Navicast (but not a free) platform to develop a webtv module for Drupal 6. It is based on Output APIs. There are few limitation with the platform APIs that I reported. Navicast Studio a desktop application build around their input APIs used to upload video and adjust video properties. The platform has built in tagging system to categorize videos. Comments on video contents is also managed by the platform.

I used it with Flow Player API module.

I developed Web TV around my own entities.


Drupal Commerce Extra Login required I've enabled the Commerce Extra Login module and the login form now now appears when an anonymous or a user who is not yet logged in checks out.

Is there a settings which will make login required before a user can continue through the checkout process? I don't want users continuing without logging in or creating an account.

I needed the same thing and couldn't get Commerce Extra Login to do it.

Fortunately, there's Commerce Checkout Redirect which does the trick:

  This module redirects anonymous users to a page where they can login or create a new account when they try to checkout. After the user logs in or registers, he is redirected to the checkout in order to finalize his order.


How do I get computed column using db_select? I require sum(points)? Any help on what to add in the sample code given below?

$query = db_select('digitaliq_question_points','n')
  ->fields('n',array('points'))
  ->condition("node_id", $node->nid, '=')
  ->condition('n.fld_group', $fields, 'IN');

$points = $query->execute()->fetchAll();

You can make use of the addExpression() method:

$query = db_select('digitaliq_question_points','n')
  ->fields('n',array('points'))
  ->condition("node_id", $node->nid, '=')
  ->condition('n.fld_group', $fields, 'IN');

$alias = $query->addExpression('SUM(points)', 'sum_of_points');

$points = $query->execute()->fetchAll();

Obviously that might need to change slightly based on your return value/grouping requirements but that's the method you're looking for.


Add CSS/JS to particular view? I'm having trouble understanding how to attach a library to views.  I want my assets to be included in /foo but not in /bar.  I've read through the documentation on this more than once and from my understanding this is achieved by using preprocess, such as:

function my_theme_preprocess_page(&$variables) {
  if($variables['is_front']){
    $variables['#attached']['library'][] = 'my_theme/my_library';
  }
}

I'm new to Drupal so forgive my inherit ignorance, but what does $variables contain?  'is_front' is easy enough, but how do I apply this to views or content types?

Thank you all in advance.

but what does $variables contain?

A couple of render arrays and some values that be used by twig template. Your best option is check de documentation for each preprocess function to see what are included in $variables. Docs link template_preprocess(&$var) better explanation about preprocess functions and default list of template preprocess functions

  but how do I apply this to views or content types?

For me the best option is your twig template file by including this line.

{{ attach_library('my_theme/my-library') }}

No matter how many times this will be 'attached' only one will be downloaded (or aggregate). And only will added if this particular template will be rendered.

More info about Twig debug is here


Custom User Login Template Error I am using Drupal 7 and I have added some code to my template.php file in my theme (which I found on a Drupal tutorial) so I can use a custom template for the user login form. The form works and it is using the custom template but it is generating these errors:

Notice: Undefined index: classes_array in template_process() (line 2527 of /includes/theme.inc).
Warning: implode(): Invalid arguments passed in template_process() (line 2527 of /includes/theme.inc).
Notice: Undefined index: attributes_array in template_process() (line 2533 of /includes/theme.inc).
Notice: Undefined index: title_attributes_array in template_process() (line 2534 of /includes/theme.inc).
Notice: Undefined index: content_attributes_array in template_process() (line 2535 of /includes/theme.inc).

The code I have in my template.php file is:

function cr_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'cr') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'cr_preprocess_user_login'
    ),
  );
  return $items;
}

function cr_preprocess_user_login(&$vars) {
  $vars['forgot_link'] = l(t('Forgot password?'),'user/password');
}

and my user-login.tpl.php file contains:

  <?php print drupal_render_children($form) ?>

<?php print render($forgot_link); ?>

I have been trying to find the cause of the errors which I think is probably something I have not added to my cr_theme() function but now need some help.

By playing around with the preprocess function I seem to have fixed the errors. I changed the preprocess function to:

function cr_preprocess_user_login(&$vars) {
  $vars['content_attributes_array']['class'][] = 'content';
  $vars['title_attributes_array']['class'][] = 'content';
  $vars['attributes_array']['class'][] = 'content';
  $vars['classes_array'] = array('content');
  $vars['forgot_link'] = l(t('Forgot password?'),'user/password');
}

I just added in the undefined indexes that were coming up in the errors. I'm really not completely sure what I am doing but it does seem to be removing the errors so far.

It would be great if someone could comment how this is working.


Organic Groups Vocabulary - Dynamically Load Terms I've recently installed OG Vocabulary and have been kicking the tires for the last day or so. It'll do what I need it to do, that is, provide segregated group taxonomies. However, it seems to me that the workflow is less than ideal.

I have a content type named Event. It has 2 OG fields:

og_group_ref - Allows the user to associate content to a group

og_vocabulary - Contains select lists of vocabularies based on which groups the user belongs to, and whether those groups have referenced vocabularies.

When creating a new Event, if a user belongs to multiple groups with taxonomies on that node, the user is shown a og_vocabulary field for every group. This allows a user to associate the Event to "Group A", but select terms from "Group B".

After a new Event is created and associated to a group, if a user goes back to edit that group, only vocabularies related to the group they've associated to the node show up. If the user changes the group to which the content belongs, they must save that content then edit the content again in order for the correct og_vocabulary field to show up. I'd like to be able to skip having to go back in and edit the node after changing the referenced group.

Is it possible to dynamically load the correct og_vocabulary field based on the value of og_group_ref?

I've been mucking around with AJAX to accomplish this, but I'm wondering if there's a better way to accomplish this. It's possible that this functionality is built in and I'm missing something.

I'm using D7, by the way.

Thanks for any help!

I recently encountered the same issue and the way I got around it was to use a hook_form_alter to use the appropriate taxonomy from the pre-populated selection of og_group_ref via a db_select on the taxonomy_term_data table.

I used entity_reference_prepopulate to set up the link to create group content for the group.  Seems hacky to me and would like to know if others were able to get it to work like the OP had wanted it.  Here is an excerpt of my hook_form_alter.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // ... get gid from context
  // ... i used request_uri() to get the uri and parsed out the gid
  // there may be less hacky ways of doing this.
  $query = 'SELECT tdata.tid, tdata.name FROM (SELECT vid from {og_vocab_relation} where gid=:groupid) og left join {taxonomy_term_data} tdata on (og.vid=tdata.vid)';
  $query_params = array(':groupid' => $gid);
  $taxi_terms = db_query($query, $query_params);
  $options = array();
  $options['_none'] = '- None -';
  foreach($taxi_terms as $taxi_term) {
    $options[$taxi_term->tid] = $taxi_term->name;
  }
  $form['og_vocabulary'] =  array(
    '#title' => 'Projects',
    '#type' => 'select',
    '#multiple' => TRUE,
    '#options' => $options
  );
}


How to change html of CAPTCHA module in another module? I add captcha field to form in this way

$form['captcha'] = array(
    '#type' => 'captcha',
    '#title' => 'Simple title',
    '#captcha_type' => 'captcha/Math',
    '#description' => 'Please solve it'
);

This element will be rendered as

<fieldset class="captcha form-wrapper"><legend>CAPTCHA</legend>

Please solve it
<input type="hidden" name="captcha_sid" value="102">
<input type="hidden" name="captcha_token" value="bf6179f1c98e4291e1bb2e11c733d991">

  Math question *
 20 + 0 =  <input type="text" id="edit-captcha-response" name="captcha_response" value="" size="4" maxlength="2" class="form-text required" autocomplete="off">

Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.

</fieldset>

How to change this html template ?

I guess you could override theme_captcha. here is the code

function bartik_captcha($variables){
  $element = $variables['element'];
  $output='<h2>'.$element['#title'].'</h2>';
  $output.= drupal_render_children($element);
  return $output;
}


When a variable parameter is changed in a Rules loop, the variable is unchanged outside the loop I have a Rules loop in which a variable parameter is modified.
The variable was created before the loop, and added as parameter in the loop.

However, If I check the value of the variable after the loop, it is unchanged.

Is this by design or what causes this?

Have a look at this example of a Rule (in Rules export format), which is a variation of what you're asking for:

{ "rules_show_list_of_fields" : {
    "LABEL" : "Show list of fields",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "StartOfList-" },
          "PROVIDE" : { "variable_added" : { "email_list" : "List of eMail IDs" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email" : "Current eMail" },
          "DO" : [
            { "data_set" : {
                "data" : [ "email-list" ],
                "value" : "[email-list:value][current-email:value]-"
              }
            }
          ]
        }
      },
      { "data_set" : { "data" : [ "email-list" ], "value" : "[email-list:value]EndOfList" } },
      { "drupal_message" : { "message" : "The value of the email_list variable is: [email-list:value]." } }
    ]
  }
}

Here is a summary of what this rule does:

Add a new variable email_list.
Init the email_list value with some prefix.
For each item within the loop, append the value of that item, followed by a separator character.
Add a suffix to the email_list value.

In my case I'm using a multi value text field with machine name field_email_addresses, which contains eMail Ids, and just want to dispay a Status message with a concatenation of those eMail IDs, separated by a "-", and with a prefix (=StartOfList) / suffix (=EndOfList). And I also use Rules Events "Update existing node".

BTW, You could use this rule as a template to group multiple eMails (to individual eMail IDs) in a single eMail to all of those eMail IDs.

Demo

Here is how the Status message looks like after you create a new node, or update an existing node (of type Article):

  The value of the email_list variable is: StartOfList-user2@example.com-user4@example.com-EndOfList.

Conclusion

The variable was created before the loop, and modified in the loop.
And I display the value of the variable after the loop, it is changed like I wanted it to be changed.

As per what is shown in my answer here, it seems something is wrong in your rule (which you did not show in your question).

PS: I assume this question is about D7 ...


Migrate user passwords from drupal 6 to already existing drupal 8 site I have a drupal 6 site and a drupal 8 site. The drupal 8 site already exists and I do not want to do this on an empty drupal 8 install. Also I only want to migrate passwords. The users with their corresponding UIDs have already been brought over, and they do appear in the list of users, however their old passwords do not work on the new site. I'm assuming because drupal 8 uses a different encryption system.

I looked into using this method https://www.drupal.org/docs/8/upgrade/upgrading-from-drupal-6-or-7-to-drupal-8 based on the answers provided for this question How do I migrate user passwords?
But that seems to only apply to situations when the site does not exist and I want to perform a brand new install of Drupal 8. And it supposes that I want to migrate all data when I only want to migrate the users.

Upgrading and moving over all data (nodes, block layouts, etc.) is not an option. I do not want that data in the existing drupal 8 site. I need only the users (preferably just the user passwords).

I'm willing to make a custom module to perform this import. Is there a way to migrate only the user passwords from a drupal 6 site into a drupal 8 site?

If you only want to migrate users and their passwords then you can do the same by using drush commands.
Firstly you have to install certain modules:
1.Migrate Upgrade
2.Migrate Plus
3.Migrate Tools

Then you have to create a manifest.yml file at the root of your d8 site.
The manifest.yml must look like this:

# user
- d6_user
- d6_user_profile_field
- d6_user_profile_field_instance
- d6_user_profile_entity_display
- d6_user_profile_entity_form_display
- d6_profile_values:user
- d6_filter_format
- d6_user_role
- d6_user_picture_entity_display
- d6_user_picture_entity_form_display
- d6_user_picture_file
- d6_user_picture_field
- d6_user_picture_field_instance

Then run the following drush command:

drush migrate-manifest --legacy-db url=mysql://d6user:d6pass@localhost/drupal_6 manifest.yml

For further information follow the following page:https://www.drupal.org/docs/8/upgrade/upgrade-using-drush


Hierarchy taxonomy terms for node path in drupal 7 I have a vocabulary with 3 levels and a node type with a term reference to that vocabulary.
When I create a node of that type I choose a term in the deepest level of the vocabulary and now the question comes.
I have pathauto module installed and I'd like to build a pattern like this:

[node:field_category:level-1]/[node:field_category:level-2]/[node:field_category:level-3(deepest)]/[node:title]

The problem is that can't find the right token to achieve this behaviour. This afternoon I have been searching the web and I can't find a solution.

Any ideas? ( I'm using Drupal 7)

The following solution works for me:

[node:field-yourfield:parents:join:/]/[node:title]

where yourfield stands for the name of your reference field.

Then you have to go into Configuration » Search and metadata » URL aliases Settings and under Punctuation change Slash to Do nothing, so it's not stripped from the alias.


Programmatically alter user permissions The current state of the site, is configured such that authenticated members, can post specific content types and comment on everything.

What was asked of me, was the restriction of users having tagged (taxonomy) themselves as "private" (their profiles aren't accessible), not being able to perform the above operations.

Apart from assigning a new role, on user update and having one more role to manage, is there another way to do that?

Ideally I'd like to assign to a "private" user the same rights as an anonymous user but without actually making him one, since I am already filtering for authenticated users in views and such.

Well, there is a way to do this, without the need to create an extra role. The code below should give you at least a hint on how to do it. You will need to create a custom module if you don't already have one and modify the function names and code where appropriate accordingly. Be warned though: the code is not tested :)

/**
 * Implements hook_user_load().
 */
function my_module_user_load($users) {
  foreach ($users as &$account) {
    // Check if the user's profile is private
    if (_my_module_user_profile_is_private($account)) {
      static $drupal_static_fast;
      if (!isset($drupal_static_fast)) {
        $drupal_static_fast['perm'] = &drupal_static('user_access');
      }
      $perm = &$drupal_static_fast['perm'];

      if (!isset($perm[$account->uid])) {
        // If you want, you can add here a new "virtual role"
        // $account->roles[ROLE_ID] = 'custom role';

        // Make a copy of the roles array,
        // because we don't want to make changes on the user object
        $account_roles = $account->roles;

        // Remove the authenticated role, before querying all permissions
        if (isset($account_roles[DRUPAL_AUTHENTICATED_RID])) {
          unset($account_roles[DRUPAL_AUTHENTICATED_RID]);
        }

        // Get all permissions for user's roles
        $role_permissions = user_role_permissions($account_roles);

        $perms = array();
        foreach ($role_permissions as $one_role) {
          $perms += $one_role;
        }

        $perm[$account->uid] = $perms;
      }
    }
  }
}

/**
 * Helper function.
 *
 * Checks if a user's profile is private.
 */
function _my_module_user_profile_is_private($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }
  // Check if the user's profile is private
  // ...
  return TRUE; // just for testing
}


How To Add Field In Registration Page In user page, I want to add more field like username, contact number and address. What is the common way to do it?

You can either use Profile2, or you can add your fields in /admin/config/people/accounts/fields.

From Profile2 project page:

  Designed to be the successor of the core profile module, which is
  deprecated for Drupal 7. In
  contrast to the deprecated module this module provides a new,
  fieldable 'profile' entity - leverage the power of fields!

You can find out how to create profiles in Profile2 documentation


Form validation throws a strict warning I am using the form validation in hook_form_alter() as follows.

$form['#validate'][] = '\Drupal\module_name\Controller\MyController::_field_p_servicename_validate';

In the controller I am defining it as follows.

public function _field_p_servicename_validate(&$form, FormStateInterface $form_state) {}

It throws the following exception.

  Strict warning: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\module_name\Controller\MyController::_field_p_servicename_validate() should not be called statically in Drupal\Core\Form\FormValidator->executeValidateHandlers() (line 88 of core/lib/Drupal/Core/Form/FormValidator.php)

What does it mean? How can I fix it?

There are contexts where Drupal allows you to use a notation like  '\Drupal\module_name\Controller\MyController::_field_p_rpservicename_validate' to refer to a public function of an object. In the case of validation handlers, since Drupal is calling them with call_user_func_array(), with a notation like '\Drupal\module_name\Controller\MyController::_field_p_rpservicename_validate' you are referring to a static function of a class.

Change  the definition of that method as follows, and your code will work.

public static function _field_p_rpservicename_validate(&$form, FormStateInterface $form_state) {}

Keep in mind that a static method cannot use $this.


Output taxonomy term in views unformatted using twig I'd like to output taxonomy terms as html classes for view-rows in the views unformatted template for Drupal 8.

My code:

    {% if title %}

{{ title }}

    {% endif %}
    {% for row in rows %}

             {{ row.content }}

    {% endfor %}

What am I missing?

You're a little light on details about your setup, but I can make a suggestion based on what I see. I don't know how you're settings the term variable, but row will have access to the node (assuming this is a node view) that represents the row being displayed. You can do something similar to

{{ row.content['#node'].field_tags.getValue().0.target_id }}

(assuming field_tags is your term reference field) to print the referenced term ID.

Edit: just realized how long ago this was asked... Not sure why it was showing at the top of my list. Anyhow, hopefully helpful to someone!


How can I get node creation date? How can I get node creation date and convert it to custom format in my theme, I tried to make some operations on node date in "MyTheme.theme" file and in preprocess_node section.

Code for getting node created date.

$date = $variables['node']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom PHP date formatting.
  $variables['date'] = \Drupal::service('date.formatter')->format($date, '$format');// enter date format in $format.


display data (taxonomy terms) after uploading it directly to the database I have created a taxonomy vocabulary and then uploaded via mysql all the needed tables for the different fields.

I have created a view where I can see all the terms of the vocabulary, but if I go to /admin/structure/taxonomy/myvocabulary I can only see the terms that I have edited and saved, where, which table I have to modify for the terms to be displayed at the vocabulary page?

From what I can tell those are all the taxonomy tables, but none of them seem to contain the term (url) path; thus, they must be in the url_alias table. Also, don't forget to flush your cache to see the changes.

I think it's better/safer if you use feeds to import your taxonomy terms.

Feeds

  Import or aggregate data as nodes, users, taxonomy terms or simple
  database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  PubSubHubbub support
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files

Video Tutorial


GMAP views: Use marker field I have a working GMAP view and I'd like to customize the markers basing on a list field.

I can't find documentations about this feature, in the settings of my view I setted

Marker Handling--> Use marker field

and

Field --> "myfield"

What I'd like to know is: does "myfield" has to be an image field or whatelse?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.


How to remove link to personal contact form from tabs block? I created a link to personal contact form in page content, and I want to remove it from tabs. How to do that without breaking functionality?

I didn't test the following example code though, but you will be able to remove tabs using hook_menu_local_tasks_alter() in a custom module (replace mymodule by the name of your custom module):

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  // Whether the personal contact form tab is present. You
  // can fine-tune your conditions here. The tab route was
  // taken from ./core/modules/contact/contact.links.task.yml.
  if (isset($data['tabs'][0]['entity.user.contact_form']) {
    unset($data['tabs'][0]['entity.user.contact_form']);
  }
}

As mentioned before, I did not really try the above code. You might have to check the contents of the $data array to find the right plugin id and correct position of the tab definition when visiting a user's page.

Also note, that the tabs information will be cached. So you will have to rebuild your caches for the changes to take effect and the above hook to being triggered.

The functionality will be kept, as the route behind the tab is still active when you alter the local tasks array only.


How can I programatically get the cart's dollar sum of drupal commerce? For future users <?php echo  '$' . number_format(( $total['amount'] /100),2); ?> is how.

Following this guide http://kahthong.com/2012/08/programmatically-show-number-items-drupal-commerce-shopping-cart I got the cart item total using

<?php
global $user;
$quantity = 0;
$order = commerce_cart_order_load($user->uid);
if ($order) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
    $total = commerce_line_items_total($line_items);
    $currency = commerce_currency_load($total['currency_code']);
}
print format_plural($quantity, '1 item', '@count items');
?>

however when I try to get the dollar total using <?php print $total; ?>, it just returns 'Array'.

I used Devel on the page, but the cart is just a bunch of markup in ['content']['system_main']['main']['#markup']. What I want is $106.00, is there a way I can grab that class specifically with php somehow? Or maybe there's another way to go about this.

You should have it already.  That call to "commerce_line_items_total" returns the array:

return array('amount' => $total, 'currency_code' => $currency_code);

Thus you should have the total price at $total['amount'] since you already have $total['currency_code']


How to add backgroud image to bootstrap flatly? Hi Im not a theming hero,

Im an happy user of drupal8 and bootstap theme flatly.

I would like to have this sitebranding logo as a background image.

After 2 days of watching youtube tutorials about theming up bootstrap I can;t figure it out where to make the right modifications?

please help

It's best practice to create a child theme on Bootstrap, the css modifications go into your child theme. That way you can update Bootstrap later on, otherwise your alterations would be overwritten by the update. More info on how to create a child theme can be found here


hook to redirect user before they create node? I'm running a db_query to check if the user has taken a specific action. If they haven't, I'm redirecting them to the page where they can take that action.

function my_special_module_node_view(...) {
   db_query(...);

   if( $fails ) {
     drupal_set_message(t('Error'), 'error');
     drupal_goto('new_page');
   }
}

hook_node_view is mostly working right. It redirects from most pages except any user account pages. The only problem is it doesn't catch when they are trying to create a node. What hook can I use to redirect the user before they view the node creation form?

Update

I've switched it to hook_page_alter. This catches all URLs including the node creation form, which is progress. I had to add in some logic to skip certain paths (including the new_page path to avoid an infinite loop). It seems to be working much better, except if the user does not have access to a page it still ends up in an infinite loop. My current code:

function my_special_module_page_alter() {
  db_query(...);

  if( $fails ) {
    $base_path = arg(0);
    if( !in_array($base_path, array('new_page', 'user')) ) {
      drupal_set_message(t('Error'), 'error');
      drupal_goto('new_page');
    }
  }
}

Any ideas why the pages the user does not have access to end up in a redirect loop? Is there a simple function I can call within hook_page_alter that checks "if user_has_access_to_this_page"?

If I am understanding this correctly, this might be a job for hook_init(), eg something along these lines:

function YOURMODULE_init() {
  global $user;

  if ($user->uid) {

    $fails = /* whatever */ ;

    if ($_GET['q']!='node/add/foo') {

      if ($fails) {
        drupal_set_message('How about creating foo first...');
        drupal_goto('node/add/foo');
      }

    }

  }

}


How to make services node output of file to use external URL instead of public:// URI I've got a basic web service defined in Drupal that returns JSON describing existing nodes on the server. Contained in the output is the key-value pair:

"uri":"public://audio_snippets/01 Australias.m4a"

Is there a way for the client website that consumes this service to convert the public:// URI into something a browser can actually download, like http://www.mywebservice.com/audio_snippets/01Australias.m4a

There is parse_url

Like

<?php
$url = file_create_url($field[0]['uri']);
$url = parse_url($url);
$path = $url['path'];
?>

OR  file_create_url

$usablepath = file_create_url($filesyspath);

OR

$path = str_replace('public:/', variable_get('file_public_path', 'sites/default/files'), $uri);


How do I check if a module is being used by another? I'm using a multi-site setup with Drupal 7.14 core, and I want to disable some modules within my sites/all/modules shared folder. One of them in particular is the File_Entity module.

Is there a way (drush, programmatically, bash script, etc) to check if another module (e.g. Views, custom CCK) is using it? drush pml | grep File Entity only let me see what is enabled or disabled, not if it is currently in use, or safe to remove.

drush pm-info mymodule|grep "Required by"

grep or don't grep is up to you ;)

Beware this does not list fields that require the module. This implies to views that use fields too.

fields: admin/reports/fields

views: admin/reports/fields/views-fields

those will list fields only, so if you have special pagers, formatters or something else that come from a module you will still have to search for them.


How to create menu overview? I'm creating a custom menu in the administration for my module with multiple elements. This works fine by defining the forms, routes and menu links.

How can I create a page like /admin/config for my custom menu? Is it created somehow automatically or do I really need to create a custom page that lists all submenu items in a custom controller?

You can use SystemController::systemAdminMenuBlockPage as controller in the route of parent menu of module. Some like this:

mymodule.overview:
  path: '/admin/mymodule'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'My module overview'


How to retrieve image URL from Media Bundle field in Twig Template I have created a custom media bundle using the Media Entity module.
Here is a screen grab of the media bundle:

I have created a Twig template media--image.twig.html

I am able to retrieve all of the field values via the content variable in Twig but I'm having difficulty retrieving the field_image URL.

Here is a snapshot of the output from {{ kint(content.field_image) }}:

How do I extract the URL?  I can see a target Id, so presumably I can load the entity in the preprocess function and pass through the variable but I would've expected the full target object to be available within the Twig template?

Image URL Formatter

This module adds a url formatter for image field. Then you can output
image url directly.

Enable the module, edit your image field, change the formatter to url.
Now {{ content.field_image }} will print the url instead of rendering the image.


How do I add dropdowns in Filter Criteria in Views module? I was at a local Drupal group meetup last week where a member ran through a presentation of the Views module. I was really excited when I saw that he was able to add dropdowns to the Filter Criteria that he was using as I need exactly that functionality for something that I am building.

The thing is: I can't find the settings at all in my build. I remember that there was a 'settings' link at the bottom of his Filter Criteria area, but I have nothing like that.

Could anyone explain where I can find this? Am I missing and additional module?

The filters in views and how they are exposed to the user reacts a bit differently depending on the type of filter that is used. The type of filter that used, is controlled by defining the data to views using hook_views_data and hook_views_data_alter. This is a bit code heave and not always something you need to do your self as many modules including views does a lot of this for you.

Two common filters used is

views_handler_filter_in_operator
views_handler_filter_string

The two are are fundamentally different because their assumptions and requirements are very different.

The first one, is the one that you would like to use. It's used when you store a value that has a defined list of possible values. An example could be content types which is the example that @Danielle used in her post. Since nodes can't have any random value for their content type, it's possible for views to display a list of checkboxes in the Admin interface when using this filter and a select list / multiple select list for the user when it is exposed.

The second one is used when a string is stored in the database. Using nodes as an example, the title field would be a good candidate for such a filter. Since titles can be any text, it doesn't make sense to expose title selection of a node as checkboxes or select lists, instead you get some other options like you are seeing in your view. You can filter by if the string contains a word (beginning /end / somewhere), it's length etc.

If the one that did the views integration didn't bother using the in_operator type of filter, and describe to views (by using a php function) which options are available, you will have to do it using hook_views_data_alter.

What you need to do is:

Create a subclass of views_handler_filter_in_operator
Implement get_value_options
Tell views about your new handler.

In code it would look like this

/**
 * Define my custom in_opeator
 */
class my_custom_in_operator extends views_handler_filter_in_operator {
  // overwrite the get_value_options function.
  function get_value_options() {
    if (isset($this->value_options)) {
      return;
    }
    $this->value_options array('option_1' => t('Option 1'), 'option_2' => t('Option 2'));
  }
}

/**
 * Implements hook_views_data_alter().
 */
function my_custom_views_data_alter(&$data) {
  $data['entity_type']['property']['filter']['handler'] = 'my_custom_in_operator';
}

And you're done. In reality it's actually quite simple. But finding out how to do is not as views is quite complex.


Programmatically added block doesn't appear in block admin page First of all, this is not a duplicate of this question, as I can't see my block even though I click Place Block.

Below is my block class. To the best of my knowledge, it should appear in the list, but it doesn't. What am I doing wrong? There is another block class, and that can be discovered.

<?php

namespace Drupal\tcmb\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Tcmb Currency' block.
 *
 * @Block(
 *  id = "tcmb_currency_block",
 *  admin_label = @Translation("Tcmb: currency"),
 *  category = @Translation("Tcmb")
 * )
 */

/**
 * Display TCMB currencies as a block.
 */
class TcmbCurrencyBlock extends BlockBase {

The problem was me creating a document block above the class, creating an interference between the class and annotation. Another lesson learned the hard way.


How to enter incomplete or partial date with date module? (Day-Month-Year / Month-Year / Year) I have a content type A and it has a date field.

I'm selecting Day-Month-Year for this date field. But not every content has a day and I want to select only Month and Year for these content.

If I select (enter) only month and year, it gives error:

  The value input for field Date is invalid: The value March 1979 does
  not match the expected format.

I installed and tried the Partial Date module but still couldn't do what I want although it says on the module page:

  This module provides date and time fields that allows any individual
  component to be left blank, while still providing a sortable listing
  of the fields.

How can I do that? I want to enter full date (Day-Month-Year) for some nodes and for some others partial date (only Month-Year) and maybe for some others only Year. Isn't this possible?

Day-Month-Year
Month-Year
Year

(And also there is an unsolved issue about this: Allow "fuzzy" granularity.)

It is not possible with one date field. But you can achieve it by adding two different date fields with different configuration i.e.:

Date, Month and Year for Date1 field.
only Month and Year for Date2 field.


Module not appearing in list after pushing to Acquia Cloud I have added a new module in my local code repository. After adding, I committed and pushed it to my remote repository on Acquia Cloud, but it is still not showing up in the modules list.

Can anyone suggest why this is happening?

Unless it's automated, you'll also need to pull to code from the remote repository onto your web server.


Highlight searched keyword using exposed filter views? In a view and I added an exposed filter: Search: Search Terms filter

It works fine, but I'd like to highlight the searched keyword in the results.

How can I do it?

Using search_excerpt function you can highlight the searched keyword. It show the keyword in bold.

  Returns snippets from a piece of text, with certain keywords
  highlighted. Used for formatting search results.

An example is shown below,

for eg:
 //a body field is exposed here

in your views tpl file add the following code

 <?php foreach ($rows as $id => $row):

      $keys = $_GET['body_value'];
      $row = search_excerpt($keys, $row);
 ?>

it will highlight the searched word, see the screenshot below


How to use in a view an argument like gids[0]= I have a custom content type that is associated to groups. When I create a new item, the URL is /node/add/content_type?gids[0]=xxx, where xxx is the node id of the organic group whose this content will be associated.
One of the field of this content type is a user reference. I wanted that this reference is restricted to only members of this group.
This should be accomplished easily using "select list" as the widget for the user_reference field and selecting a view which returns just the members of the group as the "View used to select the users:". og_members views seems perfect, but unfortunately it works with urls like /xxx and not ?gids[0]=xxx.
I googled a lot and tried several things, even create a new view from scratch, without success.
Any help would be appreciated...

Try Views Arguments Extras that lets you set URL params (gid[0], in this case) as arguments.
You can also "push" arguments to the View at the User-Reference field's settings page. You just need to return the URL param to the View.
You must configure the View accordingly.

return $_GET['gid[0]'];


How to add fields in Drupal Registration Form? I have installed content profile module. I just want some fields in drupal sign up page. I am using Drupal 6. How can I achieve this?

After you have enabled the module there will be a new content type called Profile available. Add fields to the content type Profile under admin/content/types.

The fields you add here will show up when the user registers.


How to add pagination to programmatically rendered search result template I am trying to implement the pagination in drupal 8 custom page.

I have a custom array which I am rendering using theme, I need to add pagination for it.

    $internal_result = array_merge($internal_result, $basic_data);
    $response = new AjaxResponse();
    $terms['internal'] = $internal_result;
    $renderable = array(
        '#theme' => 'search_result_template',
        '#data' => $terms
    );
    $rendered = \Drupal::service('renderer')->render($renderable);

I need to add pagination for above result. Can anyone help me?

I tried with the search_result template and it worked, hope this helps you :

$output['prefix']['#markup'] = '
Test page
';
//This sets up necessary global variables for the type => #pager
$page = pager_default_initialize(5, 2);
$render = [];
  $output[] = [
    '#theme' => 'search_result',
    '#result' => 's',
  ];
$pager = [
  '#type' => 'pager',
];
$output['suffix']['#markup'] = '
' . \Drupal::service('renderer')->render($pager);
return $output;

We just need to set up the global variables which help to process rendered array to output pagers items. And add a pager to the suffix.


Support Ticketing module - clients I want to use the Support Ticketing System module to create a 'help desk' for my site. However, I'm not really sure I understand the 'client' system. All I really need is for the user to be able to submit a support ticket to a department, like 'Pre-Sales' or 'Bug Report', and for a member of staff to be able to respond to their issue. I'm just wondering if the support ticket module is 'overkill' and I could code something more simple?

Or, should I just add each department as a client and let users pick which department they'd like that way?

I was using osTicket and was content with it, however I need a user-login system and all the details are already on the drupal site.

Think of "Support Client" as entity that pays for support. Or would pay if you'd charge. On your site you probably want two support clients: your company and external. Or, if you are B2B company, each of your client business should be defined as a support client, plus one for your own company. Then you can tie roles with support clients, like "marketing department" and "sales manager" are roles that belongs to "internal" support client, and "example company representative" belongs to "example support" support client.

Benefit of this is: all your internal roles can participate in your internal issues, and all roles of one of your clients can participate in theirs, but clients cannot peek at each other's support tickets, or at your internal ones.


Cannot translate a content type "The configuration objects have different language codes so they cannot be translated" I cannot translate a content type

The configuration objects have different language codes so they cannot be translated:
node.type.article : fr
core.base_field_override.node.article.title : en

I think it was because by mistake the article was created in French then after I go back to en... But I don't know how to change it ?

I tried to fix this via drush :

drush cset node.type.article langcode en

but it doesn't seems to work so I would like to know how to fix it via the admin ?

Export the configuration:

drush cex

then change the langcode in sites/default/files/config_HASH/sync and import the configuration again:

drush cim

Look for all non english langcodes that are in the base sync folder (or non default langcode, if you have another default language).


How do you allow a user to set the audience of a node to any Organic Group without giving them the "administer nodes" permission? I have a group of users that I need to be able to set the audience of story nodes to any of the Organic Groups within our systems.  Is there a way to do this without giving them the "administer nodes" permission.

I am currently assuming this isn't possible with my current set-up but was hoping there is a module out there that would allow it.

If there isn't a module where would I begin to look at creating a module that created this permission?  What Drupal API hooks would I begin with?

I created a patch to the Organic Groups module to add the "administer audience" permission.  The patch can be found here, http://drupal.org/node/1211974

Here's the patch inline,

diff --git og.module og.module
index 38cc452..0206115 100644
--- og.module
+++ og.module
@@ -558,7 +558,7 @@
  * Implementation of hook_perm().
  */
 function og_perm() {
-  return array('administer organic groups');
+  return array('administer organic groups', 'administer audience');
 }

 /**
@@ -1833,7 +1833,7 @@
   }

   $node = $form['#node'];
-  $required = variable_get('og_audience_required', 0) && !user_access('administer nodes');
+  $required = variable_get('og_audience_required', 0) && !user_access('administer nodes') && !user_access('administer audience');
   $is_optgroup = FALSE;

   // Determine the list of groups that are shown.
@@ -1843,7 +1843,7 @@
   foreach ($subs as $key => $val) {
     $options[$key] = $val['title'];
   }
-  if (user_access('administer nodes')) {
+  if (user_access('administer nodes') || user_access('administer audience')) {
     // Node admins see all of groups.
     $all = og_all_groups_options();
     $other = array_diff_assoc($all, $options);
@@ -1900,7 +1900,7 @@
   elseif (!empty($gids)) {
    // populate field from the querystring if sent
    $groups = $gids;
-   if (!user_access('administer nodes') && $simple) {
+   if ((!user_access('administer nodes') && !user_access('administer audience')) && $simple) {
      // filter out any groups where author is not a member. we cannot rely on fapi to do this when in simple mode.
      $groups = array_intersect($gids, array_keys($options));
    }
@@ -1949,7 +1949,7 @@
     // show multi-select. if less than 20 choices, use checkboxes.
     $type = $cnt >= 20 || $is_optgroup ? 'select' : 'checkboxes';
     $max_groups = variable_get('og_max_groups_'.$node->type,'');
-    $description_max_groups = ($max_groups && !user_access('administer nodes')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
+    $description_max_groups = ($max_groups && !user_access('administer nodes') && !user_access('administer audience')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
     $form['og_nodeapi']['visible']['og_groups'] = array(
       '#type' => $type,
       '#title' => t('Audience'),


Custom validation for field form? I'm using below codes in Bartik theme.

I need to make: Value cannot be 4 in integer field_total

But dont know why not working.

function bartik_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'bartik_form_validate';
}
function bartik_form_validate($form, &$form_state) {
  if ($form_state['values']['field_total'] == '4') {
    form_set_error('title', 'Total cannot be "4"');
  }
}

New added: clearing cache giving error:

Notice: Undefined index: field_total in bartik_form_validate() (line 161 of /var/www/dru7/themes/bartik/template.php).

The problem is that $form_state['values']['field_total'] does not exist.

First make sure that you have a field value called field_total.

Second try this code once you make sure you do $form_state['field_total']['#value'] to get the value of the field.


How do i setup PostgreSQL? I am following https://www.drupal.org/node/1438206, but i got stuck at Point 2. i.e Add the bin directory of postgres, /Library/PostgreSQL/8.4/bin to the PATH in your .bashrc file in your home directory. Remember to run ./.bashrc to update the path.

I installed postgreSQL using brew. Now i do not find /Library/PostgreSQL/*/bin path i.e I do not find PostgreSQL inside Library.
Also i do not find .bashrc file .

I have installed postgreSQL for sure.Please help me out.

I highly, highly suggest not installing these things directly to the operating system. It will just be more problematic instead of using a contained, virtual environment.

Instead, I advise using virtual environments (Vagrant/Docker). I use DrupalVM for development. For PostgreSQL you can see this thread for info on how to get it up and going.

Here is a Docker flavored VM with instructions on PostgreSQL support.

The linked drupal.org page you mentioned is four years old. I wouldn't follow it.


Unable to override views-view-unformatted.tpl.php I have a view page named latest and try to override the template views-view-unformatted.tpl.php by creating below templates in the theme folder

views-view-unformatted--latest.tpl.php
views-view-unformatted--latest--page.tpl.php
views-view-unformatted--page.tpl.php
views-view-unformatted.tpl.php

but none of them works. I clear the caches, rescan template files. I use views 3 and Drupal 7.23.

Can anyone please help me override this template views-view-unformatted.tpl.php

In the "Advanced" section of the views configuration, click in "Theme:informaction" and you will see all the possible templates

Regards


Show only latest updated nodes I'm getting data from a source. In the following example, there is no data in drupal database and there are 4 source "nodes" that I will import. The content type is set to create revisions.

So, first time I import data this is what I get:

The update date is 22/11/2015 12:00 for all 4 nodes and views has to show them all.

After half an hour, I make another import from the same source but, data 2 was deleted, so, It will not be imported.

I get this:

At drupal db (green block), you can see that the update date was not changed, only the other 3 nodes were changed.

Is some way (that I don't know how), I need my view to show only nodes 1, 3 and 4, basically, the latest that were updated.

Important to note that, no matter how many nodes I import, the update date will always be the same.
Also, I can add fields to my content type and set values when the nodes are first imported or updated and try to use that as filters.

How can I implement this with views? Or, if not possible with views, any other suggestion?

Drupal views support sorting with timestamps by default. You need to install the Date module to add support for date sorting in views. I also recommend that you import the data from your source with the feeds module and use another date field for your date NOT the property "updated" which is a timestamp.

Another solution is to convert the date from your source to timestamp as you import it. The tamper add on module for feeds may help you do this.


How to stop negative user points? I am using Drupal 7 and working on a rating site using Fivestar and Userpoints.

What I want is for a certain amount of points to be deducted from a user when he makes a post, and also points deducted from a user when he votes on a node.

The rating and points deduction works well, but the issue is negative points. I don't want any user's points to go below zero. I need to prevent users from having negative user points on the site.

IMO you should only allow voting for users which have at least X user points. Here is a technique to get that to work:

Grant some permission when a user's amount of user points reaches X, and take that permission away again if it gets reduced to some amount below that. The obvious permission to be used for this is by using the role which allows voting.
Monitor changes in user points for a user, by using the Rules module like so:

Use the Rules Event that captures user points being rewarded (whereas such points can be negative also ...).
Use the Rules Event (or Rules Action!) as described in How to access current amount of earned userpoints in a Rules Condition? (be aware that there is no out-of-the-box Rules Condition like "does this user have at least X user points"?).
Perform a Rules Action to grant access to the role that allows voting, when the user's amount of user points is at least X (and revoke that access if it is below X). If you'd also use the Conditional Rules module, you can perform both types of Rules Actions (grant and revoke) in a single rule.

With that, all that's left is to pick a vaue for ... X!

Note: this approach does not require any PHP coding, so "programming experience" is not required (you only need to be a bit familiar with Rules, for which there are lots of free tutorials available.


How to get collapse text to open below admin menu? I use the collapse text module on my site, when the collapsed text is longer than the screen the collapsed text header gets hidden under the admin menu when you open the collapsible. How can I make it so that it opens and then focuses the header to be just under the admin menu?

if you go to https://arupconsult.com/content/immunoglobulin-disorders/?tab=tab_item-2 and open one of the collapsibles you will see that the header is at the very top of the screen, and when I am logged in to the site the admin menu sites on top of it.

This is a screenshot of one of the collapsibles just opened while logged off.
Notice how IgM is right at the top of the screen.

This is a screenshot of the same collapsible just opened, but I am logged on.
Notice how IgM is now hidden below the admin menu.

This is a CSS issue; what you need is to move the named anchors up a bit for administrators.

Here's a sample code:

/* If you are using the core Toolbar module. */
body.toolbar a[name],
/* If you are using the contrib Administration Menu module. */
body.admin-menu a[name] {
  position: relative;
  display: block;
  visibility: hidden;
  /* This value will be different for Toolbar/Administration Menu modules. */
  top: -30px;
}


taxonomy terms that get URL aliases and then end up being ugly google sitelinks Including tags of course. I used some tags like  that I thought would be running in the background to use them as view filters, but then end up being google sitelinks such as 'subject-teaser-list'. How ugly and unprofessional that looks!

I rather have no sitelinks at all instead of these ugly looking sitelinks.
You have this result when search google for 'breinwijzer'

cheers,

you can manage which links are used for sitelinks in Google's webmaster tools.

To change the description that is used you can use nodewords (or metatag for D7).

Here is some more info about the recent change in Google's sitelinks feature.


REST Web Services - Return all fields from Content entity association I am currently using the latest release of Drupal 8.0 (downloaded and installed today).

I have two content types.  I have a entity reference on one of the content types that references content from the other content type.

Using both the Views REST Export and the built in REST API I am unable to find a way to return the associated content entity fields.  Currently what gets returned is the target_id as well as a link to the entity.  I am using the hal_json content type.

I have scoured the Drupal docs and I am unable to figure this out.  Any help would be greatly appreciated!

RESTws will retrieve your content using an Entity Metadata Wrapper. By default, this won't retrieve the referenced node. To get the nested content you'd need to write your own resource class in a custom module.

The new resource class is registered with hook_restws_resource_info().
 In your resource class, extend RestWSEntityResourceController or just implement RestWSQueryResourceControllerInterface (You can see the default implementation here.)

Your new resource class would look something like this:

class MyCustomResourceController extends RestWSEntityResourceController {

  /**
   * Override the wrapper method.
   */
  public function wrapper($id) {
    $wrapper = entity_metadata_wrapper($this->entityType, $id);
    /**Add something here to add the referenced node */
    return $wrapper;
  }

}


How do I store custom block content as configuration? I'm creating custom pages using Pages + Layout Builder. These layouts need to be stored in GIT as config files (drush cex). Currently, the layouts themselves are stored fine.
The main problem is that custom block contents are stored in the database and if someone clones the repository and applies changes using drush cim, they are missing the block contents.

Then don't use custom block types because they are stored in content entities.
Use blocks storing only configuration. You can build a custom block plugin, even with a body field. See Custom block build function to display wysiwyg body text
There are also some contrib options like Simple Block which is implementing a config entity for blocks.


Is uploading/download executable files harmful in drupal? In my site design, I have a field that is designed to hold an executable file (.exe, .bat, etc), for users to upload and download. I took pause as I was typing these extensions into the Allowed file extensions setting on the file field. Is this ok? What do I need to be aware of?

You'll want to make sure that your server is not configured to execute files of the given extensions in any way.

As a general precaution, you might also configure that file field to use the Private file system, which allows access to those files to be controlled by Drupal's permissioning system.


Show different fields on node edit and node view depending on the sub-type of the node I have a specific node type that I want to show/hide different fields in the page layout for both the node form and when viewing the node.

For various reasons I don't want to have to create a new/separate Node type for each. Not sure how best to achieve this in Drupal 7?

There are actually two content types involved here. 'Open Calls' and 'Projects'

I have an idea submission system built in D7. Users login and browse through available 'Open Calls' for projects.

Each call has a link to 'Apply Now'. This link takes users to the new node creation for a 'Project'.

Each 'Project' has an entity reference field that is required that links the Project to the Open Call. This field is auto populated when they click the Apply Now button.

Ideally, I would be able to specify in the Open Call (rather than the project) what kind of project page layout they see when clicking the Apply Now link.

I want to be able to post Open Calls for slightly different kinds of projects. For example an Open Call for artworks (paintings etc.), or alternatively an Open Call for performances.

Clicking apply now on each of these should take the user to the New Project node creation screen with different fields for artworks / performances. (Some fields will appear on both).

Take a look at the Conditional Fields module. You could make some fields dependent on one checkbox selection and other fields dependent on a second checkbox selection.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new
  States API, plus the ability to modify fields appearance and
  behavior on certain conditions when viewing content.

  Description

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API.

  A simple use case would be defining a custom “Article teaser" field
  that is shown only if a "Has teaser" checkbox is checked, but much
  more complex options are available.


Embed a single field from an existing content in ckeditor I managed to embed the full content or teaser using Entity Embed module in Drupal 8 but, is it possible to embed a single field which contains text or html without coding

You can accomplish this using tokens. The exact token used will vary based on your configuration, but if you wanted to embed a the current user's first name, you could use something like [current-user:field_first_name]. Here's one article about them. https://www.ostraining.com/blog/drupal/tokens-in-drupal-fields/


How to customize pagination for the taxonomy term view page for different vocabulary? I have 3 vocabularies as shown in this screenshot:

And I have default Taxonomy term view page with 10 items per page as shown in this screenshot:

I want to display 12 items per page only for the taxonomy term pages which are related to the terms of Categories vocabulary. Should I create new Taxonomy term view page for Categories vocabulary or is it possible to configure pagination using HOOK_preprocess_taxonomy_term ?

I've used the Taxonomy Views Integrator module which helped me set custom pagination and view modes by creating taxonomy view page for different taxonomy terms and vocabularies. Some details about this module (from its project page):

The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.
TVI will try not to interfere with views or taxonomy/term page displays if no TVI views exist for the current page request.


Display selected fields from referenced node rather than just referenced node title I've searched for an answer to this, I can't find it for the life of me.

I want to in a node display additional selected fields from referenced nodes, not just the title field of the referenced node.

Like follows:

CONTENT TYPE A, NODE A1
Title: Employee 134
First Name: John
Last Name: Smith
Content Type B Reference: Job 3

CONTENT TYPE B, NODE B1
Title: Job 3
Job: Carpenter
Description: Constructs tables and chairs.
Image: carpenter.jpg

I can currently only display for A1:

Employee 134
John
Smith
Job 3

I want it to display:

John Smith
Carpenter
[carpenter.jpg]

Using display suite, create a new display mode for Content Type B, and show only the Job and Image fields.

Modify display for Content Type A to use the new display mode.


How to change the machine name of the content type in Drupal 7 I found an annoying typo in the machine name of one of the content types, and I'd like to fix it. The only way I know is to delete the content type, and create a fresh one, but there is a plenty of fields in that content type that I don't want to recreate.

Is there a better way?

Go to structure, click content types, click edit next to the content type you want to edit. Click edit next to the machine name and change it to the name you want.

If you merely want to change the administrative name, then change that instead.


Execute Javascript when the registration form is completed I am running Facebook advertising campaign for my site. The below code needs to be executed when registration is completed.
How can I achieve this?

<script>
// Track when a registration form is completed (ex. complete subscription, sign up for a service)
fbq('track', 'CompleteRegistration');
</script>

You need to add callback for the form submission. Something like this

function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#form_id'] == 'your_form_id') {
    $form['#submit'][] = 'custom_callback';
  }
}

function custom_callback() {
  drupal_set_message('This is my custom message');
}

Now, after the form submission, the custom_callback will also be executed.

If the code is Javascript and the form submission is via Ajax, you may have a look at the Ajax framework and Ajax framework commands topics in the API documentation. How to execute custom javascript code after an ajax succes (using the Drupal Ajax framework) ? is another useful page/


Better way of adding Image as Block in home page I am designing a personal website. I wanted to display my photo in the side bar in the home page. Below is screenshot-

To get the above display, I have created a basic page in which I have inserted the dummy image using IMCE in CKEditor. Then I have created a view, which is a block of basic page. In this view, the filter criteria is the content title, which should be equal to "my passport size image". Now I have added this block to sidebar.

I am looking for a better way to achieve the same.

This is sadly a reasonable solution - one of the easiest. However, as you can see, it's sad because your content - the image - isn't being managed by the entity which is displaying it. This is very confusing when you go back and edit your content. You'll have to wonder - "Where is this being displayed?"

A better solution is to use the BEAN module. This will allow you to build a block type - much like a content type - which has an image attachment. Then, you can manage the display of that image on the block itself. In fact, you can any fields you like to your block type!

https://www.drupal.org/project/bean


Webform capability issue with Chosen The Chosen module no longer get applied to Webform select fields with the most recent updates to a Drupal Commerce 2.0 site that I am working on. I am using Chosen version 7.x-2.0-beta4+1-dev (part of Commerce Core) and Webform version 7.x-4.0-beta1. After further investigation, I noticed that the library for Chosen is not being loaded on pages with webform selects. I did some research and found the article below suggesting that, "...there is a bug in [the] Webform [Module] that removes all the #pre_render callbacks from select elements when used in Webforms..."

https://www.drupal.org/node/2122061[1]

Looking through the Webform module's source code I found the following method which should render select components. Although it doesn't appear that anything is missing.

/**
* Implements _webform_render_component().
*/
function _webform_render_select($component, $value = NULL, $filter = TRUE)

I did come across another post that mentioned CKeditor causing issues, but after updating to 4.4.4 (from 3.6.7) , the results were the same. I have also configured Chosen to apply to ALL select selectors for testing purposes.
Has anyone found a solution or work around to this issue?

I had a similar issue with a recent OpenAtrium update (2.50). Apparently Chosen changed how it gets applied to fields, and this caused it to be turned off for select fields. In my case, it was as simple as visiting admin/structure/types/manage/<content-type>/fields/<field-name> and setting the option "Apply Chosen to the select fields in this widget?" to "Apply." This is done on a field-by-field basis.


Change the location of Edit Profile I am using Profile 2.

When the user clicks the 'Edit My Profile' tab, I would like its destination to be:

/user/175/edit/about-you

Where about-you is a Profile2 type.

How do I change the path of the tabs?
I am also using TabTamer, but this module does not let you change the path, only the label and enable/disable the link.

EDIT
I have tried the below code in template.php with no results.(after changing the theme name)

function THEMENAME_menu_alter(&$items) {
  $items['user/%/edit'] = $items['user/%/edit/about-you'];
  unset($items['user/%/edit']);
}

You can do this by custom module.For this please use below code.First you need to create custom menu using hook_menu.

/**
* Implements hook_menu().
*/
function custom_menu() {
 $items['user/%/edit/about-you'] = array(
  'title' => 'About You',
  'page callback' => 'edit_about_you',
  'page arguments' => array(1),
  'access callback' => TRUE,
 );
return $items;
}

Now You need to write page callback for this menu item.

function edit_about_you($uid){
  $profile = profile2_load_by_user($uid,'profile_type'); // or by default main
  $form_state = form_state_defaults();
  form_load_include($form_state, 'inc', 'profile2_page');
  return entity_ui_get_form('profile2', $profile, 'edit', $form_state);
}

This will return profile edit page for user.Now you need to redirect user when click Edit My Profile tab for this you can user hook_init for that. Check your path argument and redirect user to new created path.

Thanks


title in page.html.twig I find out title is not exists in page.html.twig, and there is a file page-title.html.twig to theme title, then in block section we should use block title. ( ** I don't want use this strange structure for title,really I  didn't find out why Drupal do this  !!!).

any way
I want to provide it by myself, maybe hook_preprocess_page is solution,any body know how can I add title variable to page variables ?

This is my solution for adding title to page templates.
in yourthemename.theme add

function hook_preprocess_page(&$vars) {
    if(isset($vars['node'])) {
        $vars['title'] = $vars['node']->title->value;
    }
    else{
       $vars['title'] =$vars['page']['#title'];
    }
 }

then title exist in page templates.


SQL replace() function in PDO I'd like to convert the instructions from this answer into a general script that can be reused across projects.

I'm wondering how these commands can be written in Drupal 7 PDO format:

UPDATE `system` SET filename = replace(filename, 'sites/all/modules/contrib', 'profiles/distroname/modules/contrib');

Is the mysql replace function something generic to all SQL, or is it mysql specific? I understand this is an expression, but I'm not clear on how to use the PDO expression syntax in this case.

What are the advantages of writing it PDO, as opposed to just a simple db_query() with the sql query from above?  In PDO, will this truly be db agnostic?

Would it be something like this?

db_update('system')->
  expression('filename', 'replace(filename, :old, :new)', array(
    ':old' => 'sites/all/modules/contrib',
    ':new' => 'profiles/distroname/modules/contrib'
  ))
  ->execute();


Unable to install Cart with ubercart I'm trying to install Cart form ubercart after an uninstall:

I'm getting the following message what can I do?

  Unable to install Cart, image.style.uc_cart, uc_order.status.abandoned
  already exist in active configuration.

This can be done with drupal console, you can find it here: https://hechoendrupal.gitbooks.io/drupal-console/content/en/index.html

The command to use is this:
drupal module:install --overwrite-config

Just install drupal console and use the command.


Flag lists visible for one authenticated user but not for others The site in question displays a table-formatted View of relevant content, with a checkbox column for flagging. [relevant modules installed: Flag, Flag Lists, Flag Actions] The Flag List Operations widget allows creation of custom-named lists, which are viewed in a separate node. Each list name launches a full display of the flagged content. At one point this was working perfectly for authenticated users as well as for Admin. Mysteriously, now it is working for one authenticated user but not for any other authenticated user. Specifically, these other users' List names will be shown in a table view, but when clicked, the list is empty. I tried deleting the non-working users (all experimental at this point) and creating new ones. There is no obvious difference in the config of the new ones as compared to the one that works. Any suggestions about how this inconsistency could happen?

I found a solution to this problem, although I can't say I fully understand why it was happening. Seems to be a case of too many relationships in the View, causing some type of conflict that appeared only in some cases. During the building phase I had added a batch of 6 relationships, trying to get it to work but ended up with more than were necessary. I eliminated them one by one and tested, until the truly necessary ones were identified. It really only needed 2: "Flag lists: User" and "(List user) Flags: User's flagged content (current_user_flag)."


Email by Taxonomy Term For Drupal 8 webform, I see there's a way to specify custom email recipients based on a Select component. But I don't see a Taxonomy term reference as an option in the email handler. Is there a way to set that up in the UI? Using the UI would be ideal to let other form maintainers update the emails as needed. A taxonomy term reference is needed to also use Webform Permissions by Term.

Alternatively, if a select component was made using matching term keys, and the taxonomy term component was set to hidden/private, could the term component be populated with the select component? In that way, I could use the email handler with the select list and still use Webform Permissions by Term.

I found I can add an action handler that uses the select list to populate the Webform Permissions by Term element like I was thinking.

With a select list called Institution, using keys that match term keys in a taxonomy, the Update data with YAML section of the action handler can use this:

wf_permissions_by_term_element: '[webform_submission:values:institution:raw]'

The element gets updated on form completion and update, and individual result access is still limited by the Permissions by Term module.


Custom Taxonomy Term Template I would like to use a custom template for my taxonomy term pages.
I attempted doing so by creating a hook in template.php like so

function mythemename_preprocess_page(&$variables){
    if($hook == 'node'){
        if(arg(0) == 'taxonomy'){
            $vars['template_file'] == 'node-taxonomy';
        }
    }
}

And then creating a custom template called node-taxonomy.tpl.php

However the page does not change.

I understand that I can achieve something similar using views, but since other sites are using different themes on our drupal instance I'd prefer not to change anything that relies on those views.

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

taxonomy-term--tid.tpl.php
taxonomy-term--vocabulary-machine-name.tpl.php
taxonomy-term.tpl.php

Note that underscores in a vocabulary's machine name are replaced by hyphens.


Locked out of drupal I managed to lock myself out of drupal by removing the user login block.  Is there any file I can modify to enable myself to get back in?

Thanks


How can I set a different theme basing on the language currently used for the page? We have built one website in English and we want to translate it in Arabic.

Since I am new to Drupal, I am not sure how I can set a theme for English, and one for Arabic. How should I achieve this?

you can check the current language with the languageManager (docs here)

Drupal::languageManager()

and then you can set a different theme with the theme service

\Drupal::service('theme_handler')->setDefault('test_theme');

Hope it helps,


Collapsiblock module - can I have horizontal expanding tabs instead of vertical? Collapsiblock: http://drupal.org/project/collapsiblock

I am looking for a way to allow the sidebar blocks to be collapsible left-to-right instead of top-to-bottom using the Collapsiblock module. It would basically be a way to hide the left and right-column blocks until someone clicks the tab, after which the block would expand to the width of the column. It seems as though it should be a fairly straightforward change in the JS file, but I cannot figure it out. Can anyone here provide any insight into this?

Thanks!

Search slideUp and slideDown in collapsiblock.jsand replace with animate, for example:

$(this.target).animate({width:'toggle'},slidespeed);

Useful post: Slide Elements in Different Directions


How to find non-existing terms based on the list? I've few thousands terms in my vocabulary. I'd like to find out which one still are missing (without adding them) based on the list of term names.

I believe this can be achieved by some anti-join sql query, but any solution would be fine.

How this can be achieved?

If the list is in text file (list.txt), this can be achieved by grep comparision.

First, extract the list of terms from the database by drush:

$ drush sqlq "SELECT name FROM taxonomy_term_data -- WHERE vid = 1" > my_list.txt

Then compare the two lists:

$ grep -Fxv -f my_list.txt list.txt

This will print all the term names which doesn't exist in my_list.txt file.

This solution is based on: Is there a tool to get the lines in one file that are not in another?.


how to add html elements inside block and get data when saving i want to add few html elements call first name and last name,company name in top of user/register page and save that data when user click create account button..,how can i achieve that,i add html elements  in block as normal html tags like
but dont't kow how to get data...thanks

Does it have to be in a block?

If you want to add fields to the registration form and do something with the values when they submit, you really have to add them to the registration form itself, not in a block somewhere nearby.

To do this you can create a custom module that implements a form alter.

For example:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MODULENAME_form_user_register_form_alter(&$form, &$form_state) {
  // Add your fields.
  $form['firstname'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#description' => t("This is help text that will display with this field. you can leave it off if you don't need it."),
    '#required' => TRUE, // Leave this line out if you don't want a required field.
    '#weight' => -10, // This controls the field order. Smaller number is higher up the form.
  );
  $form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
  );
  $form['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company'),
  );

  // Add your own submit handler to save the values.
  $form['#submit'][] = 'MODULENAME_custom_submit_handler';
}

/**
 * Custom submit handler for user register form.
 */
function MODULENAME_custom_submit_handler($form, &$form_state) {
  // Do whatever you need to save the values here.
  // Submitted values are in $form_state['values'] like this.
  $fname = $form_state['values']['first_name'];
  $lname = $form_state['values']['last_name'];
  $company = $form_state['values']['company'];
}

Now having said all that, is there some reason you want to do this custom?
It is possible to use a module that lets you add fields to the register form, like the profile2 module.
That module lets you add profiles (essentially a group of fields, similar to a node) to users, which can also be displayed on the registration form for the user to fill out at that point.

The module handles saving the data for you, along with a lot of other features, like views support.


How to add .active class in to the menu item? I am developing a theme for Drupal 7 and I am struck up with the following issue. I can see there are fixes through jQuery. But I would like to do it in the Drupal way.

My current HTML

    Home

    About Us

Contact Us

Typhygraphy

And I want something like this

    Home

    About Us

Contact Us

Typhygraphy

The "active" class needs to be there in the
 also.

You can achieve your goal without jQuery. Just use theme_menu_link() function, or (my suggestion) theme_menu_link__your_menu()

Place this function in your template.php file:

function YOURTHEME_menu_link(array $variables) {
    $element = $variables['element'];
    $sub_menu = '';

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);

    // if link class is active, make li class as active too
    if(strpos($output,"active")>0){
        $element['#attributes']['class'][] = "active";
    }
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

You can use this function only for menus displayed as a block.
If you're theming main menu:

go to admin/appearance/settings/yourtheme and turn the main menu off.
go to admin/structure/block and place main menu block in header region
customize ul with theme_menu_tree() and li elements with theme_menu_link()


How to allow registered users to enable / disable notifications for event nodes? I have an event node type. The site needs to allow registered users to enable or disable notifications for this event. So on the event page (I have several views, etc) I would like to have a button is seen by registered users.  It would be either show "Enable notifications" or "Disable notifications" based on its current value.

Ideally this would somehow associate the user and to the event (relation?) so that I can query db for all users who have enabled notifications for this event.

Any help or ideas on how to do this?

I would use the Flag module for this. It allows per user state toggling and integrates well with Views.

Create a Flag called notify.
Change the text that is shown to "Enable notifications" and "Disable notifications".
Use Rules and Views to send out your notifications.

For extra credit create a View that shows a User all of the nodes they are receiving notifications on.


Cannot print page title in page.html.twig The following line in page.html.twig does not print the page title:

<h1>{{ title }}</h1>

The page title outputs using the Page title block, but not this piece of template code. I found the title variable in the documentation commented out at the top of page.html.twig. Does this code need to be wrapped in something else?

The variable {{ title }} is only used in maintenance and install pages where blocks are not available. See the change record https://www.drupal.org/node/2568563


In Drupal Commerce how do you auto login an anonymous user that has completed checkout? I have Drupal 7 Commerce core installed and configured manually. Not kickstart.

Currently after completing a Commerce checkout (Paypal Express) with an anonymous user, I get redirected back to the "Checkout Complete" page. The page gives a link to Review My Order, but it asks for login details which I do not have since it was an anonymous checkout.

Is there a way to auto login the user after the Successful Checkout?

In short summary to the link Clive posted in case if it ever gets deleted on the interwebs:

http://s1l.org/automatic-user-login-anonymous-checkout

Step 1 - Make sure Anonymous checkout is checked on. (Permissions > Access Checkout)

Step 2 - Make sure Commerce Immediate Login module is enabled: http://drupal.org/sandbox/simongeorges/1676742

Step 3 - Add a User Login Action to the default Commerce "Create new account for anonymous order" Rule (Configuration -> Workflow ->Rules)

--- rules/reaction/manage/Create a new account for an anonymous order

Step 4 - Click Add action > Login User (under system) > type "account-created" > SAVE

Step 5 - TEST!


How can I check in Drupal 8 an externally set $_COOKIE? I would like to check whether a Cookie exists, and if so, get the value. But it looks like Drupal is blind to external cookies that have not been set inside Drupal.

$mycookie = \Drupal::request()->cookies->all();

Returns an array with only the Drupal cookies, and I can see in my web browser that there are more (some that I am interested in and I can't modify he app that is creating those cookies). I remember there was a similar issue with Symfony 2 and session but I can't find it...

For external cookies please try with $_COOKIE['cookie_name'].

if (isset($_COOKIE['cookie_name'])) {
  print($_COOKIE['cookie_name']);
}

The code will print out the value of the cookie if present.

For a more specific answer please explain your question.Ty!