Entity Reference field using View to Mask Autocomplete with Last Name I've posted about this here as well: http://drupal.org/node/1906344

I'm trying to use an Entity Reference field to reference users with a last name field I created on a "Product Page" content type.

You see, whenever you try to reference a user, you're forced to do so with the username. So to get around this, you have to create a view that outputs the last name field from the profile and then use that view in a way that accepts an argument to key off of (i.e. - the last name).

I've created my view and on the views page, this view works. But when I use the "Filter by an entity reference view" to attach my view, I discover that it doesn't work on the node-add page. I'll start typing a last name that's associated with a registered user and, well, nothing comes up. The reference type I indicated in the "Target type" is user and the view isn't anything special: it's just an "Entity Reference" view type set to accept 1 contextual filter (the last name) and subsequently outputs the respective users if that argument matches the last name field value(s). So I don't know what's going on here...

Here's my basic setup:
- Drupal 7.x
- Entity API 7.x-1.0
- Entity Connect 7.x-1.0-beta2
- Entity Reference 7.x-1.0
- Views 7.x-3.5

I'm using Entity Connect to provide the ability to create the user if he or she doesn't exist. Otherwise, the field should reference something--which it currently doesn't.

Any help on this is appreciated and please let me know if you need more information.

Remove the contextual filter from your Entity Reference view.

The view should have all the available options. The autocomplete widget for the Entity Reference field will filter the available options based on the user input. If you change the widget type to "Check boxes/radio buttons" you can see the available options which may help diagnose the issue.


Drupal 6 : views Exposed Form : rename the label of a field : please how? I need the checkboxes labels exposed in views search pages
to be different than the checkboxes labels displayed in the node/xx/edit forms.

I found the same documentation everywhere about the way to change the label of a submit button using a template.php function (works fine) :

function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  if ($vars['form']['#id'] == 'views-exposed-form-XXX') {
    $vars['form']['submit']['#value'] = 'gagarine' ;
    unset($vars['form']['submit']['#printed']);
    $vars['button'] = drupal_render($vars['form']['submit']);
  }
}

I can't find any accurate documentation to rename a cck field label when exposed in a search page.

edit² : cleaning the thread for relative readability since I got something working

ok I came to this :
this looks like it does the job. maybe this could be rewieved by a DOCUMENTED drupal hacker.

function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // only alter the jobs search exposed filter form
  if ($vars['form']['#id'] == 'views-exposed-form-MYFORMID') {

    // change the text of an exposed field label (BEF checkboxes here)
    $vars['form'][FIELDNAMEasinurl]['#options'][0] = 'a different label in search pages' ;
    $vars['form'][FIELDNAMEasinurl]['#options'][1] = 'than in edit forms' ;
    // this particular field has a common layout not the case here :
    // this will work but not with the BEF checkboxes layout I want
    //$vars['widgets'][FIELDNAMEinternal]->widget = drupal_render($vars['form']['partage']);

    // or the field was rendered by better exposed filters (here cheboxes)
    // search into better_exposed_filters.theme the function call you need (theme_select_as..)
    $vars['widgets'][FIELDNAMEinternal]->widget = theme_select_as_checkboxes_fieldset($vars['form']['partage']);

    // Change the text on the submit button
    // [...]

  }


How can I use tab_parent/tab_root in hook_menu to have one router item appear as a local task for another router item with a different path? Say I have the path widget/123 to view a widget, and have another path to edit some properties of this widget at admin/acme/widget/123/edit. In hook_menu it looks like I can still have the admin path appear as a local task (tab) by setting the tab_parent and tab_root properties in hook_menu(), but I can't seem to get it to work. I know how to setup widget/%/edit as a local task, but in this case I'm only interested in setting a different "root" path as a local task.

Here's my code:

<?php

function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  // Edit a widget.
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'tab_parent' => 'widget/%',
    'tab_root' => 'widget/%',
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

?>

Am I misunderstanding tab_parent/root, or can this be done?

Update: I was missing a MENU_DEFAULT_LOCAK_TASK. Adding

$items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
);

allows the tabs to appear. However, they don't share the same argument position and so the argument (the widget ID) isn't passed between the two. The 'Edit' tab, for example, links to admin/acme/widget//edit. Is there a way to have different routes like this and pass the argument position around?

If I'm not mistaken the tab_root and tab_parent properties need to point to a path prefix of the router item in question - at least if there are wildcards on the path. The code responsible for this restriction is somewhat convoluted, but what you find when stepping through it is the following:

When generating the tab-links, the _menu_translate function is responsible for replacing the %-wildcards with actual values (node-id, etc). However the replacement values are not computed from the actual object-ids but are derived from the current URL. For example when accessing widget/5, the object-id is on position 1 and therefore when generating tab-links, the value 5 is only injected into paths having the %-wildcard at position 1.

This also leads to another consequence. When navigating to admin/acme/widget/5/edit, you will find that there are no tabs on this page - even if widget number 5 actually exists. This is because when generating the URLs for the other tabs, they will start with widget/acme instead of widget/5 because the value acme is at position 1 in the current path.

If you like to provide tabs on your widget page as well as have it in the backend, then simply duplicate the router item. E.g:

function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  $items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
  );

  // Edit a widget - frontend
  $items['widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  // Edit a widget - backend
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(3, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

If you like to move around stuff from a third-party module, you still can implement additional router-items on behalf of it in a custom module - or even move them using hook_menu_alter.


Automatically fill combobox in views I have created views with a node type (Property) that has term reference to vocabulary (Cities).
Vocabulary (Cities) has a terms in a hierarchical order (City-Street).

I need to do the views in which I have two combobox for vocabulary terms (City-Street) with the following behavior:

When user select a City I would like to automatically fill the second
combobox(Street).
When user select City I need a list all of the
streets for that terms. Now I have a list only when user select an
item from combobox Street. I have tried the Hierarchical Select
module and it didn't meet my needs.

Do I need to make my own module, and which hook or hooks to use, or is there another solution?

I hope that I was clear.

Best regards,

Goran


Is a session alone enough for non logged-in users to see some information? In my project I have a content type called Person that is only viewable or editable by logged-in user. In this content type, I added some fields.

I want to give a person the ability to visit his profile. So I made a module called anonymous_profile with the following code.

function anonymous_profile_menu() {
    $items = array();
    $items['anonymous-profile-login'] = array(
        'title' => t('Login'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('anonymous_profile_login_form'),
        'access arguments' => array('access anonymous person login'),
        'type' => MENU_NORMAL_ITEM,
    );

    $items['anonymous-profile'] = array(
        'title' => t('Anonymous Visit'),
        'page callback' => 'anonymous_visit_page',
        'access arguments' => array('access anonymous person login'),
    );

    $items['anonymous-profile-logout'] = array(
        'title' => t(''),
        'page callback' => 'anonymous_logout',
        'access arguments' => array('access anonymous person login'),
    );
    return $items;
}

anonymous-profile-login creates a form where users insert information in order to log in on the anonymous-profile page. anonymous-profile-logout is the logout page.

function anonymous_profile_permission() {
    return array(
        'access anonymous person login' => array(
            'title' => t('access anonymous person login'),
            'description' => t('Anonymous person login form to view profile page.'),
        ),
    );
}

This is the form object that is returned to anonymous-profile-login.

function anonymous_profile_login_form() {
    $form['field_national_id'] = array(
        '#type' => 'textfield',
        '#title' => t('National ID'),
        '#size' => 10,
        '#maxlength' => 20,
        '#required' => TRUE,
        '#description' => t('Please insert your national id'),
    );

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

    return $form;
}

This is the form submission handler.

function anonymous_profile_login_form_submit($form, &$form_state) {
    $national_id = $form_state['values']['field_national_id'];

    $login_result = false;
    if ($national_id == '123456') { //this is for test.in real , inserted national id must be searched in database...

        $login_result = true;
    }

    if ($login_result) {
        drupal_set_message('Login is ok');
        $_SESSION['anonymous_logged_user'] = $national_id ;
        drupal_goto("anonymous-profile");
    } else {
        drupal_set_message('Invalid login information', 'error');
    }
}

This is the logout page.

function anonymous_logout() {
    if (isset($_SESSION['anonymous_logged_user']))
        unset($_SESSION['anonymous_logged_user']);
    drupal_goto('anonymous-profile-login');
}

In anonymous_visit_page(), first I check the session anonymous_logged_user; if it is OK, I show the information to the user.

function anonymous_visit_page() {
    if (isset($_SESSION['anonymous_logged_user'])) {
        if ($_SESSION['anonymous_logged_user'] > 0) {

            $national_id = $_SESSION['anonymous_logged_user'];
            // load information from database bases on $national_id and print rendered html output.

        }
    }
    //--------------------------
    //visitor is not logged via form
    drupal_set_message('You must loggin in order to see your profile', 'error');
    drupal_goto('anonymous-profile-login');

}

Is this solution safe?
Is a session alone enough for this method, or must I increase the code safety?
Is there any possibility the session is stolen, and users access information without log in via form?

I am using Drupal 7.

To answer a couple of questions asked:

Extra features to increase safety? You're tying identification/authorization together here; if I know an ID number then I'm authorized to view details associated with it. A malicious actor can just throw guesses at that field to start pulling data they shouldn't have access to. You should increase your authorization criteria (e.g. ask additional details to prove the user is who they say they are)
and make the form more robust against brute-forcing (e.g. limit requests, use other bot-defeating tools, etc.).
Can a session be stolen? Yes. A PHP session is vulernable to session hijacking if you're using unsecure transport. You should enforce an encrypted session so you can rule that out.


Enforce Minimum Length by adding spaces So currently I am using the maxlength module (https://drupal.org/project/maxlength) in order to enforce the fields maximum length and I have a view set up that is embedded to a php Rules action (Execute custom PHP code).

Basically if a field is smaller than the maxlength defined, I am looking for a way to output the value with spaces.

For example: Maxlength 5. Field Value: xxx. Output: "xxx  " (without quotes)

I can't seem to find the right module/php code to do this.

I think I have 3 directions I can go with this.

I have it save the spaces to the field based on the maxlength specified when saving the field. I don't like this option much since it actually adds spaces to the value in the database.
I somehow edit the view to display the spaces based on the maxlength of the field.
I edit the Rules views_embed_view php output.

Any help would be extremely helpful. Thank you.

Edit: I am using Drupal 7 by the way.

In template file for your field you can use good old PHP sprintf:

$right = sprintf("[%10s]\n",    $s); // right-justification with spaces
$left  = sprintf("[%-10s]\n",   $s); // left-justification with spaces

$right === "    monkey";
$left  === "monkey    ";

In your case
    <?php print $output; ?>

should turn into:

 <?php printf("[%10s]", $output); /* if you want spaces before string */?>


How do I use translated taxonomy terms in exposed views filters? I have a multilingual website with 5 languages.  I want to add exposed filters to the top of my views generated pages. Everthing works fine in English, my source language, but when I create a view for a foreign language and create the exposed filter for taxonomy, I can only choose the English list. I thought this would translate automatically once the page changed languages, but this is not the case.

To see what I am talking about, please click here
http://noboribetsu-spa.jp/ja/泊まる

What module do I need or what do I need to do to get these transalted terms to show up in the exposed filter select list?

thanks

The answer to this is to use the i18nviews module, which is independent of the modules included in i18n. Once the module is installed then in your view chose Filter: Has taxonomy (translated terms).  Even though the selection will be in the source language they will then translate properly on the page views.

Note: at the time of this post il8nviews is in development, has little to no documentation, and is a bit difficult to work with, but hopefully that should be cleared up soon.


Drupal 7, Dev Site, will not Aggregate Javascript or CSS I have two installations of the same site. The first is sub.website.com, and is the main website. The second is sub.website.com/drupaldev.  On the /drupaldev site I cannot get the javascript or CSS to aggregate, which is causing myriad odd problems. I have checked the tmp directory, changed it, modified permissions and re-installed the site from scratch. None of these things has allowed me to get the website to aggregate.

Is the problem that I am hosting the development site as a folder of the main site?

This could really be a myriad of problems.  More than likely, your files directory isn't writable.  Browse to the Status Report (admin/reports/status) and make sure the File System section says Writable.  While you are at it, make sure everything on the report is green.

Running a second Drupal site in a subdirectory of the first site is a tricky situation.  The main concern is the way Apache handles .htaccess files in a directory tree.  htaccess rules apply to the directory that the file is in, plus all subdirectories.  This means that your site in /drupaldev is going to inherit the directives from the root htaccess file.  This may or may not cause problems, but in general, this is a big red-flag.


how to create an AJAX field widget I'm trying to create a field widget which is a collection of multiple fields. I'm using hook_field_widget_info() and hook_field_widget_form(), something like this:

function module_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => 'container',
    '#element_validate' => array('custom_validation_function'),
  );

  $options = array('some values here');
  $element['existing'] = array(
    '#type' => 'select',
    '#title' => 'Recipient & delivery address',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => $wrapper_id,
      'callback' => '_my_custom_ajax_callback'
    )
  );
  $element['new'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $new_entity = entity_create('entity_type', array('type' => 'bundle'));

  field_attach_form('entity_type', $new_entity, $element['new'], $form_state);

  return $element;
}

function _my_custom_ajax_callback($form, &$form_state) {
  return $form['new'];
}

The problem is that in the ajax callback the $form array is different than the one in the hook_field_widget_form(). In the ajax callback the form array is the entire form structure, not just the one defining that widget...

Any ideas?

I've tried to do this a few times and never really got very far (for the reasons you've already mentioned).

The way I found to do it instead was to install the Field Collection module (and Field Collection Table for a better UX), and use that to group the fields I need into a single field, which is represented as a single widget.

Then I just hook into the particular form that's showing the field and add the AJAX that way. As coincidence would have it I've just done exactly this a few hours ago. I know this is out of context but here's a (slightly anonymised) dump of the code I used; hopefully it'll give you a place to start if you choose to go down this route:

function MYMODULE_form_directory_listing_node_form_alter(&$form, &$form_state, $form_id) {
  $selected_country_tid = $form['field_address'][LANGUAGE_NONE][0]['field_country'][LANGUAGE_NONE]['#default_value'][0];

  $form['field_address'][LANGUAGE_NONE][0]['field_country'][LANGUAGE_NONE]['#ajax'] = array(
    'wrapper' => 'directory-form-county-wrapper',
    'callback' => 'MYMODULE_form_directory_listing_country_ajax'
  );

  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#prefix'] = '
';
  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#suffix'] = '
';

  $selected_country_term = taxonomy_term_load($selected_country_tid);

  $options = array();
  foreach (_MYMODULE_get_country_counties($selected_country_term) as $county) {
    $options[$county->tid] = $county->name;
  }

  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#options'] = $options;
}

function MYMODULE_form_directory_listing_country_ajax(&$form, &$form_state) {
  return $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE];
}

field_address in the above example is the Field Collection field.


Fatal error: Class 'SelectQuery' not found in includes/database/database.inc on line 813 Fatal error: Class 'SelectQuery' not found in /home/content/71/11241671/html/drupal/includes/database/database.inc on line 813

We built a site in a subfolder called /drupal while building the site, and then moved the files to the root directory when we were finished but it gave the above error on a WSOD.

I have tried:

flushing the cache before moving
tried the registry rebuild
truncating and replacing the registry and registry_file tables with a fresh install copy, and rebuilding the registry again
rewrite base in htaccess
setting a new base url in settings.php

But nothing has worked.

The second we put the files back into the /drupal folder, it works again. It also looks like the error mentions the file in the /drupal directory, which isnt there anymore.

This is on 7.37

Anyone have any ideas?

Rolling back this patch... https://www.drupal.org/node/2170453 solved the first problem, and then using htaccess to define the correct php version fixed the next error.


How do I send emails from a .php file? I have developed a separate functionality using PHP in a sub folder of my Drupal site (e.g. mysite.com/myfolder/myfunc.php).

Now I want to send emails using Drupal functions. Since this is not a custom module I can't use hook_mail().

How do I send an email through Drupal?

Try like this:

$to = 'ABCD@example.com';
$subject = 'Email in PHP';
$message = 'This is a test email message';
$headers = 'From: ABCD@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers, 'ABCD@example.com');


How to write data to a custom field I had another question at Save data to custom field columns using entity_metadata_wrapper and a similar issue at https://drupal.org/node/2110161, which nobody has been able to figure out yet.

Since entity_metadata_wrapper isn't working for writing custom field values, how can I do this manually?  I've tried the following code, but when I view the node afterwards, the field value is blank.

$fieldname = 'field_device_id';
    $query = db_insert('field_data_' . $fieldname)
        ->fields(array(
          'entity_type' => 'node',
          'bundle' => 'equipment',
          'entity_id' => $new_ent->getIdentifier(),
          'language' => 'und',
          'delta' => 0,
          $fieldname . '_esn_hex' => isset($conversion_values['ESN_HEX']) ? $conversion_values['ESN_HEX'] : NULL,
          $fieldname . '_esn_dec' => isset($conversion_values['ESN_DEC']) ? $conversion_values['ESN_DEC'] : NULL,
          $fieldname . '_meid_hex' => isset($conversion_values['MEID_HEX']) ? $conversion_values['MEID_HEX'] : NULL,
          $fieldname . '_meid_dec' => isset($conversion_values['MEID_DEC']) ? $conversion_values['MEID_DEC'] : NULL,
          $fieldname . '_imei_hex' => isset($conversion_values['IMEI_HEX']) ? $conversion_values['IMEI_HEX'] : NULL,
          $fieldname . '_imei_dec' => isset($conversion_values['IMEI_DEC']) ? $conversion_values['IMEI_DEC'] : NULL,
          $fieldname . '_iccid_hex' => isset($conversion_values['ICCID_HEX']) ? $conversion_values['ICCID_HEX'] : NULL,
          $fieldname . '_iccid_dec' => isset($conversion_values['ICCID_DEC']) ? $conversion_values['ICCID_DEC'] : NULL,
          $fieldname . '_raw_id' => $id,
        ))
        ->execute();
  }

This code runs after a submit handler passes in a device id that a user has entered, and converts it to several different formats, which are available in $conversion_values.

There has got to be a way to programmatically write values to custom field columns defined in hook_schema.

As far as the procedural method is concerned, you would use exactly the same method for a custom field as you would a contrib/core field.

Core field:

$node->body[LANGUAGE_NONE][0] = array(
  'value' = '
Some body text
',
  'format' => 'full_html',
);

Your custom field:

$node->field_whatever[LANGUAGE_NONE][0] = array(
  'esn_hex' => $some_val,
  'esn_dec' => $some_other_val,
  // etc...
);

To persist changes to both, use node_save() (or entity_save(), or whataver helper method the entity you're using provides).

node_save($node);

That's all you need to do. Manipulating the field tables manually is not recommended, as you bypass a lot of hooks that need to run, cache management, etc.

To use custom fields with an EntityMetadataWrapper, you need to go a bit further and describe the field and its columns to the entity module.

This involves adding property_type and property_callbacks to your field definition in hook_field_info(), and providing appropriate callbacks for those. There's a bit more information in this post


Additional attribute for menu link How I can add itemprop="url" for each link () in main menu?
So, I need to get from
Test

to
Test

Is it possible to do it in preprocess? I would like not to use any module for this.

Try
function HOOK_link_alter(&$variables) or function HOOK_preprocess_menu(&$variables)
Or just override the menu template (menu--main.html.twig) and replace line
{{ link(item.title, item.url, {'class': link_classes}) }}
with
{{ link(item.title, item.url, item.attributes.addClass(link_classes).setAttribute('itemprop', 'url') }}


How to hide a webform field from a node display when the per-user submission limit has been reached I have a Webform field on my node, which links to an application form. The form is set to allow one submission per user (per node). I want the link to disappear after the user has submitted the form.

Any good ways to do this?

This works (below, added to MY_THEME.theme), but I haven't stress-tested it:

function TEMPLATE_preprocess_node(&$variables) {
  // Hide field_registration_form if already submitted to it.
  if($variables['node']->bundle() == 'CONTENT_TYPE') {
    $current_user = \Drupal::currentUser();
    $uid = $current_user->id();
    $webform = Webform::load('WEBFORM_ID');
    if ($webform->hasSubmissions()) {
      $query = \Drupal::entityQuery('webform_submission')
        ->condition('webform_id', 'WEBFORM_ID');
      $result = $query->execute();
      $submission_data = [];
      foreach ($result as $item) {
        $submission = \Drupal\webform\Entity\WebformSubmission::load($item);
        $submission_data[] = $submission->getData()['user'];
      }
      if (in_array($uid, $submission_data)) {
        unset($variables['content']['field_registration_form']);
      }
    }
  }
}


Drupal 7: Protect entire site in a maintaince mode-esque fashion Looking for a way to lock down the site like maintenance mode, but without having to use maintenance mode.

I don't want to use maintenance mode because I want to have that feature available for it's proper use.

However, I would like to able to have the site viewable as normal for logged in users, and anonymous users just get a screen telling them to login or register. Probably with a login/register box as well.  So hopefully something with a template.

Any modules out there or maybe a simple custom module?

Remove the permission that allows users to view published content.  They'll get an access denied message.  Create a custom 403 page with the login info and poof!  Robert's your mother's brother.


How do I render a field on a node twice with two different field formatters? Is it possible to render a field on a node twice with different field formatters?

I have a content type with the a field type "Email". This field needs to give me as output:

A link to the default email form ("Email contact form")
The original input in the field ("Default email link")

I have put the field formats in quotes above.

Does anyone have a clue on how to do this, or if this is even possible?

You can output the field twice, using different formatters in the template

e.g, in node.tpl.php something like:

$output = array();
$email = field_get_items('node', $node, 'field_email');
$output[] = field_view_value('node', $node, 'field_email', $email[0], array(
            'type' => 'email_contact'));
$output[] = field_view_value('node', $node, 'field_email', $email[0],array(
            'type' => 'email_default'));
print implode(PHP_EOL, $output);


Point visitors to directory depending on Drupal site visited I am in the process of completing a transition from my client's old sites to a Drupal installation with multiple sites (this is my first experience with Drupal). Some of their older migrated content contains links to files available for download, which were previously located at an address in a format like firstsite.com/files/foo.zip.

They are insistent that these links not be changed, but since all of their sites are now in the same installation and there is overlap between file names (multiple sites may have a foo.zip to download), they cannot simply put all of their files in a /files subdirectory of the root (as these links would deliver a visitor to).

Is there a way I could deliver incoming requests for /files to the public files directory of each site? For example, if firstsite.com/files/foo.zip is requested, take them to /sites/firstsite.com/files/foo.zip?

I have attempted using .htaccess matched redirects but these apply universally and I cannot seem to capture the part of the request that precedes /files/foo.zip, and am not familiar enough with RewriteCond/RewriteRule pairs to build a working set for each site. Does Drupal have inbuilt functionality for this kind of legacy adaptation, or are there specific .htaccess rules that are suited to this procedure?

If you used a drupal multi-site installation for the various websites. Then each site may have it's own dedicated Files directory which may be set in Admin -> Media -> File System per subsite.


URL alias with taxonomy term (multiple vocabularies). How do I choose one? I'm trying to setup a content type that has a multiple level taxonomy vocabulary assigned. The same content has a CCK taxonomy field for other use, but I don't want to use it on the URL.

The problem is that when I put in the URL alias "[term]/[title-raw]," it selects the CCK field, not the vocabulary assigned through the Taxonomy module. I tried to change the order  of the fields, but nothing changes.

What can I do, apart from putting the other vocabulary through CCK as well?

[term] -- Name of top taxonomy term

Top taxonomy term is the term with the lowest weight from the vocabulary with the lowest weight.

Reorder vocabularies at admin/content/taxonomy, move the desired one to the top and you should be good. :-)


If I download a sub-theme do I install it under the main theme's directory? For example, I found this theme, which says it requires the Nucleus Base theme.

Does that mean that I need to install it in the Nucleus Base theme directory?

Yes, you should install it under main themes directory i.e. sites/all/themes.

Download Nucleus Base theme and put it inside sites/all/themes/ folder
Download TB Purity theme and put it inside sites/all/themes/ folder.
Go to Appearance and enable TB Purity theme.

The concept of base theme is it provides code base to its sub-theme, so, you don't really need to enable Base theme, just keep it there for your Sub-theme to find the codes that it needs to run.


Exporting Drupal 6 blog as CSV I am using Drupal 6 for a client and i want to export Blog entry as a CSV along with the title and Body content and images.

I have installed Views data export Module and went to

views ---> Add and gave views name like: blog, blog_entry, export_test

and from view type I tried: node, node_revisions

but it says: It seems the page you are looking for does not exist. Please make sure you typed the address correctly, or try again later.

How do I export it?
I want title, body and images

Very unclear what you did. Read the Views Data Export module's documentation here. It also has a youtube video at the end (for D7 though)


8 - Alter HTTP Response Headers I noticed this question, which discusses various ways to alter HTTP Response Headers.

Where would I be able to execute:

$response->headers->remove('X-Frame-Options');

I attempted to place this within my THEMENAME.theme file, but perhaps I am not doing it right because $response is not defined where I am using it.

Where does $response come from?

Where can I execute $response->headers->remove('X-Frame-Options');?

Note: I understand the risks of removing the HTTP Header.  This is for development/testing purposes only.

Got it!

From these two sources:

How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)?
https://wunderkraut.se/blogg/remove-xframe-options-and-set-contentsecuritypolicy

I realized that I was missing a mymodule.info.yml file.

mymodule
  ├── mymodule.info.yml
  ├── mymodule.services.yml
  └── src
    └── EventSubscriber
      └── RemoveXFrameOptionsSubscriber.php

Then, go to /admin/modules in the backend (Extend tab) and install the new module & clear all caches afterwards.

Woohoo!


Difference between APC & Memcached and how both can be used for cache bins I'm trying to understand the difference between Memcached and APC and why people talk about using one or the other or both. I can't understand why you wouldn't use both because I thought they had completely different roles. Here's my understanding:

APC

This caches chunks of PHP code and stores it in RAM. Then when you need to run that same piece of code again it's already cached and runs from memory lightning fast.

In my particular case of running PHP-FPM, this would reduce the load on that.

Memcached

(I'll ignore the difference between the two php modules and treat them as the same thing for this purpose)

This caches DB objects and stores them in RAM. Then when drupal needs to call the same database object all the information is sitting there and it doesn't need to go to the database.

In my particular case of running MySQL, this would reduce the load on that.

Drupal Cache Bins

There are a bunch of questions on Drupal Stack Exchange about caching and cache bins both which mention APC & memcached:

In Where is the best place for cache bins, Memcache is
recommended because of stability issues with APC.
In Is there any gain using Memcached module when APC is running good..., it's said the choice comes down to personal preference.
In Using Drupal 7 with APC, Varnish and Memcache... it talks about combining both of them.

So several of the really informative questions in this area recommend just using Memcached and a couple other ones say there's not a huge difference to introducing both.

But I don't understand how this works. Aren't they caching completely different things?

Suppose I have a view which is used a lot. Isn't memcached caching the DB objects that are shown in the view and APC is caching the module code which calls them?

Is the difference that you can only use one cache for each Drupal cache bin, so you can either choose to cache DB objects or PHP code and in practice most Drupal cache bins have either little performance difference between the two or are too large to cache all the PHP so caching DB objects is the only reasonable option?

(And thus why most people suggest memcache as the default cache bin option i.e. $conf['cache_default_class'] = 'MemCacheDrupal';)

APCu
Does not share the cache with other servers but is faster.

Memcached
Can be shared with other servers and is slower.

If you have 2 or more web servers (apache/nginx) for the same Drupal site you'll want Memcached. If you are running on a single machine then APCu will be the quickest. You'll want OPcache turned on no matter what.

LCache is a module designed to fix the issues with using APCu in a 2 or more web server environment.


prevent user with ID 1 edit I would like to prevent admin site (user id 2) to remove or change password user with id 1 although i need to admin add users and edit another users.
how to do this?

This is a Drupal no, no.  Leave root user alone. Just leave it.  If you are worry about security, change the username admin, to something else (admin is the most commonly use name hacker try to use).   Then just use uid 2 to administrate the site.


How to send the emails related to the user account in HTML? I want to send the emails related to the user account in HTML version:

forgotten password
new account
account canceled
...

If I make a copied paste of my HTML code, it does not work.

/admin/config/people/accounts

How to send the emails related to the user account in HTML ?

The mimemail module is what usually would be the right solution for this, but is seems to contain an error, so that it does'nt add HTML to the user account mails.

Check issue here, mimemail issue.


Arrange formatted fields in Views row using a template I want to render the rows of my “Recent content” Views page using a template in order to

subdivide the rows into multiple divs,
freely move around the rendered fields within these divs, and
apply some custom PHP where needed.

Idea A (fails): I could achieve this by creating a new Display Suite layout for nodes and using this layout to render my view set to display format “Content”. However, I need to group the rows by a specific field, and grouping by fields is not available in the “Content” display format – for this, I would need to chose the display format “Fields”.

Idea B (fails): When displaying fields (say, as an unformatted list), I can make use a copy of

views-view.tpl.php to adjust the coarse layout of the view, e.g., put an additional div around the whole content block;
views-view-fields.tpl.php to adjust how a single field should be rendered;
views-view-unformatted.tpl.php to adjust the coarse layout of rows, e.g. put
an additional div around the whole row. However, here the $row variable is not an array of rendered fields but rather a string containing the full html markup of the row, so I cannot access single fields and move them around within the row as I wish.

Idea C (works, but isn't it extremely inefficient?): I could display an unformatted list of fields, but render only the Node-ID-field. Then, in views-view-unformatted.tpl.php I can load the whole node corresponding to the current row via $node = node_load($row); and access all fields attached to it via $node->field_whatever. These I can then move around as I wish, wrap in divs, and apply custom PHP.

Idea C seems to work, but it also seems highly inefficient, as I will have to load the full node for every row. Also, I want to leverage the many views display formatters that my fields come equipped with, which I would have to re-build manually.

Question: Is there a way to specify formats for specific fields within the Views UI, submit only these to a template (and not the whole node), and move them around freely within the row as explained above?

I had a similar issue recently and this is what I did.

Let's say for the sake of argument that we have 6 fields: A to F. I wanted to wrap A-C in a layer eg "col-1" and D-F in a second layer eg "col-2". I overrided the field templates (views-view-fields--field-*.tpl.php) for A, C, D, F as such:

Added a
 element in A, without a matching closing tag
.
Added a
 element in D, without a matching closing tag
.
Added the respective closing tags
 i n C and F.

This may show some error or warning in your IDE, but the rendered HTML should be ok as long as the order of the fields in the views allows it (eg don't re-arrange D to be above C).


EntityFieldQuery with pager and db_or using addTag I'm having an issue that I hope some of you can help me with.

Drupal version: 7.36

I've created a list of all nodes of a certain content type using EntityFieldQuery. Since there are a lot of nodes with this content there's also pagination with 6 nodes pr page (not that it matters). Right above my list I have a little search field, where the user can search within this list of nodes with the specified content type. With this I'm using the addTag and db_or method described here: Using hook_query_TAG_alter to add 'OR' queries to EntityFieldQuery. With this the user searches both in the title and the content.

However. For some reason it doens't quite work while having $query->pager() or $query->range() and using the $query->leftJoin() function at the same time. If I outcomment the $query->leftJoin() and the connected db_or->condition() everything works fine. Or if I outcomment the $query->pager(6) everything works fine as well.

Here is all my code for getting the list of content types:

function node_load_by_type($type, $options = array()) {
    $settings = array(
        'limit' => array_key_exists('limit', $options) ? $options['limit'] : -1,
        'pager' => array_key_exists('pager', $options) ? true : false,
        'offset' => array_key_exists('offset', $options) ? $options['offset'] : 0,
        'orderDirection' => array_key_exists('orderDirection', $options) ? $options['orderDirection'] : 'DESC',
        'keywords' => array_key_exists('keywords', $options) ? $options['keywords'] : false,
    );

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', $type)
        ->propertyCondition('status' , 1)
        ->propertyCondition('nid', arg(1), '!=')
        ->propertyOrderBy('created', $settings['orderDirection']);

    if ($settings['limit'] !== -1 && $settings['pager']) {
        $query->pager($settings['limit']);
    } else if ($settings['limit'] !== -1) {
        $query->range($settings['offset'], $settings['limit']);
    }

    if ($settings['keywords']) {
        $query->addTag('search');
        $query->addMetaData('keywords', $settings['keywords']);
    }

    $results = $query->execute();

    if (is_array($results) && array_key_exists('node', $results)) {
        $results = node_load_multiple(array_keys($results['node']));

        if ($settings['limit'] !== -1 && $settings['pager']) {
            $results = theme('article_list', array('nodes' => $results, 'pager' => theme('pager', $query->pager)));
        }
    }

    return $results;
}

function THEME_query_search_alter(QueryAlterableInterface $query) {
    $keywords = $query->getMetaData('keywords');
    $words = "%" . $keywords . "%";

    $or = db_or()->condition('title', $words, 'LIKE');
    $query->leftJoin('field_data_body', 'n', 'node.nid = n.entity_id');
    $or->condition('n.body_value', $words, 'LIKE');
    $query->condition($or);
}

Has anyone experienced this before and found the solution? Or can simply see in my code somewhere that there's an error which is causing my problem.
Ideas for doing it differently is also welcome.

Thanks in advance. :)

UPDATE:

More testing tells me that what triggers this is actually joining another database table into the $query. If I don't use pagination but still the $query->leftJoin(), $query->join() or any similar functions the search actually returns a count of a lot of results even though there might only be 1 result.

Using the global variable $pager_total_items I can see that when there's actually only 1 result, it tells me that there are 1917 results. Then the pagination goes mental and doesn't know what to do, so it creates a lot of pages with the 1 result on each page.

I found the answer to this issue.

Apparently the THEME_query_search_alter hook was triggered twice (also saw this happen when altering the standard Drupal user search query) and the new table was therefore joined into the final database query twice.

So when it tried to find results in the same table two times it kinda broke the search results, and returned these many many results instead of just a few.

The fix was then to check if the new table was already joined into the query, and this is how I did it (only changed the THEME_query_search_alter hook):

function hedeselskabet_query_search_alter(QueryAlterableInterface $query) {
    $keywords = $query->getMetaData('keywords');
    $words = "%" . $keywords . "%";

    if (!array_key_exists('n', $query->getTables())) {
        $or = db_or()->condition('title', $words, 'LIKE');
        $query->leftJoin('field_data_body', 'n', 'node.nid = n.entity_id');
        $or->condition('n.body_value', $words, 'LIKE');
        $query->condition($or);
    }
}

And now everything works. :)


How do I make a block title output as a link? I have a couple of Views block displays that are being shown inside of Panels content panes.  I am trying to get the block titles to be links to overview (static) pages.  The devel_themer module suggested that I make a template file named panels-pane--block--views-case-studies-block-block.tpl.php ("Case Studies Block" is the block name.)

When I try to load the page now, I get errors about undefined variables (block_html_id, block).

I think this probably has something to do with Panels and Views templates clashing, maybe?  I'm still getting my feet wet with theming/overrides.  Any suggestions?

You can simply edit your View, and set the title of your view to this:

My Link

Click on Apply and then Save your view.


how to give the id of image in drupal 7 views? I have a view in drupal 7 and I am displaying node title and node image .
I need to give id for a image.
Now I am getting:

But I need Id .Means I need

If a unique class is acceptable, you can add a class to a field using built-in features. Under the field settings:


How to load a field from a user that is being viewed I am looking to load a field from a user's profile that is being viewed.For example, I am looking at another users profile and it will load their associated field.

I am programmatically adding a picture to the tpl (probably should be template.php) and then I am adding it to the background-image of a div. My code loads the user but then switches the user to user being viewed. It is obviously not good to be able to switch users.

Here is my code:

<?php
   $user = user_load(arg(1));
   $picture = field_get_items('user', $user, 'field_picture');
   $file = $picture['filename'];
   $url = $base_url . '/files/' . $file;
<?

I cannot find a secure way to do this. Anyone have an idea?

Thank you for your time.

Try creating a user-profile.tpl.php file in your theme and messing around with that.

Default contents are:

<div class="profile">
  <?php print $user_profile; ?>
</div>

And I suggest using a variable name other than $user as $user is a global variable referring to the logged in user.


Add comments to Webform Submission pages We use webforms for a variety of purposes such as feedback questionnaires, contact forms and request forms.

For the request forms we would like to attach comments on the submission page. This is so after the form has been submitted the User and admins can communicate on the follow up from the Request.

From what I understand the submissions pages are unique and only viewable to users who submitted them OR admins.

Anyone have any idea how I could attach unique comment forms to these submissions individually so that only the User who submitted the form and the admins can comment? Would this require a module or is this something which can be a theme override in template.php?

You would need to create a module for this. It doesn't need to be complex though. But you need a place to store the comments and some code to add the form and handle form submissions.

If you wanted to make something a little bit fancy, you could notify users when new comment on submissions are made.


How can I conditionally create a user account based on field in registration? Here is the scenario:
Prospective employees (PE) who need to access this Drupal site for onboarding resources will be sent an access code from someone in HR (to prevent random people from creating accounts).
The PE goes to Drupal site and "registers" for a user account and they enter the access code into a field.
Only approve the account if the access code is correct. If it is correct, approve account and set role to prospect. If it is not correct, block account (until that user registers with correct access code or alternately, someone in HR manually approves it).
What should the account settings be for who can register account? How to test access value and approve/grant role or block based on registration field? Is there a hook or class to extend?

Create a new field on the user object, field_registration_code.

Set the form field to show on the registration page.

Use hook_form_alter() to hide the field when not registering, if the code is not to be used in the future. Don't hide the form field on the 'manage form' tab, else it will not be rendered on the registration page.

Create a service with the following method:
/**
 * Validates a registration code.
 *
 * This function checks if the submitted  code is a valid
 * registration code, and if it is, invalidates the code, and
 * returns TRUE. If the access code is invalid, it returns FALSE.
 *
 * @param string $registrationCode
 *   The code to be validate.
 *
 * @return bool
 *   TRUE if the code was valid, FALSE otherwise.
 */
 public function validateRegistrationCode(string $registrationCode): bool;

Implement hook_ENTITY_TYPE_insert(), implemented as hook_user_insert(). This is called after the user entity has been saved. You can use that hook to check if the given code is validated, and if not, block the account. It can then be activated by an admin through the admin interface.
function HOOK_user_insert(EntityInterface $user) {
  if ($this->myService->validateRegistrationCode($entity->field_registration_code->value)) {
    // Add roles to user here.
  }
  else {
    $user->block()->save();
  }
}


How do I assign a template to the user edit form? I am trying to create a twig template for user edit page.

I have tried

/**
 * Implements hook_theme_suggestions_alter().
 */
function my_module_user_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if($variables['element']['#type'] == 'form' && $variables['element']['#form_id'] == 'user_form') {
    $original_theme_hook = $variables['theme_hook_original'];
    $suggestions[] = $original_theme_hook . '__bs_' . str_replace('-', '_', $variables['element']['#id']);
  }
  return $suggestions;
}

I have added my template in my module under templates/form__bs_user_form.html.twig

I have also added in my form_alter:

$form['#theme'] = ['bs_user_form'];

and

function my_module_user_theme($existing, $type, $theme, $path) {
  return [
    'bs_user_form' => [
      'render element' => 'form',
      ],
  ];
}

It does retrieve this error:
Argument 1 passed to Drupal\Core\Render\Element::setAttributes() must be of the type array, null given

How can I assign a template to the user edit form?

Solved, I removed my_module_user_theme_suggestions_alter and I got it working.
If anyone has a better solution feel free to add it to the answers.

To add an additional template level to a form, add the #theme key to the form array:

$form['#theme'] = ['bs_user_form'];

and in my_module.module:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'bs_user_form' => [
      'render element' => 'form',
      ],
  ];
}

The template name is then bs-user-form.html.twig, where you can print the form with {{ form }} or theme it like for example:

entity-moderation-form.html.twig

{{ form.current }}

{{ form.new_state }}

{{ form.revision_log }}

{{ form.submit }}

{{ form|without('current', 'new_state', 'revision_log', 'submit') }}

You can add theme suggestion to the theme name, but don't use form__ as base hook, because this is already used for the Form element, which caused the error.


Change link within block http://www.ascoworld.com/services

On the above page, there is a block with three icons that links to the wrong pages. I want to change where they link to but can't seem to find out how. Apologies, but I am as new as can be at this. I didn't create the website and have never used Drupal before, I just got passed it and told to fix these issues.

Thanks!

The page layout is broken but I assume that you are talking about Services menu block. Based on the HTML source it is a menu block and a main menu to be specific. So to the change the link go to Structure > Menus > Main Menu and change the link path there.

UPDATE:

Since the page is broken in my end my above answer is wrong. As @iamroald comment it is created via Views. Go to Structure > Views > Services. It seems like there is a Token substitution in there.


Migration Custom Plugin Return Value I have a migration and it is very simple. I have a CSV file of employee number and years of service. I have added the two fields to the users in the system and populate them when the users have been added. I now I have a yearly file to update the years of service value. I created the below Migration to import/update the seniority:

id: seniority_import
label: Seniority CSV file import
description: Seniority CSV file import
migration_group: timeoff
migration_tags:
  - seniority_timeoff
langcode: en
status: true
dependencies:
  enforced:
    module:
    - timeoff_seniority
source:
  plugin: csv
  track_changes: true
  path: "/Users/rfulcher/Downloads/Seniority2017-2.csv"
  keys:
    - EMPNO
  column_names:
    0:
      EMPNO: "Employee Number"
    1:
      SENIORITY: "Employee Seniority"
process:
  uid:
    -
      plugin: user_lookup
      source: EMPNO
      value_key: field_employee_id
      entity_type: user
      bundle: 1
      bundle_key: status
      ignore_case: true
    -
      plugin: skip_on_empty
      method: row
      source: uid
      message: 'no empno found'
  field_employee_id: {}
  field_seniority: SENIORITY
destination:
  plugin: entity:user
  overwrite_properties:
    - field_seniority

I also create the custom process plugin to lookup the uid of the user using the employee number

   <?php

namespace Drupal\timeoff_seniority\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Returns a user if exists.
 *
 * Example:
 *
 * @code
 * process:
 *   field_your_field_name:
 *     -
 *       plugin: your_plugin_name
 *       source: some_source_value
 * @endcode
 *
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "user_lookup"
 * )
 */
class UserLookup extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $user_uid = $this->getUserByEmpNo($value);

    if ($user_uid == FALSE){
      drush_print('usernotfound for ' . $value . ' returning 0');
      return 0;
    } else {
      drush_print('userfound:'.$user_uid.': for ' . $value);
      return $user_uid;
    }
  }

  protected function getUserByEmpNo($employeenumber) {

    $id = \Drupal::entityQuery('user')
                  ->condition('field_employee_id', $employeenumber)
                  ->execute();
    $users =  \Drupal\user\Entity\User::loadMultiple($id);

    if (!empty($users)) {
      foreach ($users as $user) {
        $update_id = $user->id();
        return $update_id;
      }
    } else {
      return FALSE;
    }
  }

  public function prepareRow($row) {

  }
}

The import runs and I find the uid and return the value but it is like the migration ignores it and skips the row.

Am I missing something. I have worked on this way too long and this should be simple but I must not be understanding how this is supposed to work or something. I am totally at a loss.

Simple csv file with just two fields empno, seniority. Nothing fancy. Any help with this would be appreciated, thanks very much.

Thanks

I think the problem might be the source on the skip_on_empty plugin. It looks like you're trying to refer to the result of the previous plugin to obtain the destination uid; I don't think you can do that until after all plugins have run on the field.

Even if you can make that reference, there's a special syntax for referring to destination fields on the source side, which is an @ symbol plus the field name (e.g. '@uid').

A solution that should remove all doubt would be to load the uid in a fake field, and re-use it for the proper destination field. For example:

process:
  _uid:
    plugin: user_lookup
    source: EMPNO
    value_key: field_employee_id
    entity_type: user
    bundle: 1
    bundle_key: status
    ignore_case: true
  uid:
    plugin: skip_on_empty
    method: row
    source: '@_uid'
    message: 'no empno found'

Of course that might be wrong, and you may just have meant to use EMPNO instead of uid for the source, in which case you should just fix that and move the skip_on_empty plugin so it runs first, saving yourself DB queries with empty conditions.


Drupal 8 RESTful POST 400 Bad Request I'm trying to use the RESTful service for creating a node with Javascript using the script below, but I only receive a 400 (Bad Request) error. I have enabled all the formats and set permissions for authenticated users.

The reports shows the following error:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: No route found for "GET /entity/node": Method Not Allowed (Allow: POST) in Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest() (line 163 of /Applications/MAMP/htdocs/comedinewithme/vendor/symfony/http-kernel/EventListener/RouterListener.php).

Do I need to set an authorization in the header? Isn't this what the csrf token is for though? And how should this be formatted? I'm completely lost!

function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://example.com/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  _links: {
    type: {
      href: 'http://example.com/rest/type/node/article'
    }
  },
  type: {
    target_id: 'article'
  },
  title: {
    value: 'Example node title'
  }
};

getCsrfToken(function (csrfToken) {
  postNode(csrfToken, newNode);
});

Figured it out: for the _links href I was using a relative URL instead of absolute.


When creating a Panel Page and selecting a layout, the page layout is not overidden I'm using Omega theme and have built 4 custom layouts for my sub-theme. If I activate layouts and select one in the admin my Omega sub-theme, everything is fine.

Now I want to use those layouts as the base for a Panel Page. When I do that, it injects the layout into the content section of the main (default) .tpl theme file.

My expectation is that it will completely replace that theme file the same way it does if I activate and use the layout in my sub-theme admin.

I've made sure to check disable Drupal blocks/regions when starting to build the layout.

I even tried using the stock layouts that come with Omega and no luck.

I can't think of anything else to try, especially since the layouts work outside of Panels.

Yes, that's how Panels is designed to work.  It can only take over the content rendered to the main content region.  If you want Panels to take over all regions then you need to use Panels Everywhere which is, incidentally, compatible with Omega 4.


Trying to disable mail on contact form, but it's still required on submit I am trying to make optional the mail field from the contact form. I manage to remove the asterisk by implementing the hook_form_alter:

function contact_field_form_alter(&$form, &$form_state, $form_id) {
    $form['mail']['#required'] = FALSE;
}

However on form submission, I get the message "You must enter a valid e-mail address". I seems that, although the field is optional on the form, it still tries to validate it. Can somebody tell me how to make it really optional?

Thanks in advance

Are you talking about the site wide contact form or the personal contact forms that each user can have? I'll talk about the site wide form, but the following roughly applies to the personal one as well.

The email validation is hard wired in contact_site_form_validate, and the $mail is also needed in the submission handler, so there is no nice way around it.

Easy way: Set the default value for the mail field to an address that you own and then disable access to the field like this:

function contact_field_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contact_site_form') {
    $form['mail']['#required'] = FALSE;
    $form['mail']['#default_value'] = 'me@my-site.com';
    $form['mail']['#access'] = FALSE;
  }
}

This will completely hide the mail field.

Hardcore way: In your form alter you could overwrite the default validation and submission callbacks (using $form['#validate'] and $form['#submit']) and replace them with your custom ones. This does not come without the risk of side effects. If you have other modules that want to add custom stuff and logic for contact forms, then this will probably break them.

As an alternative, you could use the webform module. It gives you a lot more flexibility concerning the information that you want to request and having an optional email field in there is very easy to do.

Update: You can also try the following (untested):

function contact_field_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contact_site_form') {
    $form['mail']['#required'] = FALSE;
    $form['mail']['#default_value'] = '';
    // This makes our custom validation come first.
    array_unshift($form['#validate'], 'my_custom_validation');
  }
}

function my_custom_validation($form, &$form_state) {
  // This fills an empty mail value with a default one.
  if (empty($form_state['values']['mail']) {
    form_set_value($form['mail'], 'me@my-site.com', $form_state);
  }
  // After this the default validation will run.
}

This will remove the asterisk, hide any preset value and in the validation handler a default value for the mail field is set if none has been submitted by the user. That way the hard wired validation shouldn't have a reason to complain.


File upload and file access I should upload an Excel file to a site that define a content type with a file CCK field; the download method is public. How do I set the permissions for the upload folder, if I would like to allow the PHP code to read this file, without to allow users to read this file using its URL?
If the folder permissions don't resolve this problem, which module should I use?

If you want to prevent users from downloading the file directly by URL, you should not use the public download method. You should use the private method and use the functions in file.inc to access the files with PHP.


Where are the facet blocks for search? In drupal 8, I have added couple of facets at this page /admin/config/search/facets

According to the documentation I should now have some blocks to put on the search page.  But I do not see any blocks that represent those facets on the Admin block page(admin/structure/block)

the block for the faceted search does not show up when I look for it in place block modal dialog.

What step am I missing?

The block is already created; you just need to place it following these steps:

Go to Structure > Block layout
Click on _Place block; you will get the list of available blocks
Search for the facet block and click on Place block


File permissions after module update Everytime I update a module the (linux) file permissions are changed. I use 755 permissions for my directories and 644 for files inside the modules directory.
Is there anyway I can tell drupal the default file permissions for every module update ?

This is probably not Drupal's fault. Check the default file permissions on your server!


Direct Link to a Quick Tab Is there a way for me to create a direct link to a Quick Tab? I have a taxonony term page with two tabs one contains some view result and the other is specific page of site like quiz take url(node/23/take).

If you want to find the link to load a tab, just hover over the tab and copy the link of that tab. You will notice that the link has an argument appended on the end that looks something like:

?qt-myquicktab=1#qt-quicktabs

      Note: The # sign and anything after that in the argument above is not actually required.
      You should change it to ?qt-myquicktab=1

This tells Quicktab to load the second tab (Quicktab starts counting at 0) in the third Quicktab block that you have created (a Quicktab ID of 3).

All you need to do is,place this URL argument on the end of any link that you want to load the alternative tab as the default and you are done.


Is it possible to implement date field as one select list? Currently when we use default date field with widget select list, it shows like 3 drop-downs with Year, month and date. Is there any way to make it as one drop down. I need to display few dates from today's date( may be 5 or 10 dates).

My date field should look like below section. Format can be different but will display whole date in one select list.

September 19 2014
September 20 2014
September 21 2014

I would recommend replacing the date field with text box and add a date pop to allow certain dates. This could be easily done by hook_form_alter in your custom module. See below:

    /**
     * Implements hook_form_alter().
     */
    function yourmodule_form_alter(&$form, $form_state, $form_id) {
      switch($form_id) {
        case 'your_form_id':
          $form['yourfield']['#type'] = 'date_popup';
          $form['yourfield']['#date_format'] = 'd/m/Y';
          $form['yourfield']['#datepicker_options'] = array('minDate' => '-15D', 'maxDate' => '-1D');
          $form['yourfield']['#readonly'] = TRUE;
          break;
      }
    }

You will need the Date  module enabled before you can use this.
Let me know how you go..


How do I render content "as is" from custom controller I've created a custom controller that pulls content from another node (the body). That content is defined in the node as Raw HTML.

  public function page(Request $request): array {

    $nid = $request->attributes->get('_nid');
    $node_storage = $this->entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);
    $content = $node->get('field_content')->value;

    // Load Entity using passed NID from key.
    $build = $content;
    // Return new Response($build);
    $render_array['snippet'] = [
      '#theme' => 'webpart_snippet',
      '#content' => $build,
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    return $render_array;

  }

I would like to render that content as if it were a native Symfony response. (e.g., correctly parse and HTML tags AND scripts)

In the node that I'm pulling in, I have, for example

This is text

and that is exactly what is showing on the page

It should be

This is text

I have defined a custom theme as well as twig template

/**
 * Implements hook_theme().
 * Declare a new theme
 */
function custom_webpart_snippet_theme() {
  return [
    'webpart_snippet' => [
      'variables' => [
        'content' => '',
      ],
    ],
  ];
}

Since this is a text area field, you need to specify a type of render element, processed_text.

$render_array['snippet'] = [
  '#theme' => 'webpart_snippet',
  '#type' => 'processed_text',
  '#text' => $node->field_content->value,
  '#format' => $node->field_content->format,
  '#prefix' => '
',
  '#suffix' => '
',
];


How to combine two filters in search api views? I have a search index which is indexing both content and files.
I have configured the search api views which displays the search results.
On this view, I have a filter on type which displays the content types as links using better exposed filter.
Is there any way to add another option to the same filter files but clicking on it will display files in the search results only.
Is it possible? Any custom solution hint?
I have tried the combined global filter but that only works with fields not with rendered entity.

I used an aggregated field of search api. And combined the Content: content type and Media: bundle fields.
And used that field in the search api views filter.
But the filter was a text field. So to display it as links, I have created a  custom views filter for that aggregated field.


Where to use menu_link_save I want to create some menu items, i have code for it

   $item = array(
  'link_path' => 'guarantee/validto' ,
  'link_title' => "meeeeeeeeeeeeeeeeeeeeeeeeeeeeeenu",
  'plid' => 0,
  'hidden' => 1,
        'weight' => 0,
        'menu_name' => 'main-menu',
        'module' => 'guarantee',
   );
   menu_link_save($item);

But nowhere i can find where i should place this part of code. Can someone could suggest me where to place it to create manu items? I have my moudle enabled/installed and i need to create 10 menu items like above. What will be the best solution?
is

You don't need to put in the update function.
It can go anywhere in your module just Remember to clear the cache after you update the module so you can see it.

If you're adding new menu items in a module update you should put:

cache_clear_all('*', 'cache_menu', TRUE);

In the mymodule_update_7000 function and it will clear the menu cache automatically when you update the module.

Additionally: You might be better using hook_menu for the menu items in your module.

something like this:

function mymodule_menu() {
  $items['guarantee/validto'] = array(
    'title' => 'meeeeeeeeeeeeeeeeeeeeeeeeeeeeeenu',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
    'menu_name' => 'main-menu',
    'page callback'   => 'drupal_goto',
    'page arguments' => array('guarantee/validto'),
  );
  return $items;
}

It can go anywhere you like in your mymodule.module file but generally goes near the top. Again, you don't need to put in the update function but remember to clear the cache after.


How to call function in mail which is configured using Rules in drupal I want to call function in mail body. I am using Rules modules for sending mail on some event triggers.

anyone have idea, how can i achieve this?

You can alter the mail content using hook_mail_alter

  hook_mail_alter() allows modification of email messages created and
  sent with drupal_mail(). Usage examples include adding and/or changing
  message text, message fields, and message headers.


Multiple forms for one content type using one module I want to create the following functionality:

Multiple interrelated forms needed

Form 1,
Form 1 detail and
Form 1 user detail

But the user can fill in the forms only in order.. I mean when the first form is not inserted then the detail and user detail form aren't available to the user.. and additionally I want to relate those forms also..

Is this possible with just one content type? Any ideas how I can achieve this in Drupal 7?

You can use drupal Webfroms for this purpose.

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

Some good examples could be contests, personalized contact forms, or petitions. Each of these could have a customized form for end-users to fill out. If you need to build a lot of customized, one-off forms, Webform is a more suitable solution than creating content types and using CCK or Field module.

here is the way you can create a multi step form which solves your purpose


Possibility to limit old content that is displayed to a new user I am setting up a website with Drupal 7. I would like to provide premium content for subscribers on monthly basis. I would like provide ability to buy a recurring subscription.

To avoid leeching old content, that has previously been published, is it possible to limit visibility of blog posts form history?

Let me try to clarify the use case:

I would like to provide content to my Premium subscribers in December 2012. All the users that are members in December 2012 would be eligible to see all the content created then. Since I would like this type of subscription to be real time, it would need to restrict the usage of content created before one's membership. When January 2013 arrives, I would like to have recurring membership continue, but new users that arrive in January, would be restricted to content that have been published only when they are subscribers.

The best would be, that if one purchased Dec 2012, left Jan 2013 away and resubscribed Feb 2013, he or she would see material produced in Dec 2012 and Feb 2013, but not Jan 2013.

Dripping Content would be nice, but I am not providing that kind of cumulative courses but time based content instead, and would not like to provide new users the ability to leech all the old material that they've not paid for at the time.

Thank you in advance!

To do this, you probably should implement hook_node_access($node, $op, $account).

You should return:

NODE_ACCESS_ALLOW if content is new, or user have premium role
NODE_ACCESS_DENY if content is old and user does not have premium role
NODE_ACCESS_IGNORE if you do not want to control access for this content type

There are already contributed modules to sell roles, or to take payments, so this part should be easy.

Note that hook's documentation says:

  See Node access rights for a full explanation.

I strongly advise to do it.


Alter a field by select list in entity form I have a problem with Ajax and some fields in my entity form. i have a select list in my form and when i change the selected option i wanna increment another field. To explain better, i can create some entity called "modification", in this entity i have a select list with options "option 1, option 2, option3". When i will create an entity with "option 1", my field incrément will be "1", in a create a second entity with "option 1" the incrément will be "2". But if i create a third entity with "option 3" my increment will be "1".

The first thing i need to do is to collect the element list choosen automatically and do an EntityFieldQuery. When i got the count of result i just want to put the count in my field "increment".

Here is my code in hook_form_alter (field_pjt_phase is my list) :

$form['field_pjt_phase']['und']['#ajax'] = array(
     'event' => 'change',
     'callback' => 'projetcreate_modification_callback',
     //'wrapper' => 'field_event_1_role_replace',
);

And my callback :

function projetcreate_modification_callback($form, $form_state) {
      //$valeur = $form_state['values']['list_eltmission'];
      //My EntityQUery to take the last increment....
      //return $form['field_event_1_role'];
      var_dump($form);
}

And here a picture of my fields :

How can i execute the Query when i change the select list ? How to put the result of my coult entityquery in my second field ?

Thanks for your help.

A good place to start is the aJax example module, and specifically the dependant example.

In that example, the seconds list is updated when the first list is changed, and it's value it updated according to its helper function _ajax_example_get_second_dropdown_options($selected) which is passed the value of the first list.

You could do something similar except use a simple text field for the second field but place the helper function on default value or value :

'#default_value' => _ajax_myentityfieldquery($selected),

and in the helper _ajax_myentityfieldquery return the result of your EntityFieldQuery function.


Is there any way to cancel Panels' overlay edit windows? I don't want to edit Panel panes via overlay edit-windows and therefore I tried to disable the core "Overlay" module at admin/modules but it seems to effect everything except the overlay of the Panels module.

Note: The reason I want to disable Panels' overlay is because it's slow to me (especially in Dev periods when I disable cache, and that it sometimes stuck and loads "Forever")... Besides, it cannot be open in a new tab, as I would prefer.

Do you know how to disable it?

I did some research and looked into Panels 3 code so far I don't see any nojs fallbacks. You can also check if there are fallbacks when you try to disable Javascript in the browser.

This may not be the answer on how to disable Panels modals but you may increase PHP, MySQL and or Apache settings and increase memory to your local host.


How to install a specific version of drush? How can I install the a specific version of Drush, for example 5.9.0?

The recommended way to install Drush is via composer.

composer global require drush/drush:5.9.0

See the Drush README for instructions on installing composer.


CCK textfield with checkbox How can I add a CCK field that has a checkbox and a textfield in Drupal 6? so I want to have something like this:

[x] Option1 _______________
[ ] Option2 _______________
[ ] Option3 _______________
[x] Option4 _______________

Just define 4 checkboxes and 4 textfields. If you use a bit of CSS you can get them to look like they're compound fields by floating left and clearing after the textfields. You might need to hook into the validate functions (using hook_form_alter) if you want these fields to be any smarter than that.


Adding a library to a module using composer I'm working on a module which will require a library that is already in composer.

I added a line to my module's composer.json file:

"require": {
   "markrogoyski/math-php" : "dev-master"
}

I ran the command:

composer update .

and a "vendor" directory was created in my module's directory and the files were downloaded.  However, If I add a use statement to the file my_module/src/Controller/Test.php I get an error:

----Test.php----

<?php
namespace Drupal\lims\Controller;

use Drupal\Core\Controller\ControllerBase;
use Math\Functions\Map\Single;

class Sample extends ControllerBase {
    public function content() {
        print_r(Single::square([1,2,3,4,5]));
    }
}

I see the error:

PHP Fatal error:  Class 'Math\\Functions\\Map\\Single' not found in [module path]/src/Controller/Test.php on line 9

Is there another step that I need to do to get the library autoloaded in the correct namespace?

Using composer update, Composer created the vendor directory, and the autoload.php file, which is necessary to autoload the library. Unfortunately, Drupal doesn't load all the autoload.php files found in each of the directories containing a module.

Instead of adding the dependency of your module in the composer.json file used by Drupal, you should edit its extra/merge-plugin section to include the directory containing the modules you add.  (I added the "modules/*/composer.json" line.)

"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
},

In this way, running composer update from the Drupal root directory would  add the required classes in the vendor directory used by Drupal, making them automatically loaded.

If the modules you install are all hosted on drupal.org (i.e., you don't use any custom module), you can instead edit the repositories section to contain the following lines.

"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packagist.drupal-composer.org"
    }
}

In this way, you could add a module hosted on drupal.org running composer require drupal/module-name from the Drupal root directory, and Composer would install its dependencies (declared in the module's composer.json file) in the vendor directory, making the classes automatically loaded.


How to filter view based on a parent node On my website, i have some products and some master products.

Each products depend on a master product, which can have multiple products under itself. There are 2 different content type.

In the product content type, master product is an Entity Reference.

I'm trying to filter my view to get all similar products : basically, i need a view to get all products that have the same tint has the current product.

The tricky part is that the tint is a field of the master product.

Does anyone has any part of an answer?

Thanks!

If you are displaying all similar products on another node page - load the master node by adding an entity reference relationship to your view. I don't think you can  compare values of two different nodes in a view. So, Use the view PHP module to write a filter script that can compare both the fields from the nodes.

Check out this 'Question' on using the view PHP module


Address book not visible to registered users We are using drupal commece 2 on drupal 8 and I noticed, that /user/xx/address-book/ only works for the admin user, not for normal registered ones.
It appears to be a permission issue, but under /admin/people/permissions I can not find anything billing / shipping / address related.
Anybody knows which box to tick?

Ok, after checking a bit the commerce module, it looks like this is tied to profile view permissions and also addresses are linked to customer profiles.
I made it work by enabling the following Profile permissions under /admin/people/permissions:

Customer: Create profiles (enables to create new addresses)
Customer: Delete own profiles (enables to delete addresses)
Customer: Update own profiles
Customer: View own profiles (enables the address-book tab for registered customers)
View own profiles (just in case)


Save patch changes after module upgrading Am I need to apply patch after every module upgrading? I had a patch, I changed manually handler of views module but yesterday after upgrading Views module I lost all my changes.

Is it possible to apply patch only once?

Well...no, not really.

When you apply a patch, you change the contents of the file. When you upgrade the module, you overwrite the contents of the file again, so your changes have been lost. This is a simple file-system issue and transcends Drupal's involvement entirely.

I guess you could set up some fancy file watching script which automatically applies your patch after files have been changed, or automate your upgrades in such a way that the patch is applied straight afterwards - but again that's nothing to do with Drupal as such, it's about your own workflow techniques. You'll also need to factor in the fact that your original patch may no longer apply to the newly updated file(s), so some manual intervention is probably wise.

Patches are of course unavoidable sometimes, but wherever possible don't alter core or contrib modules (for this very reason). 90% of the time you can find a clean way round the problem if you look hard enough


Custom submit handler for theme settings form I am creating a new D8 theme and having slideshow functionality in it. For slideshow, we have title, description and image field in the theme settings form. I am able to alter the theme setting form using THEME_NAME_form_system_theme_settings_alter, but when I add a custom submit handler the form seems to break and get internal server error.

My objective for adding custom submit is to make the uploaded files status as permanent.

Here is my code,

function THEME_NAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // $form['#submit'][] = 'custom_settings_form_submit'; //tried this as well
  $form['actions']['submit']['#submit'][] = '_custom_settings_form_submit';
}

function _custom_settings_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $account = \Drupal::currentUser();
  $values = $form_state->getValues();
  for ($i = 0; $i <= SLIDESHOW_COUNT; $i++) {
    if (isset($values['slide_image_path' . $i]) && !empty($values['slide_image_path' . $i])) {
      // Load the file via file.fid.
      $file = file_load($values['slide_image_path' . $i][0]);
      // Change status to permanent.
      $file->setPermanent();
      $file->save();
      // $file_usage = \Drupal::service('file.usage');
      // $file_usage->add($file, 'user', 'user', $account->id());
    }
  }
}

NOTE:
This is the error present in apache error log:
PHP Fatal error:  Invalid placeholder (!message) in string: %type: !message in %function (line %line of %file). in /core/lib/Drupal/Component/Render/FormattableMarkup.php on line 240

Does anyone have any idea where I'm doing it wrong? or is there any workaround for making the file status permanent?

From Drupal 8: Use Custom Submit Handler for Theme Settings Form:

Use this method to add custom submit handler for theme settings form in drupal 8.

/**
 * Implements hook_form_system_theme_settings_alter().
 */
function MY_THEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $theme_file = drupal_get_path('theme', 'MY_THEME') . '/MY_THEME.theme';
  $build_info = $form_state->getBuildInfo();
  if (!in_array($theme_file, $build_info['files'])) {
    $build_info['files'][] = $theme_file;
  }
  $form_state->setBuildInfo($build_info);

  $form['#submit'][] = 'MY_THEME_form_system_theme_settings_submit';
}

function MY_THEME_form_system_theme_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // TODO: Extra submssio logic.
  // This submit handler will be called before default submit handler for this form.
}


Base field provided by a module is not accessable this is a follow up to my question here.
In my .module file I use the following code to add a base field to all my nodes:

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 */
function seo_fields_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['seo_fields'] = array(
    '#type' => 'details',
    '#title' => t('Metadata for SEO'),
    '#open' => FALSE,
    '#group' => 'advanced',
    '#weight' => 110,
  );

  $form['seo_description']['#group'] = 'seo_fields';
}

/**
 * Implements hook_entity_base_field_info().
 */

function seo_fields_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $fields = array();

    $fields['seo_description'] = BaseFieldDefinition::create('string_long')
          ->setName('seo_description')
          ->setLabel(t('SEO description for this entity'))
          ->setDescription(t('If not present, the module will try to create it from entity body.'))
          ->setDefaultValue('')
          ->setSetting('case_sensitive', TRUE)
          ->setDisplayOptions('view', array(
            'label' => 'hidden',
            'type' => 'string',
            'weight' => -4,
          ))
          ->setDisplayOptions('form', array(
            'type' => 'string_textarea',
            'weight' => 1,
            'settings' => array(
              'rows' => 4,
            ),
          ));

    return $fields;
  }
}

After running update.php the field is created without any error, I am able to edit it in the node form and it saves values to the database, but once I try to access it's value (in templates or preprocess functions / through EntityInterface) I always get an empty string. Even the node form shows an empty field after input and saving (even though the value clearly exists in the DB).
Any help?

I'm going to guess and say that this is because of Unrevisioned base fields are ignored during entity load.

As a workaround (or maybe it actually makes sense to do so), add ->setRevisionable(TRUE).


Services 3.x json cache for anonymous user Does the services module always invoke php to return data in json format? Is there anyway to cache the json output to be served for anonymous users (i.e. retrieve json data without invoking php)? First request will hit php and all subsequent hits should hit the cache.

My endpoint looks like this api/anon and it does not have any session authentication.

My request looks like this http://localhost/api/anon/node/[nid]

Thanks

Even in my experience, the boost module doesn't seem to cache responses from the Services module end points the last time I tried. But here's a discussion on this topic in the module's issue tracker. There's a patch for this requirement http://drupal.org/node/1219484


AJAX callback inserts empty div with large amounts of data - Whats happening? Drupal 7 - Created a module that lists out a bunch of tabular data from an external oracle database. The list has a number of select boxes to narrow down criteria. After setting up the menu file I have the following callbacks:

function listAll($form,&$form_state) {
    //Page callback for drupal_get_form

    $form['semesterSelect'] = array(
        '#type' => 'select',
        '#title' => 'Semester',
        '#options' => array('Fall','Winter','Spring','Summer'),
        '#default_value' => 'Fall',
        '#ajax' => array(
            'callback' => 'callbackSemesterSelect',
            'wrapper' => 'courseListDiv',
        ),
    );

    $form['courseList'] = array(
        '#type' => 'markup',
        '#prefix' => '
',
        '#suffix' => '
',
    );

    if (!empty($form_state['values']['semesterSelect'])) {
        $form['courseList']['#markup'] = getCourseTable();
    } else {
        $form['courseList']['#markup'] = 'Select a semester';
    }

    return $form;
}

function callbackSemesterSelect($form, $form_state) {
    return $form['courseList'];
}

function getCourseTable() {

/***
* This function uses ob_start() and ob_get_clean() to return an HTML formatted table
*/

}

What I have noticed is that if my table goes over 30 or so rows the output ends up being an empty div where courseListDiv was previously. When its under 30 rows it displays the courseList element with prefix/suffix as expected. Is the output buffering causing this? is there a limit on ajax data or something in drupal that might be causing this?

Turns out there was some UTF8 encoding in a field that was causing the output to not be rendered. Appears to be something in the output buffering that caused this and not drupal. Adding a utf8_decode when the fields print has resolved the issue.


How to attach JSON data to JS variable without it being escaped I'm having so much trouble with drupal 8 right now.

when in Drupal 7 I could do:

drupal_add_js("var a = 'b';");

and be done with it, for the life of my, I can't figure out how to attach data to a JS variable in Drupal 8

I had to write a custom THEME_preprocess_page function to add the JSON value to drupalSettings like this:

$variables['page']['content']['#attached']['drupalSettings']['customPricelist'] = $result;

but in reality the result get's escaped with quotation marks like:

"{"some":"stuff"}"

and is not usable..

Any ideas?

something like:

$variables['page']['content']['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with alert("Hello world!");.
       '#value' => 'alert("Hello world!");',
       // set attributes like src to load a file
       '#attributes' => array('src' => ''),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world'
  ];
}


Display the value of a field list in views suppose we have this field list:

Status
  1 => foo
  2 => bar
  3 => foo_bar

in the views page I want to display

Status
------
foo
bar
foo_bar

but now it give me:

Status
------
1
2
3

In your view, click on the field, under Formatter select 'Default'.


After Module updates got "Warning: require_once() " I am using Drupal -7 and my website is on cloud(not local host).
This is NOT a multi site and using Omegasubtheme.

I have just updated workbench Moderation module from 1.3 to 1.4 and have also added Workbench Media module(7.x-1.1) to my dev. site.
After running update script, I got bunch of errors on my site. So, I again moved Worbench Moderation Module from 1.4 to 1.3.

Devel Generate and Devel Node Access Modules were enabled in my site and I made those module disabled.

After that, I got these errors so I made them enabled again.
I found this thread but, this is for database.inc for memory allocation error message in database.inc.

Devel Module

Can anyone help me how to get rid of these errors?

Errors which I got on front page:

  Warning: require_once() [function.require-once]: Unable to allocate
  memory for pool. in _registry_check_code() (line 3177 of
  /docroot/includes/bootstrap.inc).
      Warning: require_once() [function.require-once]: Unable to allocate memory for pool. in _registry_check_code() (line 3177 of
  /docroot/includes/bootstrap.inc).

Errors on available updates module page:

Warning: require_once() [function.require-once]: Unable to allocate memory for pool. in menu_execute_active_handler() (line 515

  of /docroot/includes/menu.inc).
      Warning: require_once() [function.require-once]: Unable to allocate memory for pool. in module_load_include() (line 330 of
  /docroot/includes/module.inc).

It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially because of the "... have also added Workbench Media module ...".

Assuming this is NOT a multi site, consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Another possibility that you may want to verify, is to "perform a clear cache" (it doesn't hurt, and occasionally helps solving various issues).

Curious to hear if that helps somehow ...


Why comments replies are not showing as indented? Why are comment replies not indented? I have already enabled comments threading in the settings for the content type.

All comments and their replies are shown in the same sequence and it is getting hard to find out to which comment another comment is replying.

I am using the Bootstrap theme. When I change the enabled them to the Bartik theme, comments are correctly shown as expected.

What you can do is to give the "reply" (it might have a unique id or class), some margin left to indent it under the comments.

The reason that it is indented in Bartik, is that Bartik is the standard theme and is fully compatible with drupal core.


how to show admin/reports/dblog in terminal ( cli ) While developing I really like a dedicated screen with all the drupal log messages.
Working on mac or *nix creating a new terminal window and doing a tail -f on the log file would be really nice. So I can do a tail -f on the apache error.log but I want to show the drupal log that is shown in admin/reports/dblog
Where can I find it and or is it possible to let it output to a terminal screen and if so how?

You can use drush to do this:

$ drush help | grep watchdog
 watchdog-delete       Delete watchdog messages.
 watchdog-list         Show available message types and severity levels. A
 (wd-list)             prompt will ask for a choice to show watchdog messages.
 watchdog-show         Show watchdog messages.

drush watchdog-show has too many options to fully show here, but these are the examples:

 drush watchdog-show                       Show a listing of most recent 10
                                           messages.
 drush watchdog-show 64                    Show in detail message with id 64.
 drush watchdog-show "cron run succesful"  Show a listing of most recent 10
                                           messages containing the string "cron
                                           run succesful".
 drush watchdog-show --count=46            Show a listing of most recent 46
                                           messages.
 drush watchdog-show --severity=notice     Show a listing of most recent 10
                                           messages with a severity of notice.
 drush watchdog-show --type=php            Show a listing of most recent 10
                                           messages of type php.
 drush watchdog-show --tail --full         Show a listing of most recent 10
                                           messages with extended information
                                           about each one and continue showing
                                           messages as they are registered in
                                           the watchdog.
 drush watchdog-show --tail                Do a tail of the watchdog with a
 --sleep-delay=2                           delay of two seconds between each
                                           poll to the database.


Need help with taxonomy term creating a users view I have a taxonomy field in the user registration form called location, I have a view listing all location terms (taxonomy terms).

I'm having trouble linking the terms to a view (containing the users info based on the location term), when the taxonomy term is clicked in a list of all terms, to display users that have the taxonomy term (with the same location). By default the taxonomy term view is set to display content and I'm having trouble changing that to display users.

You can create a View or Views with pages to accomplish this. The presentation of nodes connected to a taxonomy term on its display page is baked into Drupal separately from Views, I think. I'm not positive about that; I never use it. I'm more likely to go around it for reasons similar to what you're describing.

One page can easily present a list of of your location taxonomy terms. I would use a field-based view, and show the name of the term from the list. Uncheck the box that has the field link to the term directly, and instead check the box for the field to function as a custom link (under "Rewrite Results"), put in some URL that will include the location name, e.g., /user-location/{{ term_name }}. Scroll further down and you'll see "Replacement Patterns". Use what seems appropriate there.

The other page may be field-based or entity-based dependent on your specific needs. It keys off users, and makes use of a contextual filter. That contextual filter is the location term name taken from the URL. The page URL will use the one you set in the first page. Thus this page will present user info filtered by the location term.