How do I re-attach AJAX behaviours to a managed_file field? I currently have a form which is generated by the FAPI via an jQuery AJAX call, and then is inserted into the DOM.

This works fine, but the problem is that managed_file field within the newly generated form have lost all their AJAX behaviours. I've tried a couple of things to try get Drupal to reattach the behaviours after the form is generated but I'm having no luck.

Here's my code for retrieving and inserting the new form into the DOM:

$.ajax({
type: 'POST',
url: '/example-get-form',
dataType: 'json',
data: 'get=1',
success: function(response){

  //insert new form into DOM
  var newForm = response.data.form;
  $('.profile-form.edit').append(newForm);
  Drupal.attachBehaviors();
}
});

As you can see from the frontend code, we retrieve the rendered form HTML via AJAX and then insert it into our container div with the selector ".profile-form.edit". The form is rendered and inserted into the DOM correctly, but the problem is that the dyanmic form's managed_file field can either be empty or contain an image, so both the "Upload" and "Remove" buttons needs to have their AJAX behaviours reattached.

Here's the code for generating the form via the callback URL called from my jQuery script:

//generate form and send via JSON
$response['data']['form'] = drupal_get_form('mymodule_example_form');
$response['data']['form'] = render($response['data']['form']);

return drupal_json_output($response);
drupal_exit();

Any help to put me on the right track would be greatly appreciated!

The main problem is that you're not loading the form in Drupal way in the AJAX requests. When you use the normal jQuery ajax to load the form, then the necessary actions(Generating new scripts and re-attaching the behaviors) won't happen.

So you should follow the below process to achieve it.

Create a page with ajax Link/button - clicking on it should load the form(This
may change based on your need)
Create form generation callback
Create a ajax callback which will returns the form

Below is the complete example module which loads the form with the managed file field using ajax.

<?php

/**
 * @file
 * Provides File module pages for testing purposes.
 */

/**
 * Implements hook_menu().
 */
function test_menu() {
  $items = array();

  $items['file/test'] = array(
    'title' => 'Managed file test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access content'),
  );
  $items['ajax/test'] = array(
    'title' => 'Managed file test',
    'page callback' => 'file_ajax_page',
    'access arguments' => array('access content'),
  );
  $items['ajax/form'] = array(
    'title' => 'Managed file test',
    'page callback' => 'file_ajax_form',
    'access arguments' => array('access content'),
  );

  return $items;
}

/**
 * Generates the Test page.
 */
function file_ajax_page() {
    // Make sure Drupal Ajax framework javascript is around.
  drupal_add_library('system', 'drupal.ajax');
  $output = '';
  // Generate a Ajax Link to load the form.
  $output .= l(t('Delete'), 'ajax/form', array('attributes' => array('class' => 'use-ajax')));
  // Specify the container for the form.
  $output .= '

';
    return $output;
}

/**
 * Returns the processed file form.
 */
function file_ajax_form() {
    $commands = array();

    // Treat them in Drupal way to load the form in AJAX, so that all the necessary scripts will be loaded.
  $commands[] = ajax_command_html('.form-container', drupal_render(drupal_get_form('test_form')));
  ajax_deliver( array(
    '#type' => 'ajax',
    '#commands' => $commands,
  ));
}

/**
 * Form constructor for testing a 'managed_file' element.
 *
 * @see file_module_test_form_submit()
 * @ingroup forms
 */
function test_form($form, &$form_state, $tree = TRUE, $extended = FALSE, $default_fid = NULL) {
  $form['#tree'] = (bool) $tree;

  $form['nested']['file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Managed file'),
    '#upload_location' => 'public://test',
    '#progress_message' => t('Please wait...'),
    '#extended' => (bool) $extended,
    '#size' => 13,
  );
  if ($default_fid) {
    $form['nested']['file']['#default_value'] = $extended ? array('fid' => $default_fid) : $default_fid;
  }

  $form['textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Type a value and ensure it stays'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

/**
 * Form submission handler for file_module_test_form().
 */
function test_form_submit($form, &$form_state) {
  if ($form['#tree']) {
    $fid = $form['nested']['file']['#extended'] ? $form_state['values']['nested']['file']['fid'] : $form_state['values']['nested']['file'];
  }
  else {
    $fid = $form['nested']['file']['#extended'] ? $form_state['values']['file']['fid'] : $form_state['values']['file'];
  }
  drupal_set_message(t('The file id is %fid.', array('%fid' => $fid)));
}

This way Drupal will do all the works for you if you specify what/how do you want:)

I took File Test module in the core as the base for this example.


Multiple values in a row How do I get multiple values (from one field) in a row in the node template? I have a field where a user can select up to 3 values. I would like that to be displayed this way:

  Industry: industry1, industry2, industry3

I don't want it displayed like this:

  Industry: industry1
            industry2
            industry3

I am using Drupal 7.

If it's just adding the commas to an array, PHP has implode().

implode(', ', $fields).

I think iRex is asking how to get the values. In this case, I would use the following code.

$fields = array();
foreach ($node->field_name['und'] as $field) {
  $fields[] = $field['value'];
}


Search for content by title or add edit link to node I have a Drupal 7 installation with a lot of content and it seems quite limiting that I cannot filter the content in the content administration screen by title. Is there a plugin that will add a filter to the title? I haven't found one so far after a lot of searching.

Alternatively the ability to add an edit link (near the nodequeue add/remove links) would be very useful. Is there a way to do that?

Yes, there's the Administration Views module, which replaces a bunch of the default admin pages with configurable views:

  Replaces administrative overview/listing pages with actual views for superior usability.

Features:

  Filter all administrative views via AJAX.
  Perform any kind of bulk/mass operations on items in administrative views.
  Filter content by title, node type, author, published status, and/or vocabulary.
  Filter comments by title, author, node title, or published status.
  Filter users by name, ban/blocked status, or user roles.

You'll also need the Views module for this


Redirect user after node add/edit I want to redirect users to a custom page, after they create a node or edit it.

You can use hook_form_alter to add a custom submit handler where you can set the redirection path.

See the FAPI for more details about form redirection.


Drupal 6 to Pressflow migration: MyISAM to InnoDB? I will soon be migrating from Drupal 6 to Pressflow. As Pressflow encourages InnoDB for certain tables, how can I promote these recommendations when migrating an existing site?

Is this something which update.php handles?

In addition, as my Drupal site is not the latest Drupal core version, should I update to latest core first, and then sideways to the corresponding Pressflow version, or can I go straight from 6.19 to Pressflow 6.22?

You should be fine going from Drupal 6.19 to Pressflow 6.22 but make sure you backup files and database just in case.
As for converting the tables your best doing that either through mysql cli, or phpmyadmin.

I would treat these as two separate jobs: First, migrate to Pressflow and confirm the site is working; then, secondly, start moving tables.


Views Exposed Filter Form Submit handler I have a Views with an exposed filter block and put the block on the front page.

I use the following code to add a custom submit handler.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'views_exposed_form' )
  {
    array_unshift($form['#submit'], 'manage_custom_filters');
  }
}

function manage_custom_filters($form, &$form_state) {
 dpm($form['#id']);  // output views name
}

Here is the question, whenever i load the front page, the manage_custom_filters get called, i suppose it will be called only when i submit the exposed filter form?

I did the same thing for node form submit, it does not behave like the views exposed filter form. manage_custom_filters only get called when i submit the form.

Is this the correct behavior of views exposed filter form?

How do i differentiate the manage_custom_filters is get called by 'on load' or submit action?

The views exposed form will be submitted every time you view it. If you check the render_exposed_form() you can see they are setting the $form_state['always_process'] => TRUE, this means that the form will be submitted always while processing it. And this is understanable because submitting the exposed form and passing the argument in $GET are the same in view.


How to reuse the same custom template in Ajax callback I am currently trying to display a list of nodes with a custom form containing taxonomy dropdowns (placed above node list) to filter out the contents. Now, on page load all content is displaying well by theming with custom template. Now my form is an Ajax form. After filtering I want to display the result with by using same template just passing the filter array of the node(s). Please find my ajax submit callback code.

Not working. render() works only if I pass nodes by loading node by viewMultiples. is there any way I can use similiar to theme() of drupal 7 like theme('my_content_build_page', $nodes)?

$nodes= Myclass::getNodesByEntityQuery($params);
$build = \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'full');
$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand(
    '.result_message', '
'.render($build).'
'
  )
);
return $response;

On page load I am theming

$page_params['content'] = MyClass::getNodesByEntityQuery($params);

$build = [
  '#theme' => 'my_content_build_page',
  '#page_params' => $page_params,
];

Can I reuse the same template in Ajax Callback?

The replacement for theme() is a build array with a '#theme' key, as you already have for the page.

In Drupal 8 pass this or the other build array from your question unrendered to an ajax html command, because render() in custom code should be avoided if possible:

$build = [
  '#type' => 'container',
  '#attributes' => [
    'class' => ['my_top_message'],
  ],
];

$build['content'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes, 'full');

$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand('.result_message', $build)
);
return $response;


Date Validation according to different type I met a problem when create a new content.

I created a content type, it has a field named Type, this field have two values.
When select "normal", another field Date will be hidden. When select "renewal", another field Date will display.

Now I want to compare start date and end date before save this content.
On one way, I used field validation, but it always give warning for both "normal" and "renewal".

On the other, I add new rules to compare the date, but it gives warning always after saved the content.

Anyone could help me to solve this problem? very appreciate for this.

use strtotime() on both the date fields and then compare that value in the validate function of the form.


Create a block with sorting in drop down Using Organic group module, In the block I want to create sort dropdown as shown in image. Which will allow to sort the data according to various parameters like date, tag, group etc.

How can I achieve it programmatically.

You can use table display to manage the listing of all the posts.
Now to filter/sort the data you can user ctools jump menu. Using Ctools jump menu you can create various menu items for different sorting type.

To see the example of Ctools jump menu see the ctools_ajax_sample module which comes with Ctools module package.


When I click a radio button its value should display in textfield Above is the sample screenshot of my form where I would like to do is:

When I click/check on radio button "One" then its value should display in  textfield of "Display".

Code:

function test_radio_menu() {
  $items['test_radio'] = array(
    'title' => 'test_radio',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_radio_form'),
    'access arguments' => array('access content'),
    'access callback' => TRUE,
    );
  return $items;
}

/**
* Implements hook_form().
*/

function test_radio_form($form, &$form_submit){

/* the options to display in our form radio buttons */
$options = array(
  'one' => t('One'),
   'two' => t('Two'),
);

$form['count'] = array(
  '#title' => t('Count'),
  '#type' => 'radios',
  '#options' => $options,

);

$form['display'] = array(
'#title' => t('Display'),
'#type' => 'textfield',
'#value' => ,
  );

$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
  );

return $form;
}

You should use drupal ajax form
 try this code

function test_radio_form($form, &$form_submit){

/* the options to display in our form radio buttons */
$options = array(
  'one' => t('One'),
   'two' => t('Two'),
);

$form['count'] = array(
  '#title' => t('Count'),
  '#type' => 'radios',
  '#options' => $options,
  '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_print_search_idnumber_wrapper',
  ),

);

$form['display'] = array(
'#title' => t('Display'),
'#type' => 'textfield',
'#value' => isset($form_state['values']['count']) ? $form_state['values']['count'] : '',
'#prefix' => '
',
'#suffix' => '
',
  );

$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
  );

return $form;
}
function myid_print_all_submitted_id_callback($form, $form_state)
{
      return $form['display'];
}


How to move the form label into the input field on all node edit forms I have been able to customize it in the search form using template file. I am not able to figure out how to do this in the node creation/edit forms.
eg: http://drupal.org search box at the left top.

I overrode the form in the template.php

$form['title']['#attributes'] = array(
  'onblur' => "if (this.value == '') {this.value = '".$form['title']['#value']."';} this.style.color = '#333333';",
  'onfocus' => "if (this.value == '".$form['title']['#value']."') {this.value = '';} this.style.color = '#333333';"
);


Files inside the CSS folder gets automatically deleted when I clear the cache When i set my uploads path to ../ on file system, my files inside the css folder get deleted when i clear the cache. My aim is to be able to upload my files on the root outside drupal installation which is possible so far except the deletion of my files. I tried deleting the content of the .htaccess file that gets created in the root folder but there's no luck.

My directory structure is:

root/

----css

-------menu.css(file that get erased)

----drupal

-------drupal installation

----js

-------javascript

----other HTML files

Thank you

What you are doing is dangerous. It opens a security hole in your installation. But that's your problem.

Drupal caches pre-combined css and js files in, respectively:

public://css
public://js

It's hardcoded, and you can do nothing about it. This means that if you will set public to mean your ../, Drupal will use ../css and ../js for CSS and JS caching purposes - all purposes even cache clear. For performance reasons Drupal does not care if it was this installation that created cache item when you tell it to clear it all. Why should it? Clear is clear after all.

Long story short: Don't set drupal's public:// to anything you don't want Drupal to manage. If you really have to, symlink specific directories, or write custom module to manage such uploads.


How do I get a HTML value from $form_state? I am dynamically showing the radio box values from database on a form.

<input id="edit-info-prog-dates-0" class="form-radio" type="radio" value="0" name="info[prog_dates]">

Aug 13, 2012 - Sep 24, 2012

$350.00 CAD

I am using the following code to generate the above HTML.

 $form['info']['prog_dates'] = array(
    '#type' => 'radios',
    '#title' => t('Select Dates'),
    '#required' => TRUE,
    '#options' => $dates,
    '#prefix' => '
',
    '#suffix' => '
'
);

I want to save the value for the cost in database. If I write the following code, I am only getting the input value '0'.

$form_state['info']['prog_dates']

How do I fetch the cost value, which is inside the  and  in HTML?

From the HTML you show, I get that the partial content of $dates is the following.

$dates = array(
  0 => '
Aug 13, 2012 - Sep 24, 2012

$350.00 CAD
'
);

What you can do to get the 350.0 value is changing $dates to the following.

$dates = array(
  '350.0' => '
Aug 13, 2012 - Sep 24, 2012

$350.00 CAD
',
  // ...
);

In that way, $form_state['values']['info']['prog_dates'] would contain '350.0', if the users select the radio button I shown.

From the HTML you shown, I get that in the form you set #tree to TRUE. Differently, the HTML name assigned to the radio form field would not be info[prog_dates] as in your case, but prog_dates. If I am wrong about that, it means you need to check the value of $form_state['values']['prog_dates'], instead of $form_state['values']['info']['prog_dates'].


Modify text of error message for required field I have a checkbox with a link in its title text. This is a required field and the error message references the title including the link. How can I modify the error message to remove the link from the error message text?

hook_field_validate() appears not to be called; that was my first attempt after doing some searching.

Quick and easy fix is to use the String Overrides module. Here is a quote about it (from the module's project page):

Provides a quick and easy way to replace any text on the site.
Features:

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


Adding Ajax on existing dropdown list I added this code in my template.php

function PORTO_SUB_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'rapporto_di_lavoro_node_form') {

    $form['field_livello']['und']['#ajax'] = array(
                                  'callback' => 'my_test_callback',
                                  'wrapper' => 'callback_wrapper',
                                  'progress' => array(
                                    'message' => 'caricamento',
                                    'type' => 'throbber',
                                    ),
                                );        }}

function my_test_callback($form, &$form_state) {
dpm($form_state);
}

When I select an item I can see the throbble, but no dpm() message.
What's wrong?

As I'm still not modifying fields, I don't need to unset or indicate wrapper, aren’t I?

similar question is here.

Dynamic select list in the form (dependent dropdown)

you can get your solution from here.


How do I control the available options for an exposed filter? I have an exposed filter "country" for my member list view  (I'm using addressfield module to store the country).
I would like to only show countries in my exposed filters where I have members. I can manually restrict the filter by select countries.

Which one would be the best option, between the following ones?

theming views-exposed-form.tpl.php
using hook_form_alter()
hiding some fields with CSS

I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).

To do this in the most efficient/easy way possible, you should create your own filter handler.

For a really simple example:

<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

Then, in your module's .info file, add the file containing this class (in this example, 'custom_handler_filter_countries.inc') to the .info file's files array (files[] = includes/custom_handler_filter_countries.inc).

To make your particular view use this views handler instead of the default handler, you should be able to change the handler in hook_views_pre_view(), I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.


Add JS to Commerce Add to Cart form I'd like to add my own JS functions to the Commerce "add to cart" form when a user makes selections on various product attributes.

When the user clicks through the options available, I need to scan the form using JS for the current values of the radiobuttons/selects.  I need this to happen as soon as the form elements have changed.

edit:
Having some success with the following, however since the form changes every single attribute this makes my javascript function run many, many times.

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      //look at form values here.
      //this fires after each form element is updated

    }
  }
})(jQuery);

Forgive me if this question sounds a bit lazy, I am reading the documentation, but I've not seen anything yet.

When you use Drupal's "attach" behaviors, use the provided context parameter in your jQuery selectors to limit the selector scope to only the part of the page that is being modified by AJAX:

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      $('.my-input', context).val('foo');
    }
  }
})(jQuery);


Send Registration Emails To Non-Administrator role / Rules Data Selector By Role I'm about to lose it here so hopefully someone here can help me.

I'm working in D8 and I would like to allow users of a certain role (Managers) administrate new site users. There is a permission for that and it works fine, but I can't find a way to send an email to users of the Managers role. It seems that they will only send to the Administrator account (me).

Some people online suggested that I might use Rules to get this to work for me, but this has made things even more confusing. I started down the path with the event being "After saving new user". I click "Add Action" and pick "Send Email". Some screenshots have shown me that in previous versions there might be a "Send Email to Role" option, but that's gone here for some reason.

I'm now at a "Send To" field, which can use the Data Selector. I can't quite use the Data Selector to get to a role. I can choose "user.role" or "user.roles", but then the autocomplete kind of gives up on me. "user.roles" will start giving me numbers after or "entity", but nothing gets me to sending an email to all users with a specific role.

Does anyone know how to get this to work? I'm not married to the Rules module. It just seemed to be the only option because Drupal won't send the default emails to anyone that isn't Account 1.

I highly recommend you don't do this, but if you put the following code into a file rules/src/Plugin/RulesAction/SystemSendEmailToRole.php then it'll give you a new action where you can enter the machine name of the role you want to send to (e.g. "myadmins") and it'll do what you want (I tested it, it works though no money back & no guarantee!):

https://gist.github.com/stevepurkiss/9b36eb79311d16c65e8d4d0ba9f1854b

All I did was copy the send email action, swap the 'to' string field to 'role', then load up all user ids with that role, foreach loop through them and insert their email address one by one as it loops through.

Looks like it could be extended to cope with multiple roles like the original code copes with multiple email addresses but this is the best you get in the half hour since I saw your post, and for free ;)

Of course it'll break if you update rules, there's no guarantees, but I did a bit of Rules 7->8 upgrading actions a couple of years back so know my way around a little. Not a lot, but a little ;)

Please also consider supporting rules too, this stuff doesn't appear from thin air, it's a collaboration!

HTH

Steve


How to get values of selected options in Form api? I am using Form api to build one form.In that I have used select type field and for that options are coming from an array. Below is the code

  $fnames = array();
  $dir_path = variable_get('file_public_path', conf_path(). '/files');
  $files1 = scandir($dir_path);
  $dirs = glob($dir_path . '/*' , GLOB_ONLYDIR);
    foreach($dirs as $directs){
     $names = explode('/', $directs);//
     $fnames[] = end($names);
    }

  $form['select_list'] = array(
    '#type' => 'select',
    '#title' => t('Folder Names'),
    '#options' => $fnames,
  );

While displaying on the select list it will display all names but when I will fetch the value in one of the submit function it will show only index value not the name.

function custom_submit_file_upload($form, &$form_state){
  $foldername = $form_state['values']['select_list'];
}

Here it shows,

$foldername = 0 or 1 or 2 whatever I select in the options,

but I need name of the selected element not the index values.
Please suggest me to get the names.Thank you in advance..

Since the form submission handler has access to the $form variable, you just use the following code.

$foldername = $form['select_list']['#options'][$form_state['values']['select_list']];

To make it clear with an example: $form['select_list']['#options'] is an array like array( 1 => 'first folder', 2 => 'second folder'), and $form_state['values']['select_list'] is a value between 1 and 2.


"Add More" button to form I'm trying to add an "add more" field to a form in my custom module. I've been looking at the examples module, with no luck.

Here's what I have so far:

$form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '
',
  '#suffix' => '
',
);

if (empty($form_state['num_names'])) {
  $form_state['num_names'] = 1;
}

for ($i = 0; $i < $form_state['num_names']; $i++) {
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
}

$form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('spower_add_more_add_one'),
  // See the examples in ajax_example.module for more details on the
  // properties of #ajax.
  '#ajax' => array(
    'callback' => 'spower_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);

if ($form_state['num_names'] > 1) {
  $form['names_fieldset']['remove_name'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#submit' => array('spower_add_more_remove_one'),
    '#ajax' => array(
      'callback' => 'spower_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
}

function spower_theme($existing, $type, $theme, $path) {
  $base = array(
    'render element' => 'form',
  );

  return array(
    'spower_my_form' => $base + array(
      'template' => 'spower',
    ),
  );
}

function spower_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function spower_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function spower_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

The problem is that when I click "add more", the entire form is submitted.

If the above isn't clear, I've added the module at http://pastebin.com/Hn7bkM2v and the spower_elements.inc at http://pastebin.com/CwHW5mSm.

Thanks for the help.

It's a well known problem of Drupal 7 - every form button is rendered with type="submit".

What you need to do, is to add prevent="click submit mousedown" to your button, to prevent actual submission. Maybe only one of those 3 is really needed, but this combination gave me pretty consistent results.

OK, but the above only prevents form from actual saving data. It still gets validated, and that's not exactly what you want, right? I already got answer on how to omit form's validation at AJAX button click.

Other approach would be to either add custom form element, let's call it real_button, a copy of button but with type="button", or to change type on document ready using jQuery.


POST parameters not received in drupal module I am sending a POST to a Drupal module. How can I receive the parameters values in the module and display?

I have tried using $val = $_REQUEST[''], $_POST[''], $_GET[''] but it is just showing the null value.

I want to get the POST request and send the response back in JSON.

function module_menu(){
  $items = array();
  $items['page-json'] = array(
  'title' => 'JSON Output',
  'page callback' => 'json_page',
  'page arguments' => array(1),
  'access callback' => TRUE,
);
  return $items;
}
function json_page(){
  $dt = $_REQUEST['param'];
  return drupal_json($dt);
}

You cannot use an empty string with those super global variables. You need to use a string that is the parameter you request, such as in $_GET['q'], or $_REQUEST['q'].


Custom pager for View The client I'm building a site for has a collection of content that they want paged by its ReleaseYear Field. The pager they want should look like:

[ < | 2011 | 2012 | 2013 | 2014 | 2015 | > ]

How I build a pager like that?

As a clue,  you should alter the theme_pager_link function. copy this function in the template.php, if the years are started from 2001, you need to alter the pager so that every link of the pager be summed with 2000, it is the function

function THEME_pager_link($variables) {
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $text = $text + 2000;  ------>>>>> in this line every number is added with 2000
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

the indicated line with  ------>>>>> add every number with 2000, the only shortage of this solution is that the current number won't be summed with 2000. A few modification to this code will solve this problem as well. you can also add any css class to $attributes variable.


How to Setup Multilingual Section (Not Site) I support an existing site that contains a multilingual section.  We have a link to this section on the homepage and it just consists of some basic pages.  Now I have been asked to incorporate one of our existing content types into this section (i.e. Content Type A - English, Content Type A - Spanish).  The node/add form and the node display pages all need to be in Spanish.  I also need to be prepared to support additional content types, additional languages, etc.

So I'm experimenting with the Locale and Internationalization modules.  The problem I'm having is that it seems to be designed for an entire multilingual site.  I need the site to remain an English site.  For example, when an anonymous user creates a spanish node, the user is returned to homepage:  www.example.com/es.  The homepage is not going to be translated.  User should be returned to www.example.com.  I also noticed all of the links on www.example.com/es include the es prefix in the path.

Question(s):  Is this the right approach to a multilingual section?  If so, is there a way to configure Drupal to understand that www.example.com/es, www.example.com/es/mypage, etc. do not exist?

Yes you are right, internationalization is made for a full website in several languages. But you will be probably be able to achieve what you want by using views everywhere.

Instead of displaying a classical node, you will display a view with 1 node inside a block, inside a panel (probably).
You setup your view to use the language your want and the content type you want, that should do the trick. It's a bit different approach if you compare it with the standard drupal approach of creating page.

To ensure that the node page is not accessible, you can use the module node page disabled.

I hope it helps

Cheers


Main page teaser with module paragraphs? The paragraphs module is the only module I know which would enable me to create flexible content with floating inline images without using a WYSIWYG editor. I use the beta4 paragraphs version in connection with the Garland theme.

I was able to setup certain paragraph bundles and also a content type where it is possible to add up paragraphs to different type (e.g. text only, text with image etc.)
See example below:

However, I failed totally to configure a teaser view which makes sense. The reason: I cannot control the number of paragraph bundles to be shown in the teaser view as ist can be seen here:

In my test site the number fields next to the Fomat field in the above picture is missing. So I can only show the total article or nothing as teaser. How can I fix this?

The “manage display” teaser configuration page did not show the number of paragraphs to be displayed in the teaser view since the "Display Suite" module was not installed. I missed the display suite module because it was not mentioned in the cited article about paragraphs. :-(

It is, however, easily possible to also generate reasonable teaser views without having the Display Suite module installed: Just configure a content type with 2 fields for the page content: The first serves as single teaser/introduction field and the second serves as vehicle to choose among multiple and per CSS differently formatted paragraphs for the following content. The first field I call “intro field” in the following.

For the intro field (to me) there seem to be certain restrictions: If one wants to use a flexible paragraph item for this purpose, it seems to be only possible to show or hide the element on the teaser or full content page, respectively. (Within this respect, text_with_summary appears to make no sense as element of a paragraph bundle).

On the other hand, one could also use an unwrapped text_with_summary field as the first part of an article. This enables the full teaser functionality where one can select from mere shortening or providing an alternative abstract. Most important the manage display page will now let you choose “summary or trimmed” as teaser.


Filter a view based on current user's roles? Using Drupal 7, Views 3 and the Node Reference module, I'm using a view to populate a node reference field on a custom content type. (So it's a view of "Reference" display type.)

I want to filter this view to show (and allow users to select) only:

published content (OK)
content of a certain type (OK)
only nodes created by the current user (OK)
OR if the current user is admin or some other role, bypass the previous filter (3) and show all nodes (but still respect filters 1 and 2) (not OK)

Filters 1 and 2 are always mandatory; then either filter 3 OR 4 must also be mandatory. I know I can rearrange filters into filter groups to make this work. The problem is that I cannot find a way to build filter 4.

For filter 3, I had to bring in a Relationship of type "Content: Author", which made a lot of new filters appear, including the "User: Current" that I used for filter 3 (node author == current user).

For filter 4, I need to filter based on the role of the current user (not author), and I cannot find how to do that.

In the filters list there's a new "User: Roles" filter available, but it only refers to the "Content: Author" relationship, so it only checks the node author's roles. That's not what I need: I need to check the current user's roles.

I'm guessing I have to add a new Relationship to bring in the current user data (something like "User: current"), and then filter on that data, but I cannot find that in the Add Relationship screen.

Any idea how to do that?

Following @Jimajamma's suggestion, here's what I used. I adapted his code slightly for Drupal 7 and to allow for other roles than Administrators full access to the results.

In the View, add a contextual filter on Author: Uid, and use the following settings:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

Provide default value
Type: PHP Code

Use the following code:

global $user;

if (
    in_array('administrator', $user->roles) ||
    in_array('editor', $user->roles)
)
{return -1;}
else
{return $user->uid;}

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED

Specify validation criteria
Validator: PHP Code

Use the following code:

if ($argument == -1)
{return FALSE;}
else
{return TRUE;}

Action to take if filter value does not validate: Display all results for the specified field (this is what will give admins access to all results)

And that's it!

Notes:

Compared to my initial settings, the relationship (Content: Author) isn't needed anymore; neither is the "Author" filter (which was brought in by the relationship anyway).

Apparently, for Drupal 6 the condition in the first PHP snippet should rather be if (in_array('super user', array_values($user->roles))).


Drupal Commons: notify all users on creation of new group In Drupal Commons (D7) I'd like to have all users notified by email when a new group is created.

Is there a way to do that?

You can use the Rules module and set it to fire an action, when a group is created.

CVS Instructions
You could also implement this User register notify

But since Drupal Commons uses Organic Groups
you might be able to use this Organic Groups Notifications
but take a look at the Rules module and Flag module.

best regards


creating a custom entity which stores multiple bundles as per user input? I want to create an custom entity(Lets say payroll entity) which has the following fields
1. Basic salary
2. Earnings
3. Deductions

It is possible by Entities

But now I would like to add some new feature

Basic salary(field)
Earnings(Bundle) contains (bun1, bun2, bun3 fields)
Deduction(Bundle ded1,ded2 and ded3 fields )

If a user wants to set his employee's Earnings and other details he can manual sets it .For an example if a user needs to set his/her employee's salary like daily allowance, travel allowance, bonus etc)  he/she can do it from their own choice . And there should not be any restrictions for the no. of fields to add either bundles or fields . A user add custom bundles as well as custom fields.

Satyabrata,

Not sure i got the requirement correct. Have you considered using entity reference + inline entity form? You can attach bundles to the main bundle and can create them (sub bundles) from the main bundle using inline entity form .

Hope it helps.


Show links depending on role's name I want to show a custom link for each role on my site. To do so, I will put PHP code in my page.tpl.php. I want to add an if statement that checks if the current user's role is equal to something, then print the link.

How can I get the current user role?

global $user;
if($user->roles[1] || $user->roles[2]){
//Do Something
}


Theme's css and js files are not being loaded I was trying to create a theme for Drupal 8.1.8. My CSS and JS files unfortunately cannot be loaded. I have checked if I used any tab characters, but I have used always 2 space characters for an indent.

I have read the documentation page at Drupal.org: https://www.drupal.org/theme-guide/8/assets. I was trying around 2 hours with all possible combination. Also I tried the google search, Drupal core code inspection.. I could not figure it out.

My theme is located at themes/englishtrainer. The css is located in themes/englishtrainer/css and the javascript files are in themes/englishtrainer/js. The theme can be enabled as a theme without problems.

The contents of my theme's files in the following.

englishtrainer.info.yml:

name: Englishtrainer
type: theme
version: 8.x-1.0
core: 8.x
package: Custom
# Scripts & Styles
libraries:
  - englishtrainer/global-styling

englishtrainer.libraries.yml:

global-styling:
  version: 1.x
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

css/css-test.css:

body {
    background-color: red;
}

js/js-test.js:

alert('it is loaded!');

I was checking the html markup for any occurrences. The javascript console has been also checked. It does not contain any entries.

Do you have any idea?

englishtrainer.info.yml:

name: Englishtrainer
type: theme
core: 8.x
version: '1.0.0'
libraries:
  - englishtrainer/base
regions:
  header: Header

No need for package

englishtrainer.libraries.yml:

base:
  version: VERSION
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

Use base to start things off and the VERSION keyword will take the version info from englishtrainer.info.yml.


How can I find out if the present theme version would work In the last years I've used pixture reloaded, a subtheme to adaptive theme, on some drupal sites and I was wondering whether this will work on Drupal 9. I've seen that the Adaptive theme homepage has not been reachable for some weeks and that the last update of Adaptive themes was 3 years ago. So I don't expect them to further develop the theme. How can I find out if the present version would work in Drupal 9?

Install the Upgrade Status module and then visit /admin/reports/upgrade-status and scan the Adaptive Theme and your sub-theme and get a report on all problems regarding Drupal 9 compatibility.

  This module scans the code of the contributed and custom projects you
  have installed, and reports on any deprecated code that must be
  replaced before the next major version. Available project updates are
  also suggested to keep your site up to date as project will resolve
  deprecation errors over time.

  Due to third party PHP library dependencies, the module needs to be
  installed with Composer.


How to insert HTML that includes an ampersand> I've created a custom block, and I'm trying to get this custom block to output a specific piece of HTML. The HTML needs to be different on every page, because it needs to include the page's URL in it. For instance, if the page is http://www.businesskorea.co.kr/article/7789/content-business-marginalized-samsung-reorganizes-media-solution-center-owing-poor, then the block should output:

This is to be compatible with daum.net's news publishing functionality. The code that I've written up for this custom block looks like this:

<?php

/**
* Implements hook_block_info().
*/

function bkcustom_block_info() {
  $blocks = array();
  $blocks['bkcustom_daum_json_block'] = array(
    'info' => t('BKCustom Daum JSON'),
  );
  return $blocks;
}

/**
* Implements hook_block_view().
*/

function bkcustom_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'bkcustom_daum_json_block':
      $block['subject'] = '';
      $block['content'] = BKCUSTOM_DAUM_JSON_BLOCK_CONTENT();
      break;
  }
  return $block;
}

function BKCUSTOM_DAUM_JSON_BLOCK_CONTENT() {
  $path_alias = drupal_get_path_alias($_GET["q"]);

  $encoded_path_alias = urlencode($path_alias);

  $output = t("");

  return $output;
}

Which outputs almost, but not quite, what I need. The output changes ampersands to &amp;, and somehow deletes the final forward slash (/) at the end of the IMG tag. The output looks like this:

The most frustrating part of this exercise is that if I delete the opening and closing brackets, <>, the code works perfectly and prints out each character exactly as I need it to. That's how I tested to see if it would work. But when I introduce opening and closing brackets, the code changes and the JSON query or whatever the crap this is fails.

How can I preserve the & and / characters?

t function is for texts, not for HTML, so it is perfectly allowed to fail. Also, you should not use dynamic strings in t's first argument at all, it is meant to be static.

Whenever possible, you should use renderable arrays. In your specific case this seems a bit difficult, so first thing to, if you are willing to settle for quick and dirty, do would be just forget t and output tag directly.


How to delete a user via REST I'm trying to delete user account via REST API.

Here is my code:

// .xml asks for xml data in response.
$service_url = 'http://www.example.com/rest/user/login';

$post_data = [
  'username' => 'test',
  'password' => 'pass',
];

// Format post data as application/x-www-form-urlencoded.
$post_data = http_build_query($post_data, '', '&');

// Set up the request.
$curl = curl_init($service_url);

// Have curl_exec return a string.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// Do a POST.
curl_setopt($curl, CURLOPT_POST, TRUE);
// POST this data.
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// Output to command line
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);

// Make the request.
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name . '=' . $xml->sessid;

// Get token.
$curl_get = curl_init();
curl_setopt_array($curl_get, [
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL            => 'http://www.example.com/services/session/token',
]);
$csrf_token = curl_exec($curl_get);
curl_close($curl_get);

// A user ID.
$id = 1500;
// The token.
$token = $csrf_token;

// Set up the curl resource
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/rest/user/$id?access_token=$token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

$response = curl_exec($ch);

// Close curl resource to free up system resources.
curl_close($ch);

It returns:

  Access denied for user anonymous

How do I need to write the code to delete a user?

First you need to login:

$loginData = ['username' => 'yourusername', 'password' => 'yourpassword'];

$ch = curl_init("http://pathtodrupal.com/endpoint/user/login.json");

curl_setopt_array($ch, [
  CURL_OPT              => TRUE,
  CURLOPTRETURNTRANSFER => TRUE,
  CURLOPT_HTTPHEADER    => ['Content-Type: application/json'],
  CURLOPT_POSTFIELDS    => json_encode($loginData),
]);

$response = curl_exec($ch);

$responseData = json_decode($response, TRUE);

Once you send a POST request to login you get the following response back:

  {u'session_name': u'SESScxx45656f30', u'sessid':
  u'mOE9NdG6Bk3EADSvKJHGGy8jgkQ', u'token':
  u'-HVkXhARIynpmJxow5NUIYTRXSc', u'user': {u'status': u'1', u'picture':
  u'0', u'uuid': u'514c987e7-15f0-43cc-9c6f-53279c216f30', u'uid': u'1',
  u'language': u'', u'created': u'1310006971', u'init':
  u'morinfo@dbasepu.com', u'timezone': u'America/New_York', u'access':
  u'1429109927', u'theme': u'', u'roles': {u'2': u'authenticated user'},
  u'signature': u'', u'signature_format': u'1', u'mail':
  u'mor@morinfo.com', u'login': 1429111638, u'data': {u'ckeditor_width':
  u'100%', u'form_build_id': u'form-60703ffc3';lk6c0fe03cebe9',
  u'ckeditor_lang': u'en', u'ckeditor_show_toggle': u't',
  u'last_category_id': 1, u'ckeditor_auto_lang': u't',
  u'ckeditor_default': u't', u'site_access': {u'1': u'1'},
  u'last_site_id': 1}, u'name': u'bewmrn'}}

In your subsequent requests you want set the the set in the header the X-CSRF-Token to $response['token'] and Cookie to $response['session_name'].=.$response['sessid']. This should work.


How to retrieve node body from nid with an SQL query in Drupal 7? From this question I learned that I have to look in field_data_body to retrieve the body of a node from a database.

field_data_body does not have an nid field though.

What query can I use to retrieve the body from an nid?

To clarify: I simply wanted to quickly fetch a text from a database dump without installing the dump on an actual site. So not looking for PHP here.

field_data_body does not have an nid field though.

Because a field can be attached to any entity, which may have a different primary key than nid.

If you really must use direct SQL, you can query the field like this

SELECT body_value FROM field_data_body WHERE entity_type = 'node' AND entity_id = 1

However, this bypasses several of Drupal's layers, so it's normally strongly discouraged to use direct queries.

Instead, it's better to

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('nid', 1)
;
$result = $query->execute();

$nodes = node_load_multiple(array_keys($result['node']));

foreach ($nodes as $node) {
  $bodies = field_get_items('node', $node, 'body');
  foreach ($bodies as $body) {
    var_dump($body['safe_value']);
  }
}

The EFQ version have several advantages

It's safe. You can't (easily) accidentally open injection attacks.
It outputs a safely escaped value, avoiding XSS attacks.
It works if a node has multiple values for the body field.
It works on sites with multiple languages.


I get a syntax error when I try to execute a query Each time I run the following code, I get an error.

$result = db_query(“SELECT nid FROM 'msg'”);
foreach ($result as $record) {
  // Do something with each $record
}

The error is the following one:

  Parse error: syntax error, unexpected T_STRING

How do I fix the error?

You should do

$result = db_query("SELECT id FROM {mg}");

It doesn't look like you should get parse error unless you really use “” and not ""


'default_value' plugin does not run if 'get' returns null or empty value I’ve got a D7 to D8 migration where I’m trying to migrate a field with a null value in D7 to a default value in D8. Process pipeline is similar to this:

  field_privacy:
    -
      plugin: get
      source: field_office_privacy
    -
      plugin: default_value
      default_value: 'open’

It seems if the field value is null, the default_value plugin never runs.

When D7 has a non-null value, then the field migrates perfectly via the get plugin. The D8 API documentation gives this pipeline as an example of exactly what I'm trying to do, yet I cannot get it to work. When I should get a value for all 164 items selected by the migration source, I instead only get 132, which precisely matches the number of fields in D7 that have non-null values.

How can I set a default value when get doesn't find a value?

The catch here is that you should not use the get process plugin explicitly. The behaviour you want is already implicitly used the default_value plugin. This is because get is the default process plugin and can be shorthanded. In your case this should work:

 field_privacy:
   plugin: default_value
   source: field_office_privacy
   default_value: 'open’

Also see documentation for get and default_value


The best way to implement custom variables with Google Analytics I need to use Google Analytics custom variables , but I want to give a different variable value depending of the urls.

I'm checking the G.A module, but I don't see how to define the variables to say when to use one token or other depending of the url.

The only way I see is build a token that checks the url and gives me back the value.

I'm thinking in something more close to Paths Breadcrumbs where you can define context and choose a token/value depending of the context.

"Custom variables" are now Custom dimensions and metrics.

The Google Analytics module supports custom dimensions and metrics.

See the module's README.txt:

  One example for custom dimensions tracking is the "User roles" tracking.

  In the Google Analytics Management Interface you need to setup Dimension #1    with name e.g. "User roles". This step is required. Do
  not miss it, please.
  Enter the below configuration data into the custom dimensions settings form    under admin/config/system/googleanalytics. You can
  also choose another index,    but keep it always in sync with the
  index used in step #1.

  Index: 1    Value: [current-user:role-names]


Tag autocompletion fails for anonymous users? On a site, anonymous can create content. The content type has a term reference field, which works fine for logged in users.

However, for anonymous, the fields JS is "dead", no autocompletion happens, and I can't even see an http request going off.

Obviously I assumed is has to be a permissions issue as it only affects anonymous, but I can't seem to figure out what permission that would be, and if it was, then it seems like the http request would go off.

Figured it out myself while I was typing the question.

Since JS didn't work at all, I checked the console, found a CKEditor related error, fixed it, and things went back to normal.


Drupal 7 Really Slow on admin pages I have a Drupal 7 installation and several admin pages are incredibly slow and time out after 30 seconds.  I've tried several things without success:

APC is enabled
innodb_buffer_pool_size is set to 100 M
No unused modules are enabled.  I still have 155 modules enabled, for localization, commerce, captcha, questions & answers, etc.
Standard cache is enabled and JS/CSS compression enabled. Memcached not being used.
Drupal 7, latest version

Even with that, the site is still really slow and there are pages that won't open (time out).  For example, installing a module will always fail the first time.  Accessing the settings of the Language Selection Page module will always fail, and so on.  Any recommendations other than increasing the timeout?

I'm using WAMP.

UPDATE: The time out error shows it takes a while in this function mainly: drupal_flush_all_caches( )   ..\system.admin.inc:1766

Sometimes in other functions too.

If you can profile your site that's always helpful. https://drupal.stackexchange.com/questions/724/why-is-drupal-7-so-slow

https://groups.drupal.org/node/210683 - Older post but some patches have still not been committed.
https://groups.drupal.org/node/415883 - Speedups for the DB layer (caches mainly).

Because of windows checkout this post and this group
https://groups.drupal.org/node/242443
https://groups.drupal.org/drupal-windows


Site turned to maintenance mode without changing any settings I have a client who's site maintenance came up without anyone touching it. What would cause something like this?

I have theories that it's the backup module. Would that be possible?

I just went and turned maintenance mode off last night and just now but the maintenance mode eventually goes back up.

I reviewed this thread but it wasn't related: How to access the admin pages for a site stuck in maintenance mode?

Since, I'm pretty sure that clean url's are turned on already.

Drupal will show a site as offline if it cannot connect to the database, so you may want to check that the database is up and running.


Views 3 | How to programatically unset or add new value to a view's footer / header display? I have added 1 view display into my view's footer via "Global: View area | The view to insert into this area." and a regular "Global: Text area".

So my view has 2 footer displays, one being another view display and the other a normal text area.

Now I want to unset/hide either one of the footer display based on a condition, perhaps via hook_views_pre_render()

I was expecting to find documentation on something like:

$view->display['MY_VIEW_DISPLAY_ID']->handler->handlers['footer']['FOOTER_DISPLAY_ID']->unset_display();

But obviously that is not the way to go. Is it possible to accomplish that via hook_views_pre_render() or any other means? If so, how?

The snap code below has been tested only on D7. In case this code does not work on D6, check out the comments on this post here.

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'VIEW_NAME' && $display_id == 'DISPLAY_ID') {

    // To find out the DISPLAY_NAME, FIELD_NAME and FIELD_VALUE use the devel module function
    // below to print them out.
    // Replacing 'footer' by 'header' works the same way.
    dpm($view->display_handler->options['footer']['DISPLAY_NAME']['FIELD_NAME']);

    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'FIELD_NAME', 'FIELD_VALUE');

    // In this case scenario you needed to unset the footer display.
    // For the embedded view display you do like this:
    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'view_to_insert', '');
    // For the normal text area display you do like this:
    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'content', '');
  }
}

Due to comments, to determine what views name and display came to this function, make next (of course, "devel" module should be enabled)

    function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
      dsm($view->name);
      dsm($display_id);
      if ($view->name == 'VIEW_NAME' && $display_id == 'DISPLAY_ID') {
...
      }
    }

And update views page.


When I change a node title and hit save, I get 'page not found' I have a site which behaves strangely, whenever I change the node title, it give a page not found error.
I think it has to do with Drupal trying to find the node by path alias, but why?
It should find it by node ID?

I have even installed the module Global Redirect, but that does not help.

Suggestions are welcome!

When you change the title of a node when URL auto-alias is turned on, you will need to fix your links to that node or do the options below. You are getting the page not found error, because it's trying to go back to the view version of the node that now has a different URL. You have the following options:

Install redirect. Then set up a redirect to the old URL. If you install this first, it will automatically track the changes of the URL moving forward.

Alternatively, you can go to the node and uncheck the auto-alias option and hand-assign the URL back to what it was before you changed the title. I recommend the redirect module though.


Branched user permissions for editing content types What is the best way to implement the user permissions (in brackets) in following pattern with Content Types as follows:

Parent (editable by owner & tagged parent-editors)

Name
Description
...
Tagged Parent-editors (users)

Child (editable by owner & tagged child-editors & tagged parent-editors

Name
Description
...
Tagged Child-editors (users)
Entity reference: Parents

SubChild (editable by owner & tagged child-editors & tagged parent-editors)

Name
Description
...
Entity reference: Childs

Where "..." are some other fields, dependant on the ContentType.

Parent A editors must not be able to edit Parent B

I've looked into the Module Node Access User Reference which seems like it may do this potentially, but I was wondering if there is a standard way of doing this or whether anybody has some prefered/suggested Modules for doing this or even a completely different solution!

I think you may try Node Privacy by Role module.
First create three roles Parent Editors, Child Editors, Subchild Editors
Then while creating a node you will be asked about the permission to edit the node.
But this might not help you when you want to protect nodes per user.

There is also another module Taxonomy Access Control Lite which governs access to nodes based on the taxonomy terms applided to nodes.
In this you can create terms for Parent Editors, Child Editors and Subchild Editors

Apart from that there is also good discussion here:

http://drupal.org/node/24073

http://drupal.org/node/285369


NID as a contextual filter doesn't work on some nodes I have a view where the NID is getting passed as a contextual filter for a specific content type, but some nodes doesn't pass at all and for some of them there is no problem.

I've checked the database, and I can see that the node NID I am trying to expose is there, but I still can't see it in Preview with contextual filters.

Finally I configured what was the problem. There were two referenced fields related with Relationship in view, and for those two relations I have checked the box "Require this relationship". So whenever I created content without any of those fields, content view was empty. When I unchecked  "Require this relationship" boxes, everything works good.
How ever thanks for your effords to help me.


How to do automatic card authorization during checkout process? I have a website that uses Drupal Commerce, we use Authorize.net for authorization and use AcceptJS as a plugin. When you put in the credit card information, it checks with Auth to make sure that you're using a real credit card and saves it as a payment method without authorizing the actual value. It gets saved in Auth, as well as the commerce_payment_methods table with a remote_id for Auth. Currently in our workflow, after you submit your order, in Commerce->orders->payments, you have to add the payment and manually authorize/capture the amount. I want it to automatically authorize the amount when you finalize checkout, however I'm running into difficulty figuring out where and how I do this. I know it must be something simple. Can anyone help?

Is this a Drupal 7 or a Drupal 8 site? That will impact the admin URL as noted below:
8: /admin/commerce/config/payment-gateways/
7: /admin/commerce/config/payment-methods/

You will want to edit the Authorize payment method, and look for "Default credit card transaction type" - that setting should be "Authorization and capture" as opposed to "Authorization only"


Detect when 'Remove' is clicked on a file widget form element? I have a handful of file fields that have the following default Drupal behavior:

User can upload a file
User can upload another file in place
User can remove file

Standard config. Whats happening is the user wants the file being replaced to be deleted before the new one is uploaded, and thus, avoiding the issue where files have their names replaced with _N identifiers to ensure unique filenames.

This is because they are referencing physical file paths from the menu and WYSIWYG fields - which means the old replaced file is being referenced instead of the new one. Since these are core file fields and over 100 files have been uploaded, I cannot switch out to a Media field. I'm also not sure if that would even solve the problem at hand, anyway.

Is there any way I can hook into this widget via form alter, detect a click on the upload field, and if a new file is being added, delete the old one in place so that the file being uploaded the name stays intact and thus preserving link targets?

I have looked at the form with both hook_form_alter and hook_field_widget_form_alter - but I am not really seeing anything I can use to hook into.

You can use javascript onclick() function

<button onclick="myFunction()">Click me</button>

or jQuery

$("#remove").click(function(){
    alert("The remove was clicked.");
});


Drupal 8 how to show entity reference field in views exposed filter as select list? I have content types as Leaves and Branch. and I have an Branch ER field in Leaves.
How to show Branch as select list in views exposed filter Drupal 8?

I really need a solution asap.

Thanks.

How about the Views Entity Reference Filter module? The module is also capable of showing the values of the referenced entities in a filter instead of the IDs.


How to include specific roles in auto-complete search? I am using the auto-complete module for searches. It works like a charm. I am looking for to learn how to show only specific roles on the results it pulls. There are advanced areas in the configuration and I think something could be used there, yet I am not sure what.

The best way to do this is create a View of the search results you would want. e.g. If you create a view of Users with role, "editor", then Autocomplete can be used to pull only from that view. Using the Filters ability of views, this should be a relatively simple task.

http://drupal.org/project/search_autocomplete supports this feature.


Block on specific pages and node types I'm trying to make a block display on a specific page and inside a node type; I got this code from drupal.org, but I keep getting this error.

Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 178 of /home/content/45/6861545/html/includes/entity.inc).
Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 354 of /home/content/45/6861545/html/includes/entity.inc).

This is the code I used.

$match = FALSE;
$types = array('middle_content' => 1);
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type])) {
    $match = TRUE;
  }
}

if (substr($_SERVER["REQUEST_URI"], 0, 10) == '/test'){
  $match = TRUE;
}

if (substr($_SERVER["REQUEST_URI"], 0) == "/node/add/middle_content") {
  $match = TRUE;
}

return $match;

To actually fix that error, see my answer to a stackoverflow question.

However, in that case, your code can be simplified a lot using menu_get_object():

$types = array('middle_content' => 1);
if ($node = menu_get_object()) {
  if (isset($types[$node->type])) {
    return TRUE;
  }
}

And anyway, you should avoid PHP in blocks etc (See What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?), check out Context. It allows you to configure your blocks (among other things) for conditions exactly like this without having to write code. It is also much faster.


Drupal Commerce 2 Promote Product to Front Page I am using drupal commerce 2 to create an ecommerce website. Need to promote some products to front page but there is no option in product types to promote the product to front page. In Drupal Commerce 1 we use to reference the product in product display node and that can be easily promoted to front page. Is there any different method to do that ?

"Promoted to front page" is an archaism from the early days of Drupal, so it wasn't transferred into Commerce. Nowadays you can create any number of fields, and filter on them:

1) Go to your product type.
2) Create your own boolean field called "Promoted to front page"
3) Use it from your View.


How to alter a form of content-type to prepopulate FieldCollection of EntityReference fields? I have three content types :

Classroom (some fields)
Student (some fields and one EntityReference to Classroom)
KMDone (some fields and a FieldCollection)

KMDone is a content type which contains :
- a date
- a FieldCollection "kmdone_students"

The FieldCollection "kmdone_students" contains itself
- an EntityReference to the Student
- a distance "go" (Numeric fied)
- a distance "back" (Numeric fied)

Everything works fine except one point :

The generated form for the KMDone content-type requires to click several times on the "Add More" button to have enough rows for every student, choose one student on each select of each row, and then fill the form. Which is not confortable and can give some encoding errors due to user.

So, I would like to alter the form and prepopulate one "row" for each student.

It seems I have to work with the hook_form_alter hook, but how can I can I prepopulate one "row" in the FieldCollection (as if the user clicked on "Add more" button) for each EntityReference ?
To say it in other words : if the original form SelectBox have 17 students, I would like then to prepopulate 17 rows and set the EntityReference field for each student.

Many thanks in advance for your tips !

Kind regards,

Short answer is : You can't via hook_form_alter

Long answer : there is a workaround there : https://www.drupal.org/node/1337804


print title and contents on a custom tpl.php template? im making a custom theme for drupal, and im having a hard time trying to understand how to adapt one of my themes to drupal 7.

Right now im having an issue because i need to set some classes on all the blocks of a sidebar. i decided to make a block--sidebar.tpl.php file and there i set all the structure of the blocks.

So far so good but now, the block shows up, but im unable to get the title and contents of the block correctly. How can i achieve this?, thank you.

A different approach would be to:

Use the Block Class module - which will also allow you to add
more classes per block.
Use CSS to apply the same styling to all blocks in the sidebar:

.sidebar .block { border: 1px solid #ccc}
.sidebar .block-title {color: blue}


Problem with jquery or jquery ui (animating color) I have found a jquery code which animates colors. I made a fiddle from it (after minor change), and it's working perfectly on jsfiddle:
http://jsfiddle.net/kFuzp/

Unfortunately, it's not working on my Drupal site. I have JQuery Update module and updated to 1.8, using jQuery CDN. The code (as in jsfiddle) is inserted using drupal_add_js ($script1, 'inline') in mytheme_preprocess_page(). When I debug the code in Chrome, it just runs (I can observe how the color_index changes etc using breakpoints). But the <p> background color is always white.

By the way, when I change the animation property to { opacity: color_index/7 } then the opacity animation is working (slowly) both in jsfiddle and in Drupal.

Why it's not working in Drupal and how to fix it?

It sounds like you're having a problem with your jQuery selector.

Are you using changing the properties for all paragraphs? Or just a particular one? Or a class?

Below are the selectors for each option respectively:

$("p")...

$("p#theIdofTheParagraph")...

$("p.theClassofTheParagraphs")...


Show referenced entity I have 2 content types. For example UserGroup and User. UserGroup has Entity reference field and there are unlimited of Users. I would like to show in views something like this:

User group name

User 1
User n

User group name

User 1
User n

and for the User their fields (contact, birthday etc.)

Now I set relationships field_users (which is set in UserGroup) and Format -> Show -> Fields. There are Name (UserGroup), Name (User via relationship) but I see:

UserGroup1

User1

UserGroup1

User2

and etc.

Please tell me how can I fix it. Thank you.

Select the group level in Views here:

and then here


How to programmatically use the "between" operator in Drupal Views I have a price field and I want to see if the value of this field is between multiple price segments.

E.g.: (price BETWEEN 0 AND 100) OR (price BETWEEN 150 AND 200)

So how can I use the "between" operator in Drupal Views to programmatically alter a query?

I believe you are using hook_views_query_alter. So see the example to add OR in condition. Check out code :

$this->query->add_where(
  $this->options['group'],
    db_or()
      ->condition($field, array(0, 100), 'BETWEEN')
      ->condition($field, array(150, 200), 'BETWEEN')
  );


Computed code db query issue -- working in PHPmyadmin but not field On my site, I have venues, and reviews of the venues, related with an entity reference field. I'm creating a computed field to store the UID of the first person to create a review for each venue. To do so I've written the below query. Now, it works fine when I enter the simplified sql directly into PHPmyadmin, and substitute $entity->nid with an actual nid, but for some reason it just will not work when I add it into the computed code field, with the added db_query and fetch portions. Any ideas?

if (!$entity->nid) node_save($entity);

$entity_field[0]['value'] =
db_query (
    SELECT entity_id
    FROM (
        db_query (
            SELECT *
            FROM field_data_field_review_venue_reference AS ReviewRow
            WHERE field_review_venue_reference_target_id = $entity->nid
        )->fetchrow()
    ) AS uid
    LIMIT 1
)->fetchfield();

What you wrote is not PHP code, which is what a computed field is expecting.
I would rather use the following code.

$entity_field[0]['value'] = db_query("SELECT entity_id FROM {field_data_field_review_venue_reference} vr WHERE vr.field_review_venue_reference_target_id = :id", array(':id' => $entity->nid))
  ->fetchField();


Remove site name from template using twig function I try to get rid of the site name which come with the twig expresseion {{ page.header }}.

To get further details of that variable I enabled twig debug mode and printed it {{ kint(page.header) }}.

It seems that block--system-branding-block.html.twig is used within {{ page.header }}. At the end of file it shows.

{% if site_name %}

      <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}

{% endif %}

The question is how to use a twig function to remove that item from {{ page.header }}.
There is a filter which is called without and I already applied it to page.header|without('site_name'). But that didnt work.

Additional question, how to establish a connection between the printed variables from {{ kint(...) }} and the template file. Iam looking for that specific div which displays the site name but I can't find it in the printed variables from debug in order to remove it.

You can remove the block in the block layout.

If you don't want to do it in the ui, you have to look for the block name. This is probably sitebranding.

For example to remove the block with the name sitebranding from the region header in the page template:

{{ page.header|without('sitebranding') }}

If you are looking for the site name in the kint print out, it is not always possible to find the actual content early in the templates. Often it is processed at a later stage.


Mapping a csv field to Meta Title and Meta Description using feeds and metatag I have a csv of node data that I want to import into drupal. I'm using the feeds parse, and I can map the Page Title, Body, and other fields just fine. The issue I'm having is trying to map the CSV fields to the Meta Tag and Meta Description items (provided by the metatag module). Since metatag does not store it's information as a drupal field, I cannot map it with the feeds UI.

One possible solution I have considered is to use a metatag module that does use node fields to store meta data, but that would require a shift in the way our content editors handle things, and the installation of that seperate module on all of our maintained sites. I'd rather just use feeds with metatag

I'm a beginner when it comes to using the feeds api, and want to know if it is possible to write a custom mapping function that could populate metatag data for nodes from a feeds import.

You could create fields for the metadata, hide them in "Manage display" and map them to the Metatag module (add the field tokens as content), as I described in the answer to "How can to make required the fields keywords and description of the metatags module?".

Now in your CSV import you add the metadata to your manually created fields, and the Metatag module will fetch the content.


Can behat log in as an administrator for testing while using LDAP? I'm using the Behat Drupal Extension. When I try to run a behat test on a sandbox server, I see the following. I see that a temporary admin user is being create but it can't seem to log in. How might I remedy this so that behat can login?

$ behat

Feature: First   Playing with features and exploring

  @api   Scenario: Run cron
# features/first.feature:6
    Given I am logged in as a user with the "administrator" role # Drupal\DrupalExtension\Context\DrupalContext::assertAuthenticatedByRole()
      Failed to log in as user 'ss5vWjZY' with role 'administrator' (Exception)
    When I run cron                                              # Drupal\DrupalExtension\Context\DrupalContext::assertCron()
    And am on "admin/reports/dblog"                              # Drupal\DrupalExtension\Context\MinkContext::visit()
    Then I should see the link "Cron run completed"              # Drupal\DrupalExtension\Context\MinkContext::assertLinkVisible()

I've changed my LDAP configuration back to mixed mode:

And only admins are allowed to create a new account

I had this issue as well. It turned out to be a problem with LDAP. Switching to Mixed Mode allow the DrupalExtension to function properly. Since we don't want mixed by default, I added a pre-test setup function

public static function prepare($scope)
     {
        $data = array(
          'sids' => array (
            'directory' => 'directory',
          ),
          'authenticationMode' => 1,
          'loginConflictResolve' => 2,
          'acctCreation' => 4,
          'loginUIUsernameTxt' => NULL,
          'loginUIPasswordTxt' => NULL,
          'ldapUserHelpLinkUrl' => NULL,
          'ldapUserHelpLinkText' => 'Logon Help',
          'emailOption' => 3,
          'emailUpdate' => 1,
          'allowOnlyIfTextInDn' => array (),
          'excludeIfTextInDn' => array (),
          'allowTestPhp' => '',
          'excludeIfNoAuthorizations' => NULL,
          'ssoRemoteUserStripDomainName' => NULL,
          'seamlessLogin' => NULL,
          'ldapImplementation' => NULL,
          'cookieExpire' => NULL,

        );
        variable_set('ldap_authentication_conf', $data);
     }

The key is the line 'authenticationMode' => 1,


How to change programmatically exposed filters in views I have a page view with exposed filters. One of the filters is term vocabulary, and that's dropdown list, user can select only one category (term).

I want to set programmatically one term from dropdown list when I came from specific URL. I tried with views_query_alter where $category is tid.

 $set_exposed_input  = array();
 $set_exposed_input['field_category_tid'] = $category;

 if ($set_exposed_input) {
    $view->set_exposed_input($set_exposed_input);
 }

For drupal 7 you can use

$view->exposed_input[$key] = $value;

This is

$view->exposed_input['title'] = 'My title is a cat';

For a full example you can try this:

$name = 'name_of_view';
$display = 'page_1';
$alter = array('exposed' =>array('title' => 'title_value'));

$view = views_get_view($name);
$view->init_display($display);
$view->preview=TRUE;
$view->is_cacheable = FALSE;

if(isset($alter['exposed'])){
  foreach($alter['exposed'] as $key => $valor){

     $view->exposed_input[$key] = $valor;

  }
}

$view->pre_execute();
$output = $view->display_handler->preview();
$view->post_execute();

print_r($view->result);

Other way is using the views set_option function

$filters = $view->display_handler->get_option('filters');

foreach($alter['exposed'] as $key => $valor){
   $filters[$key]['value'] = $valor;
   $view->display_handler->set_option('filters', $filters);
}


How can i debug why files are not being created when using migrate files to media module? I run the drush migrate-duplicate-file-detection migd8_grants_media_step1 successfully, and then run the node migration and step 1, however the media is being populated with the name only, the file is not attached nor are the files being moved over to the sites default/files/grants directory as they should
Steps to reproduce
this is my step 1 yml.
# File to Media Migration configuration for grants Media migration

id: migd8_grants_media_step1
label: Grants Media Step 1
migration_group: cncs
source:
  key: migrate
  plugin: media_entity_generator_d7
  entity_type: node
  bundle: grants
  langcode: und
  d7_file_url: 'https://www.externalwebsite/sites/default/files/'
  field_names:
  - field_files

destination:
  plugin: entity:media

process:

  bundle:
    plugin: default_value
    default_value: document

# Using the alt tag if available, else the file name.
  name:
    plugin: media_name
    source: file_name

# This process plugin will skip the whole row if a existing media is found.
  existing_media_file:
    plugin: check_media_duplicate
    source: target_id

# This process plugin will skip the whole row if a duplicate document is found.
  unique_file_id:
    plugin: check_duplicate
    source: target_id

# Map the field
field_media_document/target_id: target_id
field_media_document/target_id:
  plugin: media_file_copy
  move: FALSE
  reuse: TRUE
  path: 'public://grants/'
  source: file_path

langcode: und

uid:
  plugin: default_value
  default_value: 1

You have an an error in your yml file, should be:
# Map the field
field_media_image/title: title
field_media_image/target_id:
    plugin: media_file_copy
    move: FALSE
    reuse: TRUE
    path: 'public://grants/'
    source: file_path

langcode: langcode


add an additional item to an array in Drupal Settings javascript from php I've got a hook_node_view which I'm trying to add a property of the node to an array that I have created in the Drupal.settings

drupal_add_js(array('embedded_videos'=>array()));

So in the node_view I can do

function mymod_node_view($node, $view_mode, $langcode) {
if($node->type == 'video'){
   drupal_add_js(array(
    'vimn_video' => array('embedded_videos' => $node->nid,
      ),
    ),
  'setting');
}

But this overwrites what is in there, whereas I want to add to the array. Because this node_view is running multiple times as I have 2 video nodes embedded into an article node.

Any ideas appreciated. I am new to the usage of Drupal.settings javascript api.

edit: The issue was that I needed to put $node->nid into an array array($node->nid), then it will add an item to the array rather than overwriting it.

Your first declaration should indicate that you are passing a setting to drupal_add_js():

drupal_add_js(array('your_module' => array()), 'setting');

Then you can add other properties to your array in hook_node_view():

function your_module_node_view($node, $view_mode, $langcode) {
    $your_array = array(
      'vimn_video' => array(
        'embedded_videos' => array($node->nid), // NOTE: $node->nid as an array
      ),
    );
    drupal_add_js(array('your_module' => $your_array), 'setting');
}

You can retrieve the properties from javascript as:

Drupal.settings.your_module.vimn_video.embedded_videos; // an array with node ids.


Why doesn't my code send emails? I am using the following code to send emails, but it doesn't work. What is wrong with it?

function yukerja_view_contact_import_form_submit($form, &$form_state){
  global $user;
  $c_user = user_load_by_name($user->name);
  $uid = $c_user->uid;
  $profile = profile2_load_by_user($uid, 'recruiter');
  $field = $profile->field_recruiter_company;
  $tid = $field['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  $company = $term->name;
  $query = db_select('import_contact');
  $query->fields('import_contact', array('name', 'email', 'company', 'operator_insert', 'status', 'matches'))
    ->condition('company', $company,'=')
    ->orderBy('name', 'ASC');
  $table = $query->execute();
  $a;
  $b;
  $email_user = array();
  foreach ($table as $key => $values) {
    $email_user[$key + 1] = array(
      'name' => $values->name,
      'email' => $values->email,
      'company' => $values->company,
      'operator_insert' => $values->operator_insert,
      'matches' => $values->matches,
    );
  }

  $params = array();
  foreach ($form_state['values']['table_user'] as $key => $value) {
    if(!$value == 0) {
      $email = $email_user[$key]['email'];
      $params = array(
        'name'            => $email_user[$key]['name'],
        'email'           => $email,
        'company'         => $email_user[$key]['company'],
        'operator_insert' => $email_user[$key]['operator_insert'],
        'matches'         => $email_user[$key]['matches'],
        'link_jobklik'    => 'http://dev.yukerja.gotpantheon.com',
        'subject'         => 'Invitation',
        'body'            => 'body tes',
        'from'            => 'as'
      );

      $module = 'yukerja_view_contact';
      $key = 'key';
      $language = language_default();
      $from = $params['operator_insert'] . "@jobklik.com";
      $send = FALSE;
      $message = drupal_mail($module, $key, $email, $language, $params, $from, $send);

      $message['subject'] = $params['subject'];
      $message['body'] = array();
      $message['body'][] = "Invitation";
      $message['body'][] = $params['link_jobklik'];

      // Retrieve the responsible implementation for this message.
      $system = drupal_mail_system($module, $key);

      // Format the message body.
      $message = $system->format($message);

      // Send e-mail.
      $message['result'] = $system->mail($message);
      // drupal_mail('yukerja_view_contact', 'invitation', $email, language_default(), $params, $params['from'], TRUE);

    }
  }
}

I think your code is good enough to send email, but you need SMTP server to send the mail (which you has not specified), in case you have a mail server , the easy solution is install SMTP module which needs the SMTP server address and your are good to send email.

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


How to add custom CSS per media query in Omega 3 theme? My Omega 3 theme has the following layouts in the grid settings:

Narrow layout: all and (min-width: 740px) and (min-device-width: 740px), (max-device-width: 800px) and (min-width: 740px) and (orientation:landscape)

Normal layout: all and (min-width: 980px) and (min-device-width: 980px), all and (max-device-width: 1024px) and (min-width: 1024px) and (orientation:landscape)

Wide Layout: all and (min-width: 1220px)

I need to add some custom CSS within each media query. At the moment ive added them within my existing custom CSS file by copying the media query and adding an @import.

@media all and (max-width: 739px) {
    //styles
}

@media all and (min-width: 740px) and (min-device-width: 740px),
(max-device-width: 800px) and (min-width: 740px) and (orientation:landscape) {
    //styles
}

@media all and (min-width: 980px) and (min-device-width: 980px),
all and (max-device-width: 1024px) and (min-width: 1024px) and (orientation:landscape) {
    //styles
}

@media all and (min-width: 1220px) {
    //styles
}

Is there a better practice way of doing this / what are the other ways? Is there a way that integrates with the theme more fully?

Part of the magic of Omega3 is that it does that for you!

Omega will always load the global.css file. If you are in a mobile layout (too narrow for a grid), that is the only file that loads. When you increase the browsers width to narrow, then omega 3 dynamically loads:

global.css
SUBTHEME-alpha-default.css (loads for all non-mobile-layouts)
SUBTHEME-alpha-default-narrow.css

If you keep increasing your browsers width to the normal layout, then these css files are loaded:

global.css
SUBTHEME-alpha-default.css
SUBTHEME-alpha-default-narrow.css
SUBTHEME-alpha-default-normal.css

Note that any CSS definitions you have in SUBTHEME-alpha-default-normal.css will override definitions in global.css, SUBTHEME-alpha-default.css, and SUBTHEME-alpha-default-narrow.css

To answer your question then, custom CSS for the narrow layout should go in SUBTHEME-alpha-default-narrow.css, custom CSS for the normal layout goes in SUBTHEME-alpha-default-normal.css, and custom CSS for the wide layout goes in SUBTHEME-alpha-default-wide.css. Just put it in and let Omega3 do the rest!

See https://groups.drupal.org/node/156719 for more info


How to check if entity's property has a value How can I check if entity's property has a value? I don't think this is the "drupal way" to check it like this

$page_optimization->title->value() !== ''

Is there any method, something like $page_optimization->title->hasValue() etc.

If you look at the entity module, specifically the EntityMetadataWrapper class, there is no method of checking whether or not something has a value.  If a value returns empty you are essentially checking whether or not the value exists by getting an empty value.

For example a single value uses the EntityValueWrapper and only has one method and that is to return the value.  The EntityMetadataWrapper class has few public methods and none that returns whether or not a value is set.  If you wanted to extend one of the classes you could probably build your own method.

/**
 * Wraps a single value.
 */
class EntityValueWrapper extends EntityMetadataWrapper {

  /**
   * Overrides EntityMetadataWrapper#value().
   * Sanitizes or decode textual data if necessary.
   */
  public function value(array $options = array()) {
    $data = parent::value();
    if ($this->type == 'text' && isset($data)) {
      $info = $this->info + array('sanitized' => FALSE, 'sanitize' => 'check_plain');
      $options += array('sanitize' => FALSE, 'decode' => FALSE);
      if ($options['sanitize'] && !$info['sanitized']) {
        return call_user_func($info['sanitize'], $data);
      }
      elseif ($options['decode'] && $info['sanitized']) {
        return decode_entities(strip_tags($data));
      }
    }
    return $data;
  }
}


Form API: Form field not being translated I'm implementing a gender field in a custom registration form.

The gender field also exists as a user field, so I'd like to call the label and allowed values from the existing instance. I've written it as a conditional override just in case...:

$form['gender'] = array(
    '#title' => t('Gender'),
    '#type' => 'radios',
    '#options' => array('female' => t('Female'), 'male' => t('Male')),
    '#required' => TRUE,
);
if($field = field_info_field('field_gender')) {
    $form['gender']['#options'] = $field['settings']['allowed_values'];
    $info = field_info_instance('user', 'field_gender', 'user');
    $form['gender']['#title'] = t($info['label']);
}

Everything's working great, except for the multilingual part: despite having translated the field instance at the admin account settings using i18n, the extracted options and title of the existing field are not being translated upon changing the front-end language. They DO get translated however when visiting the user account page in a different language.

It seems my custom form doesn't send its strings through i18n...?

Can anyone point me out the pitfall please?

Thanks

UPDATE

I used

$func = function($val) { return t($val); };
$form['gender']['#options'] = array_map($func, $field['settings']['allowed_values']);

as suggested by Shameem to translate the options.  But now it seems t() is fetching translations from the Locale module repository. How to direct t() to fetch it from i18n?

the field options are not going through the t function.

you would need to take each value from the following array and make it go through the t() function

$field['settings']['allowed_values'];

and please check that $info['label'] is a plain text and not an array.


Add a "view in JSON" local task How can I add a Preview in JSON local task?

My link is exactly the same of entity.node.canonical, but I have to add a query string (?_format=json). I know how to add the local task, but I don't know how to append the query string to the URL.

You need to configure URL options in links.task.yml file. See Url::fromUri for details.

your_module.export:
  title: Export
  route_name: entity.node.canonical
  options:
    query: {_format: json}
  base_route: entity.node.canonical


Content: tags contextual filter seems to only match the first tag I have a contextual filter on the field content: tags set to "Match any value," but in practice, it appears that only nodes that match the first tag are displayed. For instance a node with the tags "blue, green" would show only other nodes tagged "blue."

It usually work better when you add a relationship to the view, where you relate the content to the taxonomy term.
Then you unlock a whole new collection of fields and filters.

Choose to filter by taxonomy - name instead of content - tags.


Attach a node to a menu link OR attach custom fields to menu links? My client would like to add content to the top-level links in the main menu, in order to have "Featured" content that is displayed in the drop-down menu. They must be able to choose which piece of content will be shown, and which menu link it will be associated with. I figure I have two options:

1) Creating a "Featured in Menu" Content Type and adding a drop-down menu of top-level menu links as a field. The problem with this is I am not sure how to output a custom field that will list top-level main menu links. There does not seem to be a module currently that will achieve this, so I guess I would have to do it from scratch.

2) Adding custom fields to the main menu links themselves (image, title, node reference). I tried using the Power Menu module to achieve this, however every version of the module I tried gave SQL errors and broke the Edit Menu page. I'm hesitant to debug and pursue a fix for that module if it could end up being unstable.

I'm not sure which solution would be preferable but either way I'm stuck! I would very much appreciate some help on how to achieve either one of these solutions. (Or if I'm totally over-thinking this and there's a much easier way to achieve this, by all means please let me know.) For the record, I'm using Drupal 7.

Thanks!

Look into like Menu Views or GigaMenu or MegaMenu ... there are a few solutions that let you place a view in a menu.

Then you can either add a field to a content type such as, "include in featured menu" of type boolean, that you use as a Filter in your View. Or, re-use the "promote to frontpage" re-labeled to fit your needs on a specific content type.


Registration field not to be saved After a lot of searching, I've been unable to find the answer by myself, so here's my problem (with Drupal 7) :

I've been able to add new fields to my user registration form (config/people/accounts/fields) and even hide fields on the form... But I would like to do the opposite : display a field on the registration form whose only purpose would be to assign a value to another field upon validation. There would be no need for this field to be stored in the database (like a transient property in Java).

Is there a way to achieve that ?
Thx

Yep!
Take a look at:

yourtheme_form_user_register_form_alter

Add a new value to the form there,  and then change the form's saving function. In your new saving function you can do whatever you need to do with custom validation and re-assigning that value.

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7


how to include multiple jquery files is it possible to include multiple jquery files like this one ?

(function ($) {
  Drupal.behaviors.mymodule = {
        attach: function(context) {
    //my code
        }
    }
}(jQuery));

I use this to include the files

drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.test1.js');
drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.test2.js');

both files are loaded but it seems that only the first is executed while test2 is ignored

can you help me with that ?

thanks

In Behaviors, behavior name don't need to be the same as module name. And it cannot be repeated, unless you want to disable earlier implementation.

If you separated your code, it means it's there to do different things. So just name them accordingly, like Drupal.behaviors.mymoduleDoSomething and Drupal.behaviors.mymoduleDoOtherThing.


$content variable in block.tpl.php I have customized a block.tpl.php file and I want to access the individual fields in it. But when I put print render($content['field_name']) in my code nothing is printed out. And also print_r(array_keys($content)) doesn't give anything.

I have used the above codes in my page.tpl and node.tpl files successfully before.

I'm on D7.

So is it done somehow differently in block template? What's going on?

If you have a look at the code for the original block.tpl.php file, $content doesn't actually get run through render(), as it's already been rendered to a string.

If you want to alter the block content while it's still in a structured array you should use a hook_block_view_alter() implementation in a custom module. This is the example from the docs page:

function hook_block_view_alter(&$data, $block) {
  // Remove the contextual links on all blocks that provide them.
  if (is_array($data['content']) && isset($data['content']['#contextual_links'])) {
    unset($data['content']['#contextual_links']);
  }
  // Add a theme wrapper function defined by the current module to all blocks
  // provided by the "somemodule" module.
  if (is_array($data['content']) && $block->module == 'somemodule') {
    $data['content']['#theme_wrappers'][] = 'mymodule_special_block';
  }
}

How successful you'll be using this method depends on how well the modules that provide the blocks respect render arrays. If an implementation of hook_block() by a particular module flattens the block content to a string before it is made alterable, then you'll have to make the changes somewhere else in the process (probably using a theme preprocess/override).