Twig Tokens in Views not Rendering Inside an HTML Element I'm using views to create a custom block of shortcut icons and need the images to link to the corresponding content. Using Rewrite Results I can overwrite the output of the view and have an anchor tag wrap around the image, however when I inspecting the output on the site, the href is blank making the images useless as links. Everything else renders though.

The view uses two fields, all from the same content type (shortcut). It consists of an image and a URL field. The image field is called first and then hidden to get the tokens, and the URL field holds the actual rewrite text. All of the these Twig tokens are listed as available within the Replacement Patterns dialog box.

{{ field_image }}

{{ field_url }}

Does Twig Debug affect the output for content like this? Is there another format I should be using? I tried calling and hiding via CSS the {{field_url}} first, before the rest of the rewrite text to see if it had to do with render inheritance but it still didn't change the blank href output.

Any insight on why the Twig token won't render inside HTML would be GREATLY appreciated. Thank you.

Problem solved. There were two issue at play; first off when I was messing with the Twig templates to trying and format the view the hard way, I inserted an extra <a href=""> in one of the templates and failed to remove it. My template was wrapping the empty tag around the properly generated content making it useless.

The second problem was that for some odd reason, the block was calling/using the same custom theme hook twice. I haven't figured out what was causing this error, but deleting the bock and forcing the new one to revert to a more general template hook solved the rendering issue.

However Twig debug still shows that there are two custom theme hooks of the same name available for use. No clue what is causing this behavior.


Putting sent private messages into a block I used this tip to put private the Drupal 7 private messages into blocks, in order to put those blocks on a quicktabs block:

<?php
/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $blocks = array();
  $blocks['messages_list'] = array(
    'info' => t('Messages List'),
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['messages_sent'] = array(
    'info' => t('Sent Messages'),
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['new_message'] = array(
    'info' => t('New Private Message'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
require_once('sites/all/modules/privatemsg/privatemsg.pages.inc');
function MYMODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'messages_list':
      global $user;
      $block['subject'] = t('Private Messages List');
      $block['content'] =
        drupal_get_form('privatemsg_list', 'list', $user);
      break;

    case 'messages_list':
      global $user;
      $block['subject'] = t('Private Sent Messages');
      $block['content'] =
        drupal_get_form('privatemsg_list', 'sent', $user);
      break;
    case 'new_message':
      $block['subject'] = t('New Private Message');
      $block['content'] = drupal_get_form('privatemsg_new');
      break;
  }
  return $block;
} ?>

It works quite well, but I have the following issues:

Tab 1 (Inbox): Why I can't delete messages on the message list, or change their status.
Tab 2 (Sent messages): How do I see the sent messages list? Is there a separate form?
Tab 3 (New message): After sending a new message, how to I redirect the user back to the messages list?
How to avoid needing to include sites/all/modules/privatemsg/privatemsg.pages.inc (If I want to put this block on a non-standard URL, not starting with '/messages', I get an error that a function in that file is not found.

Notes (EDITED):

Drupal 7 Privatemsg views integration module is stuck (you can see the latest patch here). Forms integration works, somewhat.

Alternate approachers:

Edit it with the data module (which allows to make a view on any table) + VBO. IF they work together.
Recreate the whole solution with Views + VBO.

Please advise

Thanks

Amnon

No need to use quicktabs. The tabs functionality is inherent if you use the privatemsg_filter addon module - inbox, sent messages and all mail are exposed as three tabs.

It was only needed to add a 4th tab with the option to send a new private message.

The tab already existed as a page, so adding it was simple using hook_menu_alter().

So the final code is:

<?php
function MYMODULE_menu_alter(&$items) {
  // Make the privatemsg new link a tab
  $items['messages/new']['type'] = MENU_LOCAL_TASK;
}
?>


Set value field before submit I'm trying to set a value before the form is submitted. The field is calculated by two other fields. One of them is a property of an entity reference. This is what I do:

function nodeoverlay_node_submit($node, $form, &$form_state) {
    if($node->type == 'zoekertje')
    {
        $korting = $form['field_field_korting']['und'][0]['value']['#value'];
        $node = field_get_items('node', $node, 'field_product_zoekertje');
        $node = node_load($node[0]['target_id']);
        $aankooprijs = $node->field_aankoopprijs['und'][0]['safe_value'];
        $price = floatval($aankooprijs - (($aankooprijs/100)*$korting));

        $form['field_verkoopprijs']['und'][0]['value']['#value'] = $price;
        $form['field_verkoopprijs']['und'][0]['value']['#default_value'] = $price;

        $form_state['field']['field_verkoopprijs']['und']['instance']['default_value'] = $price;
        $form_state['values']['field_verkoopprijs']['und'][0]['value'] = $price;
    }
}

I've tried different things to set my value of the field field_verkoopprijs but the result is always empty (and yes, my $price variable contains a float variable).

What can I do?

From hook_node_submit():

  This hook is intended for adjusting non-field-related properties

I think the proper place for this will be hook_node_presave() . To change field there you need to set, for example:

$node->some_field_name[LANGUAGE_NONE][0]['value'] = 'your value';

If you want to set reference field then:

$node->some_reference_field_name[LANGUAGE_NONE][0]['target_id'] = 'your value';

You may also want to consider using computed_field module for this.


How can I redirect users upon login sometimes but not break the "Forgot password?" function? I'm using Rules to redirect users with certain roles upon login using the Page Redirect action.  The "Force redirect" option is set to true (changing this to false does not fix the problem, and if it is false then users who log in from a block on the front page are taken back to the front page, which is not what I want).

My problem occurs when a user forgets their password and requests a one-time login link via e-mail. When the user clicks the link, he/she is taken to the login page.  From this page, pressing "Login" will redirect the user according to my custom rule instead of taking the user to the page where the password can be changed.

How can I redirect my users using Rules without breaking the forgot password function?

You can do that with a rule like that:

{ "rules_after_login_redirect_to_news" : {
    "LABEL" : "After login redirect to news.",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "0",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_login" ],
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "^user\/reset\/",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "news" } } ]
  }
}


Hover over image and display above like EBAY and AMAZON I've tried searching but i cant figure out how to achieve this effect.

Basically i have a VIEW of a content type PICTURE. In the view a main Image is displayed and 3 other images displayed below it, i want to have an effect when a user hovers over one of the 3 images below then the main image shows that image, it doesnt matter if the image stays there or goes back to its original once users mouse goes off the image, but just having it change is what im struggling with. I see this effect done on Amazon as a good example.

Anyone have any ideas? Or even maybe a name for this sort of JQuery effect so i can search for it and try to implement it in to my Views TPL file or something?

Thanks a bunch

Hi You can use combination of Views Slideshow & Views Slideshow JCarousel to make such effect.

See this video also:

http://buildamodule.com/video/advanced-site-building-in-drupal-7-building-a-slideshow-using-views-slideshow-how-to-create-a-pager-of-thumbnail-images-in-views-slideshow


Change quote to « » I'm using Drupal 7. A lot of text are using quotes like "text" or «text».
I want that for all older text on the site as well as for new text there will be one type of quotes used: «text».

Can you help me with that? Maybe some text filter or module can do this? Tnx for advice.

You can try this module:

Custom filter

  This module allows you to create content filter using regular
  expressions. Instead of creating a new module for each filter you
  need, now you can easily create and organize your own filters. Your
  filter will appear in the input format configuration page.

Pattern: /([^\"]*)\"([^\"]*)\"([^\"]*)/i

PHP Code: do not tick

Replacement Pattern: $1«$2»$3

REMEMBER to flush the cache!

ALSO note that this pattern could wreak havoc with tag attributes. So you will have to expand it to exclude quotes surrounding attributes. But that is a question for stackexchange.com.


"Fetch entity by property" for multi-value term reference field Node A and user both have a term reference field which referenced to the same vocabulary,  the term reference field of Node A is single-value, but that of user is multi-value.

I created a rule: after saving a new Node A , Fetch entity by property, the Entity type is User, the Property is the multi-value term reference field, but I cannot select the single-value field in the node, the page hints the property value should be "Data types: Select data of the type List of taxonomy term items." When I select "node:field-problem-category" (the single-value term reference field) and save, the page shows error: The data type of the configured argument does not match the parameter's value requirement. I have to select node:field-problem-category:parent. But thus no entity can be fetched.

I followed the instruction here, but no luck.

Any help would be appreciated!

BTW:It will be best that the "Fetch entity by property" can provide an operator like PHP function in_array.

At last, I solved this problem using Views Rules module, just set the Data type of the Rules parameters (providing to contextual filter) to Text. Then add a view loop in the rule action. A view's multi-value field contextual filter can have only one value.


Autofilling fields based on another field I have a very complex situation where I need some advice. I have a content type my_content, which has a field collection field attached to it field_mycollection, which has an entity reference field referencing to user field_my_userreference, a phone field field_my_phone, a text field field_my_text, and another text field field_my_anothertext.

My Content
|_ field_mycollection
   |_ field_my_userreference
   |_ field_my_phone
   |_ field_my_text
   |_ field_my_anothertext

The user entity has also have fields field_my_phone, field_my_text and field_my_yetanothertext which the latter has a different machine name.

What I want to do, if in my_content edit/add form, in field_my_userreference a user is selected, the other fields should be auto-populated from the selected user's data. The auto-populated fields should still be editable.

How could I achieve this goal? I'd like to do it, if possible, with some coding, using hook_form_FORM_ID_alter().

If you want it to happen live, and all fields are on the form already, safest way would be to use hook_form_FORM_ID_alter() to add following to a form:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'module_name') . '/js/copy_field_value.js',
);

Then in copy_field_value.js create behavior:

(function($) {
  Drupal.behaviors.moduleNameCopyFieldValue = {
    attach: function (context, settings) {

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function () {
        // above you can use change instead of blur if element is not changed by another js
        if (!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"
    }
  };
})(jQuery);

You can also use hook_form_FORM_ID_alter() to add #ajax parameter to source field, but it would make your form to call a server on each field copy. If you need to actually query database, it is the way to go. It would be pretty broad to describe it anew here. You need to alter $form_state["input"] array to update real values seen by user. Do it in form creation function, wrapping it with isset to avoid notices.

If your form element is $form["something"]["something"]["element"], its value will be in $form_state["input"]["something"]["something"]["element"] - and you can set it in hook_form_alter all right, just remember to take both $form and $form_state by reference.

Note: .on() method was added in jQuery 1.7, so you will need jQuery Update to use this answer directly, or translate my code to use .change() or .blur() method.


Can I use the first value of a multivalue field as another field? ("Cover" use case) My content type uses an unlimited number of images as "screenshot".
I would like to be able to manage the FIRST screenshot of the set as the "cover" of the content type, so to define a "field_cover" and telling Drupal "The value for this field is the first value of field_screenshot".
In this way I could reference field_cover in my views for some special cases (like showing the latest mynodes in home page, using the "cover" as the image).

I'm not aware of a "wrapper" field type, but you have a few options.

I've done the same myself in Views by filtering by the "delta" value, which is the individual values in a multivalue field. That way it's easy to require "delta = 0" and get the first value. This has a limitation of currently not working with arguments/contextual filters though.

A second option is the to ctools recently added support for delta values. You can render a field and set both offset, range and reversal of deltas.

Final option I can think of is Computed Field, which could be programmatically coded to act as field wrapper.


Filter strong and b from content through views I'm use CKeditor, which inserts b and strong tags for bold text, and sometimes when Drupal is showing teasers, only the opening tag is included. Resulting in the bold type face cascading down and being applied to all the text below it. Is there any way to filter out particular html tags(strong, b) from the teaser display in views?

EDIT: If one chooses to use fields, there is also the option in views to strip all html but leave particular tags, which is can accomplish the same thing but from the opposite direction

I assume you are using "show teasers option" for rows if yes switch to fields option.

Once you are using the fields add body field and add "Trim this field" then you could either click field may contain html, which will close the html tags before cut-off or you could pick strip html all together...


How to prevent that import with Feeds and Elysia cron gets stuck I have several Feeds which are called by Elysia cron.
The feeds are called at a given time, and later the last two feeds are called each 2 minutes, because it was the only way of preventing them from stopping. However, when data has increased in size and complexity, the cron process is stopped because one or both of the last Feeds are stuck and never ending.

I have seen that by updating the database table elysia_cron by setting the field running to 0, the Feeds are completed.

So my idea was to create a daemon to regularly update the process and thus prevent the hanging of the Feeds process.

What am I missing, shouldn't this check had been already incorporated into the module itself? What other ideas could prevent the failed import?

I have discovered that temporarily switching off the modules PathAuto and SubPathAuto improved the speed x10, making all these problems dissapear forever. No more feeds stuck or hanged. Later, I enable the modules again, and everything is ready.


How can I enable JavaScript form validation for AJAX submit buttons? Drupal 8 comes with client-side JavaScript form validation; however, for a submit button with #ajax, it is disabled. How can I enable it?

I had the same question this morning. Here's how I got it to work.

Add an invisible button and specify the #ajax on that.

$form['actions'] = array(
  '#type' => 'actions',
  'submit' =>array(
    '#type' => 'submit',
    '#value' => 'Submit',
  ),
  'validation-hack' => array(
    '#type' => 'button',
    '#value' => 'validated',
    '#attributes' => array('style' => 'display:none'),
    '#ajax' => array(
      'callback' => array($this, 'doSomething'),
      'event' => 'click',
      'progress' => array(
        'type' => 'throbber',
        'message' => 'Example...',
      ),
    ),
  ),
);

Then add a submit handler on the form that stops the form submission and then calls click on the hidden button.

  (function($, Drupal) {
    Drupal.behaviors.example = {
      attach: function(context, settings) {
        $(context).find('#example-form-id').submit(function(evt) {
          evt.preventDefault();
          evt.stopPropagation();
          $('#edit-validation-hack').click();
        });
      }
    }
  })(jQuery, Drupal);

Hope this helps you, or anybody else that may stumble across this.


Grant a role access to certain content Is there a way to only grant a role access to certain content?
So that every user given that role can access what they need without others being able to, while still being limited from accessing content that only other roles can access?

Also is there a way to automatically grant new roles to users as a result of performing certain actions?
Just like how some forums work where you can only start new threads when you've written 10 replies? Only this will be people being able to access a new level of the site when they have say uploaded a file or corresponded with a certain person and that person has given a thumbs up?
The latter I suppose could come in form of you being granted a role when a certain level is reached that enables you to give other users roles up to a certain limit?

Cheers,
Thor

There are a variety of content access modules, so you might want to look around to find one that best suits your specific needs but a good start is often https://drupal.org/project/content_access

As for automatic role delegation, there are a variety of ways you can do so, too. Rules is a great place to start https://drupal.org/project/rules but depending on what your requirements are, you might need to write a custom module. There are also a variety of rules-related modules that expand on it's offerings that might help you out. Rules is very capable for many things but sadly, if you have very specific needs it might be a little more complex than point-and-click.


show/hide fieldgroup with ajax drupal 7 I have a field group that contain sub field group with almost 30 fields
also I have a checkbox field that I want ajaxly show hide field group accoridng   checking event of it.

I have no problem with ajaxly show hide a field according to checking.but I have no idea how I can perform with  fieldgroup.
Any idea?

Have you take a look at conditionals fields, works great for node-form and can help you to build your own code.

Oskar


Features conflicts when field bases are used by other feature I recently downloaded the Features module and was so glad over how smoothly I now can export functionality from dev to prod. But now when I'm trying to create a second feature I'm getting conflicts because I already used a lot of the same field bases in my first feature.

What can I do to resolve this? Are you not suppose to be able to use the same fields in different features? It doesn't seem right that I should have to define as many fields for "body text" that I have features, or image fields for that matter. Those fields could and should be shared right?

What are my options here?

Say you have two Features, and one field that is used in both Features, then you only need to export the field base ONCE.

This is why I generally have a "controller" Feature that contains field bases, update hooks etc, and then for every other Feature I export the field instance, and then add a dependency on my controller feature.

Basically, you are right - you don't need to export the field bases every time, just export them once and then add dependencies.


Specify on which subdomain to show node (Multisite with shared Database) I'm using multisite with shared database. Is there any way I can specify on which subdomain I want the content to be displayed (on node creation)?

So If I create a node, I would like to have checkboxes that say (subdomain1, subdomain2, subdomain3).

Thanks in advance

You need this:

https://drupal.org/project/domain

On each node it will ask to affiliate content for specific domain and they would appear only over those for which you have selected.


Format 'Table Of Files' Field Display For Commerce Product Display? We have a Commerce Product Display for a Product Variation. If you're not familiar with Commerce Kickstart, it's basically just a form to add an item to a shopping cart. Each Product Display includes links to various PDF documents. The display format for the PDF field is 'table of files'. It works, however it looks clunky.

I'm having trouble locating the tpl or inc file that controls formatting for this type of field ('Table Of Files'). We don't want to globally change table display, we just want to alter it on this one Display.

Where is the php located to theme this? Or is there a function I need to add to my theme to hook into that display?

Specifically, we want to:

Get rid of the header.
Get rid of the file size column.

I am not sure which tpl.php file you will need to override, but you can try to "inspect" for it using Devel Themer and then override it with your own tpl.php.

This doc page has some common overrides and you can kind of get the override pattern. I am guessing you will need to something like field--field-name--content-type.tpl.php.


How to upload files using the Feeds module? I created a custom content type and I want to upload an XML file using the Feeds module. Can somebody explain how to do the mapping correctly? Should I add a new importer or use a node importer?

I want to perform the upload using an XML file. I have unicode characters in my file.

I am not able to convert it to a CSV file. I have tried converting using Open Office but it is not working.

I find using feeds a bit complicated.

Are there other solutions to upload files into database?

Note: When I try to upload to says no new nodes created.

You need to use Feeds XPath Parser module.

You may need this module if you would like to:

  Import XML or HTML documents into nodes, users, taxonomy terms, or
  regular database tables.
  Scrape webpages like regular feed sources with scheduling, updating, and expiring.
  Extract content from HTML documents to create a semantic data bank or mashup.

Below links will help you to set up.

Feeds XPath Parser, a full-fledged XML parser that utilizes the XPath syntax for scraping feeds.
Importing from XML, from drupal.forhumanists.org.
Drupal 101: What I learnt from hours of troubleshooting Feeds.


How to report about how many users have registered in a given timeframe? We want to know how many users registered to our website as a report.

I'm looking for a way (or a solution) in D7 that allows me to give me a report of how many user have registered to my website. Ideally will show me how many user register yesterday, weekly, monthly and annual.

Here are some modules to consider, for anybody who is not able or willing to write some PHP coding to answer such typical reporting question (or anybody who does not want to enable the PHP filter in a site):

The Forena module can be used for such types of reporting. It comes with all sorts of Sample reports and solutions, such as the Site administration reports, which contain data about the actual Drupal site. Here are some details about those reports:

Active Users - A variation of D7's admin/people, including hyperlinks to the Logs for User report.
Active Users Email - A demo of the ability to send email to all active users of a drupal site.
Logs for User - Most recent watchdog log entries for a user (specified as a report parameter).
Role Details - A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

Cloning these sample reports into custom variations is straight forward. E.g. tune the active users report with some report parameters to only report about user registered this week.
For somebody looking for info related to visitors of a website (registered users is a subset of them, no?), the Visitors module might be a valid alternative to consider also (and/or addition to the above module). Obviously, to submit a registration request one has to "visit" an URL like user/register (or something similar).

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module. Refer to the Visitors community docu for some more details.

Extra reporting features can be enabled via these sub-modules:

The Visitors GeoIP module, to also report about countries and cities.
The Visitors Browscap module, providing statistics on visiting browsers.

Both modules also support charting of those data (a typical related requirement ...)

Disclosure: I'm a (co-)maintainer of Forena, and the maintainer of Visitors.


How can I create 301 redirects from "unclean" URLs? I am moving a Wordpress site to Drupal and want to ensure that proper 301 redirects are in place for SEO purposes.

The old urls are in the form of: http:www.domain.com/?page_id=123

I was hoping this would be simple enough with the Redirect module, but when attempting to enter a path such as ?page_id=123 I see the following message.

  The source path /?page_id=123 is likely a valid path. It is preferred to create URL aliases for existing paths rather than redirects.

I want to be absolutely sure that a 301 redirect is created but I am unsure that adding an alias is the correct method for this.

Another approach I have considered is adding the following code to the .htaccess file in the web root.

Redirect 301 /?page_id=123 https://www.exacmple.com/node/321

Again, I am unsure if this approach is recommended for Drupal 8.

How should I add redirects and avoid the new Drupal site is penalized in search results?

The warning you're seeing is generated by the Redirect module when you try to redirect from a path (the part without the query string) which is already a valid Drupal path, which is true for your case (your redirect's source path is the site root, /): https://git.drupalcode.org/project/redirect/-/blob/8.x-1.x/src/Plugin/Field/FieldWidget/RedirectSourceWidget.php#L68. The query string is ignored in this validation step.

Without a query parameter, this would "cover up" the existing path and make it inaccessible, which is why the warning exists. But since your redirect does specify a query, this isn't a problem - the redirect only happens if the query matches ?page_id=123.

The warning should be safe to ignore; your initial approach was likely correct.


How can a user choose items from a view? I've 3 types of users:

Author
Reader
Site Admin

What I've done so far?:

I've created Content Type named Book. Authorscreate account on my site & login & then add the information about the books they authored. I've a View with page-display named books which lists all the books.

What do I need?

Reader should be able to pick 'x' no. of books from the this view. The no. of books a Reader can pick depends on his level Voracious Reader, Moderate Reader, Occasional Reader.
After Reader choosing Book(s), Site Admin will be see the list of books picked by all Readers.
He'll then ship  the book to their address (offline) & update the status as "Shipped".
of course Readers should be able to see the list of all the books they've chosen along with its status.

How do I accomplish the rest?

Use flags module along with the default view it provides.

  Flags may be per-user, meaning that each user can mark an item
  individually,

You can create two flags one called Marked and an other one called Delivered. Reader should be able to flag a Book as Marked but only Site Admin should be able to mark a Book as delivered.

If you are looking for more control consider using Workflow and then defining the states Marked and Delivered. You can set the access levels accordingly for the status change.


How do I add a menu router that works even in the maintenance mode? when a Drupal site is in maintenance mode (not due to a technical fault), users without permission cannot access any page other than /user.

Is there any special hook to define a specific menu router should be allowed in maintenance mode ?

I checked user_menu but there does not seem to be any clue about this.

You can use hook_menu_site_status_alter() to change the site status for a specific path.

Control site status before menu dispatching.
The hook is called after checking whether the site is offline but before the current router item is retrieved and executed by menu_execute_active_handler(). If the site is in offline mode, $menu_site_status is set to MENU_SITE_OFFLINE.

The user module implements that hook (user_menu_site_status_alter()) to make sure the site is always online for the user, user/login, user/password and user/reset/* paths. It should be simple enough to use the logic from that function to implement it for your custom path, e.g.
function MYMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  if ($menu_site_status == MENU_SITE_OFFLINE && $path == 'my-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}


Drupal 7 - div popup inside the overlay (node/123/edit) I'm trying to display a pop up dialog (using a hidden block) inside the overlay when editing a node.

When i click to edit a node, the overlay appears with all the custom fields of a given content type as usual. It is clean and white and everything in the background is darkened out.

So now i have logic in place (using jQUery) that's supposed to change my div's display to 'show' on keyup for a specific field on top of the overlay edit node.

I've tried adding a z-index of over 1000 and still nothing. The drupal overlay is using a z-index of 501 but my custom div still wont display on top of/over it.

This is my CSS for the hidden block:

#block-block-block-26 {
  z-index: 2000 !important;
  position: fixed;
  display: none;
  text-align: center;
  border: 1px solid #333;
  width: 200px;
  height: 80px;
  border-radius: 5px;
  padding: 10px;
}

This is my function inside jQuery:

 $('#edit-field-pi-estimated-ini-capital-und-0-value').keyup(function() {
        var txtVal = this.value;
        if(txtVal == 0 && txtVal != '') {
          $('#block-block-block-26').show();
          return false;
        }
  });

any idea how to make my div appear over the overlay?

Thanks

The code is fine, problem was with jquery version.


Custom date format in email body I have a confirmation email. In the confirmation email i print the Date of the event (Date field) in the e-mail body by [entity-fetched:field_event_date].

This is working fine but the Date is printed like 2016-04-13 16:30:00 to 2016-04-13 20:00:00

How do i print a custom Date format like i.e. 09-Jan-2016 in my email body?

[Updated] You will need to have the Token and Entity Token modules enabled. Then you'll print custom date format with the following token

[entity-fetched:field-event-date:value:custom:d-M-Y]

the token should produce the date in the format

09-Jan-2016

refer to PHP Manual for custom date formats.


Views: Limit amount of a node type by percentage I have a view showing nodes of two different types sorted by date.
I want to limit the maximum number of nodes shown of the one type by, say, 25% percent of the total nodes per page.

How would I go about that?

This might be a job for _views_pre_render().  In it, you can go through your views results and modify them to your module's content.  The issue here is creating a view result big enough to make your percentages work. For example, let's say you want to have that view of 4 nodes, but only 1 of which is of a certain type.  Since you are sorting by date, if the first 4 are all of that type, you grab one but need to keep looking for 3 of the other type.

In a dull ax approach, you could, though, create a view that returned 100, or however many is reasonable on your site based upon what you actually see re mix of nodes, of both types sorted by date and then do something like:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    //  drupal_set_message('
' . print_r($view->result[0], true) . '
'); // just the first row
    //  drupal_set_message('
' . print_r($view->result, true) . '
');    // all of them

    $max=1;    // hardcoded for example purposes
    $total=4;  // hardcoded for example purposes

    $new_result=array();

    foreach ($view->result as $result) {

      if ($max && $result->FIELDTHATHASTHENODETYPEINIT==NODETYPEWEARELOOKINGFOR) {
        $new_result[]=$result;
        $max--; $total--;
      } elseif (--$total) {
        $new_result[]=$result;
      }

    }

    $view->result=$new_result;

  }

  // any other views_pre_render()ing here

}

which if my logic gene is in gear today will cycle through your view results and pick out at most $max nodes of one type and then fill up $new_results up to $total with the rest of the view results and then replace the results of the view with that.

The issue, again, is that if all the results are of one node type, or there aren't enough of the other node type to fill up $new_result, you will have less than $total results returned.

(One or both of the drupal_set_message()s will/might be helpful for figuring out FIELDTHATHASTHENODETYPEINIT.  If there isn't one in your view already, you can put one in and then not display/hide it if necessary.)


How to define positive AND negative depth on taxonomy filter in views' module? I am looking for a way to have an exposed filter in a view, based on the option "has taxonomy terms with depth", that can look for a term in a positive and a negative depth.

An example : I want that when "EUROPE" is selected, all contents that have "WORLD" or "SPAIN" "ENGLAND" Show-up in the results.

Does anyone has an idea ?

Thank you in advance.

I've done stuff like this (eg, World and nesting of regions in the world with heirarchical taxonomies).

Take a look at Taxonomy Edge. It provides view integrations to provide search filters for "Taxonomy edge: Parent term ID" and I believe "Taxonomy edge: Parent term has child term". I mean it adds some useful parent and child Views search filters (I dont believe it adds a single positive or negative search as you've described).


How to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment I have written my first deployment_module for a Drupal 7 site and installed it into a virtual host on my development server.

I would like to check to see if my hook_update_N() functions have been invoked correctly and so am wondering how to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment.

I imagine some Drush command would be easiest way to find out. Failing that, it is probably set in the database somewhere.

Any ideas?

It's in the system table. This query:

SELECT schema_version FROM system WHERE name='mymodule';

will let you know the last update hook successfully completed.

if you want to use drush, there's drush sql-query

drush sql-query "SELECT schema_version FROM system WHERE name='mymodule'"


Change Quantity of multiple products and add it to cart I've been looking a while for a good solution to add 2 products with the same quantity to the cart with rules. In my case a customer can buy a basic product and if he wants an additional product he can get it only with the same quantity. Is this possible with rules? I didn't find any dynamic solution for this.

This should be possible. What I would do (from the bottom of my head, other alternatives can be easily implemented) is described below.

Assumptions:

There is an entity reference field to indicate relevant products.
There is no relation of 'additional' products back to 'main' or other products (the additional products are refered to by main products and they have no other reference to any other).
You have basic Views knowledge
You have basic Rules knowledge
You have basic Views Rules knowledge

Method:

Create a rule on event 'add an item to the cart'
Condition: the added item has reference to 'additional' products (so this is not an additional product).
Redirect to a view page which presents all products that are relevant to the current user's cart items (a view on order items entities).
The view should have an add to cart button without quantity
Create a rule on the same event 'add to cart'
Condition: the added item has no reference.
Loop through all cart items and call a rules component.
Create a rules component with 2 arguments (item added, item from loop) and 1 condition: if item from loop has reference to the item added), return the quantity.
Set the item quantity to the one returned by the component.
Optionally redirect to somewhere else.

Mind that the condition needs a bit of care. Alternatively, you can avoid Rules altogether and create a custom module which will use the Drupal Commerce API.


Media module and wysiwyg inserts image link rather than rendered image I'm using wyswig and ckeditor with media module to insert images into the body field of a node.

Instead of displaying the image it displays a link to the image. Viewing source this is what is inserted:

 feature_MB2.jpg

I have "Convert Media tags to markup checked" and I am NOT limiting HTML tags. Any ideas why it's stripping out the "[" and "]"?

Thanks,
Jon

You can fix this in the web admin GUI:

Configuration > Media > File Types > Image > Manage File Display > Check the "Image" box.


Views gives 200 instead of 404 if incorrect argument and a pager is present I am using with success the global null variable as described here
How do I set my views to return a 404 using Global: Null under contextual filters?

The solution by Kiam works fine, until a pager is added.

So,
myviews/mybadarg returns 404, but
myviews/mybadarg?page=2022 returns 200

Any tips why?

I tried enabling and disabling pager but no luck.

I found a solution: I had to set "Show page not found" in the Global Null argument "When the filter value is not in the URL."


Remove links under main page When I add a new 'Basic Page' or an 'Article', a link to the Home page appears under the 'Main Menu' and I have no idea how to remove it.

How can I remove these links?

These links are navigation links, so called "breadcrumbs". They inform the site visitors where they are on the site.

You are using the Bartik core theme -- take a look at /sites/themes/bartik/templates -- there is a file page.tpl.php. On about line 176 the following code

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

renders these breadcrumbs.

You could comment or remove these lines to avoid rendering navigation links. If you make changes to theme files remember to flush cache to see the changes.

But a better solution would be to create a Bartik subtheme (because each time you update the Drupal core, all your changes made to this file will be overridden, I would also not recommend to touch core files).

You could consider to choose another theme which has additional settings options like for displaying breadcrumbs.


Featured product-Drupal commerce I have this issue:I have on a product display a "Featured" checkbox.
I want when this "Featured" checkbox be selected,the price of the product to be increased by some amount when being added to the cart.
So:Normal product will cost 100$ ,if Featured is selected the price will be +50 (150$).
Can this be done with a rule?If so,how?
thanks

Event:  adding product to the cart.
Conditions:
1. Entity has field (the featured field).
2. Data comparison:  (is that field "on"?)
Action: add amount to the unit price.

I'm not looking directly at the Rules interface, but that should get you well on the correct path.


How to create timestamp field? I get Undefined index: timestamp:normal in DatabaseSchema_mysql->processField() I am getting the following error for the field within a hook_schema()

  Notice: Undefined index: timestamp:normal in
  DatabaseSchema_mysql->processField() (line 205 of
  /D7/../includes/database/mysql/schema.inc).

function hook_schema() {

$schema['abc'] = array(
  'description' => t('asdc'),
  'fields' => array(
    'rec_create_date' => array(
      'type' => 'timestamp',
      'not null' => FALSE,
      'default' => NULL,
  ),
 ),
)
}

Looking at DatabaseSchema_mysql::getFieldTypeMap we can see that timestamp itself is not implemented:

$map = array(
    'varchar:normal' => 'VARCHAR',
    'char:normal' => 'CHAR',
    'text:tiny' => 'TINYTEXT',
    'text:small' => 'TINYTEXT',
    'text:medium' => 'MEDIUMTEXT',
    'text:big' => 'LONGTEXT',
    'text:normal' => 'TEXT',
    'serial:tiny' => 'TINYINT',
    'serial:small' => 'SMALLINT',
    'serial:medium' => 'MEDIUMINT',
    'serial:big' => 'BIGINT',
    'serial:normal' => 'INT',
    'int:tiny' => 'TINYINT',
    'int:small' => 'SMALLINT',
    'int:medium' => 'MEDIUMINT',
    'int:big' => 'BIGINT',
    'int:normal' => 'INT',
    'float:tiny' => 'FLOAT',
    'float:small' => 'FLOAT',
    'float:medium' => 'FLOAT',
    'float:big' => 'DOUBLE',
    'float:normal' => 'FLOAT',
    'numeric:normal' => 'DECIMAL',
    'blob:big' => 'LONGBLOB',
    'blob:normal' => 'BLOB',
  );

So, according to Schema API

  'mysql_type', 'pgsql_type', 'sqlite_type', etc.: If you need to use a record type not included in the officially supported list of types above, you can specify a type for each database backend. In this case, you can leave out the type parameter, but be advised that your schema will fail to load on backends that do not have a type specified. A possible solution can be to use the "text" type as a fallback.

In your specific case "int" makes more sense than "text" as fallback.

Or simply do as core modules, go with "int" for timestamps and calculate everything date-based in PHP code.


Can Panels just be uninstalled if you want to switch themes? I used panels + panels everywhere with precision theme to build a website.

I now rather want to use Zen theme with basic blocks.

I wish to keep the content types with their fields.

If I uninstall panels will all instances of it be removed from the site?
Or should I rather just rebuild the site from a new clean installation?

Usually, uninstalling removes everything created by the module, its setting and its database tables.

But for what you are after, you don't even need to uninstall them, not even disabling to be honest, just don't use panels tools in your new theme.

Considering that, I would delay the idea of removing them and the old theme to after the new one is ready.
Just because of "how i did it in the other theme?" kind of questions


How to theme main menu in three columns I have a main menu block which i am showing at top-navigation.
I need to theme main menu but not sure how to apply classes to the root level menu items and sub menus.

i tried below snippet but not getting result. Can anybody tell me how to achieve this.

   $main_menu,
  'attributes' => array(
  'id' => 'main-menu',
  'class' => array('links', 'navlist1', 'clearfix'),
  ),
  ));
  ?>

Below is the screenshot image which output i want to show in main-menu

For a quick non-programmatic solution, you can consider using the Menu blocks module to render 2nd level menu items in 6 separate blocks, then render the blocks in the regions you want. On top of this you can also add customer classes on menu items with Menu attributes module.
If you don't mind a javascript approach, you can manipulate dom to move the sub menus around.
If you are familiar with the theme layer, you can create your custom theme function for main menu by implementing themename_links__system_main_menu.


Installed drush 8, got Parse error Got Drush 8 installed alright, but when I try to drush up my Drupal 8.0.0 site I get a Parse error: syntax error, unexpected '[' in /is/htdocs/.../.composer/vendor/drush/drush/includes/output.inc on line 188

Line 188 looks alright to me. What may be wrong?

You are running with php 5.3 or earlier.  Drush 8 needs php 5.4 or later. Unfortunately, php 5.3 does not understand array syntax, so the failure is raised before any Drush code runs.  For other sorts of errors, Drush will tell you that your php is too old.

I am guessing you are using php 5.5 for Drupal 8; check which php and php --version to see if your php-cli is the same version as your Web server php.

UPDATE:

Set the environment variable DRUSH_PHP to the full path of the PHP executable that you would like to run.  Note that this will only work if you are using a Composer or git install of Drush; if you are using drush.phar, this feature is not available. For the .phar, you would need to use a shell script named "php" that calls php5.6. Then, set your PATH such that your php script comes before the one offered by default on the platform.


Turn off responsive behavior for Bootstrap 3 I know how to turn off responsive in bootrap . but how it can be in drupal theme. As i am using Drupal Bootstrap and created a subtheme. can that subtheme be non-responsive ??

You can reset Media queries breakpoints, it will not work.
Here is path: bootstrap/bootstrap_subtheme/less/variable.less
at line number 209.

Check it.


How to hide Article Fields which are displaying on the front end Please help me, i just started learning drupal and implementing it.

I have a problem in hiding fields which are displaying in article pages.

Please check this page . "Body" field is displaying in all Articles. Please help me.

Please find the attached screen shot for reference.

Guessing there is no views implemented.

Go to manage display settings of article content type [ admin/structure/types/manage/article/display ]. In Label column select 'hidden' for body row.

You are done.


multiple views want single search field is it possible in drupal? I have developed Multiple views with multiple nodes.like(View1 , View2,View 3).

In these three views Name field is same.
so is that based on Name filed search feature is possible or not.
I have tried with views default search criteria,but its working for only particular views only.

any suggestions please?

You can't use a single exposed filter for multiple views.
There is a workaround though:

Make a new view that displays the three types of nodes you declared before.
Make sure you use "display: content" in your view
Choose a view mode
Expose the name field that is used on the different content types

So it all comes down to using 1 view


How can I include some functions globally? I've created a few helper functions specifically for a project and I want them to be available globally.

I know I can include them via composer with the files key. I was wondering if there was a more "drupal way" sort of ...way, to include them?

The Drupal 8 way to define helper methods is to put them in a class as static methods.

Example from core:

namespace Drupal\Component\Utility;
/**
 * Provides helper methods for byte conversions.
 */
class Bytes {

  const KILOBYTE = 1024;

  /**
   * Parses a given byte size.
   *
   * @param mixed $size
   *   An integer or string size expressed as a number of bytes with optional SI
   *   or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
   *
   * @return int
   *   An integer representation of the size in bytes.
   */
  public static function toInt($size) {
    // Remove the non-unit characters from the size.
    $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
    // Remove the non-numeric characters from the size.
    $size = preg_replace('/[^0-9\.]/', '', $size);
    if ($unit) {
      // Find the position of the unit in the ordered string which is the power
      // of magnitude to multiply a kilobyte by.
      return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
    }
    else {
      return round($size);
    }
  }

}

and use it in code:

$upload_max = Bytes::toInt(ini_get('upload_max_filesize'));


Last Comment Name field is not removed after account cancellation After cancelling the user under(Delete the account and make its content belong to the Anonymous user). Forum posted by is changed to "Anonymous" but
comment name is still displayed in the forum.

Also i noticed it in the table, node_comment_statistics

How can i remove the Last Comment Name while cancelling, because i need to remove entire user information from my database.

Update 1:

Last_Comment_Name is mapped from the table Comment column name

The forum module doesn't respond to any user deletion activity so you'll have to build your own solution here. You can create a custom module with a  hook_user_cancel implementation that will:

Check that the canceled user account is being anonymized.
Look up the username's entries in the node_comment_statistics (and other relevant tables).
Execute a UPDATE DB query that replace the name with "anonymous" (or whatever anonymized name you like).


Show a message after file_transfer is executed I am using file_transfer to send a download to the http client.
The problem is that file_transfer executes drupal_exit so that no more code is executed after it.
How do you show a message or redirect to another page after sending a file_transfer ?

By default, you can't - when someone clicks a link to a file that's force-downloaded, it happens as a separate request/process entirely. For security reasons your web site will not be able to tell when/if that download has completed.

I think the easiest thing you can do is implement some javascript on the download link, which auto-refreshes the page as soon as you've clicked it, and while the file is still downloading. You could use a query string or similar to note that a message should be displayed or that a redirect should happen.

If you need something more complicated, you might be able to implement an AJAX-based polling mechanism, which contacts the server and checks the connection status for that file. It's not a trivial task though, and I think you'd need to change the file_transfer module quite a bit to implement that. It also might require some advanced server configuration. All beyond the scope of Drupal, so I'd advise getting a solution working independently first, and only then worry about getting it inside Drupal.

There are some ideas here, and related logic here


Vocabulary contains too many choices Hello I've created a vocabulary which contains a lot of ingredients can i make it easier to choose them. At the moment it is a long list. If it is somehow possible to make a search form where i can select multiple ingredients it would be great. Modules or other soloutions?

I would suggest trying the Chosen module. It provides autocomplete functionality with multiselect capability. Using the multiselect field you can hold ctrl while selecting to keep the list open. Here's a demo.


How to send a message to users who flagged a taxonomy term? I want to send a message to users who have flagged, for example, the Toys taxonomy term. But only when a new node is created and contains the taxonomy term of Toys.

Any suggestions?

I would create this using a Custom PHP code in Rules and execute the following conditional code on 'After saving new content of type...' event trigger :

if( count(taxonomy_get_term_by_name('[node:field-tags]')) ) return TRUE;
else return FALSE;

Then create an 'action to send an email'.

Requires -PHP Filter,-Rules.
-Here the content type assumes the default 'Article' with default Tags field 'field_tags'

{ "rules_tst" : {
"LABEL" : "Test Rule",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "php" ],
"ON" : { "node_insert--article" : { "bundle" : "article" } },
"IF" : [
  { "php_eval" : { "code" : "if( count(taxonomy_get_term_by_name(\u0027[node:field-tags]\u0027)) ) return TRUE; \r\nelse return FALSE;  " } }
],
"DO" : [
  { "mail" : {
      "to" : "me@mine.com",
      "subject" : "test subject Toys confirmed!",
      "message" : "There are toys to play with!",
      "language" : [ "" ]
    }
  }
]

}
}

I ahve included an importable for you to test.


Commerce Event Registration How to create a commerce site which also has the ability to take registration information during/before/after registration?

I am developing a website which offers a variety of training courses. When adding a particular course to the basket, I would like the to be able to take the details of the people (multiple attendees) who will be attending the course.

How can this be achieved?

There's a module for that: Commerce Registration. You've got a registration field attached to your commerce products and you can work from them to build a solution, for a distribution that uses this for events check out COD, that might fit your needs.


simpler theme/view mechanism/function? Is there a module that provide a base/framework for simpler/faster rendering of a view(in MVC terms).. a function like

  render_tpl('path/to/my/tpl/myview.tpl, array('var1'=>$var1,
  'var2'=>$var2);

?
You see something much simpler than having to declare my theme to the theme registry via hook_theme etc... (sometimes it seems overkill just to render a simple layout)

There wasn't enough space in the comment field, so I'll write a full answer :)

As far as I know, there is no way to do that using existing Drupal modules or functions. If you really want to do something alternative, look into guidelines/recipes for creating own functions for simple templating parsing.

  don't you feel that it is sometimes overkill/tedious just to theme something very simple with hook_theme etc...?

With the same logic, you could argue that you don't need any hook_menu() implementations, and that all you could do is have a .php file in the root of the site from where you would query the database directly :)

It all boils down to conventions because they imply more efficient/simpler maintenance, security, self-explanatory code for other people working on the same project, etc.

However, if you are the only one who is responsible for the site, you're free to do whatever works.

P. S. Toying around and stripping Drupal/turning it into something else can be very good for learning how things work at the higher level. Few years ago I maintained an in-house stripped version of Drupal 5 and 6 for own purposes, with different folder structure, without many modules/features I did not need and some other tweaks. It was a great learning experience.


How to add file extensions to list of acceptable in IMCE I am using Ckeditor editor/IMCE file upload.
How do I get to the config settings where I can add more extensions which are accepted?

Go to admin/config/content/wysiwyg. Under the textformat table if CKEditor is choosen on full html for example under the operations column, select edit. And you should see buttons and plugins, and you should find the Imce checkbox listed as one of the last checkboxes


How to export custom entity using Features? I am trying to export custom entity using Features module but I am not able to see anything under create features.

I have enabled exportable as TRUE in hook_entity_info.

I have already added entity_exportable_schema_fields() under my custom schema .

Follow https://www.drupal.org/node/1021526 for detailed instructions.


How to associate programatically the translation of new term to the original existing term? I've terms which share the same id in stored in field and I'd like to associate translation between them, so they're grouped on the same page at /taxonomy/term/%/translate

So I've existing original English term, then I'm creating manually term with different language, so I'm expecting this term to associate with the original one.

Not sure which hook would be the best, or it doesn't matter:

hook_taxonomy_term_presave
hook_taxonomy_term_insert

So in example I've:

/**
 * Implements hook_taxonomy_term_presave().
 */
function foo_taxonomy_term_presave($term) {
  $bundle = 'countries'; // Example bundle name
  $vid = ($voc = taxonomy_vocabulary_machine_name_load($bundle)) ? $voc->vid : NULL;
  if ($term->vid == $vid && module_exists('i18n_string') && $term->language <> 'en') {

    if ($shared_id = $term->field_shared_id[key($term->field_shared_id)][0]['value']) {

      // Find term which points to the same country, but in English
      $query = new EntityFieldQuery();
      $org_term_res = $query
        ->entityCondition('entity_type', 'taxonomy_term')
        ->entityCondition('bundle', $bundle)
        ->propertyCondition('vid', $vid)
        ->fieldCondition('field_shared_id', 'value', $shared_id, '=')
        ->propertyCondition('language', 'en')
        ->execute();

      // Load term in the main language
      if ($org_term = taxonomy_term_load(reset(reset($org_term_res))->tid)) {
        // If original term is loaded, continue translation
        $langcode = $term->language;
        $key = i18n_object_info('taxonomy_term', 'key');

        $result_translation = i18n_string_translation_update(
          array('taxonomy', 'term', $term->{$key}, 'name'), // Array or string concatenated with ':' that contains textgroup and string context where to store source and translation.
          $term->name,      // Translation string for this language code.
          $langcode,        // The language code to translate to a language other than what is used to display the page.
          $org_term->name   // Optional source string, just in case it needs to be created.
        );
        watchdog('foo', "Added !source translation: !translated in !lang (key: !key)", array('!source' => $org_term->name, '!translated' => $term->name, '!lang' => $term->language, '!key' => $term->{$key}), WATCHDOG_NOTICE);

      } // end: if

      i18n_string_object_update('taxonomy_term', $term); // not sure if it's needed for something

    } // end: if
  } // end: if

}

So the main translate part is in i18n_string_translation_update().
But it simply doesn't work as expected. The $result_translation returns the right data, but the association is not visible in UI at taxonomy/term/%/translate

There is no much documentation about it apart of Using the i18n API from other modules

So I'm using the right function in the right way?

Related:

how to get the translated taxonomy term programmatically?

Here is the function which takes $term as current term and $org_term which is original/source term.

<?php
/**
 * Custom function to add term translations.
 */
function foo_add_term_translation($term, $org_term) {
  if ($org_term->i18n_tsid) {
    // Already part of a set, grab that set.
    $i18n_tsid = $org_term->i18n_tsid;
    $translation_set = i18n_translation_set_load($org_term->i18n_tsid);
    $translation_set->add_item($term);
    $translation_set->save_translations();
    watchdog('foo', "Added !source translation: !translated in !lang.", array('!source' => $org_term->name, '!translated' => $term->name, '!lang' => $term->language), WATCHDOG_NOTICE);
  }
  else {
    // We have no translation source nid, this could be a new set.
  }
}

More code examples you'll find in i18n_translation module.

This could be called either during insert or update as below:

/**
 * Implements hook_taxonomy_term_insert().
 */
function foo_taxonomy_term_insert($term) {
  foo_add_term_translation_wrapper($term);
}

/**
 * Implements hook_taxonomy_term_update().
 */
function foo_taxonomy_term_update($term) {
  foo_add_term_translation_wrapper($term);
}

Here is helpful wrapper function with example to load the original term where two terms share the same field value:

/**
 * Custom wrapper to update term translation.
 */
function foo_add_term_translation_wrapper($term) {

  $bundle = 'countries'; // Example bundle name
  $vid = ($voc = taxonomy_vocabulary_machine_name_load($bundle)) ? $voc->vid : NULL;
  if ($term->vid == $vid && module_exists('i18n_taxonomy') && $term->language <> 'en' && empty($term->translation_set)) {

    if ($shared_id = $term->field_shared_id[key($term->field_shared_id)][0]['value']) {

      // Find term which points to the same country, but in English
      $query = new EntityFieldQuery();
      $org_term_res = $query
        ->entityCondition('entity_type', 'taxonomy_term')
        ->entityCondition('bundle', $bundle)
        ->propertyCondition('vid', $vid)
        ->fieldCondition('field_shared_id', 'value', $shared_id, '=')
        ->propertyCondition('language', 'en')
        ->execute();

      // Load term in the main language
      if ($org_term = taxonomy_term_load(reset(reset($org_term_res))->tid)) {
        foo_add_term_translation($term, $org_term);
      } // end: if

    } // end: if
  } // end: if

}

See also:

https://drupal.org/node/2102933


Will my managed file get deleted? At this url:

/admin/config/media/file-system

There is a setting:

Delete temporary files after X hours

Does this specifically refer to files in /tmp ? Or whatever I set as my temporary folder? Or will it possibly delete "unused" files?

I ask, because I use file_save_data to save files. And I'm worried that Drupal at some points decides to delete some of these files, as they won't be referenced anywhere except in my own custom table.

Files uploaded to managed files will be set as temporary. You need to set the file status as permanent, and add a usage, to prevent the file from being deleted.

Setting files as permanent can be done using File::setPermanent(). File usages can be added as follows:

$fid = 1; // The file ID
$file = \Drupal\file\Entity\File::load($fid);
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', $entity_type, $entity_id);

This will add a 'usage' for the file. When deleted, you need to remove the file usage. Files that have been set to permanent, and have a file usage applied, will not be deleted.


Countdown with Views i'm trying to format a countdown block in views to look like .  This was done with the Countdown Module, however I'd like it to change automatically based on the nearest event date and not have to enter in each event manually.  I can set this up in views, however I'm having trouble trying to figure out how to format it.  Right now it looks like this. So i'd like hence/ago to read since or until after the number of days, followed by the event name.  Thanks for any help!

Sharon

If you use Display Suite, you can create a custom field with the Display Suite Format and use the following (with your own date field name). You could also use a custom PHP field or some kind of hook, but the following logic still applies.

<?php
if (!empty($entity->field_event_start)) {

    // Get the starting time value and the timezone.
    $start_value = $entity->field_event_start['und'][0]['value'];
    $timezone = $entity->field_event_start['und'][0]['timezone'];

    // Create the date objects for now and the day of the event.
    $start_date = new DateObject($start_value, $timezone);
    $now = new DateObject(time(), $timezone);

    // Take the difference between now and the beginning date, in days format.
    $duration = $now->difference($start_date, 'days');
    print $duration . ' Days';
}
?>

You should end of with something like the following, and then jazz it up with your own styling.

Edit

I just realized you wanted "since" as in after, so just switch it up a bit and use the end date instead of the start date, if one exists. I also made a quick video on how to add in the custom code field, so hopefully this helps!

Custom Date Since field in Display Suite


Can emails be sent asynchronously via rules? (Using Queue?) I have some rules set up to send email notifications for forum messages, comments and articles. Sometimes the number of users that need to receive the email are quite large and the page doesn't refresh before the server has sent all the emails.
Can the sending be done in the background something? Isn't that what the core module "Queue" is there for?

Oh the joys of email. Email is sent via the servers underlying or configured MTA. PHP merely passes-off the email content to be delivered. Depending on your email configuration PHP may wait for bounce notifications for example ... or simply spool the emails to disk and wait for the MTA to flush the outgoing mail folder.

Emails from Drupal though do not need to occur on page-load or form submission. If you want you could use Rules to slowly fill a Queue (a "list") of emails to send out from the "website" periodically.

Depending on how you want to process that Queue, whether in realtime using a Process or Job/Worker library is up to you. Or you could batch up the sending of the emails using Drupal (and/or Drush) and it's built in Cron support.

Or, for instance you could use one of the many email campaign modules for Drupal such as:

Emma https://github.com/myemma/integration-emma-drupal
Mailchimp https://www.drupal.org/project/mailchimp

to completely offload the work from your server. How you wish to approach this problem, it's feasibility and cost are up to you.

EDIT:

This module works to provide Rules to fill Queues using Drupal Entities, Rules Queue. Google is your friend! :D

For some example code that uses hook_cron to send Queue'd emails:
http://www.jide.fr/english/using-rules-and-the-queue-api-to-batch-send-mass-mails


How should I use token_replace()? Could somebody give me an example of how to use token_replace()?
I'm trying to write a custom PHP rule for the Rules module that will rewrite few fields of a new saved content, using the values from tokens.

$text = token_replace('token example - [node:title]', array('node' => node_load(123)));


Managed File is stuck with a temporary URI, even after saving it as permanent file I was having this problem: Files uploaded via custom configuration form are eventually lost.

So, I used the solution, basically:

$file->setPermanent();
$file->save();

But then, even thou $file->isTemporary() is FALSE, the URI and URL seem to indicate that the file is still temporary:

URI: $file->getFileUri() yields temporary://filename.jpg

URL: file_create_url($file->getFileUri()) yields /system/temporary?file=filename.jpg

You need to mark file as "used", there is file.usage service for that, you can do it by next code: \Drupal::service('file.usage')->add($file), but after removing file from config or changing it by another file don't forget to remove file usage by \Drupal::service('file.usage')->delete($file), otherwise file would not be removed from file system.

In drupal 8.3 default behavior about unused files was changed and by default all unused files should not be deleted, until variable make_unused_managed_files_temporary is true.


Drupal Internationalization / Translation When you translate a website using the i8ln module it doesn't automatically translate all the words in fields correct?

Also, what do you need to do to efficiently translate all the words ?

Is it a process that requires manually translating all the text with the i8ln module?

I reviewed some drupal documentation about this but it seems to only be germane to contributing local translations to the server: http://drupal.org/node/11130

I'm looking to have the localization server automatically translate it for me.

I don't know if I completely understand your question correctly, but I think there's some confusion. The Drupal translations from localize.drupal.org and the locale core module, will only help you translate the interface. If there's something missing or you want some custom translations you can always use: http://drupal.org/project/l10n_client - and to keep it up-to date: http://drupal.org/project/l10n_update

The i18n module allows users to translate the content into different languages, but it does not auto-translate. There are some modules that uses Google's APIs to auto translate but one violates Google's TOS and the other one will stop working when google pulls there translation API

http://drupal.org/project/gtrans
http://drupal.org/project/i18n_auto


Drupal 8 and MailChimp I'm syncing a Drupal 8 webform to populate a MailChimp lits via the MailChimp module. As well as capturing the first and last name I also want to capture the City and Province.

However when I submit I only seem to capture the email address in MailChimp.

In Drupal 8 I configured my form for each field as the following:

Email Field (this works)
Title: Email
Key: email
Type: Email

First Name (this does not transfer to MailChimp)
Title: First Name
key: fname
Type: Text field

Last Name (this does not transfer to MailChimp)
Title: Last Name
key: lname
Type: Text field

In MailChimp I set up in the List fields and |MERGE| tags the following:

First Name *|FNAME|*
Last Name *|LNAME|*

Has anyone else had issues with merging fields from Drupal 8 into MailChimp via the MailChimp module?

I've recently built a subscriber module with a small piece of custom code. I prefer working with webform handlers instead of the Mailchimp module.
In a custom module add a folder src/Plugin/WebformHandler and create a file newsletterSubscription.php. Add the following code:

<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "newslettersubscription",
 *   label = @Translation("Newsletter subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions in Mailchimp"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class newsletterSubscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const MAILCHIMP_API_KEY = 'x'; // see https://mailchimp.com/help/about-api-keys
  const LIST_ID = 'x'; // see https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // The data to send to the API
    $postData = array(
      "email_address" => "$email",
      "status" => "subscribed",
      "merge_fields" => array(
        "FNAME" => "$first_name",
        "LNAME" => "$last_name"
      )
    );

    // Setup cURL
    // To get the correct dataserver, see the url of your mailchimp back-end, mine is https://us20.admin.mailchimp.com/account/api/
    $ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.self::LIST_ID.'/members/');
    curl_setopt_array($ch, array(
      CURLOPT_POST => TRUE,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.self::MAILCHIMP_API_KEY,
        'Content-Type: application/json'
      ),
      CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);
    $readable_response = json_decode($response);
    if($readable_response->status == 403) {
      \Drupal::logger('Mailchimp_subscriber')->error($readable_response->title.': '.$readable_response->detail .'. Raw values:'.print_r($values));
      \Drupal::messenger()->addError('Something went wrong. Please contact your webmaster.');
    }
    if($readable_response->status == 'subscribed') {
      \Drupal::messenger()->addStatus('You are now successfully subscribed.');
    }
    if($readable_response->status == 400) {
      if($readable_response->title == 'Member Exists') {
        \Drupal::messenger()->addWarning('You are already subscribed to this mailing list.');
      }
    }

    return true;
  }
}

Read more on how to enable and use the handler here: How to create a mailchimp subscription with drupal 8 webform and custom handlers (Video)


Contextual filters not allowing multiple values I'm using Drupal 7 and Views 7.x-3.8. I have a taxonomy term "A" which is related with another taxonomy term "B". I want to retrieve a list of "A", but filtered by those "B" that are present in the URL as query parameters. There can be more than one "B" in the URL.

So I've created a contextual filter with PHP code that finds all "B" IDs in the URL and ends up with something like: "return $B1+$B2+$B3...;". Of course, I've checked the Allow multiple values option.

If I pass only one value (e.g. return "15";), the query runs OK and it brings me all "A" related with the B with ID 15, but if I pass two or more values (e.g. return "15+20";), I get a No query was run message, and nothing in the view.

Is this bug for the Views module? I've also tried to replace the PHP code with a simple return "15+20"; in order to simplify the test case, but I get the same error.

I don't know if this would answer your questions, but I just noticed that, not only you need to check "Allow multiple values", you also need to specify "Term IDs separated by , or +" in the "Filter value type" select list.

(using Views 7.x-3.14 at the moment)


How can I get numbered classes on rows? I worked briefly with Drupal 7 and I thought it was possible there but in Drupal 8 is it possible to have a view output an increasing numbered CSS classes for Views rows?

This is what I want.

I know I can add a CSS class to every row and give every row the same class.

In Drupal 7 and 8 the add view row classes is check-marked by default.

The problem is that in Drupal 8, it does not work. (looks like this is a bug)

As you can see in the above picture, the number is missing on the div class.
Luckily, there is a workaround solution.
In FIELDS, add Global: View result counter and hide it from display
In FORMAT, click on Settings (the 1st one)
For row class, put for example: hello-{{ counter }} and uncheck-mark "add view row class", as you don't need it.

Result


How to data compare the price or, subtotal in Ubercart flat rate shipping quotes Using Drupal 7.43 and Ubercart 7.3.9
I am trying to set up flat rate shipping for two parameters.

For orders with a subtotal above $34.00
For orders with a subtotal below $34.00

Unfortunately, there are no options under data comparison for the Subtotal... Only the Order total.

Or, I would like to create a flat rate shipping rates that vary by price ranges.

For products with a price above $34.00
For products with a price below $34.00

Can't figure that one out either. Any help will be greatly appreciated!

Never mind... I had negate checked!
This is how I did it...

Data comparison
Parameter: Data to compare: [order:delivery-address..., Data value: United States

AND

Data comparison
Parameter: Data to compare: [order:order-total], Operator: is greater than, Data value: 34

Data comparison
Parameter: Data to compare: [order:delivery-address..., Data value: United States

AND

Data comparison
Parameter: Data to compare: [order:order-total], Operator: is less than, Data value: 34


Is filtering using images possible? Novice here. I'm on Drupal 7.

I have a content type with a title, image and body field. I've created two views to display that content. The two views are on a page and I need help connecting them so that clicking/tapping on the image in View 2 will change content in View 1. Ideally this happens without page reload and View 1 fades in as new image in View 2 is clicked/tapped.

This seems like a filtering thing but I can't filter using images, I don't think!? Are Views the best way to set this up? If yes, what specifically needs to happen for the two Views to connect? If there is an easier way to set this up, what would it be? Help all! Any direction is appreciated.

Edit: I wrote this for Drupal 8 before reading that the question is for D7. Hopefully it works in D7 as well.

You can do this using a views attachment. I'm basing it off the image you provided.

Set up

Create a new content type, call it Person, give it a title, image and body field. Set up the teaser for that content type according to how you want the selected person to display in the top view.
Install the Ajax links API module. This is required for this solution to work.

View 1, the list

The list is the bottom half of the image, which is a list of the people, showing a thumbnail of the image, and the title of the person.

Create a new view of the people content type. Create a page for this view.

Set 'format' to 'grid'
Set 'show' to 'fields'
Add a field for Content: ID. Check 'exclude from display'
Add a field for Content: Image (or whatever you named the image). Make sure it comes AFTER the Content: ID above. Rewrite the results to {{ [FIELD_NAME] }}. Note that you have to replace [FIELD_NAME] with the name of the field, and [VIEW ID] with the machine name of your view.
Add a field for Content: Title. Make sure it comes AFTER the Content: ID above. Rewrite the results to {{ title }}. Note that you have to replace [VIEW ID] with the machine name of your view.
Set up a pager if necessary, and customize the number of items to be shown in the grid.

Now you have a page that lists off your items in a grid, with both the title and the image ajaxified using the Ajax links Api module, ready to load content into a div. The final thing to do is to load the content into the div.

View 2, the attachment

Next, a View's attachment is created. This will display the teaser for the first person in the list, when the page is loaded.

Click the "+Add" Link, and select "Attachment"
Set 'Format' to 'Unformatted list'
Set 'Show' to 'Content', and select 'Teaser' as the view mode.
Under 'Attachment Settings', set 'Attach to' to the first view you created (the page view).
Set 'Attachment Position' to 'Before'
Set 'Inherit contextual filters' to 'Yes'
Set the pager type to 'Display a specified number of items', and set it to show a single item.

Now, when the page from the first view is loaded, the teaser for the first person will be loaded. You can alter the display of the teaser of the person content type accordingly, to show whichever fields you need.

View 3, the ajax-loaded content

The first view is set up with ajaxified links, set to display the content of the path /node/%/teaser. This page does not yet exist. The final step is to set up this page, so that the links can load this content into the container specified in the ajax links.

Click the "+Add" Link, and select "Page"
Set the title to <none>
Set the format to 'Unformatted list'
Set 'Show' to 'Content' with the 'view mode' to 'teaser'
Set the 'path' to /node/%/teaser
Set the 'pager' to 'Display a set number of items' and set it to show 1 item.
Add a contextual filter for Content: ID. 'When the value is not in the URL' set it to 'show page not found'

Now you should be able to access the page created in the first view, and click on the links to ajax load the content replacing the attachment that is initially shown on page load.


Commerce - how to set no payment for free orders when 100% coupon applied I'm working with a one-page checkout process, where cart contents, account info, billing, payment, and coupon information are all under Checkout. Coupons are handled by commerce_coupon.

This has worked fine, but now I want to allow free orders using 100% discount coupons, and I'm having trouble getting the right payment method selected when the coupon is applied.

To handle order totals being <= 0 because of coupons applied, I've added additional conditions to two payment methods as follows:

Stripe - commerce-order:commerce-order-total > 0.00

No Payment - commerce-order:commerce-order-total <= 0.00

Here's what happens:

When the order arrives at checkout. Stripe is selected as the payment method. When the 100% coupon is applied, the order total drops to zero as expected (through an AJAX refresh), but stripe stays selected as the payment method and the no payment option is not visible. If I reload the page manually, Stripe goes away and the No payment option is selected.

What I want:

Ideally, when a user applies a 100% coupon to the order at checkout, Stripe would disappear from available payment methods and "No payment required" would be automatically selected. Even better would be to also remove the billing information if the order total is <= 0, since there is no reason to collect it.

How can I achieve this?

I'm happy to work directly in code if that's a better approach.

Looking at your conditions, both of them match at $0.00. You'd at least need to switch Stripe to > 0 for it to work. However, simply adding a coupon on the checkout form doesn't trigger a refresh of the entire page. By that time, the form has already been built with the payment methods shown, and the only AJAX functionality on the pane is to switch out what payment details form elements may be visible.

You're either going to need review / payment on its own step (not a bad idea since you're using coupons anyways) or else write your own code to Ajax refresh the payment options as other elements on the form are updated.


When you have multilingual content not in the Original language Bilingual content is fine, but what do you do in Drupal 8 when you have content only in a secondary language. I've got a site in English & Japanese, with pages mostly in English (Original language), but some pages only in Japanese.

How to create content in a secondary language:

Go to the language settings of a content type and change it from "Site's default language (English)" to a secondary language or enable

  [x] Show language selector on create and edit pages

so that the editor can select a different language for each piece of content. As long as you don't add a translation to this content it stays monolingual (in the secondary language). You can even restrict a content type to this by disabling:

  [ ] Enable translation


How to store Views templates with a module instead of a theme I have created several views templates that are currently stored in my active themes directory.  In would prefer these templates be stored within my module directory.

My question is, how can I bring these theme files (views-view-field.tpl.php for example.) into my modules directory and have them be seen by Views?

Looking at the Views modules, I can see that default templates are stored in views/theme, but I don't see how it has been implemented.

This took me a while to figure out as well. The following code should be placed in your .module file (the code assumes your module is called "NAME")

/**
* Implements hook_views_api().
*
* Enabling using templates inside module
*/
function NAME_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'NAME'),
    'template path' => drupal_get_path('module', 'NAME'),
  );
}

This will tell Views to look in the root directory of your module. I personally am a fan of adding a subdirectory to the module to hold template files. To do this append the directory name to the end of the template path, eg:

'template path' => drupal_get_path('module', 'NAME') . '/templates',


CKEditor for Drupal 7 does not show the page contents This page http://sunsethill-ubud.com/bistro contents some text. When I look at it as admin, I can use the Edit tab. But if I click this tab, I get an empty page in CKEditor:

I tried playing with or without additional modules, with the version of jQuery, with uninstalling and installing again CKEditor, and so on. Probably the problem is very simple, but I don't see any solution.

Thanks in advance for any help!

I solved my problem. In my numerous attempts, I had checked the wysiwyg filter in the configuration page of CKEditor. I unchecked it, and everything is OK now.


How to do multiple file uploads from a block's form? In the hook_block_configure of my block, I'm defining the form for my block.  I want it to have multiple file uploads, so I'm using "cardinality", but the following code isn't working for me.  I only get the one file field.

$form['background_image'] = array(
  '#type' => 'managed_file',
  '#title' => t('A Background Image'),
  '#description' => t('An image file.'),
  '#cardinality' => -1,
);

Any ideas?

I'm using Drupal 7.

Note: I don't want to just upload multiple files at once.  I want the user to be able to upload "one more file" or delete one of the existing ones.

I think the '#cardinality' it's not a form attribute, I couldn't find on the docs.

But I could find it on the field_multiple_value_form().

I suggest you to take another approach and use the AJAX framework, I found a couple of guides (guide_1 and guide_2) that might be helpful.


How to filter a field in the add content window in Drupal? I am very new to Drupal so I'm sorry for my lack of familiarity with Drupal terminology.

I have a content type with multiple fields (A, B, C, etc..). Each field is a selectable vocabulary list. I would like the user to select any terms in A and B fields. But I want only relevant terms to display in the C field (depending on A and B selections). In this way, A and B are independent fields and terms that appear in C are dependent.

Example:

Content type: Food dish at a restaurant

Field A: Appears on Menu type (Breakfast menu, lunch menu, dinner menu, wine list,etc.)

Field C: Appear in Menu section (Appetizers, Entrees, Deserts, etc.)

If the user selects "Breakfast Menu" for field A, it wouldn't make much sense to allow the user to select "Desert" for field C. But selecting "Appetizers" or "Entrees" would be fine. I want to filter the selectable terms in field C depending on which options are selected for field A.

Thank you for helping me out! Really :)

You can try the Conditional Fields module. It allows you to show/hide fields based on the value of other fields.

The Hierarchical Select module suggested in jimajamma's answer is meant only for hierarchically structured vocabularies. Conditional fields doesn't have a fancy animated interface like HS, but it provides more flexibility. For instance, you could make a text field depend on a taxonomy term:


Hide user fields on profile2 registration form I am working on multi-user website with 3 roles in Drupal 7 website. I'm using profile2 module for custom fields for different users, also profile2 path for profile/user registration.

Problem came up with Location module because I need 3 different location cck (different fields from location cck are allowed) fields from every user/profile role. I got stuck with this more than 2 months. It would be nice that I can use Profile2 and Location cck but it's not possible because Views module does not extract different Location fields for my Profile2 CCK fields in different profiles (for example I need only phone or city field from location in some view).

The only way to achieve this (so far) is to make 3 location cck fields in user account fields and with field permission module grant privileges for specific roles.

But! I need to expose that location fields on profile2 registration paths with all other fields from specific profile and they need to be required.

Is there a way to hide location cck fields on the registration form based on user type (buyer, seller, etc)?

to hide and show fields on user registration form while using Profile2 path - try the following in hook_form_alter in template.php.

if ($form_id == 'user_register_form') {

// get current path
$request_path = request_path();

// check if current path corresponds to your registration form for a particular role
if (strpos($request_path,'buyer') !== false) {

// removes the field that should be hidden
$form['field_1']['und'][0]['value']['#access'] = FALSE;

// or
unset($form['field_1']['und'][0]['value']);

// set the state of the field to required
 $form['field_2']['und'][0]['value']['#required'] = TRUE;

}
}

simple warning - you may find that Location  module fields that utilize ajax (same goes for Address Field module) have a bug that breaks the user reg. form produced by Profile2 Path if it is submitted with errors and exposes fields hidden with method described above. Look for insight in this issue (https://www.drupal.org/node/2558335).


How to make one facet default? I want to set facet value default, when we search it will automatically checked 1st facet.

You should define hook_search_api_solr_query_alter and something like this:

/**
 * Implements hook_search_api_solr_query_alter().
 */
function MODULE_search_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  $call_args['params']['fq'][] = 'FACET_MACHINE_NAME:YOUR_VALUE';
}

I hope it helped you.

The other way to do this described here http://www.eilyin.name/note/how-set-value-facet-default-drupal-54


How do I remove unused links? There Drupal links, such as sitename.com/?q=user or sitename.com/?q=user/register that a user may use for direct login or registration to my site.

What I want to do is to disable those types of direct links.
I have placed my custom blocks for login and sign up in the first page, so if a user hits the URLs above, a strange view of mysite is displayed because it has 2 registration forms: One exists because of my custom block and another exists because Drupal's default registration form

Does anyone know how could I disable or remove all the links of type sitename.com/link and the only link that can direct to mysite to be sitename.com?
I know that seems hard because it maybe is not configured in Drupal's layer, but on HTTP protocol.
So if that is not possible, can you think of any solution to avoid the above mess?

There is two options using a custom module:

Disable access to this path using hook_menu_alter()

function MYMODULE_menu_alter(&$items) {
  unset($items['user/register']);
}

This option will send the user to an access denied page.
Redirect the user to the home page (or another one)

function MYMODULE_module_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'MYMODULE_go_home';
}
function MYMODULE_go_home() {
  drupal_goto('/');
}

Inspiration: Disabling /node view and other hidden views in Drupal?

PS: I'm not sure why you want to remove /user ? For this special path you can also use hook_user_view().


Mailchimp with Rules I installed MailChimp module and i am using Rules module to send emails to subscribed users. For gmail this emails are going in spam. But when i send an email from mailchimp, it's ok, no spam. There are 3 ways i see now -

Use rules and fetch subscribed users, then send email to them
programmaticaly(worst)
Configure rules to send emails from mailchimp.
Find another way to send emails and not get to spam.

Can i somehow make campaigns for mailchimp and send them with rules automaticaly, or you can suggest another mail module for such task?

I'm not 100% sure how this works with your setup and Mailchimp, But i have all of my site emails sending through SendGrid using the SMTP Authentication Support module. So far none have been sent to spam.

One thing to note about SendGrid: Their free account sends your emails through a shared IP. Sometimes they can get blacklisted from time to time. But you can eventually purchase a private ip through them to ensure even better spam protection.


Accessing values entered in custom fields added to install_configure_form In my installation profile, I have added a text field to the install_configure_form by including:

if (!function_exists("system_form_install_configure_form_alter")) {
  function system_form_install_configure_form_alter(&$form, $form_state) {
    $form['site_information']['site_name']['#default_value'] = st('Organization name');
    $form['site_information']['org_short_name'] = array(
      '#type' => 'textfield',
        '#title' => st('Short name'),
        '#description' => st('This will be used as a casual reference to the association throughout the site. If left blank, the Site name will be used.'),
      '#attributes' => ['placeholder' => 'e.g. FBI'],
        '#size' => 60,
        '#maxlength' => 60,
    );
    // Move the email to the bottom
    $form['site_information']['site_mail']['#weight'] = 1;
  }
}

Now, I'm trying to read and persist what the user entered using a _submit function:

function my_profile_install_configure_form_submit(&$form, $form_state) {
  $values = $form_state['values'];
  $name = !empty($values['org_short_name']) ? $values['org_short_name'] : $values['site_name'];

  variable_set('short_name', $name);
}

Unfortunately, I don't think the my_profile_install_configure_form_submit function is getting called because the short_name is not getting created. How should I be accessing and persisting the custom elements in that form?

Thanks!

Altering the site configuration form is not different from altering other forms, as done from a module.

If myprofile.profile is used in your profile, its content should be similar to the following one.

  function myprofile_form_install_configure_form_alter(&$form, $form_state) {
    $form['site_information']['site_name']['#default_value'] = st('Organization name');
    $form['site_information']['org_short_name'] = array(
      '#type' => 'textfield',
        '#title' => st('Short name'),
        '#description' => st('This will be used as a casual reference to the association throughout the site. If left blank, the Site name will be used.'),
      '#attributes' => ['placeholder' => 'e.g. FBI'],
        '#size' => 60,
        '#maxlength' => 60,
    );
    // Move the email to the bottom
    $form['site_information']['site_mail']['#weight'] = 1;

    $form['actions']['submit']['#submit'][] = 'myprofile_install_configure_form_submit';
  }

  // Notice which argument is passed by reference.
  function myprofile_install_configure_form_submit($form, &$form_state) {
    $name = !empty($form_state['values']['org_short_name']) ? $form_state['values']['org_short_name'] : $form_state['values']['site_name'];

    variable_set('short_name', $name);
  }

As for variable_set() working in this case, it works, since install_configure_form_submit() (the default submission handler for the site configuration form) uses it.

  variable_set('site_name', $form_state['values']['site_name']);
  variable_set('site_mail', $form_state['values']['site_mail']);
  variable_set('date_default_timezone', $form_state['values']['date_default_timezone']);


Define variables for template files I am trying to move the first chunk of code including the PHP logo call, and the breadcrumbs into the header region. I have created the block, and made it capable of reading PHP. I understand I need to write a preprocess function in template.php, but I am not sure how this is done. I am working in Drupal 7.

Can anyone show me an example, and explain how this works, or point me in the right direction?

Defining a variable in a template_preprocess() function is straightforward:

/**
* Implements hook_preprocess().
*/
function yourthemename_preprocess(&$variables, $hook) {

    $variables['your_variable_name'] = "some value";

}

In your template file, you would just output it directly, for example using the following code:

<?php print $your_variable_name; ?>

I'm not sure this answers your real question, but I could use a little more information. Why are you trying to move the logo/breadcrumbs using a preprocess function? Which theme are you using? If you're moving these around, it is usually easier to just edit the page.tpl.php file in your theme, and work with them from there.


Taxonomy vs Content Types or Entities With all the power of D7 Views 3.x and modules like Node Reference and/or various entity reference modules, alongside flexibility of fieldable taxonomies, I have trouble deciding data structure scenarios for taxonomy vs content types. What are some use cases?

I suggest you to check these 2 posts:

http://www.4sitestudios.com/blog/sep-13-2013/when-use-content-types-taxonomies-and-custom-entities-drupal

https://drupal.org/node/2075921


How to return node object on programatically node creation I can create  node programmatically  with following snippet

 use \Drupal\node\Entity\Node;

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',

])->save();

but it only returned "1" on successful,I want to return the created node object . how can I achieve that?

It's Entity::save() that returns the integer, so:

$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
]);

$node->save();

return $node;


How to set up html email from rules? I want to send a HTML email from rules but I cannot get it correct.

Installed mime, html, mail. Created rule. only a trigger and action send html email.
In the rule: no message key defined, subject is something like [node:nid], body is [node:body]

Made a template at campain monitor, now i have foo.html. Renamed foo.html to mimemail-message.tpl.php in default theme directory and put [node:id] and [node:body] on the correct place. Soo, the css is in the tpl file.

1) When testing I get an html email (logo is visible) but no colors.
Installed and configured: sites/all/libraries/emogrifier/emogrifier.php
Mailsystem is using mime, mime is using full html filter including emogrifier.
No change in the result.
I read the message with gmail. Adblockes disabled.

Any suggestion what to do ?

2) How to get replacement of the tokens. Which tokens are available for this tpl file?

I forgot to enable the module  mimemail_compress. After enabling this it was solved.