How to: Admin flags content, owners of content gets email nofication I'm building a site where users of the role Contributor submits content (songs). Songs gets rated by users of the role Curator and the best rated Songs are added to Playlists by the Admin.

The Admin is presented with the best rated tracks in a Views table. I'd like to have a flag on each Song with these values:

Playlist add confirmed
Playlist add pending (default mode)

When admin flags the Song with the 'Playlist add confirmed' mode this should fire an email (via rules?) to the Contributor who submitted the Song in mention notifying the Contributor of the good news.

The admin table of best rated tracks are ready and working but I'm stuck at getting the Flags and email notifications working.

How would you do this?

Part 1 - Rules Component to send an eMail

Here is a Rules Component (in Rules export format) to send an eMail to a user indicated as a parameter of the Rules Component (adapt the subject and eMail body to your own needs):

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Your eMail subject goes here ...",
          "message" : "Your message body goes here ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Part 2 - Rule to trigger the Rules Component

Here is the rule (in Rules export format) to execute the Rules Component from Part 1 (adapt the machine name of the flag you're using prior to importing it in your own site):

{ "rules_send_email_to_author_of_a_flagged_node" : {
    "LABEL" : "Send eMail to author of a flagged node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_playlist_confirmation" : [] },
    "DO" : [
      { "component_rules_send_email_notification" : { "user_to_notify" : [ "flagged-node:author" ] } }
    ]
  }
}

This rule gets triggered (Rules Event) when a node is flagged with a flag that has machine name playlist_confirmation. Note the value of the parameter passed to the Rules Component, i.e. flagged-node:author (the author of the node being flagged). Obviously, you want to limit access to this flag to users like your admin only.

That's really it.

PS: you don't really need to use a Rules Component, since you could "integrate" (hardcode) what the Rules Component does in your actual rule also. So that's rather a matter of coding style. If you'd make your eMail subject and message body another parameter for the Rules Component, you can re-use that Rules Component for all sorts of eMails you want to send via Rules. And if some day you'd want to replace sending eMails (by Rules) by using the (amazing) Message module, you'd only have to adapt your Rules Component for it.


How to decide in hook_nodeapi() if it was invoked after creating/updating node via Services module? I am developing a custom module, which should do things in hook_nodeapi() only if the node is being created/edited via Services. I couldn't find any data that is available at this point for deciding if the node is via Services or not.

I am aware of a possible solution, using request_uri() and deciding based on that (https://drupal.stackexchange.com/a/8568/1930), but it seems so wrong. Hardcoding the endpoint name is plain wrong. Workaround this by providing an admin interface and depend on configuration?

So, I would rather avoid the above, but couldn't come up with anything else so far. I am curious if others have had similar problems before and if there is a better solution.

UPDATE

The accepted answer should be used, as that is the cleanest solution. Unfortunately, I had to use a different one, which might still be useful to others so I am sharing it here: https://gist.github.com/Temaruk/5884209

I think there's a point in the system not normally telling you this, since we want to avoid any kind of coupling between the systems. Based on that I guess there's no built in way to get the information you want. Strictly speaking, you should probably consider why you are doing what you are doing, as it's not good practice.

Possible methods:
You could implement a custom node resource, which hands over node creation to the regular services callback after having done

$node->creator = 'services';

or possibly:

$node_origin = &drupal_static('node_creation_tracker');
$node_origin = 'services';

after which you could retrieve this data with the same method. Implementing a resource is not a complicated process, but requires quite a bit of knowledge about services.


Views: add custom no result behavior to a view? I am trying to add custom no result behaviour to a view. I have many pages with view panes in them. Sometimes if no results are available, I would like to be able to display a 404. This is not an option when it's a view pane. I would like to do this in a reusable way where if the view pane has that custom option then this happens.

I can hard code this stuff on one of views hook, but ideally I want to be able to configure such behavior.

This is not an option in views panes because a 404 should be returned by the page_callback handler, which in this case is the panel that is holding the pane.

Option 1, see if this module works views404, but I have not used it so I do not know for sure.

Option 2, use drupal_not_found(), though I have not tried this in a panel.  Or if you are using contextual filters try this.

Option 3, stop using panels and use view page with Bean and Context and theme regions and a bunch of other things. This way the page_callback is being handled by the view, so the view has the authority to return a 404 instead of theming the frame and other blocks and presenting those.  Downside is you have to restructure the whole site so you probably dont want that.


Ctools Custom Content Type Plugin with Image Field I was wondering if anyone has been successful with incorporating an Image field 'type'=>'managed_file' into a ctools plugin.  I created a custom ctools plugin but am having some difficulty with the image field as I am getting an error upon upload.  After some searching, it seems like this error could be caused from a file that isn't being included when the form is rebuilt after the ajax request. I've attempted to use the form_load_include to include the DRUPAL_ROOT/modules/file/file.field.inc file, and it is being loaded with the form, but I am still receiving this error:

Notice: Undefined index: content_image_pane_edit_form in drupal_retrieve_form() (line 763 of /htdocs/development/includes/form.inc).
Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'content_image_pane_edit_form' was given in drupal_retrieve_form() (line 798 of /htdocs/development/includes/form.inc).
Notice: Undefined index: pane_image in file_ajax_upload() (line 271 of /htdocs/development/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /htdocs/development/modules/file/file.module).

Here is my settings for my Custom Content Type Ctools Plugin:
/*Plugin definition*/
$plugin = array(
  'single' => TRUE,
  'title' => t('Custom: Content Image Pane'),
  'description' => t('This is a custom pane containing a title, textarea and image field.'),
  'category' => t('Custom Panes'),
  'edit form' => 'content_image_pane_edit_form',
  'render callback' => 'content_image_pane_render',
  'admin info' => 'content_image_pane_admin_info',
  'defaults' => array(
    'pane_image' => '',
    'pane_content' => '',
  )
);
/**
 * 'Edit form' callback for the content type.
 */
function content_image_pane_edit_form($form, &$form_state) {

  $form['#attributes']['enctype'] = array("multipart/form-data");

  form_load_include($form_state, 'inc', 'file', 'file.field');

  $conf = $form_state['conf'];

   $form['pane_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('Upload an Image that is associated with this content.'),
    '#default_value' => '',
    //'#default_value' => !empty($conf['pane_image']) ? variable_get($conf['pane_image']) : '',
    '#upload_location' => 'public://panes/',
    '#upload_validators' => array(
       'file_validate_extensions' => array('gif png jpeg jpg')
     ),
    '#array_parents' => array('pane_image')
  );

  $form['pane_content'] = array(
    '#title' => t('Content'),
    '#type' => 'text_format',
    '#format' => 'full_html',
    '#description' => t('Please enter the content for the custom pane here.'),
    '#default_value' => $conf['pane_content']['value'],
    '#cols' => 40,
    '#rows' => 6,
    '#resizable' => TRUE,
    '#required' => TRUE,
  );
  return $form;
}

If anyone could point me in the right direction for an answer to this that would be outstanding!

You should try to put this line:

form_load_include($form_state, 'inc', 'my_module','plugins/content_types/my_file');

at the top of your content_image_pane_edit_form function, replacing my_module and my_file with your module and plugin include file.

Ctools panes are generated in a separate modal from base Drupal forms and so when the AJAX reloads the form it cannot find the original form function. By forcing Drupal to include the full form code each time it is processed, the AJAX will be able to find the necessary function to rebuild the form.

Tested working with Drupal 7 & panes on a production site.


How to attach email from a private folder(outside root) I'm trying to attach a file to an email. It's part of job application so a person goes to a node, presses apply and it sends an email to the creator of the node. I want to attach a CV & cover letter to it.

The problem is I'm storing the CV & cover letter in a private folder outside of drupal root. (Personal info security and all that.) The code below works for public folders. How would I got about altering it to access private ones?

function tellafriend_mail($key, &$message, $params) {

        global $base_url;

        $message['subject'] = t('Your friend thought you might like this site');

        $message['body'][] = t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
        $attachment = array(
          'filecontent' => file_get_contents('http://localhost/private/counciltax.txt'),
          'filename' => 'test.txt',
          'filemime' => 'textplain',
        );
        $message['params']['attachments'][] = $attachment;
   }

You can use the drupal private file directory notation:

file_get_contents('private://counciltax.txt')


Is it generally safe to add same Drupal javascript multiple times? I am trying to load content via AJAX calls which may include Javascript and its settings.  This works more or less, but I cannot make sure whether a certain javascript code has been inserted and executed before.  Now I need to find out, whether in case of problems resulting from a modules javascript code being executed multiple times, I would need to fix the modules javascript or whether I would have to take other precautions.

My question: Given Drupal's coding standards for Javascript added by modules, should it be unproblematic to execute it multiple times?  I am aware of some modules where the javascript part is badly coded and problems will result, I just want to know whether this is allowed by some Drupal javascript standards (if any exist)

Usually, you add javascript with Drupal's behaviors as explain in the doc. If you have AJAX callbaks, javascript behaviors will be reloaded and this can cause some trouble.

For exemple, on my website I added moving clouds in the header with a javascript behavior, the speed beeing added by increments, each time I loaded an AJAX form it was sped up unintentionally. I could either add a jQuery Once behavior or use the common $(document).ready function.

So in conclusion, it depends on the way you call the code inside your javascript file. Your javascript code called inside a $(document).ready function should be loadded once, even with AJAX callbacks. On the contrary, a Drupal javascript behavior will be executed each time your DOM is updated, exept with jQuery Once enabled:

Drupal.behaviors.mybehavior = {
  attach: function (context, settings) {
    $('input.mybehavior', context).once('mybehavior', function () {
      // Apply the MyBehaviour effect to the elements only once.
    });
  }
};

Now if you are concerned with others javascript coding standards, see the official Javascript coding standards.


Project Pages of Drupal I have seen project pages in drupal under http://drupal.org/project/xyz. I don't know how that works really.

Is this a specific 'Content Type' it is, but each node (aka project) has extremely consistent layout where as the whole thing look more like an basic article or a book page. Also, the elements within also has sections and further content; so it doesn't look like a pure single node. Or is this a different entity using a module like Project? But it is not available for D7.

Specifically, I want something exactly like this, but i don't quite know how to make specialized and consistent.

Drupal.org is using the Project module.

What you see as project page is a normal node to which the Project module adds extra fields. Keep in mind that the project page is also showing blocks shown just for those pages, and which are not part of the project page output.
The Project module automatically creates a path alias for every project node. That is the reason you see http://drupal.org/project/views, instead of http://drupal.org/node/38878; if you try the last link you will see you are accessing the Views project page.

The fact the project page is just a content type is proved from the fact project is shown in http://drupal.org/node/add, which lists the possible content types for which a user can create a node.

What you see in that page depends from the permissions you have on Drupal.org; as site maintainer, I see listed some content types a normal user doesn't see, such as the Story content type.

As alternatives to using the Project module there is the Storm module, which is more complex, in some way, and lack integration with CVS, or Git repositories (as far as I can see).

  Storm is a structured system for project management, including:

  Organizations, Teams, People,
  Projects, Tasks, Tickets, Timetrackings,
  Notes, Invoices, and Expenses.

  Each part provides permissions to control the sharing of data with other Drupal users, and based on assignment of projects/tasks/tickets to particular users or teams.

The difference is that the Project module has been thought to be used on Drupal.org, even if it can be used on other sites, and the main features are the ones required from Drupal.org.

The Support Ticketing System module implements a ticketing system, and a help desk.

  The support module provides a basic ticketing system and helpdesk that is native to Drupal, offering complete email integration.

  The Support module offers the following features:

  Ticketing activity is illustrated with colorful charts (depends on the Chart API module).
  -Tickets can be assigned to users (and users can view all tickets assigned to them).
  Tickets support states (new, active, pending, closed, etc) and priorities (low, normal, high, critical, etc).
  Configurable email notifications for new and updated tickets.
  Email integration allows tickets to be created and updated via email, with support for attachments. New users can be automatically created. Ticket properties can be updated via email (using included support_mailcmd module).
  Highly configurable client and user ticket overviews, highlighting tickets that haven't been updated for a long time.
  Fully integrated with Drupal's search functionality, users can only search for tickets they have access to.
  Supports an unlimited number of clients, each with their own configuration and access permissions.
  Tickets are nodes, ticket updates are comments.


What's the easiest way of importing content of a custom D6 content type into a D8 site? I have a Drupal 6 site with three custom content types. We have tried using the Migrate Drupal UI module to migrate these to our new Drupal 8 site, but this resulted in all of the plain text fields being imported as long text fields (field type string_long when they should be string).

To fix this, I deleted all content of those types, exported the configuration created by the UI module with drush cex and used drush cim to re-import the YAML config files after changing all instances of string_long to string.

After about 3 hours of fiddling with this, I finally had a working D8 configuration with the same fields, forms and views as the original D6 site. Now it's time to migrate the content data across.

I have spent another ~6 hours researching and experimenting on how to do this, having tried the views_data_export and Feeds modules, as well as reading several resources on creating custom migration modules.

The former solution was tedious to set up and the default form for creating a feed type wouldn't allow me to create nodes with the original node IDs. So I tried to step through the code and figure out how to extend the module by myself, since the API documentation is severely outdated. This got me nowhere but extremely tired, confused and frustrated, and about 2 hours closer to my eventual demise.

I'm not even game to try the latter solution, since that would probably be just as hard. So now I've started investigating the DB structure in the hope of writing my own SQL update script...only to discover that there are not only node, node_field_data, node_revision and node_field_revision tables to contend with, but also node__<field_machine_name> and node_revision__<field_machine_name> tables for every defined field (35 of them in my case)!

This seriously can't be this hard! Surely I must be missing some crucial piece of documentation from my Google search results. So what would be the easiest method to accomplish what I want?

The two options here is the inline D6>D8 migration, or to use the Migrate API + Migrate Plus (if needed) directly to write your own migrations. The latter has example migrations you can look at. There is never going to be a case or scenario where you will want to write a manual SQL migration script. You should not need Views or Feeds for this - the Migrate API has source plugins that can connect to databases or other data sources to query and pull data.

Here is a docs page outlining how to migrate from a SQL source:

https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/migrating-data-from-a-sql-source

You would set the two databases side by side in MySQL, create a connection setting as mentioned and create a source. The class controls certain aspects of querying and the migration YAML(s) map the fields to their new destinations.

For all the nuanced aspects, I would recommend joining the migration channel in the Drupal Slack, people are always willing to help there.


Search API View, search relation fields I am creating a search api view based on Search API (with Database backend for now (will change to solr later)).

I have 2 entities that are being indexed i.e. project and client.

A project contains a projectnumber and an entity reference to a client. The client contains a firstname and lastname.

I have added a view that shows the projectnumbers and (via relation to client entity) the first and lastname.

I want my exposed fulltext search to search these 3 fields (projectnumber, firstname and lastname).

The weird thing is that he only seems to search on projectnumber and not the first and lastname.

Does anybody have a workaround/solution for this?

Thanks in advance!

There's 2 areas you need to check this is included.  It's common to have applied to the search and not realise it needs to applied in views also.

I take it so far you have made the fields in

configuration > search api > Operations 'EDIT'

"Fields" tab > 'Add Related Fields ' at the bottom.

Now you also need to add the Fields in

structure > views > your view

Filter Criteria >

On the right hand side look for 'Searched Fields'  - make sure all the fields your searching are in here.

I hope that solves it for you .


Can I assign a taxonomy to a content type's term_reference field at runtime? I need to manage a few different types of objects, let's say "car", "pickup", and "van".  These are similar enough (for my purposes) that I can define a single content type and associated code for "vehicle" and use it for all of them, along with a field that specifies the exact type of the object.  This allows me to do things like have one page that shows all the cars, one page that shows all the pickups, and so on.  I have this code running; everything is fine.

I now want to add an OPTIONAL tag field to these items, using the taxonomy / term_reference stuff in Drupal.  The catch is that I want to have a separate tag taxonomy for each of my different kinds of vehicles, so that "car" tags don't show up in the truck's autocomplete suggestions. (Trust me -- in the context of my app, this makes sense.)  The question is how to do it; the complicating factor is that the vocabulary for a tag field has to be defined when the field is added to the content type, and, remember, my content type is generic across all the types of vehicles.

So:

Ugly possibility #1: Define a single tag field -- field_vehicle_tags? -- in the content type and write some magical code in a form_alter or theme or after_build hook or somesuch that, when building the edit form for the node, checks to see what kind of vehicle is being created (this is known upon entry to the form) and bashes the appropriate vocabulary into the field's autocomplete process.  I don't know that this is actually possible, and I suspect the opportunities for screwing myself are endless.
Ugly possibility #2: Define one tag field for each kind of vehicle -- field_car_tags, field_pickup_tags, etc -- each of which is connected to its own taxonomy.  Then, use the theming hook to throw away (= not render as part of the form) all the tag fields except for the one that matches the kind of thing being edited.  This is stupid and wasteful in all sorts of ways, but I'm pretty sure it would work.

Any thoughts or alternatives?  I'm currently leaning towards #2, but if there's a better alternative, I'd love to hear about it.

You can create a Content Type named Vehicle and make inherits his fields to your Cars, Van with the help of the Bundle Inherit module. Then you can create a Taxonomy for each kind of Vehicle then you will have.

Vehicle (color, number_of_seats, etc)
 - Car (field_car_tags)
 - Van (field_van_tags)

With this you don't need to write lines of code and you can reuse the fields of the Vehicle Content Type.


add sharethis button to a slideshow I'm trying to add a button Sharethis to a slideshow "views_slideshow" that shows the whole content to the specific element in the slideshow.
the problem is I can't add this button to the slideshow, and I have it to show inside a block.

Figured it out, you just add "shareThis" to your content type you want this to show in a slide show, and since we are showing the whole content it will show with the rest of the node.


Field collection translation My site has a number of content types that have Field Collection fields. All of these field collection fields allow more than one value.

I've marked the content types as translatable, and the field collection fields as well. It does not work though; changes to translations are also visible in the original language.

Field collection is obviously an entity reference of sorts, and adding a new translation does not appear to link the field to a newly created entity, but the same one.

How do I fix this? Is this a configuration issue, or is this a bug?

For the record, if other people have a hard time figuring how the translation in Field Collection works, here's what I found out:

It does not work.

There is an issue here: https://www.drupal.org/node/2618016 that provides a patch to add support, but does not retroactively add translation support to existing field collections. If your site already has field collections you are SOL - and in my case the whole site becomes non-functional.

I'm now looking into migration towards paragraphs, but not sure how to migrate my data. Will update when I have a good solution.


get rid of dropdown list on views exposed filter I created a view with an exposed filter, that I set to autosubmitt. So when I start typing in the filter field, the list of items does get filtered live. So far I'm happy.

What I don't like is the dropdown list that also gets updated while typing. How can I tell this field to stop showing a dropdown list at all?

the 2 general options in the view are autocomplete and dropdown.  the autocomplete will give you a list of matching queries as you type.  keep in mind that if you remove that and somebody spells something incorrectly they will not get any results from the exposed filter.

if you have to get rid of the dropdown feature, use CSS to hide it.


How to set a file upload monthly quota on a role basis in Drupal 7? I'm using Drupal 7 and I'm quite a newbie here.

I'm building a small sharing/social network site where users will be able to upload different kind of files (mainly, pictures and zipped archives, but I'm not limiting the kind of files one can upload).

Is there a way to set a per-user upload limit/quota (say, 1Gb/month) on a user role basis?

Edit

Using Amazon S3 and similar services is a viable option.
Users' privacy should be protected, i.e. they should be able to set
access permissions on the files they upload (private, friends-only,
public), and it would be interesting to have the "expiry" option,
i.e. a shared file could expire and be automatically deleted from
server after a while.
I know there is IMCE module, I never tried it but from its
description it seems a bit buggy and not so safe from a privacy perspective.

The IMCE module allows, "configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions."


How to save content type before saving an exported view through code? I am using a module that defines a content type and view. When I install my module, the view is saved before the content type. So, my view states that fields of that content type are not available.

Is there any way to save content type first and then view?

.install

function _productcustomtype_installed_fields() {
    $t = get_t();
    return array(
        'example_date' => array(
            'field_name' => 'example_date',
            'label' => $t('example Date'),
            'type' => 'date'
        ),
        'example_slot' => array(
            'field_name' => 'example_slot',
            'label' => $t('example Slot '),
            'type' => 'list_text'
        )
    );
}

function _productcustomtype_installed_instances() {
    $t = get_t();
    return array(
        'example_date' => array(
            'field_name' => 'example_date',
            'type' => 'text',
            'label' => $t('example Date'),
            'widget' => array(
                'type' => 'date_popup'
            ),
            'date_format' => 'Y-m-d',
            'display' => array(
                'default' => array(
                    'label' => $t('example Date'),
                    'type' => 'date_popup'
                )
            )
        ),
        'example_slot' => array(
            'field_name' => 'example_slot',
            'type' => 'text',
            'label' => $t('example Slot'),
            'widget' => array(
                'type' => 'list_text'
            ),
            'display' => array(
                'default' => array(
                    'label' => $t('example Slot'),
                    'type' => 'list_text'
                )
            )
        )
    );
}

function add_custom_fields() {
    foreach (_productcustomtype_installed_fields() as $field) {
        field_create_field($field);
    }
    foreach (_productcustomtype_installed_instances() as $fieldinstance) {
        $fieldinstance['entity_type'] = 'node';
        $fieldinstance['bundle'] = 'example_calendar';
        print_r($fieldinstance);
        field_create_instance($fieldinstance);
    }
}

function example_install() {
    node_types_rebuild();
    $types = node_type_get_types();
    add_custom_fields();
}

.module file

/**
 *
 * @return type
 * Implements hook_node_info
 */
function example_node_info() {
  return array(
    'example_calendar' => array(
      'name' => t('example Calendar'),
      'base' => 'example',
      'description' => t('A example content type'),
      'has_title' => TRUE,
      'locked' => FALSE,
    ),
  );
}

/**
 *
 * @param type $node
 * @param type $form_state
 * @return type
 * Implements hook_form
 */
function example_form($node, $form_state) {
  $type = node_type_get_type($node);
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE, '#weight' => -5
  );

  return $form;
}

/**
 *
 * @return type
 * Implements hook_views_api
 */
function example_views_api() {
  return array(
    'api' => 3.0,
  );
}

/**
 *
 * @return type
 * Implements hook_views_default_views
 */
function example_views_default_views() {
//node View code goes here
}

Change your install function to

$name = 'your content type Machine name';

// Define the node type.
$jobs = array(
'type' => $name,
'name' => $t('your content type name'),
'base' => 'node_content',
'title_label' => $t(' Title'),
'description' => $t('Description.'),
'custom' => TRUE,
);

// Set other node defaults not declared above.
$content_type = node_type_set_defaults($jobs);

Remove node info hook from .module file and start your function name in .module file with your module name.


Assign programmatically created order to anonymous user I want to create a pre-made order in Drupal Commerce for an anonymous user, and redirect the user to the checkout.

My use-case is that I have two sites: One big Drupal Commerce site (up and running since 2011), and another site that sells a few very specific products. The second site is not a Drupal site.

Ideally I want users on the second site to be able to select a few products, click "checkout" and be redirected to the checkout page on the Drupal site, with an order that contains the products that he/she selected on site two.

Now, selecting products etc. won't be an issue (second site has access to all product data via Services API), but I have no idea how to create the order for the anonymous user in Drupal and make it belong to him/her.

I read this blog entry which could've been of use (send user to page that creates the order and then redirects user to checkout) but apparently that doesn't work for anonymous users.

Any help would be greatly appreciated!

I think you may be thinking about this incorrectly. If I were you, I'd write a custom module that created a new path designed to create a shopping cart for whoever lands on it with the requested products. You can include a token or something in the URL to ensure each one only gets processed once, and you can redirect to /cart or some other route after the order is created to try to reduce duplicate carts.

This means on the secondary site you're just storing in a cookie or the session the product IDs that you'll then use to construct the cart when you pass them to the Drupal site via query parameters or something like that. It isn't really possible to create a remote session for someone and then force assign the session ID to them when they land on your site afaik.


open atrium - securely share videos Just started learning a more about open atrium.

Is there a way to securely share streaming videos on open atrium?

If so would this involve utilizing a contrib module?

If your videos come with some kind of embed code e.g. Youtube of Vimeo then you could embed them into Notebook pages in OA. This would make them visible only to the select users in that group.


how to use tokens as “views filter criteria” for a custom table? I created view for fields from a custom table using handlers.
I need to create a filter so that only the users who created the data can see the data.
how can I create the filter?

We do not have token based filters, but instead what we can use is 'contextual filters', with in contextual filters you can get current logged in user.

I am assuming you are storing user information(mostly uid) to know who created what.

Now since its a custom table, the relation/join for users table with your custom table you have to define while exposing it to views. Here goes the sample code.

/**
 * Implements hook_views_data().
 */
function dev_test_views_data() {

  $data = array();

  $data['custom_view_expose']['table']['group'] = t('Custom table exposed');

  $data['custom_view_expose']['table']['base'] = array(
    'title' => t('custom table exposed'),
    'help' => t('Contains records we want exposed to Views.'),
  );
  $data['custom_view_expose']['record_id'] = array(
    'title' => t('Record ID'),
    'help' => t('The record ID.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
  );
  $data['custom_view_expose']['data'] = array(
    'title' => t('Data'),
    'help' => t('The Data.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );
  // Allow views to join it with users table if needed while querying database.
  $data['custom_view_expose']['table']['join'] = array(
    'users' => array(
      'left_field' => 'uid',
      'field' => 'uid',
    ),
  );

  $data['custom_view_expose']['uid'] = array(
    'title' => t('User ID'),
    'help' => t('The record user ID.'),
    'field' => array(
      'handler' => 'views_handler_field_user',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    // Allow this field to show in relationship option.
    'relationship' => array(
      'base' => 'users',
      'field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('Users'),
    ),
    // Get this field as contextual filter option.
    'argument' => array(
      'handler' => 'views_handler_argument_user_uid',
      'numeric' => TRUE,
      'validate type' => 'uid',
    ),
  );

  return $data;
}

The above code exposes a very simple table as in screenshot

Now while creating the views within your contextual filter options will see uid as on the fields for which you can pick value to come from current logged in user, and views will automatically filter down results. Adding views screenshot

.


hide module when path is overlay Im developing a module which shows a bar (fixed, top, z-index 99999) with some content. When im in the admin interface with overlay, I want to hide the module, right now the bar is overlapping the overlay.

This code is working well if the overlay is not activated

if (arg(0) == 'admin' || arg(0) == '#overlay=admin') { $output = NULL; }

only the arg(0) == '#overlay=admin' part is not working,

any ideas?

Thanks in advance

You should use the following code, if you want to avoid outputting something when the overlay is visualized.

if (module_exists('overlay') && path_is_admin($_GET['q'])) {
  // The overlay is visualized.
}

path_is_admin() is used from overlay_init(), which contains the following code.

  // If this page shouldn't be rendered inside the overlay, redirect to the
  // parent.
  elseif (!path_is_admin($current_path)) {
    overlay_close_dialog($current_path, array('query' => drupal_get_query_parameters(NULL, array('q', 'render'))));
  }


How can I prepare a database statement and execute it many times with different input? I have a situation where I need to update a Drupal module's query to run a SELECT query [and based on the results] an INSERT for a data set of ~a million items.

Outside of Drupal I would accomplish this by first preparing my SELECT and INSERT statements, then executing them once for each item:

$db = new PDO(...);
$check = $db->prepare('SELECT COUNT(*) FROM other_tablename WHERE colname = :value');
$insert = $db->prepare('INSERT INTO tablename (colname) VALUES (:value)');
foreach ($my_many_items as $item) {
  $check->execute(array(':value' => $item));
  if ($check->fetchColumn() < 1) {
    $insert->execute(array(':value' => $item));
  }
}

With the Drupal 7 DB-API however, there seems to be no way to get a prepared statement without executing it first using db_query($query, array(':value' => $item), array('return' => Database::RETURN_STATEMENT)).

The only option I've found is to run db_query() / db_select() / db_insert() in a loop for each item which ends up requiring the query string to be re-parsed for every single iteration.

How can I prepare a database statement (with Drupal doing its table-name rewriting) and then execute it many times with different input?

Background:

The existing implementation uses db_select() to build a query using a giant SELECT ... IN clause, filters the items in PHP, then uses db_insert() to save all of the values at once. While this implementation only runs two queries, it unfortunately blows up the memory usage when handling large numbers of items:

...
$result = db_select('other_tablename', 'o')
  ->fields('o', array('colname'))
  ->condition('colname', array($my_many_items),'IN')
  ->execute()
  ->fetchAll();
$existing = array();
foreach ($result as $r) {
  $existing[] = $r->colname;
}
$insert = db_insert('tablename')->fields(array('colname'));
foreach ($my_many_items as $item) {
  if (!in_array($item, $existing)) {
    $insert->values(array('colname' => $value));
  }
}
$insert->execute();

Prepared statements can be created after changing the statement class to PDOStatement. This technique is described in How to execute stored procedures in drupal?

// Get the Drupal database connection and change the statement class to PDOStatement.
// Save the current class for cleanup later.
$conn = Database::getConnection();
$saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));

// code from the question:
$check = $conn->prepare('SELECT COUNT(*) FROM other_tablename WHERE colname = :value');
$insert = $conn->prepare('INSERT INTO tablename (colname) VALUES (:value)');
foreach ($my_many_items as $item) {
  $check->execute(array(':value' => $item));
  if ($check->fetchColumn() < 1) {
    $insert->execute(array(':value' => $item));
  }
}

// Revert the connection to its previous statement class.
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, $saved_class);


Rewrite URL to routing URL I have created a routing URL like

login.compnay_login_form:
  path: '/u/{company_name}/login'
  defaults:
    _controller: '\Drupal\login\Controller\LoginController::login_form'
    _title: 'Login'
  requirements:
    _permission: 'access content

This works with http://example.com/u/testcompany/login

But I want the URL like http://example.com/testcompany/login for that I write the below routing

login.compnay_login_form:
  path: '/{company_name}/login'
  defaults:
    _controller: '\Drupal\login\Controller\LoginController::login_form'
    _title: 'Login'
  requirements:
    _permission: 'access content'

but it's not working.

Please let me know if any other way to achieve this.

http://example.com/testcompany/login

should call to

http://example.com/u/testcompany/login

may be through htaccess or any other way?

If there is a node for each company, you can insert an alias when the node is saved.  Set up the alias created for each company to start with '/company/{company_name}', then when the alias is inserted, you can add a secondary alias for login:

/**
 * Implements hook__path_insert().
 */
function mymodule_path_insert($path) {
  if (preg_match('/company\/(.*)/', '/company/xyz', $matches) && preg_match('/node\/(\d+)$/', $path['source'])) {
  $company_name = $matches[1];
    \Drupal::service('path.alias_storage')->save("/u/$company_name/login", "$company_name/login" $path['langcode']);
  }
}

This way, the visible path will be /{company_name}/login, but the machine name as far as Drupal is concerned with be /u/{company_name}/login.

You could instead do this on entity_insert and entity_update.


How do I change what blocks show up on a user page depending on the user role of that page? It is possible to filter blocks based on the user role of the current user, but I want to be able to change blocks based on roles of the user whose page I am visiting.

User 1 is an administrator so visiting

 /user/1

users see

  Administrator block

no matter what user role the current user logged in has.

if User 1 visits

 /user/4

where user 4 is RoleX they see

RoleX Block

Where RoleX block and Administrator block are both created in views.

Is there a way to do this out of the box or do I need to write my own contextual filter

You need to expose that entity as a context to Drupal, then the visibility settings should automatically let you select between the current user and the user on the page.

Drupal core only does that for nodes at the moment, the logic for that is in \Drupal\node\ContextProvider\NodeRouteContext with its service definition:

node.node_route_context:
class: Drupal\node\ContextProvider\NodeRouteContext
arguments: ['@current_route_match']
tags:
  - { name: 'context_provider' }

So you need to duplicate that class and basically do a search and replace for node => user, remove the node.add part and put that in a custom module.


Current user geographical location I am building a website which on the contact page will have a section to find your local sales representive. I intend to do this by having a content type of sales rep with a location field and creating a view from this content on the contact page.

As an improvement to this i would like it to automatically (if the user allows it) to take the geo location of the user and automatically filter the view by this showing the users nearest sales rep.

Are there any modules in existence which i can use to achieve this? Or am I likely to have to build a custom module?

You will need custom coding to provide the argument to the view, but you could use the following modules for the geolocation functionality:

Feature-rich, server-side solution:
Smart IP

Simpler, ip-based server/client-side solution:
geoPlugin


Pay-Per-Node Functionality My client would like a content type that has to be purchased by a registered user on a node-per-node basis.

A previously registered user will see a view with the available content they can purchase and then that user can purchase individual nodes. These nodes that have been purchased will also appear in a My Library view as well.

I have found multiple tutorials on how to do this via D7; however, I can't seem to find anything that shows how to do this on D8.

Can Drupal 8's Commerce Module do this out of the box or will I need to install additional modules to reach this functionality.

I am trying to find the right configurations of Products, Orders, and Stores but so far to no avail.

We're doing something similar.

The User gets a role, that determines what he may buy
A custom field on the productVariation lists which roles it is available for
In a preprocess function we compare the user's roles to the accepted roles on the variation and set a flag
twig evaluates that flag

Since we only have 5 products, where we have to differentiate, this works. I imagine if you had hundreds, it might be cumbersome.


How do I resize image directly while uploading the image? How do I resize image directly while uploading the image?

Select image from Computer > Upload > Resize directly to dimension that I want.

Try Max Image Size module

On the module page it says:

  This module will resize uploaded images to be below the set
  dimensions. It is not an image style or other presentation layer
  module. If you want to maintain the original image you should use
  Image Resize Filter or an image style. The use case for this module is
  sites where users may upload very large images, but you do not
  want/need to keep the original.


Is there a way to add a timestamp to messages print from drupal_set_message()? Sometimes when I am editing I may accidentally edit the same page in different tabs, or I might forget  whether I have updated the page earlier or not. I use a Save and Edit button when saving and when I save I want to know when I last saved based on the notice in at the top of the page, where I normally see a message like the following.

There is some sample code for a module that changes the message handling - https://atendesigngroup.com/blog/drupal-7-drupal-8-customize-or-remove-node-creation-message. How could I change it just to add a timestamp to the message?

The problem is that at the point where these hooks are being used you have SESSION and FORM available and what you're asking for is a NODE attribute.

This can be done, simply loading the given NODE under the right conditions... but one should recognize doing this does have broader impact as these hooks are called fairly frequently.

How node_load is done is accomplished very differently in D7 and D8, not sure which one you're using from the question.  Lots of answers out there how to render fields from a node.  One more tip; your D7 install should have entity - the future proof method of getting node values is probably entity_load as nodes are entities in late D7 and all of D8...


How come I cannot fetch the name of the taxonomy term from term id? We are doing the following query below to fetch all the taxonomy term values in the term_category vocabulary term. When we do the following query below, we get NULL value returned.

Content Type:

The Article content type has a field_category that is set to this new term_category taxonomy term.
Currently no Article nodes have any value populated for the field_category field as it is optional.

Taxonomy Term:

machine name = term_category
Label = Category
no fields other than title and description (which are out of the box)
has 15 values already added to the term (such as Cloud, IT, Security)

Goal:

Using the tid from the $term_categories result set, iterate through each one to get the name of the Taxonomy term.

How come I cannot get the name of the taxonomy term value from term id?

$db = \Drupal\Core\Database\Database::getConnection();
$term_categories = $db->query('select tid, vid from taxonomy_term_data where vid ='\'term_category\'');

foreach($term_categories as $category) {
  $category_term = (\Drupal\taxonomy\Entity\Term::load($category->tid));
  ksm($category_term->label()); // returns NULL.
  ksm($category_term->getName()); // returns NULL.

  // Goal.
  ksm($category_term->getName()); // Returns Cloud
}

Output of ksm($categor_term) -> content

Currently your problem is that you're trying to call entity class methods on a stdClass object - directly querying the database means you're not using the API any more, the results you get aren't entities.

Unless there's a particular reason to do so, though, you shouldn't have to do it that way.

For example, the same query can be executed like this through the API:

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadByProperties(['vid' => 'term_category']);

foreach ($terms as $term) {
  $name = $term->getName();
}

It's quicker (loading in one go, not single loads in a loop), fewer lines of code, and when you bring caching into it, probably more performant.


How to replace the button when the user is not authenticated? I copied the twig file of my nodes into my theme.

On my nodes there is a flag displayed, but only authenticated users can see it.

Here is my code :

  {{ content.flag_like_group }}

How to replace the flag for unauthenticated users by :

   J'aime

You can use predefined logged_in variable.

{% if logged_in %}

    {{ content.flag_like_group }}

{% else %}

     J'aime

{% endif %}


Restrict Drupal Search to few content types I am having drupal 7 site with search enabled. I want to restrict the search to a particular content type/types, by excluding which types i dont want to appear in the result. How can i do this?

And can i also disable the advance search feature? Are there any module for this?

I guess that Custom Search module can help you: http://drupal.org/project/custom_search. acording Custom Search module description:

  The module adds options to select:

* which content type(s) to search

here a snapshot of Custom Search settings related with content type configuration:

Other alternative seems to be Search Configuration module http://drupal.org/project/search_config that give to Search settings (in Additional Node Search Configuration > Only of the type(s) settings) options to filter search by content type:


How to pre-populate the username field on the login page when clicking an e-mail link? I am using the Private Message module on my site; users receive a notification by e-mail when they receive a new message.

In this e-mail, there is a link to the login page.  Many users access the page via their mobile phones, so typing in their username can be a pain (they might also forget what their username is).

Is there some way to prepopulate the username via the link in the e-mail, perhaps using tokens?

You can do it using Prepopulate module. You haven't mentioned the version you are working with. It's in dev version for D7.

When you configure the email, use token in the same format given in the example to pass value of their username, which will be prepopulated when they click on your sent link.


How to display taxonomy term image in a view I have image field in taxonomy tags. Tags are term referenced in article content type, so now I want to show image field of my taxonomy term in my view. I have tried but I did not find any possible solution.

For that you can add a relationship in advanced.
Search for your term reference field in it and add the relation.

Then go to fields and search for your image field which is inside of the taxonomy. That way you will be able to add the image.


Organic Groups Create Content Link does not appear When I log in with my administrator account I am able to see the Create Content Link in my Organic Group. But when I am logged in with another account - permission to create content for content types is set - the create content link does not appear. I also activated entityreference prepopulate. Does anyone know what the problem could be?

Not sure which permission you mean with the "Permission to create content for content type is set" (consider adding the URL within admin to clarify that, is it /admin/people/permissions?).

However, it could well be that your issue is because you've not yet completed the "OG Permissions" located with something like /admin/config/group/permissions/ (and then select the 'edit' link for the group type your issue is about).


How do I convert hook_menu()? I am having site built in Drupal 7 and in future I want to migrate my site to Drupal 8.

How can I write hook_menu() and hook_menu_alter() to routing.yml files?

Here is an example taken from All functionality of hook_menu() is replaced by new systems for routing, menu links, local tasks, actions and contextual links:

Drupal 7

in modules/book/book.module:

function book_menu() {
   $items['book/export/%/%'] = array(
    'page callback' => 'book_export',
    'page arguments' => array(2, 3),
    'access arguments' => array('access printer-friendly version'),
    'type' => MENU_CALLBACK,
    'file' => 'book.pages.inc',
  );
    $items['node/%node/outline'] = array(
    'title' => 'Outline',
    'page callback' => 'book_outline',
    'page arguments' => array(1),
    'access callback' => '_book_outline_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'file' => 'book.pages.inc',
  );
...
  return $items;
}

Drupal 8

in modules/book/book.routing.yml:

book_export:
  pattern: '/book/export/{type}/{node}'
  defaults:
    # What's being returned is the entire response (not HTML, or even if HTML, we don't want additional blocks around it), so use _controller instead of _content.
    _controller: '\Drupal\book\BookController::export'
  requirements:
    _permission: 'access printer-friendly version'
book_node_outline:
  pattern: '/node/{node}/outline'
  defaults:
    _controller: '\Drupal\book\BookController::outline'
  requirements:
    # Indicates that the book outline access access system should be invoked.
    _book_outline_access: TRUE


Shipping weight not calculated? we are currently trying to get our drupal commerce 2 attaching a certain shipping method based on the weight of the order. It is pretty simple (at least I thought so): if the order is below 20kg, it is one rate, above a second rate.
Here is what I did:

enabled commerce shipping module and physical fields
added a custom physical weight field field_prod_gewicht to the default product type (the only one we have)
marked the default product variation as shippable
filled the individual products with their weights accordingly
created two shipping methods with different prices, only restricted by Shippment Weight

So far so good - on the shipping page I see indeed only the lower rate shipping method, but if I add more weight to the order, the higher rate shipping method never appears.
My suspicion is, that the weight is not calculated at all, or that there is some kind of implicit convention I did not follow.
Anybody has an idea, how to solve or debug this?
Thx a lot!

In the end it was ideed as expected a convention: If you enable the commerce shipping module a system level weight field will be added automatically to the Product Variation Entity, not the product.
This weight field is the only field, used for order weight calculations and other custom fields are ignored. All in all very logical ;)
If you want to use the weight in templates, it can be done via {{ product.variation_weight }}


Why doesn't the "auto-create feature" in the Ftools module work on Features 2.x? I've been using the Ftools module for a long time to create features more easily; this module provides a "auto-create feature" link on the features configuration page.

However, when I upgraded from Features 1.x to Features 2.x., "auto-create feature" no longer works; it simply removes everything from the .info file.  What am I doing wrong?

Features 2.x has this functionality built in, so you don't need to use ftools anymore.  Go to the feature configuration page, click Advanced options, set the Path to Generate feature module, and then click Generate feature.


REST Post creating entities with relations I am having trouble creating comments on nodes ( articles etc. ) with the Rest module.

I have enabled the endpoint in rest.settings.yml :

resources:
  'entity:node':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - basic_auth
  'entity:comment':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - basic_auth

I have followed the information here rest tutorial - headless drupal 8 and on drupal.org
I used this tutorial as a base to build my request, noting that there have been changes since the article was posted.

I am using basic_auth, setting the CSRF token as per issue and I have set permissions for the test user to edit, delete and create articles, basic pages and comments.

I am using application/json+hal because of the outstanding issue
with application/json

What is happening is the server is reponding :

403 Forbidden :
{"error":"Access denied on creating field entity_id"}

The request is failing where checking access on read only fields, which return AccessResult::forbidden();

Clearly I am missing something from my request ? I thought that the hal _links reference points to the entity_id ?

My request so far :

{
   "_links":{
      "type":{
         "href":"http://d8.dev/rest/type/comment/comment"
      },
      "http://d8.dev/rest/relation/comment/comment/entity_id":[
         {
            "href":"http://d8.dev/node/1?_format=hal_json"
         }
      ],
      "http://d8.dev/rest/relation/comment/comment/uid":[
         {
            "href":"http://d8.dev/user/1?_format=hal_json",
            "lang":"en"
         }
      ]
   },
   "_embedded":{
      "http://d8.dev/rest/relation/comment/comment/entity_id":[
         {
            "_links":{
               "self":{
                  "href":"http://d8.dev/node/1?_format=hal_json"
               },
               "type":{
                  "href":"http://d8.dev/rest/type/node/article"
               }
            },
            "uuid":[
               {
                  "value":"c4b5b929-3ccb-4cfd-8200-0ec8f9170926"
               }
            ]
         }
      ],
      "http://d8.dev/rest/relation/comment/comment/uid":[
         {
            "_links":{
               "self":{
                  "href":"http://d8.dev/user/1?_format=hal_json"
               },
               "type":{
                  "href":"http://d8.dev/rest/type/user/user"
               }
            },
            "uuid":[
               {
                  "value":"76555fc7-c4c4-4e1f-a053-83ab818bba4f"
               }
            ],
            "lang":"en"
         }
      ]
   },
   "comment_type":[
      {
         "target_id":"comment"
      }
   ],
   "comment_body":[
      {
         "value":"Hello world this is a comment",
         "format":"basic_html"
      }
   ],
   "subject":[
      {
         "value":"A comment test"
      }
   ],
   "name":[
      {
         "value":"admin"
      }
   ],
   "thread":[
      {
         "value":"01/"
      }
   ],
   "entity_type":[
      {
         "value":"node"
      }
   ],
  "field_name": [
    {
      "value": "comment"
    }
  ]
}

Okay so this issue is actually a bug. For me the issue was fixed by applying the latest patch for now, likely the patches will need work and tests.

There were issues with my request and I have changed them above to reflect how an actual comment request should look like ( at the time I am writing this ).


How to SimpleTest a module's use of drupal_alter() or module_invoke_all()? I'm developing a custom module.  My module calls drupal_alter() with a $type unique to my module, so other modules can alter the behavior of my module.

I'd like to write a SimpleTest for my module, which includes a test implementation of the hook my module calls.  This hook implementation should only be used by my SimpleTest; it should not apply when the module is installed on a full Drupal installation (so therefore I can't place my test hook implementation in the .module file).

What's the right way to do implement a hook that only applies to an active SimpleTest?

You can create a test module and place hidden = TRUE in the .info file.

This will hide the module in the user interface but you can still enable it in your setUp() method.

See http://drupalcode.org/project/drupal.git/blob/refs/heads/7.x:/modules/file/tests/file_module_test.info for an example.


Add extra text input for file field For Drupal 7, in page content type there is a multiple file upload section. Description is enabled for the file upload, but I need to add one more text input for each images to ask user enter the year file belongs to.

I am not very good at Drupal. So if I can find a clear solution it will save my day. Thank you from now.

I would recommend using the field collection module instead. Create a field collection with a file upload field, description field and file owner field (can be a text field or user reference field. Set the field collection to unlimited. Then add the field collection to your page content type. It will allow you to do more custom things moving forward.

https://www.drupal.org/project/field_collection
https://www.drupal.org/project/references


login state and a field condition like to alter a template depending on a content type, let's say article and in-depth article if the user is logged in and if a boolean checkbox field is checked or not.

So how to alter these tree conditions programmatically for let's say the video_embed_filed?

I am new to Drupal 8 and Twig.

Thank you for your replies.

Thank you for your replies.

1.content type specific template would be: node--type-article
2.{% if logged_in %} will return boolean.
3.{% if (node.field_video_embed_filed.value != NUll)  %} or null can e replaced by your condition or you can use kint devel modue for better filtering like: {{ kint(node) }}


With a standard HTML form in Drupal 8, how can I get the submit message to post in the "Status Message" block? I have a form that I want to add JS to so that when it is submitted, the confirmation text is fired into the "status messages" block or any block in the help/admin block section.

Basically, here is the form and upon submit, I want the post message to display in a block rather than the user be sent to another page.

<form name="email_signup" action="http://example.com">
<input type="text" name="emailAddress" placeholder="Enter email">
<input type="submit" value="Join">
</form>

You should create this form through the Form API in a module, then in the form submit handler you can use Messenger to do this.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Messenger%21MessengerInterface.php/function/MessengerInterface%3A%3AaddMessage/8.6.x

You can see that drupal_set_message now routes through it:

function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  @trigger_error('drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \\Drupal\\Core\\Messenger\\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931', E_USER_DEPRECATED);
  $messenger = \Drupal::messenger();
  if (isset($message)) {
    $messenger
      ->addMessage($message, $type, $repeat);
  }
  return $messenger
    ->all();
}

This is how flash/status updates are created.


How to get count in views when group by some field? I have view which display results based on taxonomy field grouping:

And results look like below :

I am trying to display count of each group in brackets next to Topic field, Is that possible to achieve with this kind of view. Please suggest.

Thanks!

You can try using this module

Term Node Count


hook_nodeapi() argument? hook_nodeapi() only has four arguments, but the function taxonomy_nodeapi($node, $op, $arg = 0) can have an additional parameter, $arg=0. Why?
$node is not passed by reference. Why?

I'm not sure how you're counting, but hook_nodeapi() has 4 arguments, as you said, while taxonomy_nodeapi() has only 3. How they are named is totally irrelevant, only the amount and order counts. PHP doesn't have named arguments, you could also name them in your hook like this: yourmodule_nodeapi($wathever, $you, $want = 0) and it would work. There is however no reason to do it, it only has the potential of confusing someone. :)

The only important part is here is that the third and fourth argument are optional and must have a default value, because they are not passed for every $op.

About &$node, that's not so nice, but not a problem. The & can be left out, which means that $node is not by reference (in PHP4, that is) but it seems that taxonomy_nodeapi() doesn't need that. The other way round would be a problem in PHP 5.3 (adding a & here when PHP doesn't expect one).


Commerce Address Book – need to reuse customer profile without address In addition to the default shipping and billing addresses I have added a customer profile in Drupal Commerce, where the customer can add additional info, like email for invoices, special marking on shipped goods, comments and so forth.

This info is often the same on each order and we have recieved feedback that customers dont want to fill in these fields again and again when placing orders.

I have tried out the Address Book module and it seems to work for billing and shipping addresses, but how can I reuse info from previous customer profile that does not include an address? Maybe just skip the dropdown address field and use a previous customer profile and still have the possibility to edit the info?

Anyone that can point me in the right direction?

EDIT 1: as i am trialling and testing the address book module, I realize that the dropdown menu is empty in my added customer profile (because there is no address field). I need to be able to choose which field in the added profile that should be saved as "options" in the dropdown menu. Is this possible to accomplish in code? I am not asking for complete solutions here. Mereley is it possible? If yes, are there hooks I can use?

EDIT 2: I discovered that the dropdown menu is not empty after all... it's just the human readable value that is missing. There are several empty options values that can be selected after which the field values are populated from the corresponding saved customer profile. So my question changes again (sorry about that). How can I add human readable values from one of the fields in my customer profile?

It turns out that the Commerce Addressbook Extra module takes care of this. In case anyone else is searching after a smooth solution.
Link to module


Is there a way to automatically cancel an account after 14 days? I'm working on a website where we are offering trial access and I want a way to automatically cancel an account after the account is more than 14 days old EXCEPT if they have submitted a feedback form in which case they get an additional 7 days (for a total of 21 days).

I think there ought to be a way to do this using Rules or cron but right now I'm stuck.

Sure you can do this, using the Rules module (and the Webform module for your form). Here is a blueprint about how to do so:

1. Rules Component to block a user

Create a (rather basic) Rules Component to "block" a user, whereas you use a "User" entity as parameter for it.

2. Rule to cancel an account

Create a (rather basic) rule like so:

Rules Event: Before saving a user account
Rules Conditions: None (feel free to add whatever fits)
Rules Action: Schedule the execution of the Rules Component (from step 1), to be executed after 14 days. For this you need to have the "Rules Scheduler" (a sub-module of Rules) enabled. Make sure to use an "id" for this scheduled task that includes the user's uid (you'll need it in Step 3).

Refer to my answer to "How to send an email notification reminder based on a user's date of entry field?" for a sample of a rule that is pretty close to what your rule should look like (especially Step 3 of it).

3. Rule to delete the scheduled rule

Use the Webform Rules module to create a rule like so:

Rules Event: After a webform has been submitted
Rules Conditions: Check the webform Id (to ensure it's the form you want to consider).
Rules Action: Delete the Scheduled rule from Step 2, and Reschedule it to be executed 21 days after there account activation date. For this you'll need the id of the Scheduled task, but if you used the user's uid for that, this should be no problem.

PS: I'm assuming this is about D7 ...


Find out which nodes use a specific filter How could I find out which nodes actually use a specific filter?

My nodes use an input format that has the Bbcode filter enabled. Now I need to know which (of the several thousand) nodes use BB code, to decide if I still need this filter (in which case I’d switch to Extensible BBCode, and for that I’d like to have a list of nodes to test if everything works correctly).

Create a view for nodes & add Content: Body (body:format) in Filter Criteria, then set the text format value as bbcode.


Related Profiles block I have two profile types teacher and students. They both have a taxonomy field “State”.

Below each teacher’s profile I want to show students from his State.

I have added two relationships:

1) User: Profile
2) Field: State (which is a taxonomy term field).

Then added a contextual filter Taxonomy term: Term ID. Under "When the filter value is NOT available" have selected default value "Taxonomy term id from url".

But it doesn't displays any matching profiles. I have done similar functionality for content entity type and it works. I guess the problem is due to profile entity type or am I missing something?

Can you please tell where I am going wrong? Thanks!

I think the problem lies in your contextual filter.  Presumably the teacher's profile page does not contain the taxonomy term ID in the URL, it usually doesn't unless you've done something tricky to put it there.

So: the view is looking at yoursite/user/[uid] and it thinks that the [uid] is the taxonomy term id (because you told it so), so doesn't find any matches and returns a nil result.

I'm not sure how to fix that, but hopefully this will help you troubleshoot.


Create multilingual homepage I created the basic page, then added alias front_page. Next, I created a translation of this node and have the same alias. In the settings admin/config/system/site-information in the field Default front page I added front_page, but on the home page is displayed when you switch the language is the same article, without translation. How to fix it?

You need to use the Variable Translation for that:

  In Configuration > Regional and languages: Multilingual settings > Variables, enable 'Default front page' as a multilingual variable.
  Go to Configuration > System > Site information > Front page.
  Change the language via the section "Select language" at the top of the page to select the language for which you're setting the front
  page option.
  Set the 'Default front page' option for the current language.
  Repeat as necessary for each available language.

Relevant link: HowTo: Different home page (default front page) for each language


unset the timezone and group in the profile form The version of Drupal is 7.x

Hi,  I need unset the timezone the user_profile_form and the timezone doesn't remove the page.  I tried with this code:

function mymodule_form_alter(&$form, &$form_state, $form_id){
if($form_id == 'user_profile_form')
 { unset($form['account']['timezone']);
}

What is my error?.

Also, I have a group in the profile named:  group_my_information.  How can I remove it with unset?  I tried this code:

unset($form['group_my_information']);

What is my error?

Thanks for your help.

The reason is because your module in which you write you hook_form_alter has a weight of 0. In your database table "system" for your site look for your new module's row and edit its weight to a higher value. I set mine to 100. After you do this "clear your caches" just in case. Then you should now see the line item in your $form variable this is "timezone". Now your unset should work.

unset($form['timezone']);

Keep in mind that if you uninstall your module you will have to re set the weight again.

If you add this in your "MYMODULENAME.install" file you will be able to set this on intall

    /**
     * Implementation of hook_install()
     */
    function MYMODULENAME_install() {
      // New module weights in core: put MYMODULENAME as the very last in the chain.
      db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULENAME'");
    }

Hope this helps


Changing a field settings on a live site in Drupal7 In the middle of entering content I discovered the length of 15 characters of a particular field I set earlier is not enough.

In Drupal6 I could change the settings of a cck field. It could be potentially dangerous, but in my case it's a lossless transform, I just want to make a maximum size of a field a little longer.

But in Drupal7 I get the message saying it's impossible to change the field settings because there is some content stored in that field in database.

This restriction seems too strict to me. A warning message seems to be enough.

So my question is what's the reasons for this behavior and what can be done in my case? Manual deleting and recreating the content is not the option.

Unlike in Drupal 6 where setting the max length of a text field didn't have any influence on the database, but merely added a validation check, Drupal 7 will actual create a column that can only hold the selected number of chars.

You can get around this, but not though the UI, as you need to alter the table in the database.

What you need to do is alter the max length of the value column in the field tables named:

field_data_[FIELD NAME]
field_revision_[FIELD NAME]

The column you need to change should be called [FIELD_NAME]_value

Then you need to alter the configuration, which is serialized data in the data column in the field_config table for the field. You can either edit it directly if you are familiar with PHP serialized data or can do it with drupal_write_record. I believe the usual API function field_update_field wont work, as it should throw an exception not allowing the field to be saved, you can however use field_info_field to get the field data as it is stored in the database.

So in short, it can be done, but requires some custom hacking on the DB not using proper APIs.

An alternative solution would be to create a new field and migrate the data and then delete the old field.


Login success but logout fails I'm trying to customize login, logout functionality in my drupal site. My custom login function works fine by using the below code:

function my_module_custom_login() {
  $username = $_POST['username'];
  $pass = $_POST['password'];
  $uid = user_authenticate($username, $pass);
  $form_states = array('uid' => $uid);
  if(!empty($uid)) {
    $user_login = user_login_submit(array(), $form_states);
    return 'user is logged in';
  }
  else {
    return 'user is not logged in';
  }
}

After calling this function I checked the "Recent Log message" in my drupal reports it tells "Session open for user abc".

Here is my logout code:

function my_module_custom_logout() {
  module_load_include('inc', 'user', 'user.pages');
  user_logout();
}

Whenever I called this function the recent log message shows "Warning: session_destroy(): Trying to destroy uninitialized session in user_logout()" That call went as an anonymous call. So the current user can't be able to logout from the site. How can I overcome from this.

The way you've structured the logic, your function will return "user is logged in" as long as your credentials are correct, not if the user session was created (i.e. the user logged in). Your subsequent error about an uninitialized session confirms that a session isn't being created (i.e. an entry being inserted into the sessions table) or your session key/cookie isn't persisting on the subsequent logout call.

You need to debug why this isn't happening. Check the drupal_session_regenerate() function call to make sure a session entry is created and that your browser/client is receiving SetCookie header with the newly created session key. If the session is created, you need check why your browser/client isn't storing and persisting the session key made on your subsequent logout call.


How do I remove the colon from my field labels? I simply want to be able to remove the colon from my rendered field labels, for example:

Hotel name:
to
Hotel name

I copied field.tpl.php and removed the colon there, but no matter what Drupal refuses to accept it and is pulling the colon from elsewhere.

How can I do this with a template.php function?

The answer is definitely to use field.tpl.php. If you look at the source for that file you can see the offending lines:

<?php if (!$label_hidden): ?>
  <div class="field-label"<?php print $title_attributes; ?>>
    <?php print $label ?>:&nbsp;

<?php endif; ?>

(spacing and indentation mine for clarity).

Removing the colon is as simple as replacing the above lines with:

<?php if (!$label_hidden): ?>
  <div class="field-label"<?php print $title_attributes; ?>>
    <?php print $label ?>&nbsp;

<?php endif; ?>

I've just tested that on a blank Drupal installation and it works perfectly; no more colons after field labels.

If you're already doing the same thing, but not getting the correct results, then I can think of one or two things that could be going awry:

You've put your custom version of field.tpl.php into a module folder, rather than in your site's active theme folder (it needs to be in the theme folder).
Another module/element in the system is also overriding field.tpl.php, in a more robust manner than you currently are. Seeing if this is the case will involve the always-tedious  disabling of each enabled module to determine where the problem is coming from.

You won't be able to make the change with a template preprocess function, as the colon is hard-coded into the template file.


Can't uninstall module because of checkbox field I've a custom module that alters the MenuLinkContent entity by adding a field. My field is defined as follow.

/**
 * Implements hook_entity_base_field_info().
 */
function svg_icon_menu_link_entity_base_field_info(EntityTypeInterface $entity_type) {

  $fields = array();

  if ( $entity_type->get('id') !== 'menu_link_content' ) {
    return $fields;
  }

  $fields['hide_label'] = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Hide label'))
    ->setDescription(t('Display only the icon.'))
    ->setDisplayOptions('form', array(
      'type' => 'checkbox',
      'weight' => 0
    ));

  return $fields;
}

By default the checkbox is saved in the DB with a value of 0 if unchecked, and with a value of 1 if checked. To Drupal there's always a value for that field, that's why it prevent me to uninstall the module with the message There is data for the field hide_label on entity type Custom menu link.

How should I manage this situation? Should I save a value of NULL if unchecked in some way, or should I have to do something when uninstalling my custom module?

You could create a custom form and set all the field values to NULL in the submit handler.

For example:

<?php

namespace Drupal\mymodule\Form;

use Drupal;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class TestForm extends FormBase {

  public function getFormId() {
    return 'test_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [
      'test' => [
        '#type' => 'submit',
        '#value' => 'Clear field values',
      ],
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $query = Drupal::entityQuery('node');
    $query->condition('type', 'menu_link_content');
    $result = $query->execute();

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

    foreach ($nodes as $node) {
      if ($node instanceof Node) {
        $node->set('your_field', NULL);
        $node->save();
      }
    }
  }

}


simplenews. confirmation of subscription for registered user purpose: confirmation of subscription for registered user

installed on the website simplenews module (https://www.drupal.org/project/simplenews).
now on the main page there is a form to subscribe to the newsletter.

if the user is not authorized, he introduces email and sends a subscription request,
he comes to notice by email that he signed up for the newsletter and confirm the proposal (!) the desire to receive the newsletter.

if the user is authorized, he sees only the button (email enter) and if you send a subscription request, it immediately becomes signed.

can to make it so that an authorized user before activating the subscription, as well as anonymous, received a notice to activate your subscription?

well, since no one here, I will use:

simplenews_subscribe_user($email, $tid, TRUE, 'website');


Files View, How to display Images related to Media Gallery? I have created a view in views to show files of type image. Under fields I have selected File Rendered. Now my view is displaying all the images.

The problem is this that I only want to display images which belongs to galleries created through media gallery module.

In my view under relationships I used File: Content using Gallery media. This is now showing the images which are related media Media Gallery.


Bulk operations: Taxonomy: Save I am just looking to do a bulk save on a bunch of taxonomy terms - need to trigger an update on a geofield - but there is no Save option in the bulk operations for Taxonomy Terms (as there is for Nodes).
When I try to update a field on the terms with Modify Entity Value, I get an AJAX error...
Ditto when I try to do a taxonomy_term_save($object) with Execute Arbitrary PHP Script.
Any ideas?

Thanks!

Simon.

taxonomy_term_save($entity); inside "Execute Arbitrary PHP Script" will do the trick.
In D7, the variable is $entity, for D6 it is $object.


Is there an easy way to adjust the block layout? I have menus that are set to Sidebar First in the Bartik theme.  When the screen size decreases, those menus are shown below the main page content.  Which file in a copied version of the Bartik theme could I play around with to change around the block configuration as shown here:

The page.tpl.php file within /themes/bartik/templates/ folder is the main layout for the theme.

So in your copied version of that you can edit that file. If you look for:
print render($page['sidebar_second']);

That is the rendered content of sidebar second region. There's also 1 for sidebar_first. So you can move these to a different location within this file if you want it to be displayed heigher/lower in the content


How to display a new taxonomy term on a select box using Webform? I am using Drupal 7. I have Webform and Webform Term Options installed. I have a taxonomy list of terms called "Training Events". Under "Load a Pre-Built Options List" I select the Training Events list, and save. I view the webform and the list of taxonomy terms is there on the select list. However, if I go to Structure -> Taxonomy -> List terms -> Add term and add a new term, that new term does not appear on the webform. Why won't it appear and do I make it appear?

The error was I was adding a new vocabulary, not a new taxonomy term to the existing vocabulary.


How do I programmatically update an existing submitted webform submission in Drupal? I am attempting to use PHP in Drupal rules to update the values in submitted webform submissions. I can access and view the data correctly. When I assign a new value to a field it will even show up correctly if I use print $submission->data[61][0]; But when I navigate to the submission results page the field hasn't been updated.

I have tried using the webform_submission_update() function to push my change but still no luck.

Question: How do I programmatically update an existing submitted webform submission in Drupal?

Code:

$submission = webform_menu_submission_load($nid, $sid);

// Two ways I've tried to update the data
$submission->data[61][0] = "testwork";
$submission->data[61]['value'][0] = 'Declined';

// If I do print $submission->data[61][0]; it will show the new value.

webform_submission_update($nid, $submission);

Here's how to do that:

// Load the webform submissions file. The webform_get_submission() and
// webform_submission_update() functions are located here.
module_load_include('inc', 'webform', 'includes/webform.submissions');

// Load the node and submission.
$node = node_load(YOUR_NODE_ID);
$submission = webform_get_submission($node->nid, YOUR_SUBMISSION_ID);

// Change submission data.
//
// To see what's available, install Devel and run dpm($submission);
$submission->data[YOUR_FORM_ELEMENT_ID][0] = 'Update';

// Finally, update the submission.
webform_submission_update($node, $submission);

Documentation:

webform_get_submission()
webform_submission_update()


Can't find View's Filters variables I'm trying to create a button that create a new content type based on the one selected in the view filter. I have had some problems finding the correct variables to use them in that case. I'm actually new in the drupal community (so don't be mean if my question is irrelevant for you).

Edit: The code is the one provided as an example for the view with seven as a theme. The part i want to edit is this one :

  **<?php if ($exposed): ?>

      <?php print $exposed; ?>
      <?php
      /**
       * Création d'un bouton de rajout de proposition (yes, this is french ^^)
       */?>
     <?php
         $chemin = "../node/add"; // i want this URL to be dynamic and to change each time
         //someone clic on a new option in the exposed filter. E.G. if he clics on volvo,     the
         //button should show "add a new volvo car" with the proper link
    print"
    <input type=\"submit\" class=\"button\" name=\"Ajout Type de Contenu\" value=\"Ajouter     une XXX\" />
    " ;
      ?>

  <?php endif; ?>**

Thanks !

If I understand correctly your current problem is getting the current values of the exposed filters.

Wherever you are putting your code, as long as you have access to the view object you can get these values using view::get_exposed_input() like this:

$filters = $view->get_exposed_input();
// You can then access the value of a specific filter like this.
$value = $filters['FILTER_NAME'];

You can then use those values to implement whatever logic you require.


Can the path of Search module (/search) be changed without altering the module, to allow use of this path by a custom module? I am dealing with a custom search that, for years, has been accessible via /search.  New site requirements call for the Search core module.  However, that module has hardcoded /search in hook_menu().

I can not find a way to change the path for the core module without changing that module, which I do not want to do.

Notes:

I have seen hook_url_inbound_alter but I don't think this will work, as I still need /search to work.
I have disabled the menu item, but that just results in a "Not Authorized" page to non-admin users.

If you don't like what module sets in it's hook_menu(), alter it with your own hook_menu_alter(). Example code:

mymodule_menu_alter(&$items) {
  // Copy search to another place
  $items['look'] = $items['search'];

  // remove all old search settings
  // optional if you will also follow next step
  unset($items['search']);

  // add your menu item below instead of usual hook_menu
  $items['search'] = array(
    // ...
  );
}

This will unset /search path, and move all it's settings to /look path.

Worth noting is that if module generates links to /search anyway, it means it has it hardcoded somewhere. Happens. If so, you need hook_form_alter() or it's analogue to alter also these links.


How can I update content automatically every X hours? I have a content type that I want updated every five hours. When some nodes haven't been updated, the I'd like to alert a content admin with a warning message containing the list of nodes that have not been updated, e.g. :

  [node:title] has not been updated! please update

The nodes can also be displayed in a block

This can be completely driven by Views & Views System Message module.

You can create a block view for node content of type XXX that has an added Filter Criteria Content: Updated date with the Operator set to Is less than or equal to and the Value type set to an An offset... of "-5 hours" Value. That will get you a block view of content XXX that was edited more than 5 hours ago.

The last part, the alert message, can be added in the Header area by selecting the Global: System message type and setting the parameters to your liking. Once the block view is saved, you can add the block to whatever region you feel most appropriate.


Moving custom content types and content I'm rebuilding a Drupal 6 site in Drupal 7.  So much needs to change, it doesn't seem worth trying to upgrade, so I'm starting from scratch.

I would love to know if there is an easy way to export all of my content.  I have about 1000 nodes of two different custom content types.  Is there a module to do this?  If not, I guess I just have to sit down and figure out how data is stored in the database in both versions?

Thanks

Both Feeds and Migrate are modules purpose-built for what you'd like to do. Migrate requires a little more coding at this point, but I like its ease of use a little more than Feeds.

Simply upgrading the site, using CCK for Drupal 7 to migrate your fields and content types, might be a better solution, though. I would create a backup copy of your site and at least give it an hour's worth of trying before resorting to a full-on content migration.


Entity Reference View format Is there a way to change the Entity Reference view to a different format than an entity reference list?

I'm trying to list taxonomy terms and other custom taxonomy fields to the user when they use the edit form of the node. Ideally, I would list the taxonomy reference as a table with multiple columns. I haven't found a way to convert this list to a table. Does anyone have any idea?

You can use Entity Reference Views module

  This module provides an advanced Entity Reference widget that uses a
  view embedded in a modal dialog for selecting items. The view can be
  paginated and have exposed filters.

You can also use tables in your views for referencing now.


Drupal 7 Change User Login block link text I've set up the standard "User Login" block to the "header" region of my theme. I clicked on "configure" and selected "Link" under "Block Type". Now the link to sign in appears as "Log In/Register". How do I change this text?
I have also LoginToboggan enabled.

You could use a template, probably named something like 'user-login.tpl.php'

For more information on 'working with template suggestions' have a look at http://drupal.org/node/223440


How to flag an entity when it is created or updated? I have a Drupal 8 site with the Flag module.
I want when a user creates or updates a node, product, store, group, ... the updated entity is flagged.
How to flag an entity when it is created or updated ?
I'm testing the "Rules" module which is finally (usable) in production.
But how do you flag down a new entity when it is created ?
What should be put in "Action", because it is no longer like in Drual 7 with an interface.

You can use HOOK_entity_presave to trigger when node gets created. I updated code for you. Make sure that you change the capital letters to correct values.
function MODULENAME_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Check which content type would you like to flag.
  // You can use https://www.php.net/manual/en/function.in-array.php to check for
  // multiple content types
  if (in_array($entity->bundle(), ['mycontentype1', 'mycontentype2'])) {
    $flag_id = 'yourflagname';

    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    // Flag an entity with a specific flag.
    // https://www.drupal.org/docs/drupal-apis/entity-api/introduction-to-entity-api-in-drupal-8
    $flag_service->flag($flag, $entity);
  }
}


GMAP Module map not showing markers after updates with js error: Clusterer is not defined I've recently taken a live site down for updates and development. I have updated from core 7.39 to 7.41 and updated numerous modules including jQuery update. After the updated, I noticed that my map was zooming to it's max extent and not displaying markers. The only diagnostic error I get is an Uncaught ReferenceError: Clusterer is not defined.I can confirm the the markers are being loaded by going into console and logging the drupal.settings.gmap.aut1map.markers variable. I don't have a lot of experience with the GMAP module, so any help would be appreciated.
Thanks in advance.

UPDATE: tried to update to dev version, no real change.
UPDATE: From what I can tell, it appears that the GMAP version I have installed is has this patch applied GMAP Clusterer.js issues

So, it's actually a rookie mistake. Updating the module wipes out all the third party js files you download. took me longer than it should to figure this out.


Ignore cache in preprocess function I have a content type 'homepage' containing one node which is used a the homepage. This node has a multivalue image field, and I need to randomly select one of those images to show on the homepage on every site visit. I have written the logic for this in the THEME_preprocess_node function in my THEME.theme file. This is working fine, but the site in question is still in development mode with most caching deactivated. I'm worried that once the site goes live and the caching is activated, it will serve the homepage from cache and therefore always show the same image until the cached version of the page expires.

Is that the case, or are the preprocess functions evaluated on every page visit even when the cache is active? If not, how can I circumvent this to get a random image every time?

This is the code I have written for this:

  $imgages = $node->get('field_frontpage_header_image');
  $random = $imgs->get(rand(0, $imgages->count() - 1))->getValue();
  $img = File::load($random['target_id']);
  $variables['random_header_image'] = ImageStyle::load('frontpage_header')->buildUrl($img->getFileUri());

I then use {{ random_header_image }} in the twig template. Maybe I can change this variable to a render array with a cache setting of max-age => 0? Not sure if this works in preprocess functions though ...

Thanks!

If it's a limited set of pictures that you have then I would just write a custom formatter that displays for example an image tag with a data attribute that has your list of image paths (maybe with the first image already set as non-JS fallback maybe). then you just need small bit of JS that picks one of those randomly and sets it as the actual src attribute. Your page is fully cacheable then and while it might still be a noticeable delay until the image shows up, that can even happen with static image links on slower connections.

And it will certainly be much faster than an ajax request.

The placeholder approach might also work and Drupal supports that kind of out of the box with dynamic page cache, doesn't need a reverse proxy or so for that. but you would have to disable the internal page cache then on that page. See http://www.qed42.com/blog/lazy-builders-drupal8 for an example on that.

The way that works with Dynamic Page cache is that the whole page with the placeholders is cached, and then calls the defined lazy builders which returns the actual content for the current request. You would want to use a similar approach as with JS, prepare all image urls for example already as arguments and then just pick one from that array and render it.


Verification mail goes to Spam Folder If the user register, the confirmation mail goes to spam folder.  After doing some R&D, I enabled "Use two e-mail fields on registration form > Set password" and tested; it goes to inbox from the web server. But as i badly need to show the demo to my supervisor from my local server instead of live, using "Acquia Dev Desktop", it goes to the spam folder.　How can I prevent the message from going to the spam filter?

You should use the SMTP Authentication Support module: http://drupal.org/project/smtp  for sending email messages. You can go there: https://stackoverflow.com/questions/8939238/gmail-smtp-configuration-for-drupal-7 to see how they can use the SMTP Authentication Support module with Google Account.


How to inject postal address into user entity via custom registration form I'm using the postal address module to obtain a user's postal address when they register on the site. The registration form is created by a custom module I made.

I'm able to get the form to display the postal address fields correctly (they modify based on your country, etc.), but when I go to process the form in HOOK_submit(), I hit a problem.

The submit function adds the user entity and puts the correct information in for the user. It also creates a new line in the field_data_field_postal_address table in the db as it should. But the address fields are all empty.

I think it is very close to working, but I suspect that something is wrong with the structure of the array I'm passing in to the 'field_postal_address' custom entity field.

function user_registration_form_submit($form, &$form_state){
drupal_set_message("User registration submitted");
dsm($form_state);

$edit = array(
    'name' => $form_state['values']['name'],
    'pass' => $form_state['values']['password'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'field_postal_address' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['address']))),
    'status' => 1,
    'access' => REQUEST_TIME,
);
$newUser = user_save(drupal_anonymous_user(), $edit);
}

So, the question is, why is this function injecting an empty row of data into the field_postal_address field?

I managed to figure out the problem. Apparently you can't load the new user array with the position of the array where the address fields are located. Instead you have to load the address array into a new variable, and pass THAT into the "field_postal_address" entity field.

So, in my solution, I loaded the address array into the $ary_address array. Then I passed that into the postal address array.

$ary_address = $form_state['values']['address']['address'];

$edit = array(
    'name' => $form_state['values']['name'],
    'field_fname' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_fname']))),
'field_lname' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_lname']))),
    'pass' => $form_state['values']['password'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'field_postal_address' => array(LANGUAGE_NONE => array($ary_address)),
    'status' => 1,
    'access' => REQUEST_TIME,
);
$newUser = user_save(drupal_anonymous_user(), $edit);