Log in without password I am looking for a mechanism to Log into Drupal system without a Password and only with some link provided.

My Use case is: Intranet system (made with ASP) passes the Link like: http://example.com/user_name=jhilke&user_email=jhilke@example.com&user_role=developer&TY89823jjkhds234.
To break down the above link separated by &

URL:      http://example.com
USERNAME: user_name=jhilke
EMAIL:    user_email=jhilke@example.com
USER ROLE:    user_role=developer
HASH:     TY89823jjkhds234

Now I need to Log in the User or Create new User (if the user doesn't exists) in Drupal site with exact Username and Role but with just the link and no password.

I have used this URL Login module so far to login to Drupal site without password and with some hash/encrypted key it generates. For eg: The link that URL Login module creates is like http://example.com/l/YUb&8767GUYuiu and logs in the user exactly as the role they are assigned, but it doesn't satisfy the other criteria like username and roles in the link.

Is there any way I can achieve this.

Have a look at

user_external_login_register

  Helper function for authentication modules. Either logs in or
  registers the current user, based on username. Either way, the global
  $user object is populated and login tasks are performed.

The example at:

https://api.drupal.org/comment/13434#comment-13434

Is a worthwhile read too.


Google Rich Snippets and Facebook Open Metagraph I want to implement support for Google Rich Snippets to show author info and fivestar ratings in Google's search engine results pages. I also want to be able to support Facebook's Open Graph to have Facebook pick the correct image when a node with an image is "liked" or embedded on Facebook.

Looks like I can use Schema.org, microdata or RDFx modules. I also came across a post suggesting to just use a preprocess hook.

The schema.org module doesn't seem to support fivestar ratings. Microdata is relatively new and I'm a bit confused about the RDFX module.

Does anyone have experience with this?

In the answer above, there are modules indicated. However, in my experience, they won't work with fivestar, for they are only generic. So, what I usually do in such cases, is to:

Create a template for that node type, like node--type.tpl.php
Create a preprocess function in your theme's template.php file, implementing hook_preprocess_HOOK(). This will translate to an actual function name like mytheme_preprocess_node(&Svariables).
In that function, use the $variables['node'] to get the data from the fivestar widget field.
Format and prepare that data for output, and add your custom variables to the $variables array.
Use the variables you provided in your preprocess function to insert the correct markup in your node file to correspond to the opengraph / rich snippets format.

Some notes:

Use devel module and dpm() function to dump the $variables in preprocess function and the data in the template file.
Use the google markup tool and the facebook markup tool to test your markup.
The logic is, prepare variables in preprocess, and put them in markup in template file. Try not to have computations (business logic) in the template file itself, use preprocess for it.


How to get total number of results in Search API View? How can I get the total number of results on a Search API View that has a limit of 5 results to display?

Some more info:
I have to make a bit more complex search where several attachments are combined on a page as a groups of results. Every group should show just the first 5 results, but also a link "see all XX results". I'm using Search API + Solr, Views with exposed fulltext search.
If I use "Global: Results summary" in header or footer, it will show maximum the limit of 5 as a number.

edit 1

Search API Solr returns 'numFound' which is what I need, but how do I use it in Views?

So after a day, here's the result:

As J. Reynolds suggested, I finished up using $view->total_rows, but:

To populate $views->total_rows, you have to use a pager in your view - that was not an option with the attachments.
If you don't use a pager, you could force populating $view->total_rows by altering the View query before its execution like this:

    function mycustommodule_views_pre_execute(&$view) {
      $view->get_total_rows = TRUE;
    }

And after that you have that $view->total_rows!


Views sorting by date I want an overview of articles sorted by their post date (some articles will be posted back in 2007). But then the possibility should be there to move an article back to the top of the list (we want to recycle old content). We don't want to change de post date manually, because this is valuable information (so the post date should be the original post date), I also don't want to use the updated date, since sometimes you'll need to edit a node without having it move back to the top of the list.

I was thinking, Weight module, but maybe there are better alternatives, i don't need as much control on the sorting as the weight module is giving.
I'm not afraid of creating (small) custom modules, if i'm properly guided through the Drupal API.

Ideally i'd want:
1. an action 'move to top' on the content overview page and a simple checkbox on a node edit page: move to top.
2. an action and checkbox that says: reset to post date, so that we can put it back in the order it's intended to be...

I was thinking a date field, that gets updated to now() every time the 'move to top' action is called... and is emptied when 'reset to post date' is chosen...

Does anyone know a module that does this? Or can guide me in creating it?

Kind regards and thank you in advance

The workflow i'm going for:

Enable custom module (i know how to create a module and activate it)
Add option in each node type I wish to have this function (maybe in the publishing options, simple checkbox should suffice)
In a node have a checkbox 'Move back to top' and 'Reset order'. Both should then edit a extra node field timestamp (*remark at the bottom). The checkboxes should not be checked when re-editing the node, since it is more of an action (it's difficult to explain, but I think it should be clear what i'm trying to say)
Have this extra date field available in views

*Remark: I read somewhere you could actually add a field to the node table itself, I think it was with schema_alter hook. If the timestamp is in this table, the query's would be faster then when it's in an axtra table (which would mean an extra join)

edit2: Went for a custom module with views, operations and actions integration.
The module is finished, maybe i'll make it public. Does anyone think this might be interesting for others?
How does this module uploading work on drupal.org?

You could add a simple checkbox to your content type and call it "sticky" or somewhat. Then you add an attachment to your view, choose position before your default view and let this attachment display only the nodes with "sticky" checked, while you exclude the sticky ones from your default view.

In the second step you can add more logic to the sorting of your sticky nodes inside your view attachment. I really like DraggableViews for such tasks. But maybe that's already too much, then you might simply add another integer field to your content type and let the sticky nodes sort by that.


How to auto redirect link with node/id to /name? I'm using Pathauto to generates all node url. There are many pages and blocks containing links with "node/id" instead of the "urlpath". When user click one of those link, it actually direct to the "node/id", not "urlpath" generated by Pathauto. How can I fix this?

PS: I dont wanna use "Redirect" and add them one by one

You are probably looking for Global Redirect. That module does what you want it to do, it checks to see if there is a path alias for things like node/1 and if there is it will redirect to that URL.

GlobalRedirect is a simple module which…

Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.

Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin module. In Drupal 6, the settings page is bundled into the module.

Note: That is straight from the module page, they haven't updated that Drupal 5-6 statement to include D7 I don't guess but I use this module in D7 and it works also.


Is there any way to reset a menu's default order (e.g. Management Menu)? I have installed Drupal Commerce Kickstart and included with the distro is a mega menu. It also restructures the menu items to a more "End-user friendly" order. I personally prefer the default order that core gives you. Is there any way of resetting the "Management menu" to it's default order (without manually reordering them again)?

This is what it looks like after disabling the mega menu and enabling good ol admin_menu

Not that i'm aware of.

It sounds like the mega menu being active is firing something like a hook_menu_alter to be evaluated by Commerce -- they've hardcoded their own ordering because its more "user friendly".

hook_menu_alter overwrites values that the menu had, so drupal has no knowledge what the default ordering was. If the mega menu is active it forces their ordering, if it isn't you get the default ordering.

You'd have to look in Commerce where they add the custom menu items, or activate the mega menu and see how their adjusting menu #weight values.

You could then write your own hook_menu_alter that undoes their changes.


Change language for date cck field of a webform in drupal7? Can we change language for date cck field of a webform in drupal7?
If I create a component of date type in webform then drupal provides a dropdown having month,day and year values in English e.g. Jan 1 2013 , I want a drop down for this component having options in different language say spanish (witout using any translation module, I am translating webform manually) Is it possible?

go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates


How to get search to display an error when no search terms are entered Right now if I don't enter a search query in the drupal search module, it returns results for 'search'. I would like it to display an error prompting the user to enter a search query instead. Is there some sort of setting?

The form submission callback for the search form is the following function.

function search_form_submit($form, &$form_state) {
  $keys = $form_state['values']['processed_keys'];
  if ($keys == '') {
    form_set_error('keys', t('Please enter some keywords.'));
    // Fall through to the drupal_goto() call.
  }

  $type = $form_state['values']['module'] ? $form_state['values']['module'] : 'node';
  $form_state['redirect'] = 'search/' . $type . '/' . $keys;
  return;
}

If, when you don't enter anything, Drupal searches for search, there must be a module that alter the content of $form_state['values']['processed_keys'] when it is an empty string.


Removing potentially malicious code from template Our drupal site was hacked at some point recently, and I've been tasked to clean it up because nobody knows much about drupal here. I think I've taken care of most of the glaring security holes, and updated all the modules I could, but I've discovered there's still some gibberish/potentially malicious code on the site that I can't seem to track down.

At the top of every page drupal includes the site's CSS files, and then there's the three IE conditional blocks that are included in the seven_preprocess_html() function in themes/templates/seven/template.php. Immediately below those conditionals is the following block (I can't actually include the code because SE won't allow the characters in the textbox):

Then there are a series of legitimate .js script tags immediately below. The code in that block is throwing illegal token errors, and appears to be breaking other things in the page. I don't know if it's actually malicious or a corrupted file/db, but I obviously want it gone. Unfortunately I can't find it anywhere in any of the template files and I'm running out of places to look.

Anybody have any ideas on where this block might exist or how I can remove it?

The script may be included from any of the files involved in the build and render pipeline of Drupal as it outputs a page so it's tough, as you say, to pinpoint the single file (it may also affect multiple files). It may also be stored in the database via something included on every page.

So, instead of spot cleaning it's recommended that you start fresh with known-to-be safe Drupal files by importing your database and custom code over a new Drupal install. Drupal provides documentation for handling a hacked site that details why this is a better strategy.

You may have been hacked via the SA-CORE-2014-005 Drupal core vulnerability but even if not this detailed rollback blog post may also help http://befused.com/drupal/drupalgeddon


Send multilingual emails notifications with Checkout Rules in Commerce module? I have an on-line store using the Drupal Commerce module. When the checkout is done the buyer get an *email notificatio*n. So far so good.

My problem is that the website is multilingual (english, french and spanish) then I need to send the email notification in the correct language.

To accomplish with this I think of:

1) creating 3 different rules, one for each language at: admin/commerce/config/checkout/rules.

2) Each rule would have a condition to compare the user current language and an action to send the email notification in the correct language

3) Then when checkout is done the correct rule should be fired to send an email in the appropriated language

Is there any other way to do it?

Look at Commerce Email:

  Adds a configuration page for the order email
  Email content can be entered into textarea/wysiwyg (if available) form
  Email content can also be set to be loaded from a template file: commerce-order-email.tpl.php
  Allows the insertion of the order items into the email, token addition: [commerce-email:order-items]
  Supports Commerce Shipping
  Allows different language versions of each email
  Optional administrator email


Using theme hook, how do I get block contents into the $comm line? if ( isset($vars['content']['#block_content']) ) { // check for custom content
    if ($vars['content']['#block_content']->type[0]->getValue()['target_id'] == 'js_file_block') { // only run on js_file_block types
      $storage = \Drupal::entityTypeManager()->getStorage('block-content');
      $comm = current($storage->loadByProperties(['type' => 'block']));
      $route_match = \Drupal::routeMatch();
      $vars['inlinejs2'] = array();
      if ($comm !== false) {
        foreach ($comm->get('field_js_url') as $script_block) {
          $vars['inlinejs2'][] = $script_block->value;
        }
      }
    }
  }

I dont know what I am doing wrong, but it will not make the array.

If you try to access the entity in a template preprocess hook, there is a much simpler way:

function MYTHEME_preprocess_block(array &$variables) {
  // check for custom content block
  if ($variables['base_plugin_id'] == 'block_content') {
    // the entity is alreary availale in the preprocess hook, no need for another query
    $blockContentEntity = $variables['elements']['content']['#block_content'];
    // my advice: pass the entire entity to the template, so you can access all the block fields
    // in Twig without further preprocessing, similar to node templates, e.g.
    // {{ block_content.field_whatever.0.value }}
    $vars['block_content'] = $blockContentEntity;
    // further processsing only for custom content blocks of type 'js_file_block'
    if ($blockContentEntity && $blockContentEntity->bundle() == 'js_file_block') {
        //...whatever you need in here...
    }
  }
}


Defining the primary address of a CiviCRM contact I have a webform with CiviCRM fields on it (webform 7.x.4.1, civicrm_webform 7.x-4.9).

I have configured 2 addresses fieldset, one for work address and one for home address.
I find it non intuitive to let the user choose the location for each address and set the first one as the primary. So i have instead defined one field that let the user choose which one is its primary address (simple select field with Home or Work value).

Now, i need to synchronize this with CiviCRM after the form is submitted. I use hook_webform_submission_insert and hook_webform_submission_update.

My question is : what is the best way to define which address is the primary for a contact (the address are already saved in the database). Api ? other ?

Alternative question : maybe there is another (more simple) way to do the same thing ?

Webform-CiviCRM will always set the first address as "primary".

You don't need to expose the location-type field if you don't want to - you can set it on the backend form. This has the downside of forcing the location type of the primary address to change to whatever you've set the first address to.

Here is a solution that will solve your problem for both creating and updating contacts, and you don't need to resort to custom code and hooks:

Set the location-type field for both addresses to be exposed (user select)
Change both location-type webform fields to type "hidden"
Set the default value for the first one to be "home" and the other "work"

Now when the user updates their address, the location type will not be changed (your default values will be overwritten by the existing data). But when creating new addresses you'll be setting sensible defaults.


How to disable a file upload button for anonymous users? I've created a commerce add to cart form with a file upload field. The user can use this to upload a logo but I don't want anonymous users to be able to do this. I can see that the file module uses ajax to handle the upload but I can't see how you can disable the upload button for non logged in users.

The Field permissions module should help you achieve this.

  The Field Permissions module allows site administrators to set
   field-level permissions to edit, view and create fields on any entity.

  Enable field permissions on any entity, not just nodes.

  Role-based field permissions allowing different viewing patterned
  based on what access the user has.

  Author-level permissions allow viewing and editing of fields based on
  who the entity owner is.

  Permissions for each field are not enabled by default. Instead,
  administrators can enable these permissions explicitly for the fields
  where this feature is needed.


Download file programmatically I have a custom module where I need to create a file and download it on form submission. So far, I managed to created the file and save it in public folder, but I cannot find a way to download it to client. This is the code I wrote so far.

public function submitForm(array &$form, FormStateInterface $form_state) {
  $file_name = $date.'-event.ics';
  $cal_file = file_unmanaged_save_data('file content',"public://cal/$file_name",FILE_EXISTS_RENAME);
  return new RedirectResponse(file_create_url("public://cal/211443-event.ics"));
}

You can return a BinaryFileResponse from a controller, or as 4k4 has added:
$response = new BinaryFileResponse("public://cal/211443-event.ics");
$form_state->setResponse($response);


Show users a view of nodes tagged with the terms they flagged - Drupal 7 I want users to be able to create taxonomy terms and other users to be able to flag these taxonomy terms (using the flag module, sort of Follow). Then i want each user to have a view of nodes which have been tagged with those taxonomy terms they flagged. Is this currently possible with views contextual filters? Any alternative also welcome.

Example use case: i flagged terms Technology and Business created by admin or other users. When a user posts a node tagged with Technology or Business, i will see the post on my wall (My wall is an admin created view of all nodes tagged with the terms that i have flagged)

Here is how this can be done:

In the View, add a Relationship to the node's taxonomy term (using  "Content: Taxonomy terms on node")
Either add a filter criteria for the term, or add a contextual filter that would limit the terms to those flagged by the particular user.


Views content in search results page I have created a content type and used this in Views. Means this content type is always display via Views only . When searching for a keyword these nodes are displaying in the search result page which is fine.

When clicking on the result it opens the individual node content page but I want to open the Views page where these nodes are in use.
Please help if anybody know the solution.

Copy the file your_site/modules/search/search-result.tpl.php to your theme and modify the code.

You can read more about this in:

Customizing search-results.tpl.php and search-result.tpl.php


How can I remove old polls/results in Drupal 7? How can I remove the links to old polls and results in Drupal 7? I unset view results for anonymous users, but they still can view results. I'd like to remove the link to old polls and poll results in template. Is it possible to do it? if the answer is yes, which code should I add to template.php to remove those links?

You can remove the links by either copying the poll-results--block-tpl.php template file to you theme and removing the line that prints $links or with template_preprocess_poll_results(&$vars) in your template.php file in your theme and removing the line that sets the links variable.

poll-results--block.tpl.php

<?php print $title ?>

  <?php print $results ?>

    <?php print t('Total votes: @votes', array('@votes' => $votes)); ?>

template_preprocess_poll_results(&$vars)

function template_preprocess_poll_results(&$variables) {
  if (isset($variables['vote']) && $variables['vote'] > -1 && user_access('cancel own vote')) {
    $elements = drupal_get_form('poll_cancel_form', $variables['nid']);
    $variables['cancel_form'] = drupal_render($elements);
  }
  $variables['title'] = check_plain($variables['raw_title']);

  if ($variables['block']) {
    $variables['theme_hook_suggestions'][] = 'poll_results__block';
  }
}


Copy taxonomy term name to another field I need coordinates for each term in a cities taxonomy I got one a site for one of my clients. I found Geofield, which I use on nodes on that very same site, and it works as it should. However in my city taxonomy Geofield has a bug that makes it unable to get coordinates based on a title, which the term name is.

So I figured that I might copy the value of the title into another field for a term - like Title Copy field, and then base Geofield coordinates by that. Now, I don't know how..

I've found Computed Field which I find to complex for this, Tokens I don't get to work, Reference auto fill needs yet another source field so it goes away.

Any ideas for a simple solution that will work with terms created from both the taxonomy UI AND when nodes add new terms from a Autocomplete field?

I am assuming you have a content type with a field
"Title" of type "Term Reference"... and you want to pass an address from this existing field to a hidden field for Geo coding or whatever else for that specific page.

I would suggest using views and entity reference to do this. This method is useful for passing multiple fields, but can be used to grab just one...

Once you have the Entity Reference module enabled and installed create a view. For the view's display options (that + sign) add 'Entity Reference'.

Add a field to this view of type: "Content: All taxonomy terms"

In the next options screen you can limit the options here to your specific 'Cities' vocabulary.

You now need to add a contextual filter 'Content:NID' to get this view to only display the city term reference for the page that it's on.

Now go back to your content type and add a field of type 'Entity Reference'. Configure it like this:

Target Type - Node
Mode - Views (filter by an entity reference view)
View used to select the entities - 'my entity reference view'

Now add your Geofield and configure it to 'Geocode from another field' - i.e. your entity reference field (which you can hide in the display options)

In the event that a city name alone is insufficient to geocode from consider adding other fields to your content type and passing them to your entity reference view.


Put multiple views in one block I want to create 3 different lists of 3 different content types. They should be displayed in one block and this block would be the only one in a particular region.

Ultimately I just want a title for this region or block respectively like news and inside three different news columns like sports, politics, business (just examples).

My ideas:

A Block view using fields with three attachments. Problem is I can't create an empty block view without any fields specified. But then I have this extra SQL Query and the result will be rendered in html anyway even if I mark it "exclude from display".
Create three different block views, assign them to the region and create a custom theme template for this region.

Are there other options. Panels? Haven't used it yet, so not sure if it would be a fit for this problem.

Create your first list as the block view itself and give it a title
of "News".
Now add the other two lists as attachments to the block
view and set the titles to be blank.
Finally, add a "Global: Text
area" to the Header of each display, containing your "Sports",
"Politics" and "Business" titles, perhaps inside <h3> tags.


Sandbox module doesn't show any download link I've recently developed a module, Drupal to SugarCRM Lea', and decided to contribute to community. I've followed every steps on drupal.org to do so. I have managed to upload all my code to the sandbox, but my project page is not showing any download links for my module.

Repository
Module page

What did I forget to do?

Sandbox projects may not have releases.

There is a "Has project releases" checkbox, in the "Releases" vertical tab when you edit your sandbox, but it will be automatically cleared.

Thus it is not possible, but if you wish, you can apply for full project access.


How can I catch the current node object and make changes into it before it is rendered? I have a content type with multiple fields.

On the node display page I want to do some modification on this node (like. changing label text etc.) and I want to do it for display only. Nothing should change in the database.

I want to know how can I do this? Where exactly can I catch the current node object and make changes into it before it is rendered?

hook_node_view_alter

This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.
If the module wishes to act on the rendered HTML of the node rather than the structured content array, it may use this hook to add a #post_render callback. Alternatively, it could also implement hook_preprocess_node(). See drupal_render() and theme() documentation respectively for details.


List users with custom fields Is there way to list all users? I haven't found such method on UserInterface. The few hints I found on internet are for version 7 or using entityManager which is deprecated. Loading custom fields is a bonus.

$users = \Drupal\user\Entity\User::loadMultiple();
$field = $user->get('field_custom_field');
$value = $field->getString();


receiving incorrect url from amazon s3 module I am using drupal 7. I have installed amazon s3 module and its dependencies. I have created a bucket for saving my files on amazon server. Everything went good.. But when i try to get the path for the file it looks like this

http://bucketname.s3.amazonaws.com/abc.pdf

Later i came to know the actual path must look like
https://s3.amazonaws.com/bucketname/abc.pdf

As a result i am unable to access the pdf. It always shows access Denied as a response.

Please help me to over come this.

You need to create a group permission for Amazon S3 in Amazon IAM and indicate who can view the bucket.

Instructions on how to grant access to your bucket here: http://blogs.aws.amazon.com/security/post/Tx3VRSWZ6B3SHAV/Writing-IAM-Policies-How-to-grant-access-to-an-Amazon-S3-bucket

Hope this helps.


How to inject custom dependence in custom entity? On Drupal 8, in a custom entity class, I'm trying to load a repository in the constructor to be able to use custom functions in the preSave().

class MyEntity extends ContentEntityBase implements MyModuleInterface {

private $customStuff;

public function __construct(array $values, $entity_type, &$bundle = FALSE, $translations = []) {
        $this->customStuff = \Drupal::service('mymodule.mymodule_repository');
  }

(The service is defined in .services.yml in the correct module)

But I have the error :

The website encountered an unexpected error. Please try again later.Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php). Drupal\Core\Entity\EntityManager->getDefinition(NULL) (Line: 410)

How to inject custom dependence in custom entity ?

How to inject custom dependence in custom entity?

You cannot; per the Services and dependency injection documentation:

  Note: It's not possible to inject services to entity object. See this issue for more details.

You'll have to get the service from \Drupal directly.


How do I set the language code for rendering in entity_view()? I'm trying to render entities using a Search API callback with entity_view().

I want to register entities of type user in the full view mode as if viewed from the Japanese language.  Here is my code:

// Explicitly set language to Japanese.
$render = entity_view('user', array(entity_id($type, $item) => $item), 'full', 'ja');

However, the output is still in English.

When I visit a user page rendered using the full view mode with a Japanese language user account, the page is displayed correctly.

So what am I doing wrong?

I'd recommend looking inside of user_view() https://api.drupal.org/api/drupal/modules!user!user.module/function/user_view/7

That function should be called by entity_view() and it contains a drupal_alter() call. Print out the $build variable that goes into drupal_alter(). Is it using Japanese? Also print it out after the drupal_alter(). Is $build now back to English? If so, some other module is altering the display.


Regions and Page Layouts How do you work with regions if your website has different page layouts? For instance, the home page is a header-content-footer page, while the article page is header-sidebar-content-footer, etc.

Learning themeing :)

Thanks!

You can do it by creating templates for different types of pages.

e.g. If you have different layouts for front page, you can create page--front.tpl.php.
It will work for front page only, for rest of the pages page.tpl.php will work.

If further you have different layouts for page types, e.g a normal layout for pages and different layouts for article type of pages then you can create two types of tpl.

node--article.php, if you have the same header and footer content and just content part design is different.
page--article.php (page–[node-type].tpl.php), Here you can customize the content part as well as different layout for header and footer part.

Also there will a customization option in the manage display part of the content type.

Hope it will help you.


How to access fields for the Registrant settings (RNG) At the RNG module there is a possibility at the Settings to add fields to the Registrant settings. As I understand the idea behind this is to add some fields to the registrant. I want to add a color to the registrant.
But how can I access these fields? After I register for an event I can see my registrants on the Registration List, but I can't see the additional fields.  I also have no idea how to add the content to these fields?
Thanks

But how can I access these fields?

As I'm sure you are aware, you can add the fields here at

Administration > Configuration > RNG > Registrant settings > Manage fields (/admin/config/rng/registrant/fields)

  I can see my registrants on the Registration List, but I can't see the additional fields.

The registration list page is simply a page provided by Views. There are a few ways to edit the view, including the quick edit button which appears on the right side of the page. On the view, there is already a pre-made relationship from event entity -> registrant entities -> identity entity. The fields added to any of the entity types, including the registrant entity type, should be automatically available by using the standard Views add field button.

  I also have no idea how to add the content to these fields?

Before of 1.2, there was no edit registrant entity form (or view registrant entity). Adding field values programmatically to registrant entities is also fully supported using the standard Drupal entity API.

I have created an issue for RNG which can be used to discuss this kind of feature: Add a way to view and edit registrants entities


Why isn't Drupal object oriented? I just started to peek into the docs and source (Drupal 6 at the moment) and noticed that there are no classes to be seen, only vast number of prefixed functions. Is this handy? Does such decision have a background? Why?

This is pretty well explained on Drupal programming from an object-oriented perspective.

In short, Drupal has existed for much longer than you could properly use OOP in PHP. Which means, PHP5.

Drupal 7 already uses classes internally in a lot of places and it will probably continue so with Drupal 8.

But this is a step by step process and not everything needs to be a class. For example, it does not make any sense to make modules into a single class.


Custom Form submit not saving I've created a custom module to add several submission buttons at the bottom of the form. One submit button should redirect users to their Profile2 profile. The other will send them to the user administration section.

The Profile2 page has a submit button to send them to the user account edit page, or to the user administration section. I was able to do this with rules, but the site admin didn't like that there weren't buttons.

So I've created a custom module to handle this, but the problem is that the data is not saved when one of the custom submission handlers is called.

//redirects to account and from profile are working but submissions not saving

function MY_MODULE_redirect_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    if (arg(3) == 'coach'){
        $form['actions']['profile'] = array(
        '#type' => 'submit',
        '#submit' => array('MY_MODULE_redirect_account'),
        '#value' => t('Save and go to Account'));
        $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#submit' => array('MY_MODULE_redirect_admin'),
        '#value' => t('Save and go to Administration'));
    }
    else {
    $form['actions']['profile'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_submit'),
      '#value' => t('Save and go to Profile'));
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_admin'),
      '#value' => t('Save and go to Administration'));
    }
  }
}

function MY_MODULE_redirect_submit(&$form, &$form_state) {
    $user = $form_state['user'];
    $form_state['redirect'] = 'user/' . $user->uid . '/edit/coach' ;
    drupal_set_message('The user account has been saved');
}

function MY_MODULE_redirect_admin(&$form, &$form_state) {
    $user = $form_state['user'];
    $form_state['redirect'] = 'admin/MY_MODULE-user';
    drupal_set_message('Your submission is complete');
}

function MY_MODULE_redirect_account(&$form, &$form_state) {
  $user = $form_state['user'];
  $form_state['redirect'] = 'user/' . $user->uid . '/edit';
  drupal_set_message('The coach profile has been saved');
}

You are altering user_profile_form. By doing this

$form['actions']['profile'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_submit'),
      '#value' => t('Save and go to Profile'));

you have dissconnected default submit handler which save the data.

// Add the final user profile form submit handler.
  $form['#submit'][] = 'user_profile_form_submit';

So you need to append your submit handler with default submit handler


Uploaded Private files access problems On my Drupal 7 install, I have content type in which user can upload files to the server, via file upload field. I was sure everything was fine, I forgot about the system (was sure it was working, tested it). But strange enough, after some time I tested it, I could not download files, not by clicking on file link on that content type, nor by pasting url of the file in adress bar.

When I tried to access files, I got HTTP request status: 403 (Forbidden in http headers, while browser shows login page and path in the adress bar was path of that file...

And strange enough, under /admin/config/media/file-system I defined private files path to be files/private, and files were uploaded to that directory. But on the content type page - link to file ignored files/private path and rather had path system/files that I have not defined anywhere!

To test things, I migrated user private files to system/files (actually created that folder and subfolder in drupal root) and defined path of the private files to be also system/files (on /admin/config/media/file-system ).

Got some "progress" -  Apache "Forbidden" page - when acessing private files. There was .htaccess file in the folder, with config

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Deny from all
Options None
Options +FollowSymLinks

And for test,  I renamed that file to bypass "Deny", and voila, I could access my newly uploaded files.
But previously uploaded files still throws mysterious HTTP request status: 403 (Forbidden in  http headers, while browser showed login page and path in the adress bar was path of that file...

I was using Public local files served by the webserver. under /admin/config/media/file-system. I noticed also, when I enter that config, if I am missing .htaccess file in private files dir, a new one is being created.

I have to mention that I implemented Varnish cache and APC in Drupal, but things are not better after clearing the cache.

Could someone please tell me what is happening and how I can set it to work correctly/securely? Thanks!

Although and older issue, it's worth noting that system/files is normal for Drupal private file mode paths.

That is because system/files is the logical application path that handles and routes to the file on the actual file system.

It is this logical path that allows the additional authentication checks that private file mode allows.

You can put your private files under sites/default/files/private and Drupal will automatically create an .htaccess file to deny direct web access to them.

However, for safety, it's recommended to put your private files directory outside the html web root. For example, one level up from your website document root, or some other designated folder.

If curious private files are served via system_menu which defines the system/files url callback to file_download.

Following that hook_file_download is used to provide access control to the requested private file.


one profile2 profile for 2 users I'm working on a website for the elemantary school of my kids.
The parents should have the option to login to the site to consult information (children in classes, addresses of other parents,...).

Currently I've created one 'family' user account where the additional information (second parent, children, class, addresses) is stored in profile2. The problem is that when the parents are divorced the second parent should have also a user account (with a different password) but the profile2 information should be the same. So I need two user accounts with the same profile2 info.

How can I manage this in Drupal?

Thanx!

Jan

For your use case, I'd suggest using Organic Groups or the Group module.

Both modules allow grouping users / content. So each family could be a group with the parents / kids as members. Address information would be stored using a common group page, while the parents could still have different profiles.

In a later stage of your site you could also create groups containing all kids of a class and so on.


Allow users to manage their own mailing list? I would like to allow each user to manage its own mailing list (import a csv list, add/remove emails).
My goal is to allow users to send an email notification to this list when they create a certain content type.

Modules like simplenews, Views_Send, or mailing_list don't seem to match my needs as they only allow to create "globals" newsletters associated with a subscription  system, not real email list "crud" by user.

Maybe should I use a generic csv data importer, views/bulk and rules to achieve this?

Start with adding a multi-value field to store eMail addresses. Say with a machine name like field_email_addresses. Assume the content type you're using for this is "Article" (pick whatever fits).

With the above in place, uou could use the Rules module to achieve your goal. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?". By using the rule included in that answer, you can discover scenarios such as these:

Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

Here is a simplified version of the rule that only shows the inserted values:

{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just add a field with machine name "field_email_addresses" to your articles content type you should be able to import this rule in your own site and experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise). That will allow you to eMail relevant parts of the node whenever some eMail Id is added to that field already.

Some suggestions to further improve this solution:

Send it to all (not just updated) eMail ids mentioned in the field_email_addresses field, by creating another rule that is triggered with Rules Event "After saving a new node of content type Article".
Also use the Flag module so that if the node is flagged by the node author (and only then), send it to all eMail ids mentioned in the field_email_addresses field (something that is straight forward to do with another rule).
Variation of the previous item (which does not require the Flag module): add an extra (boolean) field to Articles, to indicate something like "Send this node as an eMail now".
Replace that field_email_addresses field (related to the Article content type) by a similar profile field with similar purpose. So that by combining it with the Views Rules module, you create a Rules loop to eMail all those users when such article is created, flagged, etc.

The above are just some basic solutions to implement what you're looking for. To further improve it (eg: combine it with importing a CSV list) should really be a different question.


How to use features-export drush command? I'm using Drupal 7. We have a large feature that we want to break apart. I am following the instructions here, and since there are a number of objects in the feature, I want to use drush commands, instead of clicking around the UI, to export the different objects.

I am looking at the drush commands from the features 7.x-2.10 module and found features-export. I'm not sure how to use the drush help command, but I found this description in features.drush.inc

case 'drush:features-export':
  return dt("Export a feature from your site into a module.
   If called with no arguments, display a list of available components.
  ...

But I called it with no arguments, and instead of a list of components, I got this error message:

$> drush features-export
No feature name given.

Poking around more, I found the features-components command, which gives me this:

$> drush features-components
Enter a number to choose which component type to list.
 [0]   :  Cancel
 [1]   :  all
 [2]   :  breakpoints
 ...
 [11]  :  field_base
 [12]  :  field_group
 [13]  :  field_instance

Selecting 11 (field_base) gives me these tokens:

...
field_base:field_address_1
field_base:field_address_2
field_base:field_state
field_base:field_zip_code
...

So I thought that I could use a line or token from the above output in the features-export command. However, I still get errors:

$> drush features-export field_instance
No components supplied.                            [error]

$> drush features-export 11
No components supplied.                            [error]

$> drush features-export field_base:field_address_1
No components supplied.                            [error]

$> drush features-export "field_base:field_address_1"
No components supplied.                            [error]

How do I use the features-export command from the features 7.x-2.10 module?

I figured out the syntax.

First, you have to learn the name of the component. Use the features-components command for this.

Then, when you know the component, do drush features-export my_module_name 'component_type:component_name'. That will create a module with the component you specified in it.

So in my case, I would do drush features-export my_module_name 'field_base:field_address_1.

If you want to add multiple components, you have add them to an existing, enabled module. So if I want to add another component to the features module I just created, I would do

$> drush en -y my_module_name
$> drush features-export -y my_module_name 'field_base:field_address_2


Is it normal after editing an item in one display for Views to always go back to the first display Drupal7 & Views 7.x-3.3 My site installation of Views has several working Views. There is a strange behavior in the GUI and its very annoying. After editing an item, Views always goes back to the first display!?!

For example, the included example view, "Front page (Content)", has two displays, Page & Feed. To recreate this annoyance edit the Front Page View, then:

Select the display Feed;
Edit any item, such as: Display name: / Page /
Make changes, then save;

Page refresh returns to Front Page's View edit page, and in my installation the Feed display is no longer selected. Now the Page display is selected. This happens every time for all Views. After editing an item in one display, the page refreshes back to the first display (at left). This was not the case with Views 2 and Drupal 6. Its the equivalent of changing tabs after saving something.

Its just a bug of views/settings/advanced and the setting "Disable JavaScript with Views".

At the time of asking this question, I was troubleshooting errors in the Views plugin Draggableviews that were appearing in the Views UI.

Related to this is another bug where its impossible to remove a Filter Criteria value without JavaScript enabled.


Better site and database performance I'm working on a Drupal community site and I want to ask about these things:

How do I make a Drupal site more secure?
How do I make my site work as fast as possible when there is a lot of visitors and users on the site, and there is a lot of interaction with the database at the same time? How do I maintain the database consistent in this situation?
How do I configure Drupal to work during high server load? How do I configure my server's hardware to work during high load moments?

1 - Use captchas and spam filtering; Mollom is a good place to start. There is also  info on hardening Drupal in the drupal handbook, ie. http://drupal.org/writing-secure-code.

2 - For starters, turn on the performance module that comes with Drupal.

3 - This is a big question. I have heard good things about Context HTTP Headers, a module contributed by the White House Drupal team. You can find a comparison table on Caching: Moduls that make Drupal scale.


Inline Entity Form - How to change label for the EDIT button and REMOVE button I try to modify the 'Edit' and 'Remove' label on the buttons displayed in the IEF table.
I can modify the 'Add new node' buttons with the code bellow

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENTTYPE_node_form') {
    /*
    * Modify the Add node button when it's the first one
    */
    $form['MY_FIELD']['und']['form']['actions']['ief_add_save']['#value'] = t('CUSTOM TEXT');
    /*
    * Modify the Add node button when there is at least one node
    */
    $form['MY_FIELD']['und']['actions']['ief_add']['#value'] = t('CUSTOM TEXT');
  }
}

But I can't make it work for the Edit or Remove buttons

For the Edit button, I tried to add in this function:

$form['MY_FIELD']['und']['form']['actions']['ief_entity_edit']['#value'] = t('CUSTOM TEXT');

Doesn't work

$form['MY_FIELD']['und']['actions']['ief_entity_edit']['#value'] = t('CUSTOM TEXT');

Doesn't work either

Any idea ?

Try form after build. it may give you solution.

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENTTYPE_node_form') {
    /*
    * Modify the Add node button when it's the first one
    */
    $form['MY_FIELD']['und']['form']['actions']['ief_add_save']['#value'] = t('CUSTOM TEXT');
    /*
    * Modify the Add node button when there is at least one node
    */
    $form['MY_FIELD']['und']['actions']['ief_add']['#value'] = t('CUSTOM TEXT');
    $form['#after_build'][] = 'yourmodulename_after_build'; //Calls function
  }
}

Use dpm($form) or print_r($form) to find the edit button id


Views to display events with single date events and events with date range I have a views view that displays a list of events. These events have a start-date and an end-date. I have two exposed filters, one for the start-date and one for the end-date, so that users can select a date range to view events. The page can be seen here:

KODE Calendar page

The filters check that start-date <= selected start-date and that end-date is >= selected end-date. This works if the event spans several days and start- and end-date falls outside the selected dates.

The question is, how can I include events that have start-date and end-date on the same day?

I tried to have another set of filters and use the and/or functionality, but alas, I was not able to reuse the exposed filter.

Since I was completely unable to make myself understood when asking the question, I thought maybe the solution could clear things up. In the views view I filter  event dates like specified in the question. I then used the hook_views_query_alter to add an or group condition like so:

function MYMODULE_views_query_alter (&$view, &$query) {
  if ($view->name != 'events') { return; }

  global $language;
  $lang = $language->language;

  $start_date = isset ($_GET['field_from_date_value']['value']['date']) ? $_GET['field_from_date_value']['value']['date'] : date('Y-m-d');
  $end_date   = isset ($_GET['field_from_date_value2']['value']['date']) ? $_GET['field_from_date_value2']['value']['date'] : date('Y-m-d');

  $query->group_operator = 'OR';

  $status_condition = array (
    'field' => 'node.status',
    'value' => 1,
    'operator' => '='
  );

  $node_type_condition = array (
    'field' => 'node.type',
    'value' => array ('event'),
    'operator' => 'in'
  );

  $language_condition = array (
    'field' => 'node.language',
    'value' => array ($lang),
    'operator' => 'in'
  );

  $date_condition_value = array (
    'field' => "DATE_FORMAT(field_data_field_from_date.field_from_date_value, '%Y-%m-%d') >= :field_data_field_from_date_field_from_date_value",
    'value' => array (':field_data_field_from_date_field_from_date_value' => $start_date),
    'operator' => 'formula'
  );

  $date_condition_value2 = array (
    'field' => "DATE_FORMAT(field_data_field_from_date.field_from_date_value2, '%Y-%m-%d') <= :field_data_field_from_date_field_from_date_value2",
    'value' => array (':field_data_field_from_date_field_from_date_value2' => $end_date),
    'operator' => 'formula'
  );

  $condition_type = 'AND';

  $query->where[10]['conditions'] = array (
    $status_condition,
    $node_type_condition,
    $language_condition,
    $date_condition_value,
    $date_condition_value2
  );

  $query->where[10]['type'] = $condition_type;

}


Resize images automatically When I insert an image into content area it's usually larger than the content area and the pasted image overlaps with neighbouring blocks. I have to edit HTML and set width and height CSS properties.

Is it possible to configure Drupal for automatic image resizing (shrinking), so the creator of the article will only upload the image of arbitrary size?

thank you

If you attach an image field to the content type, you can define Image Styles at admin/config/media/image-styles. It is the core continuation of the Imagecache module.

This may be able to be made to work for inline images using the Media module, but YMMV.


How to redirect to original page after node create I have a link to a create node form from a particular page.  After the user creates the node and saves, I want to redirect the user back to that page (and not to the new node URL).

What is the best way to do that?

I figured it out.  Just add the '?destination=the/url/you/want/to/redirect/to' to the /node/add/your-content-type' link.


Add a class to first query result How can I add a class to first query result?

$number_of_slides = '3';
$slides_result = db_query_range("SELECT nid FROM {term_node} WHERE tid = 1 ORDER BY nid DESC", array(), 0, $number_of_slides);
while ($slidesid = db_result($slides_result)) {
$slides = node_load($slidesid);
print $slides->title;
}

anyway I tried this but it doesn't work.

aaa

bbb

ccc

If you're going to use jQuery anyway, why not just use the .first and .last selectors?

$('.item').first().addClass('first');
$('.item').last().addClass('last');


How to programatically add attachments to a user (securely) To any Drupal 7 gurus out there... I have hundreds of PDFs that need to be uploaded to users as their own private attachment. I've created the PDFs in the folder:-

../website-files/userfiles-{uid}/filename.pdf  (There's one for each uid)

My field_data_field_attachments table has the "field_attachments_fid" column with the id relating to the file_managed table.

This is all pretty self explanatory, until... I find the file_managed table has two mysterious columns:-

  __pk
   __unique_uri

Both seem to be MD5 checksums, e.g:-

  4A448458-860C-4E16-B901-F8841136C17D

So my question is; how do I correctly generate these two values for each attachment I import to the DB?

Thanks,
Darren

You want to try and use the drupal api to move these files into drupal. Since you talk about private files, I assume you've enabled a private filesystem ... or else this discussion is pointless as all your files with be public :).

Once you've done that you could take your hundreds of files and put them in your server someplace and use file_move to place them into the drupal private filesystem using a small php script.

A module tutorial with a private file upload widget can be seen at this blog post and uses the drupal api to store a private file. Private files typically use hook_file_download which that blog post also shows to allow access to the file.


Body text special characters are escaped I have this code which I am using to get the body text from a node rewrite it with a regular expression and replace it, (I am replacing all you tube video links with embed codes)
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  switch ($entity->bundle()) {
    case 'article':

    $node_body = $entity->get('body')->value;

    Drupal::logger('origin-body')->notice($node_body);

    $node_body_replaced = preg_replace('/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/', '', $node_body);

      Drupal::logger('replaced-body')->notice($node_body_replaced);
      $body_encoded = htmlspecialchars($node_body_replaced, ENT_QUOTES, 'UTF-8');
      //$entity->body = $node_body_replaced;
      $entity->set( 'body',$body_encoded  ); // This appears to be where special characters are getting escaped

     break;
  }
}

Both my logger messages show normal text output in the drupal log so I guess it happens somwhere when the node gets saved or $entity->set().  I have tried running through htmlspecialchars() and it does nothing.
For example, I am migrating content from WordPress and after running through this function my normal HTML becomes

lorem ipsum dolar lorem ipsum dolar lorem ipsum dolar lorem
ipsum dolar lorem ipsum dolar lorem ipsum dolar .

I am using Drupal 9

Assuming by my normal HTML becomes you mean the escaped HTML is rendering on the front end, you're probably just resetting the format for the body field with this line
$entity->set('body', $body_encoded);

You can target the value directly instead like this (and you shouldn't need to encode/decode anything):
$entity->body->value = preg_replace('/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/', '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>', $node_body);

If that isn't working you can try setting the format too:
// Possibly change 'full_html' to whatever's appropriate for your site.
$entity->body->format = 'full_html';


How do you handle multiple feed URLs in a migration? I have a drupal migration that also uses migrate plus from a feed URL that can be queried. For example the migration can work for a single response from the feed at

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls: http://myfeed.com/newsfeed/get.php?id=123456

I would like to migrate content at 123456 and then 123457, then 123458.  How could this be done?

You should be able to list any URLs that should be fetched:

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls:
    - http://myfeed.com/newsfeed/get.php?id=123456
    - http://myfeed.com/newsfeed/get.php?id=123457
    - http://myfeed.com/newsfeed/get.php?id=123458

The Url plugin in migrate_plus converts single url values into an array by default: https://git.drupalcode.org/project/migrate_plus/blob/HEAD/src/Plugin/migrate/source/Url.php#L34


For the purpose of creating content, how do block_view and the page callback defined in the menu hook relate? I'm slightly confused as to how I should get my content on the page from a custom module. I thought I would normally do it with the block_view hook, but apparently another way is the page callback function. While I think I understand the former, I'm not quite sure how the latter works, and what I should return from it. Should I use one or the other method? When shoul dI use which? Can I use both?

hook_block_view() and hook_menu() aren't related at all, they're two completely independent concepts.

hook_block_view() is for defining blocks, which can be assigned to regions within the page template.

Items defined in hook_menu() are pages, for which a page callback is required to build up the content for that page.

I guess the slight confusion is that in Drupal 7 the page content is automatically assigned to a block in the main system region. Whatever you return from your page callback function for a menu item will be assigned to that main system block when you access the defined page.

A block is not accessible through a URL; it is a contextual piece of information that you add to different pages/regions when you need to. Think of the shopping cart in an e-commerce site as a perfect example of a block.

A menu item defines a page that is accessible through a URL, and may well contain any number of blocks within it.


Select order type and store with hook_form_alter() In drupal commerce, I have 3 stores and 3 orders type
When placing a manual order, i am first asked to choose the store and the order type ( which are entities), with radio buttons.
With a select list, I know how to programmatically select one option, with the following code.

function reservation_form_commerce_order_add_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['type']['widget']['#default_value'][0] = 'type_order_1';
  $form['store_id']['widget']['#default_value'][0]['#value'] = 1;
}

How do I do the same with the button?

You're overthinking it. As with most elements, you just need to set #default_value on the main element definition itself. Here's working example code I tested in my own development environment:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Sets default values on the order add form for the order type and store.
 */
function example_form_commerce_order_add_form_alter(&$form, $form_state) {
  $form['type']['#default_value'] = 'default';
  $form['store_id']['#default_value'] = 2;
}

Obviously you'll need to replace the values I've set with your own. : )


Too many passes with Drupal 7 test framework I'm implementing some tests using the D7 testing framework.

All is good, except that the numbers don't seem to add up, and I wondered how pass/fail was evaluated?

The problem is that I'm getting "6 passes, 0 fails, 4 exceptions, and 2 debug messages" for two test methods.

Obviously I'm missing something, but I had assumed that a single test method would produce a single pass/fail and therefore I should only have two results.

Secondly, how can I find out more information about the exceptions that were reported?

Thanks everyone.

Each assert()ion you have in your test code will result in a pass, fail or even an exception.  The uncaught exceptions are bad fails.

If you're running your tests with scripts/run-tests.sh, then use the --verbose flag and you'll be able to see the result of each assertion and any associated error/s.


How to add Views into a Panels page I have 2 views with contextual filter, they work well stand alone.

Now I want to include those two views into a panel (called eg. trypane/ ) and pass to it the contextual filter for the views it includes (eg. 19)

So I create a new content, panel, and i've added those two views.
But when i call the panel (trypane/19) simply it doesn't work.

The infos for the views included are:

Using display Master.
1 items displayed.
Without pager.
Sending arguments.
Using arguments: %2

and a similar description for the second.

What's wrong with my setup?

You should create a views display of type "Content pane".

Then ideally configure it to take arguments from context, and specify that the view requires a node id (or whatever you actually need). This will make the view much smarter, for example allowing Panels to hide the view from the UI all together when on a non node page.

Then add the new content panes to the page. You should be asked for which node you want to use as the source for the nid. Usually there will only be one, and you can continue without changing any settings.

And your view will now show up.


How to make custom taxonomy pages per term based on fields? I have a bunch of taxonomy terms, one for each county in a state.

I am going to use the taxonomy pages as landing pages in a Google Adwords campaign that is customized per county.

So, I have some boilerplate text that I want to use on all term pages, but I want to substitute the county name (which is the term name) and the biggest city in the county (which is input as a text field on the taxonomy term).

What's a quick way to do this in Drupal 8?  I tried to edit the Taxonomy Term view, but this is showing the content tagged by the term; in my case, there is no content tagged by the term. I want to use the term name and field data on the term to customize the boilerplate text.

I solved this with Panelizer and a custom block made in Views.

View of taxonomy terms, custom block
Contextual filter- taxonomy term: term ID
Provide default value: Term ID from URL

Pathauto pattern for taxonomy terms:
[term:tid]/mylinkpath/[term:name]

Go to taxonomy term display and add panelizer, then add custom views block.


Reset Drupal 7 Site: NIDs, Revision VIDs, Taxonomy Term and Categories, etc Is there a way to keep an entire Drupal 7 site intact, excluding content?

Basically after creating a test environment with many nodes, terms, revisions, etc, I would love to be able to delete all the content/taxonomy and have the IDs reset as well.

Thanks in advance for any help.

Delete all module does what you want :)

  This module is used to delete all content and/or users from a site.
  This is mainly a developer tool, which can come in handy in several
  cases, listed below.


How to get the View Header and Footer in Custom Module? I've made a custom view and display for it like this:

How do I get the Views Header (Global Summary here) ? I'm able to get the Views title  like this:

$views = Views::getView('items_list','page_2');
$views->setOffset($page_id);
$views->execute();
$view_results = $views->result;
print_r( $views->getTitle());exit;

Hope someone could help me out.

Step1 - You will create two files header.php and footer.php.
Step2 - Create a folder "include" in your theme directory.
Step3 - Suppose that your theme directory is "abc" sites/all/themes/abc. Put header.php and footer.php file in "sites/all/themes/abc/include" theme folder.
Step3 - By using html and php you can write code in header.php and footer.php.
Step4 - Now you can include both files in page.tpl.php in header area and footer area like PHP.

  include_once($theme_path.'/include/header.php');
  include_once($theme_path.'/include/footer.php');

hope this will help


Attempt to create an instance of field that already has an instance of that field how can i check if an instance of a field has already been created so that the my_module condition doesn't try to create it again?
something like

if(!instance_exist){
//do abc
}

The function you are looking for is field_info_instance($entity_type, $field_name, $bundle);

for example:

field_info_instance('node', 'field_tags', 'article');

will return the field instance if a field 'field_tags' exists on nodes of the content type 'article', NULL otherwise.


I need help implementing an ajax block to prevent it from being cached by Boost module I have a website fully cached through boost module with a region where a block is displayed. In this block content is shown via views and the display order in the view is set to random. So far so good. This works fine when logged in. But for guest users only the first block content that hits the cache is shown.

I found a snippet on drupalgroups that should do the trick, an "ajaxified block".

This is the snippet for blocka.php

<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$block = module_invoke('statistics', 'block', 'view', 0);
print $block['content'];
?>

And this should go in a block:

<div id="info">
</div>
<script>
$('#info').load('/blocka.php');
</script>

To test this I created the "ablock.php" and put it in the root directory and also made a block with the code.

Firebug tells me that the block is there, but it doesn't show any statistic.

How can i debug this to find out, if the blocka.php is loaded?
How do i have to customize this line for my needs? In fact, i do not understand this line...

$block = module_invoke('statistics', 'block', 'view', 0);

Thanks for any advice.

Without comment to the overall approach, but rather to "I do not understand this line," module_invoke() invokes a hook in a specific module with any arguments passed. The snippet you found is for Drupal 6, so that's the major part of the issue here.

$block = module_invoke('statistics', 'block', 'view', 0);

invokes statistics_block('view', 0) which means to view the 0th block of the statistics module, and

print $block['content'];

prints out its contents (so they get loaded into your #info div later on via ajax).

But, there is no hook_block in Drupal 7, it's now hook_block_view (and hook_block_info) so you need something along the lines of...

$block = module_invoke('statistics', 'block_view', 0);

instead to accomplish what you are looking to do.

More information on all of this can be found here:

http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view/7

http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_info/7

Now, if what you are wanting to do is put the contents of a View in this block, you could do something like this one-liner instead of the module_invoke/print above:

print views_embed_view('NAME_OF_THE_VIEW');

with more information on views_embed_view here:

http://api.drupal.org/api/views/views.module/function/views_embed_view/7


revoke access of author to flags I have a workflow system for my nodes, one of the states is "Disable". also there are some flags on those nodes as well, I'd like to know if there's a way to revoke access of author to use flags when he changes the state of workflow to Disable.

Edit: There's a listing of nodes by the logged-in user which is the author, these nodes have different workflow states and different type of flags which each of those flags, does a certain action. In some cases author might wanna change workflow states to different ones, but when he changes the workflow to "Disable", he shouldn't have access to flags on that exact node that has "Disable" state on it.

Changing state to "Disable" revoke access to all flags on that node.
In a rare situation, an admin might change the Workflow state back to something else, which obviously should grant access to the flags for the author, but author himself can't change the state back when he once "disabled" it using workflow.

Example:

Author's list:

Node1 : current workflow state: active, thus accessing to all flags.

Node2 : current workflow state: disable, thus no access to flags.

  Note that Author can change workflow from Active to Disable, not vice
  versa.

  Note2: Also I managed to get a rule to flag the node as disabled if
  the node workflow state is set to disabled, so we might be able to
  use flag only relation as well, for instance if disabled flag is
  flagged, deny access to all other flags of the node.

I'm looking for any solution, contrib module or a custom one, or just combination of modules maybe (Rules & flag), whatever that works!

I'm not sure if hook_flag_access() is relevant here or not.

thanks so much.

hook_flag_access and hook_flag_multiple_access() do seem to be the way to go. You will need to write a small custom module for that, which you can read more from here.

An example implementation is below:

<?php

function MYMODULE_flag_access($flag, $entity_id, $action, $account) {
  if ($flag->name == 'NAME' && $flag->entity_type == 'node') {// Change flag name with your flag's machine name.
    $node = node_load($entity_id);
    if ($node && $node->uid == $account->uid) {
      return FALSE;
    }
  }

  return NULL;
}

function MYMODULE_flag_access_multiple($flag, $entity_ids, $account) {
  if ($flag->name == 'NAME' && $flag->entity_type == 'node') { // Change flag name with your flag's machine name.
    $nodes = node_load_multiple($entity_ids);
    foreach ($nodes as &$node) {
      $node = $node->uid == $account->uid ? FALSE : NULL;
    }
    return $nodes;
  }
  return array();
}

You will need to change "MYMODULE" with a module name of your choice, and use the same name and save it as MYMODULE.module. Accompany with the MYMODULE.info, drop in a folder and activate the module. Above is a sample code for you to start with the module. It checks if the Flag's entity type is node. If it's node, the relevant node(s) will be loaded, and the user ID will be matched against the provided account's user ID. If they match, it returns FALSE, indicating access should be denied. It does not explicitly return TRUE, to allow the basic Flag access checks and potential other modules to determine the access.


Maintaining Old Drupal Versions Is there a list of best practices (or anything on drupal.org) for maintaining Drupal versions after end-of-life, specifically, when upgrading isn't an option? The best solution, of course, is to upgrade, but some organizations do not have the resources to make that happen.

I'd like to know some good practices here, especially when it deals with financial or private data.

The Drupal LTS project looks to be dead. I do my best to monitor info problems through things like CVE, but those sources seem to only mention exploits on the currently maintained branches.

I assume you're aware that Drupal 6 has been announced to be end of life as of Feb 24, 2016, as detailed in Drupal 6 end-of-life announcement. That mean that D6 will soon be considered as "old" also, right?
So looking at your question in this D6-context , I think "a" practise that may fit for D6 ("when upgrading isn't an option", as in your question) is to Buy Drupal 6 Long-Term Support (LTS) from one of the “official” vendors (up to you to decide if it is a 'good' or 'best' practise of course).
Moreover, as a variation of that "Drupal LTS project" that you mentioned, there now seems to be the D6LTS project.
For more details, refer to "What to do about Drupal 6 End of Life?". Some more details (from this link):

What, specifically, will happen after February 24th?

All D6 modules will be marked as “unsupported” on Drupal.org - which will mean the ‘update’ module will start telling you that ALL your modules are out-of-date.
Also, the status information that the ‘update’ module uses could go away at any time - so, you’ll no longer be able to rely on that in general.
The Drupal security team will no longer be making Security Advisories (or coordinating security releases)
In general, most module maintainers will no longer pay attention to Drupal 6 issues and will stop making new releases.

What should people with Drupal 6 sites do?

Archive the site, or
Plan upgrade.
Buy Drupal 6 Long-Term Support (LTS) from one of the “official” vendors.

What makes the “official” vendors special (vs. any other vendor)?

Get confidential information from Drupal security team.
Agree to follow security team processes and release all security patches publicly.
Vetted by the Drupal security team.

How will the Drupal 6 LTS work?

Same process as security team - but work done by vendors rather than security team.
Will publish patches on the D6LTS project.
Likely, but not 100% decided:

Announce new patches on the D6LTS issue queue.
Make new Pressflow 6 releases with the Drupal core patches.

Can the community get this without working with a vendor?

Yes!
But each vendor only supporting those modules their customers depend on
Question: And what about security issues that hackers find first?


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

I end up using google analytics reports. and added the top page view in my homepage.


Is it possible to show only node contents in shadowbox pages? I'm looking for a method to display content (nodes) in a shadowbox overlay without any blocks or menus around it. even if the user is logged in.

Has someone an Idea how to do this are there even better parameters for rel shadowbox than the height and width parameter to reduce  the window size?

For Drupal7:

Add to your theme template.php (or add inner of function code to existing function prepropress_page closer to the end) next function:

/**
 * Override or insert variables into the page templates.
 */
function YOURTHEME_preprocess_page(&$vars, $hook) {
  if (isset($_GET['shadow']) && $_GET['shadow']) {
    $vars['theme_hook_suggestions'][] = 'page__empty';
  }
}

Add page--empty.tpl.php to your theme folder - take original copy from page.tpl.php, but remove printing all header, sidebars, footer regions. E.g.:

<?php
/**
 * @file
 * Returns the HTML for Drupal page only with content region = empty page.
 */
?>
<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>
<?php print render($page['content']); ?>

Make shadowbox scripts added to any page (shadowbox ui settings), and you can do next anywhere:

About

So, any link with url?shadow=1 and rel="shadowbox" will shown on shadowbox popup window only content without sidebars. Control size of window on rel="shadowbox" as documented.

For shadowbox links that generated automatically (views, fields) you should override it via settings or template.


(Field type) Link autocompletion for media entities How can I enable autocompletion for media entities in Link fields? The Link field seems to "know" only nodes, but no media entities.
Use case:
I've got a paragraph for a "card style" link consisting of 4 fields for an image, a title, a short description and a link. The paragraph must work for internal and external links, so I'm using a Link field and not an entity reference.
A common task is that editors upload a PDF to the media library, and provide a nice download link to the PDF on multiple nodes, using the paragraph mentioned above.
Tried this, doesn't work good enough:
I know that it technically would be possible to manually enter a path like /media/<media_entity_id>.  But this so bad UX that I need to find a better solution.
I also have LinkIt installed, but sadly I can't use LinkIt for Link/URL fields.
(I'm using Drupal v8.4 core media)

The short answer: Currently not supported, unfortunately:

  // @todo Support entity types other than 'node'. Will be fixed in
  //    https://www.drupal.org/node/2423093.

Until https://www.drupal.org/node/2423093 is done, the link field widget can only support a single entity type; so you can have a widget for linking to nodes or to media entities, but not both.

Worse, until https://www.drupal.org/node/2427803 is done, the entity type is hardcoded as node and not configurable.

The good news: It's still possible, if you're prepared to write a bit of code.

Other than three lines in LinkWidget that contain a hardcoded reference to node, nothing stops the code from working with a different entity type in principle. So as a workaround, you could duplicate the core LinkWidget in a custom module, change the relevant lines to media (I made a patch for this at https://gist.github.com/cburschka/b214a52bdb1fdf7349ef3b0afe56b950), and thus create an alternate widget for media links.

This still means you have to choose between either a Node or Media link field, unfortunately. If you don't want to create two different fields, you could use the Paragraphs module in order to create a single Paragraph field that can be filled with one of two paragraph types (one of which exposes the link field with the original widget, and the other with your custom Media widget). It's a bit more complex, but should still provide a decent user experience.

Edit: Alternatively, instead of using the Link module you could use a Dynamic Entity Reference field: https://www.drupal.org/project/dynamic_entity_reference

The downside is that this field could then only reference entities; external links and non-entity links wouldn't be possible anymore.


Drupal 7 Calendar - How do you modify link from day number? When I click on the day number, it currently goes through to day page.  I'd like to customise this to go to a specific event page for that day.

I can't find a hook for this.  Is there one?

The day page is generated by the day display of the view generated by the calendar module. You can customize this display as much as as you want - add header, footer, embed an attachment view, or otherwise enhance it:

You can disable the day display if you don't want the links at all.

Replacing it with another page would be much harder, but it might be possible using the panels module.


Implement parallax effect on Header image from Content type field I have a Header image which i can upload per node from my Basic-page Content type. I want to implement this parallax effect, on my Header image section. But I need to add:

.

How do I add data-image-src="/path/to/image.jpg" to the wrapping
? It has to be dynamic and per node you must be able to attach a specific image.

Where do you need to add that code? Into field.tlp.php, node.tpl.php or page.tlp.php? Is it D7 or D8?

If you need to extract src atribute (/path/to/image.jpg) from some HTML code (for example from the node.tlp.php field) then use Google. When you will have src then you can create desired
 element in your template files.

As universal answer as detailed question was.

Update:

I found that you have attached your site so I suggest this:

Create block in Views for header image field

NID as Contextual Filter
Enable cache per page
Output header image field as src (only image url) - there is such option in views or use this module
Override that field (rewrite the output of this field) with something as

enable block in proper region only for "Basic-page" CT


Getting the nid for a teaser I know how to get the nid for a node, but not for a teaser. I want to show a button in the teaser, created by a field with the PHP filter, that allows printing the node to pdf, but that requires the nid. The functions that work in the node, like menu_get_object(), don't work in the teaser.

Googling this has only brought up methods of printing a teaser if you already know the nid, not getting the nid if you only have the teaser. It should be available; it appears in the id for the teaser.

EDITED: I went with the suggestion posted below by f0ns. I don't understand why the nid is not available when it's in the teaser's id in the html, but that seems to be the case.

Use hook_node_view and for $view_mode == teaser you can add your logic.

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7


How do I edit the response of successful register.json? How can you edit the Services' json response of successful register.json to include the user's OR system's auto-generated password, plus any token?

I've tried a variety of combinations of the commented code below..

function logintoboggan_process_login($account, &$edit, $redirect = array()){
  global $user;

  $user = user_load($account->uid);
  watchdog('login debug', json_encode($edit)); // AT THIS POINT I CAN VERIFY WE HAVE THE PLAIN-TEXT PASSWORD
  //user_login_submit(array(), array('uid' => $account->uid));
  user_login_finalize($edit);
//  $user = user_load($account->uid);
//  $user->token = drupal_get_token('services'); //WE HAVE A TOKEN ALTHOUGH I DOUBT THIS WOULD WORK.
//  user_login_finalize($edit);
//  module_invoke_all('hook_user_login');
//  module_invoke_all('tripchi_user_login');
//  module_invoke_all('logintoboggan_user_login');

and even also tried hacking the drupal core on line 3888 of "/modules/user/user.module":

elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
      global $user;
      $user = user_load($account->uid);
      watchdog('login debug', json_encode($edit));  // AT THIS POINT I CAN VERIFY WE HAVE THE PLAIN-TEXT PASSWORD AND TOKEN AVAILBABLE!
      //user_login_submit(array(), array('uid' => $account->uid));
      user_login_finalize($edit);
    //  $user = user_load($account->uid);
    //  $user->token = drupal_get_token('services'); //WE HAVE A TOKEN ALTHOUGH I DOUBT THIS WOULD WORK IN TERMS OF SESSION PERSISTANCE
    //  user_login_finalize($edit);
    _user_mail_notify('register_no_approval_required', $account);
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
    drupal_set_message(t('Registration successful. You are now logged in.'));
    $form_state['redirect'] = '';
  }

if one of my test lines don't break the call altogether, on success the call just replies:

{
    "uid": "499",
    "uri": "http://localdrupal.tripchi.com/drupalgap/user/499"
}

I was never able to get back the raw text password without hacking on the logintoboggan / user modules themselves (similar to what is shown in my question).

However, I solved my same purpose of providing immediate-login-upon-registration for Services/API calls using the services_token_access module. This code only hooks onto a success registration then ads the services_token to the response which is now the only thing my client now needs for validation.

function HOOK_services_request_postprocess_alter($controller, $args, &$result) {

if ( gettype($result) == 'array' && isset($result['uri']) && isset($result['uid'])) { // THIS CONDITION MATCHES THE DEFAULT RESPONSE OF A SUCCESSFUL REGISTRATION.
        $user = (object)$result;
        $user = user_load($user->uid);
        $user = HOOK_services_account_object_alter($user);
        $result = array('token'=>$user->services_token, 'user'=>$user);
    }
    return $result;
}

function HOOK_services_account_object_alter(&$user) {
    $user->services_token = services_token_access_update_token($user->uid, FALSE); // essential for logging in later
    $user->specialstuff = 'whatever else you need';
    return $user;
}

(The services_token_access module is not particularly popular and barely supported, but worked for me.)


Opening hours - Days and times I have created a content type - Shops in College

I would like to display opening days and times. Something like this:

Monday - 09:00-18:00

Tuesday - 09:00-18:00

Wednesday - 09:00-18:00

Thursday - 09:00-18:00

Friday - 09.00-13:00

Saturday - Closed

Sunday - Closed

Is there any way I can do this by managing the fields? Or how would I go about this?

Thanks

There is a module for Drupal 7 for this called Opening Hours and for 8.x there is Office Hours.


How are global roles synced with group roles? How are global roles synced with group roles in the Drupal 8 group module?

I expect that the module would either:

Create a group roles in each group type for each global role

and/or one of the below:

Create role assignments for users in the group who have a global role that matches a group role name.
Assign global roles for users who have a group role in any group where the group role name matches a global role name.

In my testing so far it appears to do none of the above.

The group role sub-module is marked as deprecated and has a note that the functionality is in the core group module. A code review shows that the sub-module is basically empty. Therefore I take it the note is correct. I also see that the group module implements hook_rebuild and it creates a config entity for each global role.

None of the above expected results are happening however.

Take a look at the roles & permissions page for a group (and also group's documentation). By default groups treats all authenticated non-members as outsiders no matter what their role is, but there is an advanced option to define permissions based on their global drupal roles.


The site has a mix of modules installed manually and via Composer: Can I move all to Composer? I've inherited a Drupal 8 site where only few modules were installed via Composer; the rest was manually installed.

Is there a way to fix this, and move the manually installed modules to be handled by Composer?

You can just add the modules to Composer as you would normally: composer require drupal/MODULENAME.

You can then confirm everything is working OK by making a new copy of your site with Composer and verifying that the site loads correctly.

Potential issue:
If you are looking at the list of installed modules to decide what to install, you don't necessarily need to add every module; some may be dependencies of others (for example, with Composer, if you are using Pathauto module, you don't need to install Token explicitly; it will automatically be installed with Pathauto.)  However, it won't hurt anything if you force some dependencies to be installed as well, so this isn't really anything to worry about.


Users can't cancel their own order I'm using Drupal Commerce Kickstart to create an E-commerce website.
How can customers cancel their own order if they accidentally ordered some wrong product?

Find permission page (/admin/people/permissions) and You can give Authenticated users  permission to "Edit own Order orders"


How to configure edit permissions for Panel panes? Is there a way to configure edit (not view) permissions for a Panels 'pane'?

I would like to add a pane for 'custom content', for example above and below a view, so that the content manager role that I've setup can edit that part of the page. Seems really simple (and essential), but haven't found anything like this.

That blog post doesn't seem to have been followed up on.  There is some discussion here regarding more granular permissions for Panels IPE:

https://www.drupal.org/node/1821618#comment-9502245

I mention it would be great to be able to change role permissions for an individual pane such as 'Move', 'Edit', 'Change Style'.


drupal form api call function I have a select box in my drupal form and i want to call a spesific php function whenever the select option is changed. How can i achieve this?

this is my code so far:

function langSelect_form($form, &$form_state) {
    $form['langSelect'] = array(
       '#type' => 'select',
       '#options' => drupal_map_assoc(array(t('English'), t('Norsk'),t('Samisk'))),
    );
    return $form;
}

thanks!

You can go through AJAX Forms in Drupal 7. It describes how you can use ajax in your form with examples


how to use hook_field_widget_form I am trying to understand how the addressfield module is using hook_field_widget_form. When is it called and where are its parameters coming from? When I do a printout of its $instance parameter, I see that it has default values. Where are these set?

The hook is called by the Fields Widget API in order to collect information about defined widgets. Any module can define a field widget as long as it implements the necessary hooks.

Documentation about the hook itself can be found in the docs: hook_field_widget_form().

Basically it provides widget specific Form API elements that collect the necessary data for a field. The default values are set in code (or wherever the module chose to define them) and should provide sensible defaults. In the case of the Addressfield module the default values are defined in the function addressfield_default_values in the main module file addressfield.module.


How do I link to the homepage from a node? I used to had a logo provided by a theme which automatically linked to the home page. But now I replaced this with a custom block. How do I link to the homepage from that custom content type?

Using php in the block code is not an option because of caching.

You can just create a link to the path / (slash with nothing else).
That will take the user to the homepage.


What would be the minimal modules I need to have for a simple registration page? I would like to make a registration page that is only going to add Users to a list for an event, basically my site is not as concerned with accounts and detailed registration we only really care about name and a contact email that we can add to a list.  Basically it's a group that has monthly events and all we ever really need is a way to track people who say they will attend, not a lot of heavy requirements for people to modify their registrations (most won't anyway) or capture a lot of information.

The various registration and event options for Drupal look overwhelming, I am using Drupal 7 and at this point using only modules and the CMS system to add pages (no coding yet).  Is there a minimal set of modules that would give me the ability to obtain just a User's name and contact info (email or whatever) to put onto a list in a page?  Or for this is it just easier to just code a page that can add in what I want using PHP or JSON.

You should be able to do this with the default installation of the core + Views, Views UI, and CTools.  (You may be able to strip it further down by doing a custom installation of the core with some of the default core modules not enabled - but why bother).

I assume you're going to handle multiple events, and here taxonomy (in core) is your friend.  Just enable the taxonomy module (if necessary) and create one taxonomy term for each event. Add a taxonmy field (or multiple to allow one user to sign up for more that one event) to the users' profiles.  Ask users to register the events they plan to attent in their profile when they register (or later).

Then use Views to generate lists of names and contact addresses for the various events.

You may want to add refinements, such as not letting users cancel after they've signed up, but the above is a rough sketch of how to meet your minimal requirement.


Saving date field programmatically on node, but not on profile I'm saving some date field on the code both on node and profile entity. I'm success on saving it for nodes, but when I try to save for profile2 entity, using the same chunck of code, no data is saved.

I'm doing this to nodes (after creating a new node with entity API):

// Creating a node and an entity wrapper
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
// Saving the date field
$entity->field_date[LANGUAGE_NONE][0] = array(
   'value' => strtotime($date),
   'timezone' => date_default_timezone(),
   'timezone_db' => date_default_timezone(),
   'date_type' => 'datestamp'
 );
//Saving the node
$ewrapper->save();

And almost the same way with profiles:

//Creating a profile2 'info' bundle
$profile_info = profile2_create(array('type' => 'info', 'uid' => $user->uid));
// Trying to save the date field, same way as above
$profile_info->field_date[LANGUAGE_NONE][0] = array(
   'value' => strtotime($mydate),
   'timezone' => date_default_timezone(),
   'timezone_db' => date_default_timezone(),
   'date_type' => 'datestamp'
 );
// Saving the profile
profile2_save($profile_info);

If someone knows what is happening I'd appreciate!

This might or might not fix your problem but since you're using entity metadata wrappers, you should use them fully:

$profile = profile2_create(...);
$profile_wrapper = entity_metadata_wrapper('profile2', $profile);
$profile_wrapper->field_date = array(...);
$profile_wrapper->save();

The above snippet can also be used with nodes, just replacing the creation & wrapper instantiation.

Also, if you're using a single timezone, you can safely omit it and just specify the actual timestamp value.  You should probably omit the 'date_type' key too, that's inferred by the field config and could be causing issues.

In fact, you should just do: $profile_wrapper->field_date = 123456; // (timestamp)

Tested locally and it works!

You shouldn't use LANGUAGE_NONE or [0] indices because not only might it break i18n if you're translating fields but it's also not very robust.