How can I fix, or troubleshoot, Fatal Error Class not found with XHProf Module I'm seeing the following error when I enable xhprof in Drupal 8 either via Drush or via Composer.

  Class 'Drupal\xhprof\RequestMatcher\XHProfRequestMatcher' not found in /var/www/mysite/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php on line 272

I had xhprof working for a day or so, and randomly started seeing this issue. This feels very much like a Symfony/Composer autoloader issue to me, but I'm struggling with a technique or strategy for fixing or troubleshooting this.

The Call Stack feels pretty useless in this context.

I'm looking for any fix to this issue specifically, but I'm also looking for some technique or strategy for troubleshooting the missing class fatal error. The missing class error seems to keep cropping up for me with Drupal 8. I've tried to trace through the object hierarchy via xdebug, but Drupal 8 and Symfony, have a very abstracted object hierarchy. This makes it nearly impossible to be able to logically backtrack from where the error is thrown.

Why is the class not found, even though the class is definitely here: docroot/modules/contrib/xhprof/src/RequestMatcher/XHProfRequestMatcher.php?

Update:

After trying everything I could think of, I decided to just try and rebuild my VM with:

vagrant reload --provision

Sure enough, the fatal error went away. Is there some cache somewhere that drush or Drupal Console wouldn't have access to? Maybe it has something to do with the RAM or OPCACHE as @cilefen mentioned?

Note that I do not have memcache or redis running on this VM. Per a conversation on the Drupal-VM issue queue I may have been able to solve the problem by restarting PHP or just doing a reload without having to do a --provision.

The backtrace what you see could be improved by adding the following settings in your xdebug.ini file:

; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=200        ; int: Controls the protection mechanism for infinite recursion protection.

This will give you more meaningful data.

Basically you're missing a class, so you should try to clear you caches and rebuild your registry. Also restart memcached/redis if it's in use.


How to save term with term references programmatically? I've got a list of terms which I need to add or update programmatically based on their name.

To check if the term exists I'm using a combination of taxonomy_vocabulary_machine_name_load to get the vid and taxonomy_get_term_by_name to get the term if exists. Otherwise I'm creating the term as stdClass object.

When I save the term normal field (using taxonomy_term_save) in format like $term->field_address[$term->language][]['value'] = 'some address data' everything works just fine, but when it comes to save relations nothing is begin saved.

I'm saving relations as $term->field_realization[$term->language][] = array( 'target_type' => 'taxonomy_term', 'value' => $another_term->tid);.

Where $term->language = 'und'; and $another_term is a term which belongs to right field Vocabulary declared in Administer.

What am I doing wrong?

If you're using the built-in term reference field type, the column is named tid, e.g.:

$term->field_realization[$term->language][]['tid'] = $another_term->tid;

If you're using an Entity Reference field type, the column is named target_id, e.g.:

$term->field_realization[$term->language][]['target_id'] = $another_term->tid;


Search Drupal modules by dependecies I need some feature upon Entity Reference module, To clearing I need rendered version of entity in form instead of just entity label.

So before writing new module or hacking Entity reference, I should search for exist modules.

It will be good if I can see all modules dependent to Entity reference. Where can I find sucj list of modules?

There appears to be a module for this Module browser but it doesn't seem to be up to date at all unfortunately.


How to alter country dropdown in location module? I have been researching a way to limit the available countries in the drop-down that comes with the contributed locations module. I think hook_form_alter() is the way to handle just showing certain countries, but starting a hook_form_alter() snippet from hand is not something that I have the ability to achieve. After much googling I have not been able to find a code snippet to get me started.

A project I am working on now only allows registrations from the US and Canada, so I want to limit that drop-down to just those 2 countries. The function that calls the country list is location_get_iso3166_list() and the array is $countries. The location module is being used to populate pieces in the Content Profile module.

I have found a couple posts online that suggest just commenting out the countries that are not needed in the .inc file; this is not an option for this project as we are on a multi-site set-up, so changing it in the module will affect other sites. I think I need to add a hook_form_alter() snippet to the template.php.

You are correct, hook_form_alter() is a good start.  If you are looking to alter a content type form (and the CCK Location field), one method I have used is to create a really small and simple custom module implementing hook_form_alter().  Details/instructions on creating this module can be found below (for Drupal 6, should be similar if not the same for 7).

As an example, I am calling this module 'custom_countries', if you want to change the name, you can always rename the files and do a search and replace in them later.

First you need to create a new folder in your modules folder (sites/all/modules, etc).  (All files created from now on should be placed in this folder). Next, create a new file called custom_countries.info and put the following inside and save:

name = "Custom Countries"
description = "Changes the list of countries available from Location module for certain content types"
core = 6.x

Next, create another file called custom_countries.module, place the following code inside and save the file:

<?php
/**
 * @file custom_countries.module
 * Module to change the countries options of location module
 * for certain content type(s)
 */

/**
 * Implementation of hook_form_alter()
 */
function custom_countries_form_alter(&$form, $form_state, $form_id) {
  // Replace "YOUR_CONTENT_TYPE with the name of the content type desired
  if ($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    $form['#after_build'][] = 'custom_countries_after_build';
  }
}

/**
 * Make changes to countries field after all fields are rendered
 */
function custom_countries_after_build($form_element, &$form_state) {
  // Replace FIELD_NAME with the machine name of the location field for your content type
  $form_element[FIELD_NAME][0]['country']['#options'] = array(
    'ca' => 'Canada',
    'us' => 'United States',
  );
  return $form_element;
}

Important: be sure to read the comments and change 'YOUR_CONTENT_TYPE' to the machine name of the content type your location field is in (possibly just 'profile' if using default content_profile settings).  Also, change 'FIELD_NAME' to the machine name of the location field.

Finally, enable the module at admin/build/modules.

Now when you are creating/editing the content type you specified, you will only see 2 options in the countries list.  Using this method, you can now easily make changes to other forms as well.

The idea for this came from Make Location form fields available to hook_form_alter().  If in the future you decide to add other countries, the complete list of key/value pairs can be found at http://api.lullabot.com/location_get_iso3166_list/5


No content types showing under 'Add content' When I click "Add content," I get the following message:

  You have not created any content types yet. Go to the content type creation page to add a new content type.

However, under content types it lists all my content types (page, article, blog, etc). What could be causing this sort of miscommunication? The only change I made recently was moving the "Add content" link from one menu to another, but that shouldn't have affected the actual behaviour of node/add. (I did it using the admin interface as well; I didn't do any PHP editing of any sort.)

This is my recent log messages since the last content I added (edited out repeats and page not found errors):

cron    12/29/2011 - 13:02  Cron run completed. Anonymous (not verified)
php 12/29/2011 - 10:42  Notice: Undefined index: path in menu_edit_item...  admin
php 12/29/2011 - 10:42  Notice: Undefined index: path in menu_edit_item...  admin
user    12/29/2011 - 10:35  Session opened for admin.   admin
cron    12/29/2011 - 10:02  Cron run completed. Anonymous (not verified)
cron    12/29/2011 - 01:20  Cron run completed. Anonymous (not verified)
content 12/29/2011 - 00:37  page: updated Mentoring Program.    admin
content 12/29/2011 - 00:34  page: added Mentoring Program.  admin

Only change to any files was a small change to pages.tpl.php regarding rendering of page titles; and I haven't installed any modules since it last worked.

I found this :
http://drupal.org/node/997444
it seems like it's a very strange behaviour.

Basically I guess Drupal looks at that specific main menu to see what types of content can be created by users, so if even if you move all the options to a different menu none will be available.

I had to re-add the add-content link to the administration menu and re-check all the submenu items, then set it to display:none; and add the 'Add content' link to the user menu again.


build custom field in comments in drupal 6 i uses drupal 6 and i created new module.
i want to add a custom filed in comments form programmatically.
but i can not save my data in database .please help me

function mymodule_form_comment_form_alter(&$form, $form_state) {
$options = array(
    '1' => t('Yes'),
    '0' => t('No'),
    '2' => t('Empty')
);
$form['answer'] = array(
    '#title' => t('Your Answer'),
    '#type' => 'radios',
    '#required' => true,
    '#options' => $options,
    '#weight' => -1,
    '#default_value' => 'Empty'
);

In drupal 6 you should use hook_form_alter:

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'comment_form') {

$cid = 1; // TODO See bottom comment in submit funtcion about this.
$answer = db_result(db_query('SELECT answer FROM {my_module_comment} WHERE cid = %d', $cid));
$answer = $answer ? $answer : 2;

$options = array(
    '1' => t('Yes'),
    '0' => t('No'),
    '2' => t('Empty')
);
$form['answer'] = array(
    '#title' => t('Your Answer'),
    '#type' => 'radios',
    '#required' => true,
    '#options' => $options,
    '#weight' => -1,
    '#default_value' => $answer,
);
// $form['#submit'] = 'mymodule_comment_form_validate'; Uncomment and add function like submit, for validation your and other submitted data.
$form['#submit'] = 'mymodule_comment_form_submit';
}

function mymodule_comment_form_submit($form, &$form_state) {
  $cid = 1; // TODO Here you should find CID - that will link your table record with Drupal comment Id record. Use print_r or devel dsm function for investigating structure of $form_state for seeking CID value.
  $object = array('cid' => $cid, $form_state['values']['answer']);
  drupal_write_record('my_module_comment', $object); // You table have 2 columns: cid and answer columns.
}


How can I get the form validated with AJAX? I'm building pretty simple forms loaded with AJAX and displayed with Foundation Reveal. I can get the form submission to work with AJAX, and update the markup inside the reveal, but with the AJAX-powered submission button, the validation method is not executed.

Why? How can I get the form validated with AJAX?

I just want the normal form validation process, where I can add my own validation to ::validateForm and then pass control to my AJAX form submission handler.

$form['submit'] = [
  '#type' => 'submit',
  '#value' => 'Tallenna',
  '#ajax' => [
    'callback' => '::ajaxFormSubmitHandler'
  ]
];

I tried with $form['#validate'] = array('::validateForm');, but it doesn't work. I also tried calling Form::validateForm($form, $form_state) in the submission handler with the following code.

Form::validateForm($form, $form_state);
if ($form_state->hasAnyErrors()) {
  $form_state->setRebuild();
  $errors = $form_state->getErrors();
  return($form);
}
else {
  $form_state->setRebuild(FALSE);
}

I can set up the callback for a single element.

$form['field_asiakkaan_nimi'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Asiakkaan nimi'),
  '#required' => TRUE,
  '#ajax' => [
    'callback' => array($this, 'validateNimiAjax'),
    'event' => 'change',
  ],
  '#suffix' => ''
];

I can use that callback for the field processing.

  public function validateNimiAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $message = 'Nimi validoitu!';
    $response->addCommand(new HtmlCommand('.nimi-valid-message', $message));
    return $response;
  }

This doesn't seem to be the proper way to go about this.

I am also getting this error:

  The form has become outdated. Copy any unsaved work in the form below
  and then reload this page.

How can I get AJAX delivered forms validated and processed?

Here is a very basic example that will validate your data. It should give you an idea of how to handle it:

class myForm extends FormBase
{
  public function getFormId()
  {
    return 'my_form';
  }

  public function buildForm(array &$form, FormStateInterface $form_state)
  {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
    $form['some_text'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Enter a value'),
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        'wrapper' => 'my_form_wrapper',
        'callback' => '::ajaxCallback',
      ],
    ];

    return parent::buildForm($form, $form_state);
  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if($form_state->getValue('some_text') != 'Awesome')
    {
      $form->setValue('some_text', $this->t('Please enter "Awesome"'));
    }
    parent::validateForm($form, $form_state);
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    drupal_set_message($this->t('The form was submitted'));

    parent::submitForm($form, $form_state);
  }
}

With the above code, the form is built, and the ajax is set. Note that no validation needs to be set, as the validateForm() method will be called automatically if it exists. When the ajax is executed, it will always call the validate form method first. If validation is passed, then the submitForm() method will be called, but if validation is failed, it will not. Finally the ajax callback is called and the form is returned.


Custom install profile fails at creating folders I have a relatively simple custom installation profile for Drupal 8.
All it does is:

Ask for the sites domain name and the name of the theme it should scaffold.

Use the domain name to create the proper multi-site folder in /sites/<domain-name>
Use the theme name to create a theme folder under the multisite folder: /sites/<domain-name>/themes/custom/<theme-name>
Copy the relevant example files to the domain and theme folder, from the default site.

The problem I'm having is that it fails at creating the folders, due to it not being permitted to create the folders.
The /sites is set to permission 0755, and the problem is only fixed if I set sites to have permission 0777.

The folders are created using PHP's mkdir() function, as is set to create the folders recursively.

Questions:

Is there a better way to make folders during installation, than using php's mkdir(), that would fix my permission issue?
My assumption would be that the script (drupals installation UI) is being run as a different user than the one who owns the folder/filers of the site (installed via cli git and composer). How to I check which user the script is being run under? (using apache2 on centos7, in case it is relevant)

You've setup the Drupal code from the command line and now run the install from UI? Then this is normal if you have different users for the command line and the webserver, which is recommended. Only cheap hosters use one user for both. Drupal is supposed to have write access only for the sites/*/files folder and temporarily for settings.php during installation.

So you need to run this from the command line. Build the folders in a script or install the profile with a console command, which probably works without that you need to change anything in code.

Btw. this is why installing Drupal from the command line is so efficient, you get the permissions right from the start.


Contextual filter with hierarchical taxonomy terms Using contextual filters, I have created a view which shows a page of users at us/california, based on a taxonomy I have made of locations.

This taxonomy is hierarchical, though, so when the user selects San Francisco, they no longer appear on the page.

I would like them to appear on both us/california and us/california/sanfrancisco.

How can I achieve this?

I remember working on the same type of issue while ago.

The point here is Drupal will store only the deepest taxonomy item you selected and not the whole taxonomy path.

I solved that by hooking the node_save to save the whole path of taxonomy, but I'm not sure that's the best approach.

The other approach would be to find a way with views to make a join with the higher hierarchy level, by using relationships.

Another load could be to look at better_exposed_filter or hierarchical_select

I hope it helps.

Cheers


Reference a block plugin, or Form, from a Paragraph? Is there a way for a Paragraph to reference either a custom Form (built with Form API) or a block plugin that renders the same form? I only see a way to have a field that references either custom blocks (content) or configuration blocks, but not both. How can this scenario be solved?

I haven't tried it, but the Dynamic Entity Reference module looks good. The 8.x-2.x branch, although currently in alpha, sounds like it has the functionality you're looking for:

  This version allows all content entities as referenceable entities. This version also allows all config entities as referenceable entities but it is only configurable programmatically. The content and config entities can be referenced in the same field as well.

It'll mean a bit of coding to get the config entity working, but a lot less code than writing the whole thing from scratch.


Using entity reference field as filter in view I have a content type 'Player' which has an entity reference field to the content type 'Tournament'. The entity reference field allow multiple values (a player can join several tournament).

I'd like create a view of all Player nodes filtering on the 'Tournament' field. When i try to add the entity reference field as filter nothing happens (I have installed the 'Views Reference Filter'). I need also to expose the filter to the users using a droplist.

Can someone help  me? Thanks

Follow the following steps.

1) First create an entity reference field in your content type (player) and in the Entity Selection Mode
select (Simple(with optional filter by bundle) and then check Tournement checkbox, And in Additional Behaviors check (Render Views filters as select list) and save your content type.

2) Create view of type Players

3) Add new filter and choose your reference field and apply

4) Check (Expose this filter to visitors , to allow them to change it) checkbox.

6) Select Operator (Is one of) and in options check (Select all) checkbox

7) Click on Apply button and save your view.

That's all, now you are ready to filter the view using your reference field.


Use twig to style a specific block (unformated list) I have a block showing a unformated List of fields. Now I would like to use twig to style that block.

I am able to use block--views-block--blockname-block.html.twig to do the outer styling. But I could not get the fields out of the content.

Not sure to understand what you mean...

Do you want to customize the fields that appear in your block?? If so, Drupal normally provides you with available twig hooks you could use. Yours would probably be field.html.twig.

Exemple : you can customize a menu with menu.html.twig and then customize the links in that menu with links.html.twig


How do I remove the title field from a node's custom view mode In my Drupal 8 website I created a custom view mode through the UI. I use it to output nodes using a view.

In the view result I do not want the titles of the nodes to appear. The UI (content type > manage display) does not seem to give the option to hide the title.

How can I hide the title in a specific view mode for an entity via the UI or via custom code?

The output of the title is different from the other fields. The reasons for that is, that the title is used for the title block and as metadata in the html head:

html.html.twig:
<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>

If the node is used in another context, for example when it is part of a view, the title is placed in the node template as {{ label }}:

node.html.twig:
  {% if not page %}

      {{ label }}

  {% endif %}

This is controlled by the variable page, a boolean, which is true, if the view mode is full. This is standard in drupal, when the node is displayed as main content and the title should appear in the head.

If you want to change this default behavior, you have to edit the node twig or change the variable page in preprocess.

In preprocess this would look like this:

function theme_preprocess(&$variables, $hook) {

   if ($hook == 'node') {
      if ( $variables['elements']['#view_mode'] == 'teaser' ) {
         $variables['page'] = true;
      }
   }
}

This will remove the title from the view mode teaser.

Edit:

To answer the specific question in the latest comment, how to make the title field manageable in the display UI:

You have to change the field definition in a hook:

function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'node') {
    if (isset($fields['title'])) {
      $fields['title']->setDisplayConfigurable('view', TRUE);
    }
  }
}

Don't forget to remove {{ label }} from node twig, so that the title is not displayed twice.


save and generate pdfs nodes with options I have a view that list a content type A with few fields,
For PDFs generation I choose views_pdf it works perfectly and it can generate for me pdfs with the desired fields.

Im behind two problems now that I don't know how to solve them :

I want to save the PDF in my server first, so when the user click on pdf link inside the view, it save the PDF first then download it.
The PDF should be generated following options chosen by user : "download a short version", "Download a long version", ...
( inside the view I thought to make different links and for each option I create its own view. is it the best idea, or I can pass arguements to the pdf ? )

What's your advice, should I continue with views_pdf or I must switch to pdf for example...

Thanks in advance for your suggessions.

Part 1: Rules should allow you to save a PDF to the server. Step 4 on this page explains how to do so using Webforms (and Webform Rules), but it should work for node-generated PDFs: http://areatype.com/blog/create-email-pdf-files-drupal-webforms

Part 2: You can absolutely pass arguments to a Views PDF. Aren't you already doing that with the NID?


How to get the values on the other form I would like to save the form field values by using mymodule_admin(). How can I get the values saved in mymodule_admin() on the other form without using the database?

function subscription_admin() {
  $form = array();
  $form['txtSubscription'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter The Subscription Amount'),
        '#default_value' => variable_get('txtSubscription', '500'),
        '#size' => 20,
        '#maxlength' => 20,
        '#description' => t('This text field tells the subscription generation amount'),
        '#required' => TRUE,
  );
return system_settings_form($form);
}

This is the admin view form. If the administrator user changes the value, it would be changed.

mymodule_admin() is not the function that does the trick saving your variables. It's system_settings_form().

You can retrieve variables saved by system_settings_form() using variable_get() function.
So, in your case, you can get the value like this:

$txtSubscription = variable_get('txtSubscription', '');

Second parameter of the variable_get function will be returned if the variable is not set (not necessarily empty).
Notice that we used the same key as your form array's key.

During the Drupal bootrap, all variables are loaded to $GLOBALS (Thanks to kiamlaluno for the correction). Do not use this to store all your data because all of these variables will be loaded on every bootstrap.


How to make user profiles editable by site administrators For a site I'm building, Profile2 is not an option because it doesn't play with Pathauto. As an alternative, I want to extend the regular user profiles with a mugshot and a bio text field. I don't want the profile owners to have exclusive editing rights over those two extra fields; site administrators should be able to enter the profiles and edit the image and the text as required. Out of the box, this isn't workable because an administrator would need to override the user's password to make any changes to a profile, thus effectively issuing a new password for every change made. Is there a way to give administrators regular editing access to the profiles?

Yes, you can add the fields to the user entity at

admin/config/people/accounts/fields

While I think you can save the account form without updating the user password (don't enter a value for password when saving), if you want to move the password to a separate tab, you can use the module

password_tab


How to see if there is a hidden admin role with an account that has no admin access? I'm completely new to Drupal. A friend has asked me to help out with his Drupal 7 site. He created an account for me - but I'm thinking that the role given to my user account isn't really an admin account. When logging in, I don't see any way to administer modules, user permissions, etc.

I'm thinking that the admin role is hidden. For a person who is just now learning Drupal, what would be the easiest way to see if there is a hidden admin role?

... For a person who is just now learning Drupal, what would be the easiest way to see if their is a hidden admin role?

Talk to your friend, and perform these steps:

Step 1: ask for a screenprint (created by your friend, while your friend is logged in) of the list of roles shown via relative path admin/people/permissions/roles ... That will show you all "roles" defined in your site. Typically you'll have at least these 3 hardcoded (= delivered with Drupal) roles:

anonymous user (in the Drupal database this corresponds to role id = 1).
authenticated  user (in the Drupal database this corresponds to role id = 2).
administrator (in the Drupal database this corresponds to role id = 3).

Step 2: find out what the "user id" is for the user that you received, which you'll typically see (as part of the relative path) when you try to edit your own profile.
Step 3: ask for a screenprint (created by your friend, while your friend is logged in) of the granted roles shown via relative path user/uid/edit (whereas uid in it corresponds to your own user id) ... That will show you all "roles" you have been granted. Probably the role "administrator" will not have been granted.


Is it compatible with PHP 7.2? We have a Drupal 7 site running Drupal Commerce. Our host has now informed us that they will be updating PHP from 5.6.3 to PHP 7.2.

Is Drupal Commerce for Drupal 7 compatible with PHP 7.2?
I have tested Drupal 7 with PHP 7.2 on another domain; for most of the part, it appears to work. However, I have not been able to test Commerce on PHP 7.2, yet.

Compatible with PHP 7.2?

Yes, currently the only issue I see in the issue queue is:

PHP 7.2 Warning: A non-numeric value encountered in commerce_currency_amount_to_decimal()

You'll have to apply this patch yourself since it has not been committed.


Install APC and Memcache and their extensions I am building a drupal 7 site.
My site is currently hosted on the bluehost - shared hosting.

When I tried to install APC module I got the following error: "The APC module needs the apc extension see: http://www.php.net/apc. (Currently using APC Not available)"

I have no idea how to install the extension (even after I read not-so-clear guides).

I spoke with the support of bluehost, and they told my I can't install the APC extension on shared hosting.

I also tried to install the Memcache Module.
I also got here the following error: "(Currently using Extensions not available Either the memcache or memcached extensions must be installed in order to use memcache integration.)
You must enable the PECL memcached or memcache extension to use memcache.inc."

I really can't use the APC module?
Can someone please help me install the APC module & extensions?

What about the Memcache Module?
How can I install & enable the PECL?

If your stuck with shared hosting there are a couple of options to make Drupal faster.

Use some form of a file cache for the page cache. Boost & filecache's filecache_fast_pagecache option will serve cached pages a lot quicker than core does. For the other cache tables filecache or Drupal's core database cache might be quicker; you'll have to test to see what one works better on your shared hosting.
https://drupal.org/project/boost
https://drupal.org/project/filecache

Optimize your database. This is a post of things that can be done on the drupal side; there is a lot more that can be done if you can change the mysql side.
Drupal 7: Database select query FROM cache_bootstrap brings server down


Internationalization and pay.nl does not seem to work properly together, any idea how to fix that one? I am working on a website with four languages.

We use Ubercart with external payment facilities. We have Paypal and the following specific to Netherlands: eBanking, iDEAL, MisterCash. That works fine.

Now we are trying to get pay.nl to work. This one offers more methods of payments.

The request uses /nl/ as expected with a path that looks like this:

http://www.example.com/nl/order/paynl/notify/?...snip...

But the i18n module seems to change that to /en/ instead:

http://www.example.com/en/order/paynl/notify/?...snip...

And that prevents the payment from being accepted.

Any idea what could be happening? Would there be a way to prevent translations from happening when hitting /order?

Your problem might be because of the "Language negotiation" configuration.

So check this configuration, which in D6 you can find via /admin/settings/language/configure/language. Experiment with the 4 available options in the Language negotiation selection list, to see if any of these options solve your issue.


do some action when order status is changed to complete In drupal commerce I want the rules module to do some action when the order status changes to completed. In fact, after buying some product an order is added to order list. Then, what I need is that when the moderator comes and change the order status to completed the order owner get permission to see some content type.

I have tested these rules but none of them worked!!

Event: After updating an existing commerce order
Condition: Execute custom PHP code

if([commerce-order:status] == 'completed') return TRUE;
else return FALSE;

or this one:

Event: After updating an existing commerce order
Condition: Data comparison

Parameter: Data to compare: [commerce-order:status], Data value: Completed

or this one:

Event: After updating an existing commerce order
Condition: Data comparison

Parameter: Data to compare: [commerce-order:state], Data value: Completed

In fact, without adding any condition the reaction is done after adding an order by customers (do not wait for moderators to complete the order) and with any of these conditions, rules never fire and the is reaction never done.

According to the details provided by you in comments, your rule is assigning new role to the user who is currently editing the order [site:current-cart-order:owner].

You need to use [commerce-order:owner] token in "Add User Role" action.

[commerce-order:owner] represents the user who created the order, and not the user who is editing it.


Adding custom designed product to cart in drupal commerce Hi I am developing a site for T-shirt designing. I have a custom UI where all the T-shirt products in my site are loaded. customer can design the T-shirt according to their needs like changing color,adding text/image etc using my UI. At the end of UI I have a buy button where user can buy the custom product. How can I add this product to my Drupal cart when user clicks buy button? I have the product id and price loaded in my hand and am using Drupal commerce module in my site.

This is my button form

<button type="submit" class="btn btn-primary"  name="button">
                                Buy Now! </button>

I think you can done it using commerce_cart_product_add(). Pass product id and line item as parameters. For details please check here.Hope this will help you..


Command option to ignore errors during drush dl Just trying to start creating prefab lists (of modules etc.) and building my site development environment at the moment. I'm trying to call sudo drush dl (list of modules) and it works until it can't find one and stops the entire process.

Is there a switch I can use to get drush to continue through the list and perhaps even list the terms which failed to download (not important). I've just seen a sentence alluding to creating your own drush commands, but figured I'd check the community first as that could take a big chunk of scarce time!

Thank you for contributing to this great site, hopefully one day I can return the favour!

Sorry... Found out how to work around such a situation:

By skipping the explicit download function dl and just using the enable encommand

cd module path

drush en file list

you get an automatic download option, which I think by adding -y you can automatically answer yes to all pompts. It's just a problem that sometimes the module names won't always match the package name.


Why does in Drupal 8 there are two different namespaces for test cases? In Drupal 8 core modules tests are under two different namespaces which maps to two different directories under the module.

\Drupal\Tests\<mymodule>\<TestSuiteType> => <mymodule>/tests/src/<TestSuiteType>
\Drupal\<mymodule>\Tests => <mymodule>/src/Tests direcotry.

For example in field_ui module.

\Drupal\field_ui\Tests\FieldUIDeleteTest => field_ui/src/Tests/FieldUIDeleteTest.php
\Drupal\Tests\field_ui\Functional\EntityDisplayModeTest => field_ui/tests/src/Functional/EntityDisplayModeTest.php

Can someone please explain the reason behind this and any advantage of writing test cases under two different namespace for the same module?

They're just different kinds of tests, with different requirements/dependencies, and so they're split up.

From PHPUnit file structure, namespace, and required metadata:

  File structure and namespace

  There's a special relationship between the location of test files within the file structure, the namespace they use, and the class which they extend.

  Drupal Unit Test Suites: Auto-detected Tests

  Drupal 8 uses a number of test suites to allow for choosing between different kinds of tests to run.

  Drupal 8 has the following test suites:

  Simpletest: Legacy tests based on the Drupal version of the Simpletest framework.
  Unit: PHPUnit-based tests with minimal dependencies.
  Kernel: PHPUnit-based tests with a bootstrapped kernel, and a minimal number of extensions enabled.
  Functional: PHPUnit-based tests with a booted Drupal instance.
  FunctionalJavascript: PHPUnit-based tests which use PhantomJS to perform tests of Javascript functionality.

  Drupal's test system can discover these different test suites for core, core extensions, and contrib extensions, as long as the tests are placed within the proper directories so they can be discovered as belonging to one of the test suites listed above.

  Simpletest-based tests must be placed in an extension, within that extension's src/Tests directory. They will have a namespace of \Drupal\$extension\Tests.

  PHPUnit-based: Generally, the other suites must be within a tests/src/$suite_type/ directory. These tests will have a namespace of \Drupal\Tests\$extension\$suite_type.

  Traits: The third class is traits. It is possible to write a trait which will be discovered and can be used by the various different test types. Each test suite will discover the trait if it is placed in the tests/src/Traits directory, and the trait will have a namespace of \Drupal\Tests\$extension\Traits.

  Note that the class names must END with the word Test. The test methods within the class must START with the word test.

Simpletest Class, File, and Namespace structure also provides a bit more insight.


How to install a drupal distribution using Drush quickstart command? What is the command for drush qc to install a drupal distribution? I'm trying to install this one: https://drupal.org/project/onepagecv

The drush command is

drush site-install <profile>

as noted here in the quickstart documentation, you can use this to install a full drupal site using a specific profile from a single command, ex:

drush site-install onepagecv --db-url=mysql://[db_user]:[db_pass]@localhost/[db_name] --site-name=Example

This assumes you already have Drupal core downloaded and this profile in your profiles folder.


"More like this" for a view I know how to get a "more like this" block for an individual piece of content (as a block in a panel, or whatnot), however these functions don't seem to work with the results of a View.

My site has a few pages that list the content of a specific taxonomy term (Industry).  Each content type listed has an additional taxonomy term associated (Focus Area).

The view that is presented on the site allows the visitor to select the Focus Area, which when selected, limits the content on the page to matched terms.

I'm trying to get a "more like this" block for the results of the view.  There may be other content that matches the Industry and Focus Area (such as an Event or a Career) that we would like presented.

Bonus points if you can help me make the Focus Area selection persistant across the site (so that when the visitor navigates to a different Industry page, their selection for Focus Area is remembered and applied).

Use of Solr is a possibility as well.  We haven't turned it on while in development, but is part of the plan.

Thanks in advance.

I think what you are looking for is https://www.drupal.org/project/global_filter. There is a good README on how to use it: http://drupalcode.org/project/global_filter.git/blob_plain/refs/heads/7.x-1.x:/README.txt


Removing Unnecessary CSS Files I am in the process of optimizing my Drupal site by removing unnecessary css files.

Running an audit I have found that /misc/ui/jquery.ui.core.css, /misc/ui/jquery.ui.theme.css and /misc/ui/jquery.ui.slider.css are relatively large but are never called.

I have tried removing them in my template.php file with the following but they still remain. How can I unset them?

unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.slider.css']);
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.core.css']);
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.theme.css']);

You can use hook_ccs_alter

function yourmodule_css_alter(&$css) {

  unset($css['misc/ui/jquery.ui.core.css']);
}


How to prevent a node from listing programmatically? How can I prevent a node from listing, programmatically? I want to select node by nid. Beacause of some reasons, I don't want to use hook_node_grants() and hook_node_access_records()

I tried to change the _node_access_where_sql() function in the core which creates where clause for use in fetching node listings but $node or $nid is not passed to the function so I can't select node by nid

Have you tried simply unpublishing the node with Rules? Rules will allow you to programmatically unpublish content based on a variety of factors. Once unpublished, Drupal will not list the node in content with the exception of Views that are not set to only display published content.

What are you using to determine which nodes should be processed by your code?


Regarding content slider on mobile screen I am trying to make a Drupal 7 desktop site into a responsive one. There is a view of type node listing the node title and image in a grid format on front page. I want that on the mobile screen instead of a grid it just becomes a list of horizontal fields and can be navigated by touch (maybe act as a slider). Any leads how to proceed.

Please shoot out if you need any more info. Would really appreciate any suggestion.

Thanks

Option 1:

Flex Slider allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

  Touch enabled navigation
  Keyboard navigation
  Configurable slide animations
  Multiple sliders per page

Option 2:

Views Responsive Grid provides a views plugin for displaying content in a responsive(mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality


Are there any hooks that get called before modules are loaded? There are a few user tracking checks I would like to perform before the site main page gets loaded. I don't really want to have to wait for drupal to load all the modules and start running the theme code before I do this.

Are there any hooks that can be overwritten to perform my checks?

I don't recommend using hook_init() as it doesn't run on cached pages. Try using hook_boot(). As per the documentation it runs at the beginning of the page request when Drupal is still in the bootstrap. Hope this helps!


Add custom image in Views (No field) I have field structure in Views page. And i want add a image every page item. But not want create img field.,

I search this options in my Views, found 'custom text' option but not found a solution.

Is it possible? How? Thank you.

You need to add the image in that view's template file.

For views hook suggestions refer to this page http://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7

It would be best if you copy the default views-view-fields.tpl.php from views module to your theme directory and add the image there.


How to get product variation of a single product in view Let's assume I have a product named A, B, C and each of those products have variations.

Now, when I am making a block in views, when I only have the option to select product variations as seen in this image:

After this, there seems to be no way to select a product variation of say product A.

All the variations are there by default.

You need to add a context to tell the view which product you want to show. Either from the URL with product id in url, or static product id number, or some other way.

The context filter for views relies on a url or some other way to set a value. In this case you want to select one of your products that has variations. So, if your url is /myproducts/1, the context filter can be set to use 1 for the product id and show only that product along with only its variations.

How to pass Views contextual filter via URL?
https://i.stack.imgur.com/8cLtw.png

Use Provide default value from URL, then choose which part of the path will have the product id in it. Then when you link to this view, use the url that way.

On your index page view, you can make the links to products this way so it passes the product id to your page.


How to do arithmetic on a contextual filter Rather than specifying a contextual filter, is it possible to specify a contextual filter +1 (i.e. add one to the current filter value?)

If you have a view taking an argument, i understand that you can create a global text field to make a link to a different view using the original argument.

I.e. in view1/arg1 i can have a global text field which outputs as a link to
view2/arg1

Is it possible to create a global text field which outputs as a link to view2/arg1+1

i.e. adds one to the current argument?

In Views for D7 (not sure about D6) you can add a field of type "Math expression" to do this sort of thing.  Enter the expression [!1]+1 (or maybe [%1]+1) in the Math expression field, and then later text fields can refer to this value (in their Rewrite sections) as [expression].


How to update a field, after a view page is visited? Scenario:

I want to use a view to allow user to check a given code (string-like, eg "abc123") whether it is exists in the database, as well as whether the code has been checked before.

A content type called "code" is set up, has a field of "field_code_checked", either "0|Not yet checked" or "1|Checked",  and the title field represents the "code" string. The title field will be use as argument a.k.a the contextual filter of a view page to check the code.

So a view page 'check' is set up.
http://mysite.com/check/[code-title]  => e.g  http://mysite.com/check/abc123

For example:
If 'abc123' exists and field_code_checked value is '0' (not yet checked), then view will output the code node information.

My problem is: how can I manage to update 'field_code_checked' to 1, once a checking visit is done? So when abc123 node is created, it has a field_code_checked set to 0 by default, when a user visit http://mysite.com/check/abc123, I want field_code_checked of abc123 node set to be 1.
Any solution?

Thanks.

I end up use the hook hook_views_post_render() to update field value.


Add Block to Content but set it to appear after the node content? I have added a block to appear in the Content region, however it appears above the content of the node for French, but below the content of the node for English - which is strange as (as far as I know) they're both the same content type and should be the exact same templates.

Although the block name (and /url) is the same as the English nodes' url so maybe that's causing some problems which causes the block to appear after the nodes' content?

Is there any way to specifically define that you want a block to appear after the nodes' content? i.e. through weighting inside the module that adds the block?

EDIT:
I've set the weighting on the blocks admin page, it's +15 for the block and the Main Page Content is -17. I also dragged it out of that region then back (without saving) before saving but still appears above for the French node and below for the English node...

EDIT 2:
Seems to be a problem with the cache, at least a localhost version showed same error until I cleared cache... only problem is I don't have access to clear cache directly, could I code something in the module to clear the cache?

EDIT 3:
So I have access to clear cache now, except the block is still showing up above for the French node and below for the English node... even though in Block Structure, the block is below the Main Page Content.

Go to "Structure >> Block" and drop down your block to the main content.


Combine 2 fields into select I'm looking for a way of mergin 2 fields into html select item. First field is links to other nodes within drupal, second field is links to another external content. Now I would like to merge these fields into html, which I could program "onChange" to follow selected link. Any ideas? Should I override both .tpl.php for that field, then with jQuery build one select? Or maybe this could be done easier, before rendering? Or maybe views might be enough? View, type of entity, added to certain node.. but then I have problems finding way of displaying those fields at the same time. Any advices?

I'm not sure what exactly you want to achieve. Maybe this two modules are helpfull for you:

Dependent fields
Conditional fields


Is there a module similar to the Tiered Taxonomy Block module for Drupal 7? I have two taxonomies (tags, and group), and one content type (article). I want to show tags which have content in page of group/123.

I found Tiered Taxonomy Block which has similar functionality, but it is only for Drupal 6, at the moment.

What is a similar module for Drupal 7?

Not sure if there is a better solution but this can now be done in a round about way with views.

Create a term view.
Add a required relationship to its parent term.
add a required relationship to node.
add term title for both term and parent term relationship and term count.

You'll have to display the hierarchy at the theme level unless you want to use group headers.


Simple Drupal hook_menu I would like to pass data from Javascript to PHP using Drupal 7.14.  To this end, I'm trying to follow this SO post: https://stackoverflow.com/questions/4834132/how-to-pass-jquery-variable-to-drupal-ajax.

However, |hook_menu()` is not working as expected.

function example_module_menu() {
  $items = array();

  $items['example_callback/%'] = array(
    'title' => 'My Custom Callback',
    'description' => 'Description',
    'page callback' => 'my_custom_php_function',
    'page arguments' => array(1), // fill this
    // 'access arguments' => array('access content'),
    'access callback' => true,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Function that gets called from JQuery asynchronously.
 */
function my_custom_php_function($argument) {
  // Do something with $argument...
  echo $argument;
}

In my understanding, going to http://mywebsite.com/example_callback should call my_custom_php_function.  Instead, I get:

  The requested URL /example_callback was not found on this server.

Are there other steps necessary to write a simple menu callback?

Your URL is expecting an argument so your URL would have to be  http://mywebsite.com/example_callback/something. I wouldn't bother with the extra % in the path though.

So you should be doing something like and it will still pick up the arguments:

function example_module_menu() {
  $items = array();

  $items['example_callback'] = array(
    'title' => 'My Custom Callback',
    'page callback' => 'my_custom_php_function',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
 );

 return $items;
}

/**
* Function that gets called from JQuery asynchronously.
*/
function my_custom_php_function() {
  if (arg(1)) {
    // this means there is an argument
    // Do something with $argument...
  }
  return '';
}


View Contextual Filter format for Block I have created a View on my /blog/ page for displaying blog articles. For layout reasons this view is in a block.

This view has a contextual filter for Taxonomy tid on node and, since it is a block, it has a default value of Taxonomy Term ID from URL. When I enter tids in the preview box it works.

However, how do I format this in the url? /blog/1 /blog/term/1 and /blog?tid=1 all return 404 pages. How do I put the tid in the url?

Mainly contextual filter works with /blog/page/[contextual filter id] e.g. /blog/page/2

By default its hard to pass the contextual filter id to a block, but you can do it this way

If you have url blog/page/2 then you can set this as shown in the image(3rd argument is 2 that will  be passed to view block ), also add necessary relations accordingly.

Hope it will help you.


Adding an active menu trail to the main ul, in the html.tpl.php? Is there an easy way to get the active menu trail in this nav ul? I don't really understand PHP yet, I'm still learning. I personally would have setup the menu in Drupal, not in the html.tpl.php.

  <? foreach($full_menu_items as $menu_item) : ?>
  <? if($menu_item['#original_link']['has_children'] == '1') : $belowMenu = $menu_item['#below'] ?>

  <li class="<? { echo "";  } ?>">

<? echo $menu_item['#original_link']['link_title'] ?>

       <? foreach($belowMenu as $sub_menu_item) : ?>
       <? if($sub_menu_item['#original_link']['link_path']): ?>

<a href="<? echo $sub_menu_item['#original_link']['link_path']; ?>"><? echo $sub_menu_item['#original_link']['link_title']; ?>

       <? endif; ?>
       <? endforeach; ?>

        <? else: ?>
   <? if($menu_item['#original_link']['link_path']): ?>

<a href="<? echo $menu_item['#original_link']['link_path']; ?>"><? echo $menu_item['#original_link']['link_title']; ?>

   <? endif; ?>

   <? endif; ?>
   <? endforeach; ?>

Use menu_tree_page_data to get an array of the menu items. Set the trail accordingly there.

Example: http://brightplumbox.com/30Drupal7API/#/7/4


drupal_goto in new tab Shortly: How can I open a drupal_goto() result in a new tab?

More details:

I've got a list of news, made with Views, that can be imported from a RSS feed (big custom module, very complicated, etc, etc) or directly written by the site's editor.

When I click on a news, I access the node full view mode page and, if it is an imported news, I'm redirected to the source site with drupal_goto(source).

I want to redirect to the external source site in another tab. And I can't figure it out. I'm not even sure if that's possible with only PHP.

Thanks in advance for any help.

That isn't possible - drupal_goto() happens server-side, and you can only affect tabs/windows with client-side code.

You would need to stop using drupal_goto(), and instead insert some javascript into the page which opens the new URL in a new tab upon refresh.

Some (including myself) would also argue that you have no "right" to do this - let the user decide whether they want a new tab or not. Be careful of trying to force your will onto them. See Target Blank is Evil for a wonderfully opinionated bit of rhetoric on the matter.


View of events repeats month I have an events content type, and from it, I have a view that lists events. We're using a bootstrap theme, and the format of the display I'm concerned with is Bootstrap List Group. This allows us to use a field as a grouping header.

Since we want the end user to see events grouped by month, we have the display of the grouping field set to Year Month. So for example, one header would be "July 2018".

We also have the view paged, so that it shows 15 events per page. We've added a "Show More" button at the bottom.

However a problem arises when the next page of events start in the same month as the previous set ended in. So for example, the user might see this:

 August 2018
  - Labor Day Holiday
  - a cookout
  - a meeting

[ Load More ]

Then when they hit "Load More", they see this:

 August 2018
  - Labor Day Holiday
  - a cookout
  - a meeting

 August 2018
  - Ice Cream Social
  - a party
  - ...

[ Load More ]

How can I prevent the Grouping header from repeating on loading more?

Your description makes it sound like you have ajax views enabled which is probably going to be very challenging to get working correctly.

There may be a better backend way to do this, but one way that occurs to me is to fix this on the client side with javascript, by merging lists after ajax finishes loading.

Copy the Bootstrap List Group view display template into your theme's templates folder.
Add a custom data attribute to mimic the text value of the grouping's row title, and attach a custom javascript behavior to do the work on the client side.

{{ attach_library('yourtheme/prevent_duplicate_list_group') }}

  {% for key, row in rows %}

      {% if row.title %}

{{ row.title }}

      {% endif %}

{{ row.content }}

  {% endfor %}

Create a library in yourtheme.libraries.yml to add a JS behavior.

prevent_duplicate_list_group:
  js:
     js/prevent_duplicate_list_group.js

Write some custom javascript logic to look for all instances of the duplicate grouping and move the values from the second list into the first.

I've not used bootstrap views thus don't know the exact dom structure you'll need to work with, but here is something completely untested to get you started.

/**
 * @file
 * Behavior to merge duplicate List Group titles loaded from ajax-enabled views.
 */

(function ($) {
  'use strict';

  Drupal.behaviors.prevent_duplicate_list_group = {
    attach: function (context, settings) {
      $('.list-group-item-heading', context)
        .each(function (idx, element) {
          var title = $(element).attr('data-grouping'),
            duplicates = $('[data-grouping="'+ title + '"]');
          if (duplicates.length == 2) {
            var first = duplicates.eq(0).closest('ul');
            var second = duplicates.eq(1).closest('ul');
            // snagged from https://stackoverflow.com/a/28487699/413538
            // you may need to overhaul this to only walk through
            // list items from the second list up until it gets to a list item that contains an h4 and hide each individual li
            var i=1;
            $('li', first).each(function(){
              $(first).append($('li:nth-child('+i+')', second).clone());
              i++;
            });
            second.remove();
          }
        }
      );
    }
  };
})(jQuery);


Drupal Lookup Path Change I am displaying demonstration sites with iFrames and in page--demo.tpl.php I have a possibility to get NID only from path. So I managed demo's number will be the same as NID and now I have a code:

print drupal_lookup_path('alias',"demo/".$node->nid);

It works correctly but I would like to transfer that link to /node/$node->nid.

Is there any way to do so? I tried to print $node->nid underneath, but it prints wrong number (36 instead of 34).

Thanks!

$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
print $path[1];


Add new column "Block description" on block layout page I need to add a new column called Block Short Description on Block layout under /admin/structure/block.

Can anyone let me know how to achieve it?

I have Attached screenshot for reference.

That's a form. Themed as table. So I managed to do what you want via hook_form_FORM_ID_alter.

Thing is, I can't find the block description or admin label inside the block entity. So that's left. I hope you can find a way or maybe you can specify what "Block Short Description" is supposed to be.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_block_admin_display_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Add header column.
  array_splice($form['blocks']['#header'], 1, 0, 'Description');

  // Go through all blocks.
  foreach ($form['blocks'] as $bid => $block) {

    // Skip non-block elements (like '#header' or 'region-name').
    if ($bid[0] != '#' && !strpos($bid, '-')) {

      // Load block.
      $entity = \Drupal\block\Entity\Block::load($bid);

      // Load description.
      // ksm($entity);
      // Can't find one. Take the label for now. Let OP figure this out themselves.
      $description = $entity->label();

      // Add description column to row.
      // @see https://stackoverflow.com/a/3354804/2199525
      $array = $form['blocks'][$bid];
      $form['blocks'][$bid] = array_slice($array, 0, 2, TRUE) +
        ['description' => ['#markup' => $description]] +
        array_slice($array, 2, count($array) - 1, TRUE);
    }
  }
}

Answer updated to display content type restrictions.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_block_admin_display_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Add header column.
  array_splice($form['blocks']['#header'], 1, 0, 'Description');

  // Go through all blocks.
  foreach ($form['blocks'] as $bid => $block) {

    // Skip non-block elements (like '#header' or 'region-name').
    if ($bid[0] != '#' && !strpos($bid, '-')) {

      // Load block.
      $entity = \Drupal\block\Entity\Block::load($bid);

      // Load visibility settings.
      $conditions = $entity->getVisibilityConditions()->getConfiguration();

      // Load content types.
      $types = [];
      if ($node_types = isset($conditions['node_type']['bundles']) ? $conditions['node_type']['bundles'] : FALSE) {
        $node_types = Drupal\node\Entity\NodeType::loadMultiple($node_types);
        foreach ($node_types as $node_type) {
          $types[] = $node_type->label();
        }
      }

      // Set description.
      $description = 'Content types: ';
      if (!empty($types)) {
        $description .= implode(', ', $types);
      }
      else {
        $description = '- no content type restrictions -';
      }

      // Add description column to row.
      // @see https://stackoverflow.com/a/3354804/2199525
      $array = $form['blocks'][$bid];
      $form['blocks'][$bid] = array_slice($array, 0, 2, TRUE) +
        ['description' => ['#markup' => $description]] +
        array_slice($array, 2, count($array) - 1, TRUE);
    }
  }
}


How can I programmatically distinguish if a block is enabled or disabled from block layout? I have 2 custom blocks. I have added both this in regions of block layout. But when i disabled the block from layout. I must identify it from code or api that the particular block is disabled. How to know that?

Use BlockContent::getInstances to get all blocks placed for this custom block, then check for each block instance if it is enabled with $block->status().

See Get block programmatically and How can we check whether block is enabled or disabled in .theme file?


Use Exposed Filter value in no result Global text I'd like to use the value of the chosen Exposed Filter (=dropdownlist) in the Global text block when there is no result.

In detail:
Exposed filter (which is a taxonomy list) has 3 values of provinces:

Province 1
Province 2
Province 3

When there is no result using a chosen value, there should be a message (= global text, I presume), saying "Sorry, there are no addresses found in Province 2".

Is this feasible in Drupal views?

set no result text area of view from advanced "No result behavior"
then edit your view using hook views_pre_render

Access your exposed input in same hook using :

$view->exposed_input['your field name']

then in same hook set these fields:

$view->empty['area']->options['content'] = "Set your message"; ( append exposed filter here)
$view->empty['area']->options['label'] = "Set your label"


Hide child pages from menu tree Hopefully some wise Drupal guru will be able to help me with this one.

I'm using menu and menu block to output a side menu in Drupal 7.  Using Panelizer, on a basic page I can customize display and add a view pane (Case study: Teaser), which will display a list of case study teasers:

I can add a case study content type, which provides a menu link.  The problem is over time there will likely be hundreds of case studies, and it will look unwieldly to have hundrens of children/sub-pages in the menu.

I could list the links and disable them from the menu (and also keep the breadcrumb path):

However, various admin and editors will be using this, so ideally I'd like some functionality whereby sub-pages do not appeaer in the menu when a Case Study content type is used, but the breadcrumb path is still shown:

If anyone could point me in the right direction, I'd be eternally grateful :)

If you don't need the case studies to appear in the secondary nav/sidebar menu, you could try using the Path Breadcrumbs module to set custom rules for any of the following scenarios:

all "Case Study" content resides in a fixed hierarchy
"Case Study" content with a specific tag goes in a fixed hierarchy
"Case Study" content breadcrumbs are defined by url alias/path that reflects parent pages.

The module is rather flexible in the rulesets you can define.


How can I define a selection rule to use for Panels variants in code? I have some custom PHP code that I would like to use as a selection rule for about 30 different variants.  In the future, I may need to update this code, so rather than add the code 30 times, once for each variant, I would rather add it in code via a custom module so that I can more easily maintain it.

Is there a hook, etc. for adding Panels selection rules?

You can add Panels selection rules.

However, in your case, have you tried just calling a module function instead in your PHP code for the selection rule?

e.g, call a function defined in a module:

return my_module_selection_rule('foo');

instead of all the raw code there.

That way, it can be updated once in the module codebase.

I use that technique a lot for views php contextual filter handling code.

If so inclined, see

panels/plugins/task_handlers/panel_context.inc

for the default selection rules plugin definition. and

ctools_context_handler_edit_criteria

for the default form builder function for the selection rules.


How to find node that a file is attached to There is a file that I want to find the node it is attached to, or at least the user that submitted it.

I was able to create a view that finds the file itself but when I a field for node id, it displays nothing.

Create a view of files.

Add a relationship 'File Usage: Content'

Add a field 'title' and set the relationship on it to the one you created above.

Adjust the rest of the view as needed, ie add contextual filter Content: Image:fid


REST logout without logout_token I have a small app I'm working on and after I created a new build I'm unable to login or logout. This seems to happen because drupal thinks I'm logged in but my app doesn't have the user details in local storage. So I don't know the logout_token needed to logout from app.

Is there a way I can fix this?

Marius,

When you login using rest api, csrf and logout tokens are generated. use the logout_token generated to logout form your app. Make a post request to

/user/logout?_format=json&token={logout_token}

Sample code to logout from your app will be similar to

 var xhr = new XMLHttpRequest();
 xhr.withCredentials = true;

 xhr.addEventListener("readystatechange", function () {
   if (this.readyState === 4) {
     console.log(this.responseText);
   }
 });

 xhr.open("POST", "http://example.com/user/logout?_format=json&token=logout_token");
 xhr.setRequestHeader("content-type", "application/json");

 xhr.send(data);

Hope that helps.


Hook to log results of calls to drupal_mail() made by other modules? How can I get the success/failure response of drupal_mail() generated by another modules?

hook_mail_alter() doesn't return success/fail and drupal_mail() is only helpful if the message is coming from my module.

The only way I can see is implementing hook_watchdog(), and look for a error message that matches "Error sending e-mail (from %from to %to)."

function mymodule_watchdog(array $log_entry) {
  if ($log_entry['message'] == 'Error sending e-mail (from %from to %to)') {
    // ...
  }
}

The alternative would be implementing a class that replaces DefaultMailSystem, which is a class implementing MailSystemInterface. To achieve this, it is enough to change the value of the mail_system Drupal variable.


Check when core was updated I want to know which Drupal version I am currently using, and when it was updated.

There is a global VERSION that returns the current version. Is there a way to get how Drupal was updated?

Assuming you want to know when the update was really applied to your system, e.g. to check if the security fix was applied on time before the exploit was active in the wild:

If you are using drush for your updates and didn't delete recent folders, and didn't do any additional updates of your site, you can look up the last core update in your drush-backups folder. The updates have a timestamp in the folder names

e.g. in linux

find  ./drush-backups/<site-name> -name "drupal" -type d
or

find  ./drush-backups/<site-name> -name "modules/<module_name>" -type d
for a module update.

Otherwise you have to resort to the file modification attributes of the file-system, which might show write access from after the update.

To get the information in php you could try to use the php function filetime https://secure.php.net/manual/en/function.filemtime.php
on the CHANGELOG.txt file. This file should be updated with core each time, even if the content is not up to date.


How do I upgrade to Google's Universal Analytics using the Google Analytics module? I have a site using version 1.4 of the Google Analytics module and I wanted to upgrade to Universal Analytics.  The module page says that I need the 2.x version of the module, so I updated to 2.x-dev, ran update.php (no updates necessary), and cleared the cache.

I then logged into Google Analytics and went to Audience -> Demographics -> Overview, after which I clicked Validate tracking code, but this failed.

So, I went to the module's config page (admin/config/system/googleanalytics) and checked Track display features under Search and advertising.  I then cleared the cache.

I again tried to re-validate but it continues to ask me to validate.

What more do I need to do to upgrade to Universal Analytics?

I upgraded to 2.0, cleared the cache several times, and then waited about an hour-- now it works!  So I guess sometimes you just have to wait a bit after upgrading.


if user is logged in only I have a section of my drupal website that I only want displayed to users that are logged in. So if they click on "My Page" link and the user is not logged in it should redirect them to a login screen. I have attempted to complete this task by using the following code.

<?php
if (!user_is_logged_in()) drupal_goto('user/login'); ?>

This doesn't seem to throw any coding errors but none of my links such as register, login etc work. I get an error that I have a redirect loop that will never complete. I cannot seem to find a good solution for completing this.

If you write down this piece of code outside any hook or function, it is normal that it loops because the user is always "not logged in".

However, if you've created your "page" through the admin menu system, as Parvind said, you can use Menu Access module or use that piece of code:

function hook_node_view($node, $view_mode) {
  if($node->nid == 'yournodeid" && $view_mode == 'full') {
    if (!user_is_logged_in())
      drupal_goto('user/login');
  }
}

If you've created the node programmatically (hook_menu()), you can use access argument like this:

$items['testpage'] = array(
  'title' => 'Authenticated users',
  'page callback' => 'test_func',
  'description' => 'This page is accessible to authenticated users only',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK,
);


Dynamic View for Car I have made a view that contains only car manufacturer logos.

What I want is that when a user clicks on a logo they will be taken to a page that will display all cars for this manufacturer (in a view), depending on a link or something.

How to make this or to assign some arguments and where?

The Views Module and Contextual Filters

I believe the Views module can accomplish all of your requirements.

Contextual filters will allow you to feed arguments into View using URL components.  You can customize your URL's using Views re-writing features.

Video Tutorials:

Check out Johan Falk's video series called "Taming The Beast: learning Views With NodOne"

Video 17 will show you how to rewrite field output so you can build the proper links.

Videos 19-24 should cover most of what you need regarding Contextual Filters.


Drupal 7 GetLocations field geocoding off? I am using this: https://www.drupal.org/project/getlocations

The problem is, when I add a geolocations field to a content type, and type in, for example:

Boulders Beach, Kleintuin Road, Cape Town, Western Cape

If I see maps.google.co.za, I get:

-34.197116,18.451423

But the geolocations field gives me:

-34.1964859,18.45004849999998

In this specific case the difference isn't that big, but I've had a few cases where it's completely wrong. For example:

Spier Wine Farm, Stellenbosch

Correct google result:

-33.973474,18.782544

what I get on the geolocations field:

-33.9805299, 18.773583700000017

It looks like they are off by 0.007, 0.009.

Any ideas why this could be happening?

The API geocoder may be different from the Maps geocoder (see the FAQ in the API documentation). The results may even vary for users from different users from different countries. For me, Spier Wine Farm, Stellenbosch results on Google Maps in -33.9733628,18.7825561.

In general, it seems that sometimes providing less information in an address results in more exact coordinates, see this similar question on s.o.

UPDATE: Interesting fact: the same address produces even different coordinates for different browsers. Coordinates stated above came from Google Chrome. When doing the same in Mozilla Firefox, I get -33.973474,18.782544 (which is what you had in your question).


How to add link title in combine field filter my view having combine field filter.it is working based on link field. the link field title is "test" and the url is "http://example.com".when i search using "test" it is not showing any result.if i search using "example" it shows correct content.how add the title also in combine field filter. anybodys can help? thanks advance!.

Add both link field title and link field url as fields in the views.
If you don't need title field, please  check "exclude from display".
Then try searching using the content of title field(in your example. "test")


Not able to export nodes from one drupal site to other drupal site? I have 2 instances of same drupal project, where contents are different. I want to export contents from one drupal site to other drupal site.
I tried content syn module:
      I Was not able import single node having file field value.
    node_export module:
       Not able to import node

Anyone is having any idea, which is the best approach to transfer the contents between 2 drupal sites?

Error when tried with content sysn module:
Symfony\Component\Serializer\Exception\InvalidArgumentException: No "file" entity found with UUID "514d82d9-e933-4be6-9dfb-3435b58d3531" for field "0". in Drupal\content_sync\Normalizer\EntityReferenceFieldItemNormalizer->constructValue() (line 88 of /var/www/html/drupal8/modules/contrib/content_sync/src/Normalizer/EntityReferenceFieldItemNormalizer.php).

When using content_sync module, you must set the content_sync directory in your settings.php file.

From module description:

  Set the export directory in settings.php. Similar to configuration management, we want to set the export directory for YAML files using the settings.php file.le:
  Use the variable: $content_directories['sync']
  ie:

global $content_directories;

$content_directories['sync'] = '/../content/sync';

  Note: set $content_directories as global


How to alias / rewrite path to theme? The paths to css/js/images in a theme look like /sites/mysite.org/theme/*

Is there a way to rewrite those paths to – let's say – /mytheme/* ?

URL mappings can be altered with two hooks: hook_url_inbound_alter() and hook_url_outbound_alter().

hook_url_inbound_alter() is used for paths that Drupal is responding to.  See drupal_get_normal_path().

hook_url_outbound_alter() is used for paths constructed by url().

Whether or not you can accomplish this will require some experimentation, as I don't know how the theme registry will complicate matters.


Panels variant selection rules using query string in the URL I need a variant in Panels' selection rule of "String: URL path" to be related to the the query string of the URL:

Variant 1 - String: URL path = mypath/page?querystring=1

Variant 2 - String: URL path = mypath/page?querystring=2

Surprisingly I can't find a solution for this!

You can accomplish using query strings in panels if you use php code for your selection criteria.

Something along the lines of

$url_comp = explode('/', request_uri());
$desired = $url_comp[2];
check_plain($desired);
if ($desired == "page?querystring=1") {
return true;
}

will provide you with the access check on whether or not to show the panel variant. Check_plain may be called incorrectly in the code above but including some sort of check to make sure your querystring is clean would be very advantageous to prevent any sort of security issue.

You may need to adjust the position of your desired path above. url_comp[0] will return empty, url_comp[1] from your example above would return mypath and url_comp[2] would be page?querystring=1

I came up with the idea for this approach from the comments on https://api.drupal.org/comment/18449#comment-18449


How to sort taxonomy facets alphabetically in views? I have created an expose filter using facet indexed field. Added an sort expose filter to it. There is a taxonomy term field. User need to sort that field ASC/DESC alphabetically order.

But it sort depends on taxonomy ID.

For those who drop by here check this issue here

  Just make sure to have "Display value" at top and checked, put the
  order as "Ascending" and you are good to go!


Syntax Error or Access Violation I am hoping this is a simple problem. I have Drupal 7.12 and MySQL 5.1.61 running on CentOS 6. I get the following error upon saving an article with Taxonomy. Has anyone run into this problem? I am hoping it is fairly simple to fix. The only Drupal module I've added is LDAP.

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to
use near '))' at line 2: SELECT base.tid AS tid, base.vid AS vid,
base.name AS name, base.description AS description,base.format
AS format, base.weight AS weight, v.machine_name
AS vocabulary_machine_name FROM {taxonomy_term_data} base
INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE
(base.name LIKE :db_condition_placeholder_0 ESCAPE '\\')
AND (base.vid IN ()) ; Array ( [:db_condition_placeholder_0] => Exxon )
in DrupalDefaultEntityController->load() (line 196 of /var/www/html/includes/entity.inc).

As this Drupal core issue shows, this error has made an appearance from time to time. From a reading of the thread, it looks like it is often related to a content type that is referencing a missing taxonomy vocabulary. I recommend checking your vocabularies against your content types to make sure everything is correct and consistent.


How do I customize the date-submit part in comment section? I am formatting the Date/Submit part of the comment. By default when we post any comment, it comes in the format of,
Submitted by author-name on Sun, 06/12/2016 - 20:34. I am using Adaptive theme.

I would like to change (1) date part in the ago format, like

1 minute ago

24 minutes ago

an hour ago

2 hours ago

1 day ago

20 days ago

1 month ago

1 year ago

etc...

AND the (2) Sentence part as described below,

From Submitted by author-name on Sun, 06/12/2016 - 20:34 To
author-name ------- ago

Now, Sentence part I did achieve as described below,

I did some change in comment.tpl.php as shown below

From->

<?php if ($picture || $submitted): ?>
<footer<?php print $footer_attributes; ?>>
  <?php print $picture; ?>

<?php print $submitted; ?>

To->

<?php if ($picture || $submitted): ?>
<footer<?php print $footer_attributes; ?>>
  <?php print $picture; ?>
  <?php print $author; ?>

<?php print $created; ?>

So, by doing this, I can add author-name separately and date separately, so this will allow me to format the sentence the way I want

Hence now, I am getting,

author-name Sun, 06/12/2016 - 20:34

Now, how can I change the date part. Thanks

You can use format_interval() to do this.

function MYTHEME_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $variables['created'] = t('@created ago', array(
    '@created' => format_interval(REQUEST_TIME - $comment->created),
  ));
}

If you look at the source for template_preprocess_comment(), you are essentially just using format_interval() instead of format_date() to create the timestamps.  In the above, we run everything through t() so that the string "ago" gets translated properly.


How to show difference between views page and views block I have created a view page, to this same page I will add a block by clicking on add button. So whatever changes I will do in the block is affecting the view page also. So how can I configure this, so that my block changes should apply only to block and not to page.

Using This page override  option in view field configuration instead of All display


Access uploaded file by ID I have a webform that allows users to upload their CV/Resume's. The webform is sending me the file ID. I know that the URL for accessing those files is https:// example.com/sites/default/files/webform/myfilename.

Can I access the file using the file ID instead of its name, for example https:// example.com/sites/default/files/webform?fileid=1502?

If you're looking to do this in code, I believe that this question has already been answered:

Given a File ID (fid) how can I get the HTML that represents that fid?

You can also access the file's page at yoursiteurl/file/fid, but this isn't a direct link to the file.


Drupal cannot find user login page i was having some problems with my settings.php file.  I fixed this but now my user page isn't found and I cannot login.  Anyone know how to fix this?  Thanks!

Authorize.php loads but obviously i cannot get in

nevermind i think it's an issue with hostgator

Maybe this help others.
If you are using drupal with a temporary URL on a hostgator server, follow this link
http://support.hostgator.com/articles/specialized-help/technical/drupal/using-drupal-with-a-temporary-url


Cross domain ajax in a multisite setup I have a drupal multisite install so that two sites can share the same codebase. In a custom module that both sites use, the ajax works on one site but with the other site it returns the error status 200. What my module does is that it creates a new "article" node programmatically.

I read somewhere that this is a crossdomain ajax problem, even though both sites are really on the same hard drive of the same server.

The views module, which also uses ajax, works on both sites with no problem.

How can I make the ajax work? I'll give up the multisite way if it creates more problems than it solves

Update: here is the jquery code :

(function ($) {
    Drupal.behaviors.addArticle = {
        attach: function (context, settings) {
            var addstuffAjaxLink = $(".addsomething");
            addstuffAjaxLink.click(function(e) {
                var ajaxpath = 'addstuff/ajax';
                $.ajax({
                    type: "POST",
                    url: ajaxpath,
                    data: {'from_js': true},
                    dataType: "json",
                    success: function (data) {
                        if (data.message) {
                            var message= data.message;
                            alert(message);
                        }
                    },
                    error: function (xmlhttp) {
                        alert('An error occured: ' + xmlhttp.status);
                    }
                });
            });
        }
    };
})(jQuery);

and this is the custom module php code:

<?php
/**
 * Implements hook_menu().
 */
function addstuff_menu() {
  $items = array();

  $items['addstuff/ajax'] = array(
   'title' => 'Add Stuff',
    'page callback' => 'addstuff_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}
/**
 * Menu callback.
 */
function addstuff_callback() {
    if ($_POST['from_js']) {
        global $user;

        $newnode = new stdClass();
        $newnode->uid = $user->uid;
        $newnode->name = $user->name;
        $newnode->language = LANGUAGE_NONE;
        $lan=$newnode->language;
        $newnode->status = 1;
        $newnode->promote = 0;
        $newnode->sticky = 0;
        $newnode->created = timestamp;
        $newnode->title = 'New Article';
        $newnode->type = 'article';

        $newnode->field_body = array(
            $lan => array(
                array(
                    'value' => 'Click HERE to add some text.',
                    'format'=> 'full_html',
                    'safe_value' => 'Click HERE to add some text.',
                )
            )
        );
        node_save($newnode);
        $response = array(
            'message' => 'Article Created',
        );
        return drupal_json_output($response);
        exit;
    } else {
        $response = array(
            'message' => 'There was an error',
        );
        drupal_json_output($response);
        exit;
    }
}
/**
 * Implements hook_init().
 */
function addstuff_init() {
  drupal_add_js(drupal_get_path('module', 'addstuff') . '/addstuff.js');
}

The first thing I'd probably do is to change the url option of $.ajax to something like:

$.ajax({
  // your code goes here
  url: Drupal.settings.basePath + 'addstuff/ajax',
  // more of your code goes here
});

So, what could be happening (assuming of course, that you have clean URLs enabled on both sites) is that when you are on a page on your site with the Drupal path, say, node/add and click on your link, the AJAX request to addstuff/ajax without the leading slash (base path) goes to node/addaddstuff/ajax which will return HTML and not JSON as expected. Hence, jQuery throws a parseerror and Drupal calls its error handler. You can check this by inspecting the XHR requests being sent out from the Network tab of your browser's developer console.

However, this doesn't explain how your code works as expected on one site but not the other.


Display form within a custom field? I've created a module that has a 'form builder' on the admin side.  Once the form has been created, I store the form array in the database.  Then on the front end I've created a custom field that pulls the form array from the database and displays it as part of a node.  Here is the pseudo-code to show my thinking:

- Create form via admin side and store form array in database
- Create node with custom field, choose which form you wish to display
- Set url alias on the node
- When user views url, display the form as part of the node

The problem I have is that when I complete the form on the front end and press submit, nothing happens.  Looking at the html, it doesn't have a <form> tag, presumably because it's part of a node and not a hook_form.

So, I'm wondering if it's possible to display a submittable form as a custom field?  Or do I need to find another way around this?

Edit:  I'm using the following code to display the form:

function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

            // Retrieve the form from the database
            $form_data = mantis_retrieve_form_data($items[0]['mantis_form_id'], 'display');

            $element[]['#markup'] = drupal_render($form_data);

        }
    }
    return $element;
}

Edit:  $form_data structure can be seen here http://pastebin.com/JfeNGBGA  and $element is here http://pastebin.com/HU5NSHd5

You have to check your field handler, node tpl.php or field tpl.php and use drupal_render($yourform), it's the cleanest solution I see.


Custom Drupal field widget causing check_plain() error I'm working on a custom field widget for Drupal 7. Everything appears to be working correct, but now I'm getting this error:

  Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1565 includes\bootstrap.inc)

My .module hooks:

<?php
/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_hook_info() {
  return array(
    'CUSTOM_field' => array(
      'label' => t('Custom Text Area'),
      'field_types' => array('text_long'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch($instance['widget']['type']) {
    case 'CUSTOM_field':
      $element['text_long'] = array(
        '#type' => 'textarea',
        '#attributes' => array('id' => 'MYFIELD', 'rows' => '5', 'cols' => '3'),
        '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',
      );
      break;
  }
  return array('value' => $element);
}

My guess is that it's something in the way Drupal is attempting to validate my value with check_plain(), but I can't figure out what's wrong.

According to the hook description, $items is an "Array of default values for this field."  You are trying to look in an array of arrays in your default value.

You need to change this line:

    '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',

to look in the $items array, rather than the $items[$delta] array (which doesn't exist) by removing ['value'], like this:

    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',


jQuery scripts not working on my Drupal theme This script from JSFiddle that works: https://jsfiddle.net/ryXFt/704/

Does not work in my Drupal theme (yes, it does load, I can see it via Firebug). All I do is just wrap up the code to match Drupal rules.

(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
        $("#block-menu-menu-mobile ul li .nolink").click(function() {
            $('html,body').animate({
                scrollTop: $(".region-front-calander").offset().top},
                'slow');
        });
    }
  };
})(jQuery);

When clicked, console gives TypeError: $(...).offset(...) is null for line that contains scrollTop: $(".region-front-calander").offset().top},

HTML

                                    Calendar

Looks like your classes aren't matching up. I'm guessing that the ideal action you want is when you click on the calendar link, it brings the region-front-calendar up.

The issue looks like your js isn't doing anything to that region, rather it's attempting to pull up a class called "second" which dosn't exist in the html snippet you posted.

If you switch that to the region-front-calander, that might be the answer your looking for.

(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
        $("#block-menu-menu-mobile ul li .nolink").click(function() {
            $('html,body').animate({
                scrollTop: $(".region-front-calander").offset().top},
                'slow');
        });
    }
  };
})(jQuery);


Received "An illegal choice has been detected. Please contact the site administrator" while creating node with taxonomy field via service3 drupal7 I am having an error:

  {"form_errors":{"field_category][und":"An illegal choice has been detected. Please contact the site administrator."}}

Field category is a taxonomy field attached to a node. I'm trying to create a node via web services and unable to create taxonomy field. I have also match post array by doing print_r($obj) on node form validate:

PHP Array:

[field_category] => Array(
  [und] => Array(
    [0] => Array(
      [tid] => 6246
    )
  )
)

JSON conversion:

"field_category": {
  "und": [
    {
      "tid":6246
    }
  ]
}

However, in response having an error, the same problem with the other taxonomy field. What I am doing wrong with it.

I was having the same issue. After reading this I was able to figure out the problem by doing a dsm($_POST) on hook_node_update() and inspecting the array and figuring out what it expects.

In my case my array looked like this:

'field_term_subtype[und]' => '166',

In your case it would be:

{
    "title": "your title",
    "type": "page",
    "field_category": {
        "und": 6246
    }
}


Does Redis make Authcache redundant? Currently my D6 site relies heavily on Memcache and apc to deal  with high load of a busy social site. The memcache is on a single webserver and  the database on another server.

So I am wondering, apart form being persistent (hence no need for a warm-up), whether Redis makes authcache redundant and hence avoids security issues?

No, it unfortunately does not.

Redis and Authcache are two completely separate systems/concepts, one cannot be used in place of the other.

Redis is a key/value store, primarily used in Drupal as a cache backend.

Authcache provides the mechanism to store/serve cached pages to authenticated and un-authenticated users alike. It uses a cache backend such as Redis for storage, but it is not itself a cache backend.

On the flip-side, Redis is a dumb key/value store, that has no concept of authenticated/unauthenticated users. It cannot be used to replace the functionality provided by Authcache, which is necessary to (amongst other things) build appropriate cache ids based on the user's authentication status, and persist rendered pages, or parts of pages.

The How does Redis compare to Authcache?  thread you linked to, in the (now deleted) comments, puts it nice and succinctly:

  the question isn't about Authcache, it's really "Memcached vs Redis".

Which I agree with, and is actually what the original revision of your question was asking. So it kind of all makes sense.

Just in case you're basing the question on this obsolete bit of information from the Pantheon docs:

  "Redis adds caching for authenticated users, which can greatly alleviate request bottlenecks..."

Please note that advice has now been removed as it was misleading. Redis does not provide caching for authenticated users in and of itself, but it can be a part of that process if Authcache is enabled over the top.

BTW I should add that I wish Redis did make Authcache redundant - I'm right in the middle of converting a large social site to use authcache, and it's not an easy process. The above 'knowledge' has been gathered through extensive reading and back-and-forth with the Pantheon engineers.

Also, slightly off topic but possibly relevant to your decision making process: the Pantheon engineers recommend the authcache approach over something like ESI, because of the increase in the number of app-server bootstraps. So if you're looking for an advanced caching solution for auth'd users, authcache is probably the best way to go.


How to display the data of a View in table format? I created a view using "Table" as its format already. When I click on the title column record it shows the fields one by one.

Can I display the data of a view as table format?

yes there us absolutely a way

go to any view->FORMAT->Format (unformated list) click on that see below for image
click on table format ->apply display

and enable label in all fields. will display it in table format


Is this the proper way to create a recipe page Hi I have created a website that need to be able to filter between recipes.

Currently displayed everything I create in content. It is intended that the dishes should be first, and not the recipes.

How is it possible? it is a better system to do this?

Views have a "Sort Criteria".

You can sort by "Content Type" in there,  assuming you're only showing 2 content types you should be able to set Ascending or Descending order to get them displaying the way you want.


Open an image in a new pop up window when form submit button is clicked in Drupal 7 I have a form with only a submit button in it and I want to display an image in a new pop up window whenever form submit button is clicked in Drupal 7 node.

function custommodule_my_form($form, &$form_state) {
$imgurl = $form_state['build_info']['args'][1];
$form['submit'] = array(
    '#value' => 'Print Coupon',
    '#type' => 'submit',
);
return $form;
}

The image is present in the loaded node and I already have its URL inside a variable $imgurl.

Now how can add an attribute in this form so that $imgurl opens up in a new window whenever this submit button is clicked.

$form['submit']['#attributes']['onclick'] = ??

You can give like this:

$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#attributes' => array(
            'onclick' => 'function_name()'),
        )
    );


Is there any harm is manually modifying file_managed status? I'd like to manually change the status column of a record in file_managed.  The file URI is located in a permanent location. I simply forgot to change the status to 0 before performing file_save.  I have no need to for all the hooks to get called associated with saving a file.  So is it safe to manually update the status field in a file_managed record?

Along the same line, if there are no references to a particular fid in file_managed (ie no corresponding records in file_usage and no other fid references), is it safe to remove the file_managed record altogether?

No there's no harm in modifying the table manually, as long as you know what you're doing.

If there are no references to the file in the file_usage table, and you don't need the file any more, it's perfectly safe to simply delete the line from the file_managed table. Alternatively you could set the status for that file to zero in the table, and let it be deleted automatically on Drupal's cron run.

The advantage of doing it that way is that the physical file is also deleted automatically so you don't have to clean up yourself.