How to open all external links in a new tab I want to create a small module to open all external links in the menu in a new tab, how can I do that?

I think I should use hook_link_alter to do it, but i don't know how to do it so i can select all the external links only?

Links can be generated in a number of ways, which makes it hard to change consistently. For a single implementation that you want to reach most parts, you should swap the link_generator service with your own subclass. This should catch all menu items and links in general, but wont touch custom markup from wysiwyg. Here you would need to create a custom filter.

The ::generate($text, Url $url) method is what is used to actually create the create the HTML. What you want to do, it to add the _blank target attribute if the url is external.

The code for the link generator subclass, could look like this:

class MyLinkGenerator extends LinkGenerator {
  public function generate($text, Url $url) {
    if ($url->isExternal()) {
      $attributes = $url->getOption('attributes');
      $attributes['target'] = '_blank';
      $url->setOption('attributes', $attributes);
    }
    return parent::generate($text, $url);
  }
}

I wont go into how to change the class of a service, there is plenty of examples for this here and elsewhere.


hook_entity_update cancel When updating an entity I want to validate that the fields I am updating are correct. As this may be coming from VBO or a Drupal form I thought I could do it in hook_entity_update.

In hook_entity_update() is there a way to not update the entity and return/display a message.

Maybe I am coming from the wrong angle.

The right hook for this job is hook_field_attach_validate().

(As implemented by the Field Validation module, which may also do what you want.)

hook_entity_update() actually fires after the entity and all fields have already been saved (in the case of nodes, at least).


Allow content builder to 'disable' a content type form I have a site that allows users to submit a 3d print job to a lab.

The role of the site builder is: technician
The content type in question is: print job

Users can submit a print job (i.e. create a print job node).

What I'd like is to enable the technician to be able to prevent/disable/stop the user from being able to use the form at node/add/print-job when they want to prevent new print jobs from coming in (i.e. too busy at the lab).

I can use the Content Access module, but I'm hoping for something a bit less complex for the technician and that doesn't result in a 403.

I'm hoping that there is a way to do this with rules or workflow. Preferably one button/checkbox with a confirmation. Disabling the content type form will display a message written by the technician on the form path.

Any help would be greatly appreciated.

I think you'll have to do this with code.  My quick take on this would be:

Create a content type with an "Disallow jobs" check box and the body field.
Allow the technician role to view and edit this content type.
Create a node and add it to your menu with a "Disable/Enable jobs" link.

Use hook_form_alter() to:

check for the job content type form
load your Disable / Enable jobs node
Check if the disable jobs checkbox is ticked.
Replace the $form array with a markup entry using the text from the node.

Note if you need to have this turned off automatically (e.g. lab closed), you probably can use rules to modify the disable jobs node.


Access denied after installation I've completed installation without error messages, but when I visit the site and attempt to log in, I can't, and I don't receive e-mails sent to reset the password.

Here are the details:

Using XAMPP 5.6.3 under Windows 7. Installing Drupal 7.36.

Site URL: localhost/Drupal7 (entered for "Site name" on "Installing Drupal" page of installation script)
Database user name: d7db_010_drupal7
Database name: (same as database user name)
Site user name: D7_010_Drupal7 (entered for "Site maintenance account Username" on "Installing Drupal" page of installation script)
Site e-mail address: D7LocAdmin@mydomain.com (not the actual domain)
Passwords for two above user names: 10-char pws generated by www.passwordsgenerator.net

Database d7db_010_drupal7:

- Table users has two records:
    * User ID 0: All other fields either empty, null, or 0
    * User ID 1: name = D7_010_Drupal7, pw = hash, mail and init both = D7LocAdmin@mydomain.com, created = 1428953185, login = 1428953512 (See note on timestamps below.)
- Table users_roles has one record: User ID = 1, Role ID = 3
- Table watchdog has 55 records, mostly about installing and enabling modules, and:
    * Event ID 52: uid = 1, type = user, msg = Session opened for %name., location = http://localhost/Drupal7/user, timestamp = 1428953513
    * Event ID 53: uid = 0, type = access denied, msg = user/1, location = http://localhost/Drupal7/user/1, timestamp = 1428953513
    * Event ID 54: uid = 0, type = user, msg = Password reset instructions mailed to %name at %email., location = http://localhost/Drupal7/user/password, timestamp = 1428953546
    * Event ID 55: uid = 0, type = user, msg = Password reset instructions mailed to %name at %email., location = http://localhost/Drupal7/user/password, timestamp = 1428953571

Note that value of "login" for user 1 in the table "users" is one second before the timestamp of events 52 and 53.

Actions I took when installation completed:

Went to localhost/Drupal7. Prototype page came up.
Entered site user name and its password. Nothing happened. No event for this in table "watchdog".
Clicked on link for "Request new password". In form that came up, clicked on "Log in" tab. Entered site user name and its password. Result: "Access denied". This is event 53
Clicked on "Request new password" tab. Entered "D7_010_Drupal7" and clicked button. Result: "Further instructions have been sent to your e-mail address." This is event 54. No e-mail received.
Clicked on "Request new password" tab. Entered "D7LocAdmin@mydomain.com" and clicked button. Result: "Further instructions have been sent to your e-mail address." This is event 55. No e-mail received.

I sent myself an e-mail at the site e-mail address to test that it's working and I received it.

Can someone see:

(a) Why I can't log in

(b) Why I'm not receiving the e-mails

or tell me what to inspect or test further to find out?

Thank you.

===============================

Update

In order to check that the problem is not with characters in the user name or with using the wrong password, I reset the name and password to "hello" and "there". I did the following:

Ran php on "scripts\password-hash.sh there"

The response was

password: there hash: $S$DK0K/McRjrM9f7D/OwExsr8Fk.8uaU1U4CC030GbqjAArbEMIFg/

Ran the following two queries on table "d7db_010_drupal7":

UPDATE users SET name = 'hello' WHERE uid = 1;

UPDATE users SET pass = '$S$DK0K/McRjrM9f7D/OwExsr8Fk.8uaU1U4CC030GbqjAArbEMIFg/' WHERE uid = 1;

Entered "hello" and "there" on the login on the main page. Again, nothing happened.
Went to "localhost/Drupal7/user" and entered "hello" and "there". Result: Access denied.
Repeated the last step above in case of mistyping. Result again: Access denied.

Grrr!

Thank you to Alyssa Gono for solving this. She did it in a comment, so I can't formally credit her with the correct answer. But I'll lay out here what happened.

I thought at first that couldn't be it. How could a cookie be interfering with the analysis of the login credentials? But I was so frustrated by this problem that I decided to give it a try. I work in Firefox, so first I loaded IE, and logged in there, and it worked! Then I went back to Firefox and looked at my cookies. Rather than deleting them all, I looked for cookies from localhost. There were about 20 of them. I deleted those and bam! I was able to log in!

This was with the credentials "hello" and "there" set in the update above. So next I undid the changes described in that update by resetting the credentials back to the intended ones. Went back to the site, logged out and logged back in with those credentials and Wow! Problem solved.

Now I can finally get to work on developing my sites.

I'm going to submit a bug report at Drupal because it would be helpful if the sw could let the user know that a cookie is blocking the login. If it can't detect that, at least it would be helpful to suggest clearing cookies if one believes the login should be working and isn't.

Can someone explain how it is that a cookie interferes with the analysis of the login credentials?

Thank you again to Alyssa.


Entity Reference - show link on referenced node I have a "Entity Reference" field in a custom content type. I want to show on any referenced node the link to the node. How can I do it?

I found the solution! I just went to "Manage display" of the content type and I checked "Link label to the referenced entity" in the "Entity Reference" field.


Duplicate content in views I implemented the media browser module for image uploading and changed one of the image fields to utilise the media browser for a particular content type. After which, the views which displays a list of that particular content type is showing duplicate content.
After googling I found some one who had a similar problem to mine, however, I don't understand how he solved his problem. https://drupal.org/node/1764042
I would greatly appreciate any help given.
Thanks a lot.

Update:
Figured out the problem. I was using a file:usage relationship to generate the path url for rewriting the output. Hence having multiple files linked to that node would generate multiple views.

This may happen if you are have applied filters on any date field. I had similar problem, try this, in Views Advanced Settings under OTHER options, select "Query Setting" and check "Distinct" option.


How to add alt and title attributes field for user picture? In my Drupal project I have user picture enabled to all users, I want to add alt field and title field for Drupal user picture feature, so I can add my custom text instead of "user's picture" text.

I also want to utilize both fields in views as well.

Thanks,

You would need to override this function in your template.php file and override the alt tag.

Another option would be to uncheck "Enable user pictures" in account settings and add your own custom imagefield.  Then you should be able to enable alt and title fields in the field settings.  You can also use this field in views.


How change 1 line of code in a core module without hack? Every time I update Drupal core I get the error message,

  Notice: Undefined variable: forum_term (line 764)

I've implemented this hack on forum.module to get rid of this problem.

How can I implement this change without hacking the core forum.module file?

You can take 3 different strategies to mitigate the problem the hack introduces.

Don't Hack/Ignore the error: Without knowing the deeper context of when this happens, this could be (as the d.o. thread suggests) just a quirk of other contrib modules that show up during the update process. You'll need to do more investigation to see if this occurs during a critical code (e.g. a module update) and if it can be ignored.
Don't Hack/Fix the error: Assuming the error is fundamentally a part of Drupal's forum module logic (i.e. not just something caused by a contrib module), you could submit a patch for the module to get it fixed for everyone that has the same issue.
Patch Management: Depending on your own codebase, process, & issues, patching might be unavoidable here. If that's the case, you can create your own patch for Drupal core and create some process where it is consistently applied every time you need to you need to update your codebase.


How to email the results of a filtered view to a user? Required functionality (Drupal 7):

User filters a view to desired results
User enters email address in a
webform block
User is emailed the filtered list of results

I'm using Views (7.x-3.14), Webform (7.x-4.14) and Rules (7.x-2.9)

I've looked at a few modules surrounding saving your search results, but nothing I've found seems to help very much. Are there a combination of modules that I might be able to use (Rules, Cron etc.) that will achieve this or do you think I'll need to write something custom?

I'm still learning how to write custom Drupal modules so if anyone can point me in the right direction, that would be appreciated !

If your view is a page, should be as easy as grabbing the page url when the form gets submitted and based on the url (if statement) you attach a view that has a filter of "X". (slight chance that it is doable with rules and webform module)

If it's a block, gets a bit more complex. You would have to check what the filter is set to using jQuery, and then pass that variable to a custom module when the form is submitted. Then module triggers x function based on the view filter value that sends e-mail with view x.

Actually, an even more simpler option, have a hidden field of checkboxes (hide it with css) on your webform that has a box for each filter. Then with jQuery you can autocheck option x if filter is set to x.

Now since your webform contains  field of checkboxes with value x, with conditional rules hopefully you can do an if statement on your field of checkboxes and attach view x to your e-mail. (I'm making a lot of assumptions here, as I've never used webform + rules, or maybe I did once... Anyhow, hopefully this will work with Rules)


Path aliases not updating or setting automatically I have an Open Atrium site where the path aliases are not generated automatically and not updated if I change them manually.

How can I fix this?

The aliases are generated when you create an object in your site and are based upon the pathauto patterns (placeholders) you specify at:

For 6.x: Administer > Site Building > URL aliases, in the "Automated alias settings" tab.

For 7.x: Administer > Configuration > Search and Metadata > URL aliases, in the "Patterns" tab.

Pattern tab provides several default patterns that automatically alias the different content types.

Settings tab allows to refine length and case, as well as defining if an alias is to be replaced or added to the list.


Colorbox inline style="display:none" doesn't disappear I am using colorbox module.
I have an inline modal that works o.k, this is the code:

view content

    <input name="name" type="name" />
    <input name="phone" type="phone" />
    <input name="email" type="email" />

This code is an a view header.

When I click the link the modal pops but it is empty.
I've noticed that the style="display: none;" in the div does not disappear.

What can cause this?

Any help will be great.

O.k... I changed the code to this and it works...

Link to click

        <input name="name" type="name" />
        <input name="phone" type="phone" />
        <input name="email" type="email" />


Basefield 'string' shown as select list widget in entity form I've got a custom entity ('content_sharing') and defined one of the fields as $fields['entity_definition'] = BaseFieldDefinition::create('string').... The create-form I'm showing the user is loaded with an empty entity via a controller like so:

    $contentSharing = $this->entityTypeManager()
      ->getStorage('content_sharing')
      ->create([]);
    $form = $this->entityTypeManager()
      ->getFormObject('content_sharing', 'custom_mode')
      ->setEntity($contentSharing);
    $output['form'] = $this->formBuilder()->getForm($form);
    ...

What I need now is to present the user a select-list of possible strings (options) that are dynamically pre-populated everytime the form is loaded. The only FieldWidget for string fields is a textfield. I tried to come up with my own custom FieldWidget similar to this

 * @FieldWidget(
 *   id = "string_select_list",
 *   module = "content_sharing",
 *   label = @Translation("Select list for strings"),
 *   field_types = {
 *     "string"
 *   },
 *  multiple_values = FALSE
 * )
 */

class StringSelectList extends OptionsWidgetBase {

However, this resulted in an error and I  noticed that this needs to have options defined which I cannot (don't know how to) provide for my string basefield.

I could of cource just add a dummy form-element select list that provides the values for my entity field, but I wanted to use the entityform as it is without any further custom elements.

Possible with a custom widget or any other solutions?

Create a list_string base field and use as widget OptionsSelectWidget.

$fields['entity_definition'] = BaseFieldDefinition::create('list_string')
  ->setLabel(t('Entity Definition'))
  ->setSettings([
    'allowed_values' => [
      'value1' => 'Value 1',
      'value2' => 'Value 2',
    ],
  ])
  ->setDisplayOptions('form', [
    'type' => 'options_select',
  ])

To update the options dynamically add a callback to the base field settings allowed_values_function, see How do I programmatically update the allowed values of a list field?


Creating Private file directories inside public files directory I am developing a custom entity, which has a file field, which accepts .zip files. After the entity save, the contents of the zip file are decompressed into a folder specific to the .zip file, in the public files directory.

I'm am wondering if it is possible to create "private directories", which would act similar to standard Drupal private files...basically I want to restrict access to any file in the directory, but Drupal not knowing what files may be in the directory.

Basically the zip file will contain several .html files, javascript, and css files, which will be launched on the entity view page in an iframe.

Is this even possible?

Would anyone have some possible strategies to accomplish this goal?

I'm not asking how to setup a private file directory for storing and controlling access to single files, as is standard Drupal, I'm asking if it is possible to control access to any random file in a certain directory....inside the public files area.

I'm wanting to manage unmanaged files, by managing the parent directory, not the individual files

I'm open to using the Drupal core private file system, as long as Drupal doesn't have to manage the individual files specifically

Using just Drupal, it's not possible.

It's important to consider what setting store files as public means for Drupal. Essentially, it means Drupal relies on the web server for output of files URLs (vs. it being the gatekeeper to a directory non-accessible from the web server).

As such, to do what you want would require your zip processing code to do extra work of configuring your web server to restrict access (e.g. creating .htaccess files). You would also need some custom code to create proxy URLs paths to any file inside the unpacked zip directory. Lastly, you'd want to take a hard look at possible security vulnerabilities you're opening up by giving users unfettered access to run/view any arbitrary JS/HTML/CSS on your domain.


Start only one quiz per day I used quiz module version 7.x-4.0-rc2 and drupal7 to create content in my site. I created student role to access quiz content.

I want each student can start only one quiz per day. Example: Today is 22/04/12, a student can start only one quiz. If they open and start quiz1, they can't start any other quiz until to 23/04/2012.

Please help me, How to do that.
Thank you so much,
Bien Hoang

I have never used the Quiz module myself so I can only give you a generic answer.

What I would do, is to create a custom module which contains a hook implementation and a helper function:

In the helper function, check if the current has the permission to create quiz content and if the user has already posted a quiz today. You may need to write a database query to retrieve this information, but I'm not sure, that depends on the way the quiz module was programmed. Return TRUE if the user is allowed to post a quiz, return FALSE if not.
In a hook_menu_alter implementation, change the access callback property of the quiz creation form, setting it to the helper function you just wrote. This will deny access to the quiz creation page if the use is not allowed to create a new quiz.

Hope that helps.


How to change "Image style" of an Image field in a given view mode programmatically (as on "Manage display" tab after clicking the gear)? I would like to change the "Image style" of some Image fields in some given view modes, which are attached to particular content types; I would like to do this programmatically.

This is what I would like to change:

How should I do this?

Something like this should do it:

$entity_type = 'node';
$bundle = 'article';
$field_name = 'field_image';
$view_mode = 'default';

// Get the instance info
$instance_info = field_info_instance($entity_type, $field_name, $bundle);

// Change the image style
$instance_info['display'][$view_mode]['settings']['image_style'] = 'new_image_style';

// Save it
field_update_instance($instance_info);


theme profile2 fields on registration form I have two profile types
teacher and student

so far I have used profile2 module and the profile 2 registration path module.
I have the core fields added

I am trying to add profile2 fields to my user-registration template

So far my template looks like this

<?php
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
?>

<?php print drupal_render($form['account']['name']); // prints the username field ?>
<?php print drupal_render($form['account']['mail']); // prints the mail field ?>
<?php print drupal_render($form['account']['pass']); // prints the password fields ?>

<?php print drupal_render($form['actions']['submit']); // print the submit button ?>
password is not being displayed

I am not sure how i can add profile2 fields to my registration form.

This link should help you in achieving it.


Taxonomy not working with the ECK module I have created a image gallery using the ECK  module and for some reason the taxonomy is not working.

These are the step I follow to created the image gallery.

  Created a Entity called Media
  Created a Bundle called Pictures
  Add a Image Field (image field is from Flickr Field so all the images are been pull from Flickr)
  Add a term reference field (taxonomy)
  I created a views to display the images (http://test-darrylnorris.gotpantheon.com/media/pictures-gallery)
 Finally add some images to the entity media --> bundle pictures and some taxonomy.

But when I click on the taxonomy term is showing me this error

  There is currently no content classified with this term.

That's not true they are different taxonomy using the term. Also I'm using the Content Taxonomy  to provide the Auto-complete field.

How can I troubleshoot this problem ? Or why my taxonomy terms are not working?

Someone answer my question on Drupal.org forums.

  Taxonomy only works with nodes. It's been hard-coded that way.

https://www.drupal.org/node/2339147#comment-9151769


How can I programmatically load and display all available blocks? $block = Drupal\block\Entity\Block::load($block_id);
ksm($block);

This code loads only one specific block. But how can I load and display all available blocks?

Using the service plugin.manager.block we will get all blocks available definition.

$blockManager = \Drupal::service('plugin.manager.block');

$contextRepository = \Drupal::service('context.repository');

// Get blocks definition

$definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

To get details about one specific block you can use below code.

print_r($definitions['help_block']);


How do I create an AND filter for the same field I am having a problem with a view filter. I have one field called Category. The field contains a comma separated list of id numbers that represent different categories. I want to create a filter that will filter out all records that contain one id number, but not another. So my filter is Category=5601 AND Cateogry<>5612. Whenever I create this filter, the result ends up as OR instead of AND.

By default, drupal filters with AND. Maybe you clicked the rearrange and/or option by mistake intsead of just adding a new filter. Try removing both and creating again by clicking add.


Dealing with node language when manually updating node I'm trying to manually update a node and I'm not sure how the language works.

The node is in English, so $node->language = 'en';

However, all my fields data are organized like this in the node:

$node->field_name['und'][0]['value']

I thought 'und' means "language undefined", so shouldn't it be 'en' instead?

I'm trying to automate the process so is it safe to assume fields will always use 'und' in nodes?

Yes - it is safe to assume this. The locale module will deal with this by setting it to the language code of the default language, ex 'en'.

Citing from: http://drupal.org/update/modules/6/7#drupal_language_none

In Drupal 7, the LANGUAGE_NONE constant should be used for nodes or other items that do not have a specific language associated with it.

http://api.drupal.org/api/drupal/includes--bootstrap.inc/constant/LANGUAGE_NONE/7


Getting the value of a user reference field and using it to display information about that user I am quite new to module development although I have experience in modifying existing 6.x block modules developed by others. I have a need to develop a 7.x module and in spite of a lot of documentation reading seem to be missing a basic starting point. I have been looking at the documentation on drupal.org and other third party sites but through my own fault seem to be missing a basic concept.

The site I am working on has a content type called project. At present there are many project pages busing this content type. One of the field types is a User Reference field, called key_contact.

The idea is that I need to create a block that gets the key_contact's username (stored as an id number in the key_contact field) and then from that number perform an SQL query, on another table, to get the id's details and then display them in a block.

At present I have a View that can return the id and I have been asked to replace this view with a module that does the entire job.

Once I get the id for the key_contact I will have no trouble with the SQL query and formatting the output how I want it. I am familiar with creating a block module.

Where I am stuck is understanding how to get the key_contact value from the content type project page when it is loaded.

I would appreciate it if I could either be shown documentation or an example, or even an explanation, that will show me how to extract a field value from a content type like this.

You will have to use Views for Drupal 7. First time you will have to do it manually.
Then you can convert to module using Features module. Features will give you an auto generated module that will product the same view block on the behalf of Views.


Use a twig variable inside a twig render I am rendering a node field (which is an url to an image) in the node template file like bellow

Works as its supposed to, but i have some logic which tests which exact image field to render and i would like to render the field name from a variable, like so bellow (WHICH DOESNT WORK obviously :) ).

Where MYVARIBLE is the name of the field. Is this even possible in twig?
I know i can archive this with an conditional clause since there are only 2 possibilities for the field name, but this way is more

You can use the variable inside of the method get():

{{ node.get(MYVARIBLE).entity.fileuri }}


How do I create a url for views that displays values using exposed filter? I created a view block that displays in table where there is an exposed filter called category:

Category | Data
A           1
A           2
B           3
C           4

now I want to create multiple html links where their url points to
a page where this view block is displaying.

However in this page I only want to display the data view where certain filter is activated

example:

Link 1 > url points to page x with view only showing items with category A
Link 2 > url points to page x with view only showing items with category B

How do I create a url for views that displays values using exposed filter?

I think you want to use a contextual filter, not an exposed filter. The contextual filter will take an argument (such as the category term id or node id, depending on whether it's a taxonomy term or a node) and filter out all other nodes.


overlap dropdown menu and slideshow I use Zeropoint theme and the drop-down menu in this theme.
When I hover the mouse over a menu, and the menu is expanded, my submenu is placed under the slideshow and is not show completely.

Do you have any suggestion on how to solve it?

I have this problem using things like Views Slideshow and NiceMenus.  You can perhaps fix it by changing the CSS of the menu to include the following: z-index: 99. If you post a link to the site I can give you a more detailed answer.


How to change checkboxes options with ajax callback I'm sorry if this is repeated somewhere, but I really did try to look and couldn't come up with anything.

My scenario:

I have a form, and within that form I have a div/wrapper, with two elements in it: a) a text field and b) a checkboxes element

I have two different elements that change the values/options of those using the #ajax attribute

1) a textfield that, when changed, updates the value in a) and populates the options in b)
2) a button that's pressed (after the user enters some data) that adds an option to b)

1) works fine
2) semi-works; when you add (x), it doesn't show up (though the data gets stored in the DB fine). If you immediately add (y), (x) shows up in the options, but not (y). Add (z), and (y) shows up, and so on; so, it's always one back....

1) and 2) use different callback functions, but utilize the same wrapper

The form:

function waiver_create_waiver($form, &$form_state)  {
  $form['id'] = array(
    '#type' => 'textfield',
    '#title' => 'ID',
    '#ajax' => array(
      'callback' => '_update_user_info',
      'wrapper' => 'user-info-wrapper',
    ),
  );
  $form['user_info_div'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['user_info_div']['username'] = array(
    '#type' => 'textfield',
    '#title' => 'User Name',
  );

  $id = trim($form_state['values']['id']);
  $user = user_load_by_name($id);

  // Create the checkboxes
  $user_hardware = _get_users_hardware($user);
  $hardware_options = array();
  foreach($user_hardware as $h)  {
    $hardware_options[$h['hid']] = $h['hardware_type'] . ' (' . $h['manufacturer'] . ') ' . 'S/N: ' . $h['serial_number'] . ', Last Seen: ' . date('D, n/d/Y g:i a', $h['last_seen']);
  }
  $form['user_info_div']['selected_hardware_checkboxes'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Select Registered Hardware'),
    '#options' => $hardware_options,
  );

//...some textfields and selects for entering hardware info, removed for brevity...

$form['register_hardware_fieldset']['register_button'] = array(
  '#type' => 'button',
  '#value' => 'Register New User Hardware',
  '#ajax' => array(
    'callback' => '_update_hardware',
    'wrapper' => 'user-info-wrapper',
   ),
);

return $form;
}

Callback for 1) $form['id']['#ajax']

function _update_user_info($form, &$form_state) {
  $id = trim($form_state['values']['id']);
  $ldap_search = ldap_connector_query_ldap(trim($id)); // This is a custom LDAP query function
  $form['user_info_div']['username']['#value'] = ucwords(strtolower($ldap_search['cn'][0]));

  return $form['user_info_div'];
}

Callback for 2) $form['register_hardware_fieldset']['register_button']['#ajax']

function _update_hardware($form, &$form_state)  {
  $id = trim($form_state['values']['id']);
  if($id != NULL && $id != '')  {
    $user = user_load_by_name($id);
    // If the user isn't on the site yet, create an account for them
    if(!$user)  {
      $new_user = array(
          'name' => $id,
          'pass' => user_password(),
          'mail' => $id . '@email.com',
          'init' => $id . '@email.com',
          'status' => 1, // Active user
          'roles' => array(DRUPAL_AUTHENTICATED_RID => "authenticated user"),
      );
      $user = user_save(NULL, $new_user);
    }

// ...Find $hardware_type and $manufacturer from elements cut from above for brevity...

    // Insert the hardware in to the database...
    db_insert('waiver_hardware')->fields(array(
      'user_id' => $user->uid,
      'date_added' => REQUEST_TIME,
      'hardware_type' => $hardware_type,
      'manufacturer' => $manufacturer,
      ))
      ->execute();
  }
  return $form['user_info_div'];
}

EDIT: I've tried adding the options to the checkboxes element within the callback, as well as making the $form a reference call, but to no avail.

I think the problem is simply a matter of the order the functions are run in.

The AJAX callback will run after the form has been built. So even though you're adding the new item to the database, the code to build the checkbox options (from $user_hardware = _get_users_hardware($user); downwards) has already run. Since it's already run, the new DB item won't be shown until the next time the page is loaded.

If that is the problem the fix would be as simple as adding a bit of code to the end of your _update_hardware() function, to populate the new options:

// ...

// Insert the hardware in to the database...
db_insert('waiver_hardware')->fields(array(
  'user_id' => $user->uid,
  'date_added' => REQUEST_TIME,
  'hardware_type' => $hardware_type,
  'manufacturer' => $manufacturer,
))->execute();

$hardware_options = array();
foreach($user_hardware as $h)  {
  $hardware_options[$h['hid']] = $h['hardware_type'] . ' (' . $h['manufacturer'] . ') ' . 'S/N: ' . $h['serial_number'] . ', Last Seen: ' . date('D, n/d/Y g:i a', $h['last_seen']);
}

$form['user_info_div']['selected_hardware_checkboxes']['#options'] = $hardware_options;

return $form['user_info_div'];


Hide Uploaded Files in File Field in Node Edit Form I have a custom content type, Contacts. Under contacts I have a custom File field, Contracts.

I want to hide the any file that have been uploaded under the File Field, Contracts in the node edit form. It should be view-able only by the admin.

I want to display the upload option in the field to all the users, however, not the files that have already been uploaded under the node.

Please advice

Thanks

The modified code:

MODULE NAME = Hide_Uploaded_Files.

CONTENT TYPE = Candidates.

CUSTOM fIELD = field_resume.

<?php
function Hide_Uploaded_Files_form_alter(&$form, &$form_state, $form_id) {
global $user;
if ($form_id === 'Candidates_node_form' && !in_array('administrator', $user-
>roles) && $form['field_resume']['und'][0]['#default_value']['fid'] > 0) {
$form['field_resume']['#access'] = FALSE;
}
}
?>

Create a custom module and implements hooK_form_alter(). and set field access to false for other user except administrator.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id === 'CONTENTTYPE_node_form' && !in_array('administrator', $user->roles) && $form['field_image']['und'][0]['#default_value']['fid'] > 0) {
    $form['field_image']['#access'] = FALSE;
  }
}

MODULENAME = Your costom module machine name.
CONTENTTYPE = Your content type machine name.
field_image = Your custom file field machine name.


How do I use non-admin theme for page containing node form? I've created a custom route where I return node add form with a controller. It works fine, but for the administrator user it is using the administrator theme.
I tried using the following, but it doesn't help.

  options:
    _admin_route: FALSE

Is there a good approach to achieve this? As I remember, in Drupal 7, it worked fine with hook_admin_paths().

Well, the issue was related to the bug in metatag module, it was in version 8.x-1.0-beta11.

It caused break of my routes when they ended with /add. It was trying to handle prefix of path as entity type, so my routes worked fine only if I had _node_operation_route: TRUE in route options. But if this option is set _admin_route: TRUE is added by core.

I updated metatag module to the latest version (8.x-1.0 currently) and found they've added check for existing entity type, so I'm not forced to use _node_operation_route: TRUE anymore and I'm able to output custom routes in a default site theme.


How do I put a  around a form? I have created a form that I will embed in my page with a custom module. How can I wrap this form with a div that has a specific class?

I need to add it to the build which is made with the following code.

$build = array(
          'form' => $form,
          '#type' => 'markup',
          '#markup' => $html,
          '#attached' => array(

             'library' => array('pup_viewfiles/sortfiles_libraries'),
            ),
        );

There are many different ways to add markup to a form in Drupal 8.  In your build array, you could add a wrapper element, and then nest the form within:

$build['wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'my-form-wrapper', 'class' => ['my-form-wrapper']],
];

$build['wrapper']['form'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

Alternately you could add a '#prefix' and a '#suffix' to your form.

$form['#prefix'] = '
';
$form['#suffix'] = '
';

Or you could use a template for your form and add it to your theme, using the suggestion form--form-id.html.twig and add custom markup there.  (Be sure to replace underscores with hyphens in the template name.)

  <form{{ attributes }}>
    {{ children }}
  </form>
</dv>


Get only some fields with EntityFieldQuery? Drupal 7 has very promising ORM-like system of queries with EntityFieldQuery.

Currently, I understand how to make selection of nodes, but the result doesn't contain any specific information, like fileds, I'm looking for.

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'event')
                        ->propertyCondition('status', 1)
                        ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
                        ->fieldOrderBy('field_date', 'value', 'ASC')
                        ->execute();

So we need to load entire data of nodes, if we would like to get only values of one field, for example 'field_date' in current example.

$nodes = entity_load('node', array_keys($entities['node']));

If there is a way to get the value of fields, instead to load full data of all nodes, as it provokes some memory overload.

$nodesFieldDates = ???

Great question!

EntityFieldQuery  is truly good stuff,  but if you really want to get serious, you have to override the class in a custom module and add whatever behavior you need done in there.

I don't know your exact intentions, but I have referred myself to this article on the subject in the past.  Credits to Neil Hastings for this well written write-up.

Look for code examples a bit into the article for nice examples of overiding.

Hope that helps, happy coding!


using $GLOBALS['base_path'] A quick one - is it ok to use this? I can't seem to get access to $base_url in my node which is set in my settings.php file.

No, it's not OK to use it directly. Always use base_path() function instead. There are two benefits:

You will not risk accidental change in the original variable, so you will not cause other modules to fail if you'll make a mistake.
If, for whatever reason, Drupal will change way it stores base path, your module will continue to work properly.


field_collection_item not updating / old data preserved I am using SalesForce suite to pull data from SalesForce to Drupal.

In the SalesForce object I have multiple date fields.  These fields needs to map to a field-collection in the node.  The field-collection can have multiple (unlimited) values.

So for example in the SalesForce object I have

sales_force_object -> start_date
sales_force_object -> event_date
sales_force_object -> end_date

which needs to map to

node -> the_dates [0] = sales_force_object -> start_date
node -> the_dates [1] = sales_force_object -> event_date
node -> the_dates [2] = sales_force_object -> end_date

The solution was to add 'temporary' fields on the node, let's call them:

node -> sync_start_date
node -> sync_event_date
node -> sync_end_date

When I get data from SalesForce (using pull; and yes the data comes through OK) - I map the values from the SalesForce object to the sync fields.  Then just before the node is saved (updated), I use hook_node_presave to take values from the sync fields and create the field-collection items.  This is the code:

  $fc = field_collection_item_load($key_dates_entity_id);
  $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc);
  $fc_wrapper->field_date->set((int) $date);
  $fc_wrapper->save();
  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

You can safely assume that $key_dates_entity_id is the correct field-collection entity ID.

Inspecting the code I can see the entity is correctly updated (nothing wrong with the data), and when I check the MySQL general-log, I can see the data being saved to the database, however, when the set of instructions end, the old (cached) data is also saved.  In other words the DB is updated twice - once with the new value, and once with the old values: net result is field collection items are not updated.

I have tried all sorts of combinations - nothing works.  Any help please.

I would love to tell you why, but I have not been able to figure it out: I just know it works.

Initially I executed the code above in hook_node_presave($node), but obviously it did not work.  So I figured I should try hook_node_update($node) - but that did not work either.

Then I discovered drupal_register_shutdown_function and now my hook_node_update looks like this:

function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    drupal_register_shutdown_function('_update_from_sync_fields', $node);
  }
}

node_type is the type of node I am checking against.  Any case, once the node is actually saved - that is all processing is done, db transactions completed, etc - drupal will call my shutdown function.  Now when I update the field values, and in specific field-collection fields - they are saved.

Of-course saving these fields and calling:

  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

at the end of my shut-down function triggers hook_node_update again, but fortunately I have a token that tells me - so I do not execute the code again.

This solution works - what I am not happy about is the fact that it executes when Drupal is shutting down.

I think the problem is related to the fact that node_save starts a DB transaction, and when I update related entity (field-collection) items in hook_node_save or hook_node_presave I am starting another (nested) transaction.  Clearly my transaction updating field-collection items completes, but when the outer (first) transaction then complete, it is writing old/dirty data.

The trick is going to be to clear the dirty data from cache.  I was hoping entity_get_controller('node')->resetCache([$node->nid]); would do that - but clearly it does not?

So next I changed the hook_node_update to :

function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    _update_from_sync_fields ($node);
  }
}

in other words - from hook_node_update I simply call the 'shut-downfunction, then I rebuilt the drupal registry (drush rr`) and voila - it worked.  Now I am even more confused.  It is possible that my original code worked all along, but there was something wrong with the registry (or caches).  All things being equal, all the examples I read was right.

From hook_node_update, load the field collection entity, update and save the entity.  The clear the caches and do a field_attached_presave and field_attached_update like so:

  entity_get_controller('node')->resetCache([$node->nid]);
  field_attach_presave('node', $node);
  field_attach_update('node', $node);


Advaced forum area going off-page in firefox browser? I have installed advanced forum and facing the weird issue. When I hover on the configuration button gear the area covered by it shows off-page as in the image(dotted line which automatically shows in drupal modules). I did check on two sites, in case my one site has the css issue. And due to this in my one site the page border of the main-content page sifting all the way to left. You can see the dotted line in the image. For the complete views I have zoom out the browser and you can see the how entire layout gets sifted in the second image.

Edit-2:

I have created the sandbox link with a Username: admin and password: admin. If you hover on the configuration gear of the views forum tab, it shows dotted line, but the left side dotted line has no end (off the page). Why this issue matters because when I create the page-border, page border also gets off-page along with that. This happens with Firefox browser only as described in the Edit-1.

Edit-1:

I did check in all browsers, and this is happening in Firefox browser only. My current browser is 45.0.1 which is the latest one. I did check in chrome and safari also, but there is no issue.

The issue that a contextual link is causing your page to break. Please note that this issue only occurs for users that have permissions to modify panels, so your end users (visitors) should not see this.

The solution could be to disable the contextual link on the panel. Or disable the contextual links module entirely (what would remove the gear icon everywhere).

To disable contextual links only on some pages you might want to look at this question for how to disable a specific link: Is it possible to remove the contextual link for deleting a node?

Or you could try the Hide Contextual Links module.

UPDATE:

The main cause of this issue is a firefox bug, where outlines are drawn around descendant elements: https://bugzilla.mozilla.org/show_bug.cgi?id=687311

You can see it asked here on stackoverflow: https://stackoverflow.com/questions/10662902/css-outline-different-behavior-behavior-on-webkit-gecko, where the recommended action is to replace the outline with a box-shadow (no dashes), or the alternative to append overflow: hidden to the element. I tried with overflow: hidden and that worked so I'd try that first to keep the dashed line.

In Drupal, in you theme's css add:

.contextual-links-region-active {
  /* Override the old outline */
  outline: none !important;

  box-shadow: 0px 0px 0px 1px #FFF;
  /* OR */
  overflow: hidden;
}

But once again, this is a firefox bug that is likely to influence only administrators who have permissions to modify panels (I have no idea about the company you are building this for, but that cannot be many users). So ask yourself if it is worth putting effort into this.

UPDATE-2: by@codenext,

As @Neograph734 has provided the very nice research on this issue in above UPDATE(basically it is FIREFOX BUG). Please follow the following comments and question details to understand the issue. I am just providing the final solution as final solution is just the extension of this answer.

SOLUTION: The main issue is, the outline(left part) of the contextual-link-region goes off the page as shown in the second image above(a dashed line area), and along with that it takes the page-border/outline css off the page too. Hence we can put the overflow:hidden; in the #page/#content-column selector(as in my case, I have put border: and outline: css in these selectors) instead of putting it in .contextual-links-region. Hence, this way you can prevent the displacement of page-border and outline which caused the .contextua-links-region(originally the firefox bug).


Is it dangerous to call a function that deletes nodes based on criteria while a cron job is running that imports them I have custom module that performs a dbquery on a button click that deletes nodes that fit a certain criteria. Is it dangerous that I also occasionally run a cron job that imports nodes that fit this criteria? If I ran both at the same time could something break?

Depends on the way you import:

If you delete the nodes on some criteria and import the nodes as new nodes ($node->is_new = TRUE), this shouldn't be a problem.
If you are updating the existing nodes while importing and deleting the nodes at the same time, then there could be issues.

This is because the node_save() function internally calls drupal_write_record, which creates a node with an incremental nid value if the $node->is_new is set to TRUE. Or updates the exiting nodes if you are importing.


Render block in twig file drupal 8 I have created a block in custom block library, i need to render the block on all pages except home page.

Unfortunately I need to do it in twig file only because of ui issues if I enabled in the block layout UI

In twig file how can I render the block in drupal 8.

Thanks

Add following code in "themename.theme"

function themename_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('block_id');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
 $variables['your_block_name'] = $block_content;
}

in twig template file use following variable

{{ your_block_name }}


What are my alternatives to disable update notifications but without using module Update Notifications Disable? I need to disable the update notification overall Drupal 7, rather than downloading the module Update Notifications Disable because it caused a fatal error, and the site went down.

Is there any other way?

The method below will stop the "available update" emails Drupal admins receive.

Go here: http://yourwebsite.com/admin/reports/updates/settings
Remove your email(s) from the textarea: "E-mail addresses to notify when updates are available"
Save

Note: If you want to stop the "available updates" emails and the update alert messaging then simply disable the update module from http://yourwebsite.com/admin/modules


Translating variables with context in Twig templates In Drupal 8, with English and German enabled, I am trying to translate a variable using a specific context.

When visiting a page in German:

{% trans with {'context': 'Long month name'} %}
    March
{% endtrans %}

  This outputs März which is fine.

{% set month = 'March' %}

{% trans with {'context': 'Long month name'} %}
   {{ month }}
{% endtrans %}

  This outputs March which is not fine.

Why? And how am I supposed to translate variables in a Twig template?

Here is the documentation I have read.

Edit: https://www.drupal.org/node/2357633

This mentions:

  The t filter will run the variable through the Drupal t() function, which will return a translated string. This filter should be used for any interface strings manually placed in the template that will appear for users.

And also:

  The following patterns are unsafe and should not be used because they pass a variable directly to translation. This not only inflates the list of strings for translation but is also a potential vulnerability, particularly if the output can be entered by a user.

{{ var1|t }}
{{ var1|placeholder }}
{% trans %}{{ var1 }}{% endtrans %}

In Drupal 8, you can translate a string in a Twig file with a specified context in two ways :

{{ "Text to translate"|t({}, {'context' : 'Context name'}) }}

and

{% trans with {'context': 'Context name'} %}
    Text to translate
{% endtrans %}


How do I return 500 for fatal errors? When I am trying to access Drupal and the database is down, it will return a 500 error. However, when I try to access Drupal when Redis is down, it says:

  Additional uncaught exception thrown while handling exception.

  Original
  Predis\Connection\ConnectionException: Connection refused [tcp://drupal-redis-2:6379] in Predis\Connection\AbstractConnection->onConnectionError() (line 146 of /var/www/corp/sites/all/libraries/predis/src/Connection/AbstractConnection.php).

  Additional
  Predis\Connection\ConnectionException: Connection refused [tcp://drupal-redis-2:6379] in Predis\Connection\AbstractConnection->onConnectionError() (line 146 of /var/www/corp/sites/all/libraries/predis/src/Connection/AbstractConnection.php).

The HTTP code returned, however, is 200. This makes it difficult to detect if a server is down for load balancing purposes.

This question is similar to Site is down due to MySQL error but it returns 200/OK but it remains unanswered and is a little different.

This is a known issue, whose fix didn't make it into the Drupal 7 core so far. The culprit can be found within the _drupal_exception_handler(). If another error occurs while handling an exception, it just returns the messages stated in your question without setting HTTP status codes (possibly to avoid further exceptions).

Compare https://www.drupal.org/project/drupal/issues/2666908

The above issue already has a small RTBC patch that solves the problem by adding a 500 status code to the handling of the second exception:

function _drupal_exception_handler($exception) {
  require_once DRUPAL_ROOT . '/includes/errors.inc';

  try {
    // Log the message to the watchdog and return an error page to the user.
    _drupal_log_error(_drupal_decode_exception($exception), TRUE);
  }
  catch (Exception $exception2) {
    // Add a 500 status code in case an exception was thrown before the 500
    // status could be set (e.g. while loading a maintenance theme from cache).
    drupal_add_http_header('Status', '500 Internal Server Error');

    // Another uncaught exception was thrown while handling the first one.
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
    if (error_displayable()) {
      print '
Additional uncaught exception thrown while handling exception.
';
      print '
Original

' . _drupal_render_exception_safe($exception) . '
';
      print '
Additional

' . _drupal_render_exception_safe($exception2) . '

';
    }
  }
}

Given the age of that patch, the line numbering differs a little from the current version of bootstrap.inc. But it still applies cleanly and works as expected.

After you patched your Drupal, you should be able to receive the 500 error code at your load balancer, if Redis is down or the error page can't be created for another reason.

Please note, if your Drupal already sent headers/output to the browser before the error handler kicks in, above patch may have unintended side-effects. You may have to test yourself, whether your webserver still generates 500 server errors for these edge cases.


Column multiplication and keep the result in separate column I am trying to create a report where in I want to perform the column  multiplication and keep the result in separate column, say column name as "total" and finally need to calculate the sum of the total column.
So far I have tried with view calc module and searched for other option but I am stuck I am not able to achieve this! I have attached a simple report also. Can anyone help on this please?

Have you looked at the Matrix field module? It provides a table with fields in each cell, it's possible to define calculations in some of the field.

I'm the co-maintainer of the module if you have any problems.


Functional testing without using simpletest I have recently joined a Drupal project at work that is approx 50% finished.  Functional testing was never part of the project. The site has about 8 custom modules and they are not going to be used anywhere but with this client. I tried implementing the testing module in D7 but the modules were not created in a way that allows the modules to install cleanly. I tried to get them installable but I don't think there will be enough time to devote.

So, I need a solution that will allow me to test the new features we are building without having to fix the previously built portions.

I looked at Selenium but to my knowledge it requires the feature to be built before the script can be recorded. I'd like to use it Test Driven Development style. I have also been looking at Behat but honestly, I don't get it.

This question is more specific than "what is your favorite functional testing framework?". It is more specifically, "What functional testing framework works well with Drupal and works with our site as it is currently developed?".

I ended up working with Behat (http://docs.behat.org/en/latest/) and Mink for Behat (http://mink.behat.org/en/latest/) to write tests that emulated a user using a browser on my website.

However, I still needed Drupal integration for quick access to nodes, users, and roles.  I found this project (https://www.drupal.org/project/drupalextension) which incorporates Behat, Mink, and the Drupal API.  This allows me to write tests like this:

@api
Scenario: Logged out user can access the custom Landowner registration page
    Given I am not logged in
        And I am on the homepage
    When I click "Register here"
        And I am on "/register"
        And I click "Register as a Landowner"
        And I am on "/register/landowner"
    Then I should see "Landowner Registration"

Now I can test a Drupal site without the issues involved with Simpletest.


extend site information with fields How can one add fields to site information section?

Maybe explaining the purpose can lead to an other approach.
Building a template site for Hotels/B&B's wich needs to feature simple re-usablity. For example the address data, contact data, location etc centralized to make it easy to setup an new instance of the template.
Sure I can use something like this, but I don't know I can use special fields like location or address fields.
.

 'checkbox',
      '#title' => t('Use my setting'),
      '#default_value' => variable_get('extended_siteinfo_extra_setting', TRUE),
    );
  }
}
?>

Maybe creating a content type site-information and creat one node with the info, is an easier approach but it feels very wrong...

What I do is create a content type for storing this data and use Views to display/output the attached fields as a block.

Views itself natively supports importing and exporting (if I'm not mistaken through Chaos tool suite (Ctools)), and to copy the content type you could use Bundle copy.

This allows me to easily reuse parts of website structures in other projects.


Redirect form out of modal window after submit I have a form within a Colorbox Modal window which successfully submits using the _submit handler. I then successfully redirect the form to another page (which pre-loads a few fields on another form) using drupal_goto(). The problem I am having is that redirect stays in the Colorbox Modal window. I need to somehow close the modal window and transfer the url of the new form to the parent window. I can get this to work with a jquery function of

$(#my_form_id).submit(function (){
   parent.window.location="/user/register";
});

The problem with this issue is that the function calls when my form is submitted while disregarding anything that happens in the submission handler. So what ends up happening is I get the new page/form without the pre-loaded values until I refresh the page.

Do you have any thought or idea?

I would suggest using #ajax to submit the form and then allow the response to close the modal and go somewhere else. For example, here's a submit button that runs a function on click instead of submitting the form and reloading the page:

$form['submit'] = array(
  '#prefix' => '

',
  '#type' => 'button',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_super_cool_ajax_callback',
    'wrapper' => 'super-cool-wrapper',
    'method' => 'replace',
  ),
);

And then in your callback function:

function my_super_cool_ajax_callback($form, $form_state) {
  // Do what you normally would with the form submission.
  return '';
}

Now you can process the form as needed and return a response that simply redirects the user.


How do I use the geoip_language_redirect module? I am working on a multilingual website, and I have setup the multilingual concept successfully.
Now I want to redirect the users to the corresponding language URL based on the IP address or country. For example, if users are from france, I want to redirect them to http://www.example.com/fr like.

I found the geoip_language_redirect module, but I don't know how to use it.

Can anyone help me on this?

As the project page says, after you installed the module, you need to set up the geoip_redirect_mapping persistent variable with an array that associate the ISO country code with the language.

variable_set('geoip_redirect_mapping', array(
  'GB' => 'en',
  'FR' => 'fr',
  // …
));

For example, put the following code in setup.php, and save it in the same directory where Drupal has its cron.php and index.php.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
variable_set('geoip_redirect_mapping', array(
  'GB' => 'en',
  'FR' => 'fr',
  // …
));

Visit http://example.com/setup.php, and the variable will be setup. After this, you can delete the file.

If you have Drush, then you can alternatively execute the following command from the site directory (from the terminal).

php -r "print json_encode(array('GB' => 'en', 'FR' => 'fr'));"  | drush vset --format=json geoip_redirect_mapping -

For the rest, the module automatically redirects the users.

Please note the following

The project page is a little confusing. It's not clear if the persistent variable is geoip_mapping or geoip_redirect_mapping. I didn't find in the code any reference to that variable, so I cannot confirm which one is correct. I would try geoip_redirect_mapping, since that is the one used from the example code; if that doesn't work, I would try geoip_mapping. If neither of them works, I would open a support request for the module, if there isn't one already, asking to change the project page to make it clearer.


Database::setActiveConnection not working as expected? kint(Database::setActiveConnection('preview'));
\Drupal::logger('Little kitties')->info('Mau');
kint(Database::setActiveConnection('default'));

As my expectation this would create a watchdog entry in preview database.
The entry got created in the default database instead.

This means, setActiveConnection() only affects direct queries (select and db_query..)? That would be really sad.

Database::setActiveConnection() doesn't influence those objects that already have a \Drupal\Core\Database\Connection object, which means that the following code will not use the preview connection for altering the database table.

use \Drupal\Core\Database\Database;

$schema = Database::getConnection()->schema();
$old_key = Database::setActiveConnection('preview');
$schema->addField($table, $field, $spec, $keys_new);
Database::setActiveConnection($old_key);

When you call \Drupal::logger(), you get a DbLog object that was already initialised before Database::setActiveConnection('preview') is executed, which means it will use the old connection.

To be able to use the new connection for logging, you should try creating a custom logger that uses the connection you want, without you setting the connection before calling its methods.

As side note, Database::setActiveConnection() returns the old key; it's easy to restore it: Just call again Database::setActiveConnection() passing the value returned from the previous call, as I did with the code I shown.


Nodes not get indexed after running manual cron I'm experiencing some unexpected behavior of cron. I have used search_api module, that should index all nodes. Automatic cron is set to 1 hour. So after every hour, cron will run automatically.

So, the issue is, I created node, and search its content, it is not searchable.

I ran cron, then searched again, still its not searchable.

After 2-3 times hitting cron manually, the content becomes searchable.

Although, for 1-2 content types, content will become searchable after hitting cron for the first time.

I have total 4 content types, and 100 nodes in my whole site.

Forcefully running cron after 3-4 times, make nodes content searchable, else my nodes are not searchable.

Is it the known issue of Drupal core or what would be the problem, I'm not able to figure out as why nodes are not getting indexed automatically? Even after cron run for Ist time, nodes not get indexed.

Any help is really appreciated.

Module used: Search_api (version = 8.x-1.5)

Note: I can't used updated version of search_api as of now, because my current version of Drupal is 8.3.6, and latest release of search_api module is not compatible with this older Drupal version.

EDIT
I have written a custom cron too, to run cron after node gets created, but this is also not solving this late cron run issue.

function mymodule_cron() {
  $nids = \Drupal::entityQuery('node')
    ->condition('created', array(time()-3600, time()), 'BETWEEN')
    ->execute();
  // Load all the nodes.
  $nodes = Node::loadMultiple($nids);
  foreach ($nodes as $node) {
    $node->save();
  }
}

To turn off delayed indexing, navigate to the /admin/config/search/search-api page then click on the 'edit' button for the index.

On that page, at the very bottom, just above the Save button, there is a collapsed panel titled 'INDEX OPTIONS'. Open the panel and it should look like this.

This is where you can control whether indexing is immediate and the cron batch size.


SSL Issues with Mixed Content and Firefox my question is about SSL with Drupal. I've uploaded my certs to my server and got everything installed and working correctly. I've set the base_url to be my https://site domain and also put the following at the top of my htaccess file:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://domain.com/$1 [R=301,L]

Everything seems good on all my site pages on IE and Chrome. But Firefox keeps giving me a mixed content warning:

Firefox is blocking content on this page.
Some unencyrypted elements on this page have been blocked.

Why would it still be saying this if I have a properly working SSL cert (which I do) and it covers my entire site? Is there a way to get rid of it?

Thanks!

When you set $base_url, Drupal always uses it in email absolute links and whenever it has to build an absolute URL.

I have many sites running full-HTTPS, with only the $base_url set to the https URL.

We can't debug your site for you, but check the page source to see if any Javascript files are being served via HTTP.
Google Analytics, Google fonts, Google translate widgets, banners, ad serving scripts, CDN-served jQuery, etc.

Header tracking and other debug features won't probably work in your browser because when the page URL is in HTTPS, browsers do not load HTTP assets. You can still check the page source to see the HTTP references.


I want download window appear instead of showing my mp4 file I upload some mp4 files to my private folder and some users can access those files. this is my code for letting them download my mp4 files:

function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.

  // When done perform the following code
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }
  return -1;
}

my problem: once my user clicks on the link of the file google chrome starts showing the file! although they can right click on the link of the file and download that, but i want the download window appear from beginning! maybe one solution is to zip the file but what about mp4 without zipping?

You can do this using htaccess, Open your .htaccess file and add the following...

<FilesMatch "\.(mp4)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

This should force the browser to do a left click download, rather than play the content. You can do it for multiple files types as well. After the mp4 just add |mp3, so it would look like <FilesMatch “.(?i:(mp4|mp3|pdf))$”>


How to get product name by id from commerce order? How to get product name by id? I want send mail with product name to customer after confirm commerce order.

A product is an entity, so you can use entity_load().

$product = entity_load('commerce_product', $product_id);
$title = $product->title;

Commerce provides its own shortcut, though:

$product = commerce_product_load($product_id);
$title = $product->title;


Changing Commerce Credit Card option to read something else I have two radio options in my form for payment: the first says 'credit card' and the second says 'cheque' (I'm using the PayPal wpp and Cheque modules). The Cheque option is easy enough to change to say something else ('send me an invoice') and I changed that in the store > config > cheque settings.

But, does anyone know how or where to change the text for the 'Credit Card' option. I want to add more information about how we process it to the label itself.

Alter the form that has the form_id of commerce_checkout_form_review:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
 $form['commerce_payment']['payment_method']['#options']['commerce_payment_example|commerce_payment_commerce_payment_example'] = t('AWESOME PAYMENT');
}

The #options array will hold a list of payment methods that are keyed by the payment_method followed by a pipe (|) and then an instance_id. Just update the title accordingly.


Calendar legend on taxonomy via relationship? I'm working on a calendar view to show employees' vacation. For that I setup 2 content types:
-Employee: Name and Department (Term reference to 'Department' vocabulary)
-Vacation: Date field with start and end dates and Employee (Node reference to Employee content type)

I got views to show the calendar with vacation time for the employees, but I want to colorcode them based on the department their in. So I setup the relationship to the Employee content type and added the Department field using that relationship.

Views recognised the term reference field and allows me to set colors for each vocabulary term. Everything looks ok, except the actual calendar view which doesn't show any color at all. There is no "stripe" keyword in the html source.

To test I added a dummy term reference field to my Vacation content type itself to test the behaviour without a relationship and everything works as expected.

So it seems the colorcoding doesn't work on term reference fields via relationships. I could add the department reference field to my Vacation content type, but that would mean have the same reference in both the Employee and Vacation content types, which isn't something I'd like to have.

Has anyone come across this problem or better yet, solved it?
Thanks in advance.

I'm running:
Drupal 7.14
Calendar 7.x-3.4+0-dev
Date 7.x-2.5+15-dev
Views 7.x-3.3+175-dev
Chaos tools 7.x-1.0+32-dev

Try the fullcalendar module if you want to color-code calendar views.

It's also handy because you can display a legend in an autogenerated block that helps users figure out what each color represents, etc.  It's also a good solution because colors are easy to change/update via the admin configuration page.


Print specific field of a specific node I have the content type of "Front Page Section" where there are the fields "body" and "field_home_section_photo".

On the home page (page--front.tpl.php) I would like to be able to print the body and image fields separately for particular nodes with their formatting in place:

Print Node 42 Body

Print Node 42 Image

Print Node 43 Body

Print Node 43 Image

Print Node 44 Body

Print Node 45 Image

You can do this by hook_preprocess_node(&$vars) function. By this function you can check the Node ID then if it is some custom IDs, fetch the appropriate data and assign them in $vars array.

In the aggregate we have

function THEME_preprocess_node(&$vars){
    if(drupal_is_front_page() == true){
         if($vars['node']->nid == 44){
             $newNode = node_load(45);
             $wrapper = entity_metadata_wrapper('node',$newNode);
             $image = $wrapper->field_home_section_photo->value();
 //here use kpr($vars) to get the correct syntax of  field_home_section_photo in $vars
// suppose it is $var['fields']['field_home_section_photo']->value
              $var['fields']['field_home_section_photo']->value = $image;
           }
      }
}

don't forget to install entity module.


how to add dropdown checkbox list in to the search api(facet api) display widget? I want to have a checkbox list in search api(facet api) display widget.  links with checkboxes not user friendly when you have many items, but checkbox list is user friendly. I mean dropdown checkbox list. how can i do it?

What you need to do is:

In your search api configuration (screen you attached), select "MultiSelect element".
Install an appropriate dropdown widget, the jQuery UI MultiSelect Widget is probably the best option for what you need.
Configure the jQuery UI MultiSelect Widget to target your Search API's MultiSelect element:

First, figure out what the id or class of that MultiSelect field is. You can use your browser's "Inspect Element" function to figure that out while viewing the standard Search API Facets on a search page.
Once you have the right class or id, go to the configuration page of the jQuery UI MultiSelect Widget (URL is sth like your.drupal.localhost/admin/config/user-interface/jquery_ui_multiselect_widget) and add it in the "JQuery subselector" text box.

That's it, now you should have a the jQuery MultiSelect Widget rendering your standard Search API Facets MultiSelect field.

Here is a screenshot of the end result (search api block facet rendered as a jQuery UI MultiSelect Widget):

Let me know how this goes!

Appendix A: jQuery UI MultiSelect Widget Configuration

Appendix B: jQuery Update Configuration


Is there any way to reuse the same file or image? Is there any way to reuse the same file or image  while uploading
I just worry about having multiple/duplicate image files on the server - in time it could get full and slow down the server.

I have used FileField Sources module but I think its not compatible with drupal 8 its not showing configuration setup, any other alternative?

The short answer is: Yes!

And you also don't have to wait till 8.4 comes out (however that will make things easier).

I suggest you the following modules:

Media Entity
Media Entity Browser
Media Entity Image

How is it working? (in nutshell):

Instead of using "image fields" you will have reference fields to media entities (Media Entity), which provides you the opportunity to use such an entity multiple times, also by other contents.
Media Entity Image gives you just a predefined bundle to media entity, which is a nice to have.
Media entity browser gives you a widget, which opens a modal, where you can select from existing media images, or upload a new one!

Drupal 8.4 will provide this as a core feature, which will make it more stable and easier to use. But until then: these three modules also do the job.


Taxonomy in Contextual filters for Views I am new to drupal and currently I am exploring the Views module. I have a dummy website for a toy shop to learn on.
I have created taxonomy as follows where "Category," "Ages," and "Brand" are vocabularies, and the rest are taxonomy terms :

Category: Activity Centers, Electronics, …
Ages: 0-2, 2-4, …
Brand: FisherPrice, V-Tech, …

I want to create a view that displays all toys, depending on what has been passed in the contextual filters; for example, if the first argument is a term from the "Brand" vocabulary, the second argument is a "V-Tech" term, then toys belonging to these should get displayed with a URL such as http://example.com/Brand/V-Tech.

I selected "Content: Has taxonomy term ID" in the contextual filter, but I don't understand the next screen. I selected the 'Specify validation criteria' checkbox. There should not be a vocabulary option in the validator drop-down? Can anyone help me from here on?

I cloned the existing default view for taxonomy/term/%, removed all the contextual filter already existing, and then:

I added a new relationship, "Content: Taxonomy terms on node."
I added a new context filter, "Taxonomy vocabulary: Machine name," for which I didn't change any setting. (The Views module already selected the relationship I defined before.)
I added a new context filter, "Taxonomy term: Term ID."

For the "Taxonomy term: Term ID" filter I used the following settings.

I changed the path for the view to "test-term/%" and removed the feed.

The setting page for the view, once done the changes I described, appears as in the following screenshot; I highlighted the parts that are different from the setting page for the view I cloned.

What I obtained is a view that shows the nodes containing the terms from the vocabulary for which I pass the machine name as first argument.

For http://tero.local/dr71/test-term/tags ("tags" is the machine name for a vocabulary I defined in my test site), I get the following result.

For http://tero.local/dr71/test-term/tags/tags (the second "tags" string is the name of a taxonomy term that the "tags" vocabulary has), I get the following.

I didn't find any way to filter out the duplicates that appear in the first case, though. This is would happen only for those vocabulary that allows the users to select more than one term per node.

The relationship with the taxonomy terms is necessary as the view is about nodes; without the relationship, it would not be possible to use "Taxonomy vocabulary: Machine name," and "Taxonomy term: Term ID" as contextual filters. You can check it: If you remove that relationship, you will not able to add them as contextual filters.


Allows users to tag content in Drupal I have what I thought would be an obvious question but after searching for an answer I can't find anything even close.

I would like a way in Drupal to let authenticated users "tag" existing site content by selecting from one of 12 available categories. (They won't need to add any of their own categories.)

The tags they associate with individual nodes should be stored in a separate table with their uid, the nid and the tid they selected. Later this can be used to show tag distributions for nodes, but that's not immediately needed.

What's the best way to do this? The users will of course not have edit permissions on the nodes, they just need to be able to tag them.

If you have only 12, or some other manageably small number of categories, I would investigate the Flag module.  Just set up flags named to your categories and you're off and running.


Drupaliest way to remove login and registration page descriptions How to remove the descriptions from log in and registration page ?

I need to remove the description from the fields which are listed in the images.

These are both log in and registration page.

How can i do this?

you write a hook for user login form alter, then you can set the #description to null. you need something like this:

function YOURMODULE_user_login_form_alter(&$form, &$form_state) {
    $form['name']['#description'] = '';
}


Long text increase maxlength I have added a textarea and i want to store more that 1024 characters in it. Long text is the field type that i have chosen but an error comes up saying :Keywords cannot be longer than 1024 characters but is currently "xx" characters long.I tried using hook_form_alter to increase the maxlength but it does not work. Also tried the hook_form_field_ui_field_edit_form_alter to change the length from 255 to 555 but no success.Is there any other workaround for this ?

Use Field maxlength alter module

  Creating an update hook that alters the field tables
  Installing this module and simply edit the max_length in the admin    interface
  Installing this module and run the Drush command to modify the    max_length


Customising the first item in a view As a block on my homepage I'm trying to output:

Node 1

Node 2

Node 3

Node 4

where each
 represents a node, and the image/text supplied by CCK fields attached to each node.

Currently, I'm using a block view to output nodes 2-4, and an Attachment view to present the first node as outlined here:
http://www.agileapproach.com/blog-entry/the-views2-attachment-display

The problem is my output ends up more like this:

Node 1

Node 2

Node 3

Node 4

I can probably bend that output suit my purpose, but it will involve a lot of templating and configuration. I'd also like to avoid using CSS and/or JavaScript to modify the output, unless that's my only option.

Given this, what's the easiest way to get the output closer to what I need it to be?

Edit: here's some rough php code I'm using in the customfield php code field (based on Jeremy French's suggestion:
 Here's the code I'm using in my PHP Code customfield:

<?php
  ++$static;
  if ($static == 1) {
    $nd=node_load($data->nid);
    $img_path = imagecache_create_path('news_image_thumbnail', $nd->field_image[0]['filepath']);
    print '
Node 1
';
  } else {
    print "Node $static";
  }
?>

I personally use preprocess functions to do this, something like the following:

function HOOK_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'VIEW_NAME' && $vars['view']->row_index == 1) {
    // Do stuff here.
  }
}


Omega Theme: how to change the stacking order of each region for each layout? I´m starting my first theme with Omega. I´ve read the documentation, and managed to understand how it works.
My problem here is that I don´t know how to stack regions in different order for each layout.
I know that I can hide some regions with css and the different css files provided by the omega subtheme, but how to change the order?

Let me explain with an example:

I have this in my wide and tablet (normal) layout:

  HEADER SECTION:

  User Bar First -- User Bar Second -- Branding

  CONTENT SECTION: ...

  FOOTER SECTION: ...

For my mobile version I have this:

  HEADER SECTION:

  User Bar First

  User Bar Second

  Branding

  CONTENT SECTION: ...

  FOOTER SECTION: ...

And I want it to be:

  HEADER SECTION:

  User Bar First

  CONTENT SECTION: ...

  User Bar Second

  Branding

  FOOTER SECTION: ...

Any idea on how to do that?
Thanks!

The browser, not the server, knows the width of the layout. So you cannot change the stacking order on the server side and move the regions or zones up and down without having the browser talk back to the server, which Omega doesn't do.

You could use Javascript to move things around, which is painful. You could also duplicate the content you want to be in the different places, and then hide it or display it with display: none and display: block. But then you are outputting multiple copies of the content and lengthening page load time.

Here's a similar discussion about (not) changing stacking order in Omega: http://drupal.org/node/1343798.


Help with view on multiple pages I experimented for a few hours with drupal (tried contextual filters) and searched across the internet, but couldn't find a solution for my problem. (I'm not a "drupal engineer", so maybe it's very easy to solve this problem, but I couldn't).

I have view that I want to use on multiple pages on our drupal site.
If the user browses to http://www.mywebsite.com/######, is it possible to display that view, but showing only nodes that contain "######" in a specific field in the content type displayed by that view?

edit: when ####### isn't found in that field (if 'ts available in the content type), of course it should not show the view. When ######### isn't provided (http://www.mywebsite.com/), it should display the view without te filter....

You did not specify if this is a block view or a page view.

If it's a page view, you have to use /something/% as your path.

1) Add your field in question as a contextual filter. (I used title as an example)

2) Use Provide a default value

Raw Value from URL
Path is 1 assuming its yourwebsite.com/####. Path is 2 if yourwebsite.com/something/####


How do I define a template file for a specific node ID? I'm trying to define a custom template file for a specific node, using the node ID.
I read a lot of topics saying to create a node--X.tpl.php file in the templates folder.

That's what I did; unfortunately, even after flushing the theme cache many times, nothing changes.

Is there anything more I have to do?

I am using Drupal 7.

In Drupal 7, node--[node-id].tpl.php is used as template file for nodes, as well as node--[node-type].tpl.php. Nothing else needs to be done, except, as Clive wrote in his comment, you also need to have node.tpl.php in the directory containing the template files used by your theme.

Notice there is a difference between node--[node-id].tpl.php, and page--node--[node-id].tpl: The latter is also used for pages at node/[node-id]/edit, or node/[node-nid]/delete. See the comment at the beginning of theme_get_suggestions().

  Build a list of suggested theme hooks or body classes in order of specificity. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, for $base = 'page', http://www.example.com/node/1/edit would result in the following suggestions and body classes:

 page__node              page-node
 page__node__%           page-node-%
 page__node__1           page-node-1
 page__node__edit        page-node-edit


do not optimize/remove html I would like to have a page with some html content in it that CK Editor does not seem to support, in particular: I want to have a little <form tag with a couple of <input fields. I can enter it in Switch to plain text editor mode and save from there and it will keep the elements but when I want to edit the page, it'll go back to the Switch to rich text editor and remove my <form html items. How can i set CD Editor to not remove any html it may not be able to render?
Thank you!

Depending on which one you are using (filter or full html) You need to go to

/admin/config/content/formats/filtered_html

OR

/admin/config/content/formats/full_html

Then under Limit Allowed html Tags add <form> <input> into the list.

If that does not do it, try unchecking the correct faulty and chopped off html box.

Edit:

If you want to switch between text formats and not have your code erased go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.


How to filter users based on address location? I have a content type "job". There is a field "location" which contains the zip code of area. Now i want to filter users based on distance from job's zip code. Each user also have a zip code.
I already have a view which is filtering users on different criteria. Is there any way to achieve this in view?

EDIT
here is what exactly i needed.
adding a job should have a field to add the zip code of the location of the job. This should change the way the users are filtered for the job as the customer should be able to filter the users using radius selector for 1 km, 5km, 10km, less than 50 km.
Thanks


User listing not showing up with user reference when create programmatically I am using the References module to create a User Reference programmatically.  However, when I use the field that is created, there is no listing of the users to choose from.  The User Reference works when I create a field from the UI.

I first create the field as follows in my hook_install function:

    $field = array(
        'field_name' => 'vendor_user_reference',
        'type' => 'user_reference',
        'cardinality' => 1,
        'entity_types' => array('commerce_product'),
        'translatable' => FALSE,
        'locked' => TRUE,
    );
    field_create_field($field);

I then call when the product type is created the following code

$instance = field_info_instance('commerce_product', 'vendor_user_reference', $product_type['type']);

if (empty($instance)) {
    $new_instance = array(
            'field_name' => 'vendor_user_reference',
            'entity_type' => 'commerce_product',
            'bundle' => $product_type['type'],

            'label' => t('Vendor User Reference'),
            'required' => TRUE,
            'settings' => array(),
            'widget' => array(
                'type' => 'user_reference_autocomplete',
                'weight' => -10,
                'settings' => array(
                        'autocomplete_match' => 'contains',
                        'size' => 20,
                        'autocomplete_path' => 'user_reference/autocomplete',
                ), //end setting array
            ), //end widget array
            'display' => array(),
    );
    field_create_instance($new_instance);
}

This creates the field on the entity/bundle, but when I try to use it from the UI, there are no user listings.  This is the case if I use select list or autocomplete.

What am I doing wrong?

Programmatically create user reference field

I have found the solution to having the user reference field populate the user option list programmatically.  You need to initialize the referenceable_status settings when defining the user reference field.  See my answer in the Question above.


combining messages and content types in views I am using the Message  module to tell people when nodes are created, deleted or edited.  Is there a way to combine the messages module with my nodes in views.

What I want to do is show a message of a node being deleted or edited, and then show some fields of this node.  I tried using tokens inside the message module, but that does not seem to do the trick.

Workaround:

Use Drupal hooks on create/edit/delete of node, then create a custom message type that just takes text field (no entity reference).

Then in your hooks create the new message type and add for its field value the message text constructed from the node fields. Embed links to node if node is still available.

$message = message_create('general_alert');
$wrapper = entity_metadata_wrapper('message', $message); // populate with node data

// Set necessary fields to use with tokens.
$wrapper->field_message_text->set(array('value' => $text));
$message->save();

Or even better, include both an entity reference field for your message and a text field. Add the entity reference when creating/updating the node, and populate the text field when deleting the node.


Move Multi-lingual Content with Migrate Module I've got a single MySQL table with mixed english/french content in each row.  I'm trying to figure how to migrate this into a proper i18n configured Drupal site.

I can get Migrate to import the content into one language, but I want it to import it into both languages.  There are 901 rows, so it should ultimately create 1802 nodes that are linked.

I just can't figure out how to set up the Migrate module to loop through twice & link the nodes.

EDIT: I used this and was able to merge the two:

public function postImport() {
parent::postImport();

// $ii should really be determined by $count_query
$ii = 2000;
for ($i = 1; $i < $ii; $i++) {
  // Confirm SQL in phpMyAdmin to verify
  $query = "SELECT n.nid, tid.field_bv_transfer_id_value
    FROM {field_revision_field_bv_transfer_id} tid
    INNER JOIN node n ON tid.entity_id = n.nid
    WHERE tid.field_bv_transfer_id_value = $i;";
  $result = db_query($query);

  // Reset for each import
  $currentRowCount = $current_translateid = 0;
  foreach ($result as $record) {
    if ($currentRowCount % 2 == 0) {
      $node = node_load($record->nid);
      $node->pathauto_perform_alias = FALSE;
      $node->tnid = $record->nid;
      $current_translateid = $record->nid;
      node_save($node);
    } else {
      $node = node_load($record->nid);
      $node->pathauto_perform_alias = FALSE;
      $node->tnid = $current_translateid;
      node_save($node);
    }
    $currentRowCount++;
  }
}

}

You can create two migrations, both with the same mapping (except for the nids), but one saves nodes in English and the second in French.


How to populate a node reference field that has multiple values? I'm using the rules to create a new node upon changing the current node publishing status to published. And populate some field based on the updated node field. Im trying to populate a node reference field in the new created node based on the node reference field multiple values from updated node. I wasn't able to use the tokens since it returns single value. How do I get all the values using tokens and return the values in an array (using the php code)?

I managed to get multiple value node reference field using the Array Tokens module, an extension to the Token module, providing tokens for multiple-value CCK fields and taxonomy terms.

$authors = array([node:field_op_author-default-array-nid]);
$options = array();

foreach ($authors as $author) {
  $options[] = array('nid'=>$author);
}

return($options);


How to Show Multiple field value according to Row Height In Content type Having field Work Images and enter the content for that and set the relationship  and CONTEXTUAL FILTERS for the frontend.
Content Is showing fine But its showing random.
How can I show the value as in same order as in backend ?
Any Suggestion ?

You need to sort by the field delta (The position in the list). So in views add "sort criteria" and search for "work images delta"


How to add a media type to drupal_add_css in custom module I’ve got a question about adding CSS to a custom module.

Originally I’ve been given this line:

link rel="stylesheet" type="text/css" media="screen and (max-width: 640px)"    href="mobile.css"

And I’ve converted it into:

drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'screen and          (max-width: 640px');

The file is being attached, but the media setting is wrong and I don’t know what it should be. I’m in Drupal 6.

Thanks!

drupal_add_css() is defined as:

drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE)

and in your example, you are doing:

drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'screen and          (max-width: 640px');

which appears to have two problems:

You are skipping the $type argument,
You aren't closing the max-width parenthetical.

I'd suggest trying:

drupal_add_css(drupal_get_path('module', 'savingsscore') . '/css/mobile.css', 'module', 'screen and (max-width: 640px)');

and seeing it that fixes things up.


How to send an email to the admin when user fails to login? I need to implement the functionality to notify the admin user via email whenever someone fails to login entering wrong password. Basically simple email format containing the username for failed account to login. Can someone give guidance or suggestion?

P.S: I checked the Rules module but it doesn't have required Rules event like "When user fails to login".

People mistype or use wrong alternate passwords all the time. Would be overkill to send e-mail on a first failed attempt.

For security reasons, Drupal blocks user account after 5 login failed attempts.

You can use Rules Block/Unblock User to send e-mail when user gets blocked. (failed 5 times)

  This module adds rules events, as well as some default rules, for when
  a user account is blocked or unblocked.


Dynamic hook registration Is it possible to register hooks dynamically? I.e. not by hardcoding the hook handler into your code.

For instance, I'm writing a module and would like to add an option to some content type creation pages. I know this can be done using the hook_form_FORM_ID_alter hook, but since I don't know what node types will exist in the drupal installation I obviously can't hardcode the hooks.

Or will I have to use hook_form_alter or hook_form_BASE_FORM_ID_alter and check whether the option should be shown for that form? I'd really, REALLY would want to avoid that, since it's a really icky solution.

Or am I approaching this the wrong way?

The usual approach is to create a settings form for your module and save the content types on which you want your hook_form_alter to intervene. Then with a simple check you can implement you alterations.
The list of content types existing at a certain point in Drupal is easy to check.

I see no other way of actually placing your alters for specific content types. Even if you create your hook dynamically by using an unorthodox

foreach ($SELECTED_NODETYPES as $NODETYPE) {
  if (!function_exists("my_module_form_$NODETYPE_node_form_alter")) {
    function my_module_form_$NODETYPE_node_form_alter (&$form, &$form_state) {
        //your alterations
    }
  }
}

You will still have to have a list of nodetypes to check from, and on each new nodetype creation you have to be sure you flush the cache so your module will declare the new hooks and Drupal actually will take them into account.


How to set up Views PHP filter? I'm trying to use Views PHP filter feature to remove rows which don't contain some data (I can't just use "Hide if empty" feature, because the module returns a string even if there is no real value.

I'm using this string for a filter, however, if doesn't work - instead of filtering, view returns all values.

return isset($data->_field_data['nid']['entity']->field_poloha_obce_pol[und][0][geometry]);

I tried to inspire myself from some of the similar issues here, but it seems to me, that everything should be correct.

I also tested this exact code as PHP field and it returns expected value.

Try

 return empty($data->_field_data['nid']['entity']->field_poloha_obce_pol['und'][0]);


How to reset admin password if account is blocked I am using Drupal 8 and I forgot my admin password and have it blocked due to trying to login unsuccessfully 5 times. I am running my website in localhost.
How can I reset it? Is it possible to do with a SQL query?

Drush is ideal but if you don't have that installed, you'll need to do more than just a sql query because you'll need to get a hash of the password you want to use.

First find your core drupal main directory and run

php core/scripts/password-hash.sh "your_new_password"

In phpmyadmin or your sql db manager of choice find the admin user in users_field_data and replace the pass value with the hash you got from the command above.

Then truncate the 'cache_entity' table. If you were locked out from too many failed login requests also delete instances of your IP in the 'flood' table.

Then you should be able to log in with your new password.