Panel Pages and Taxonomy Term Arguments I am working on a new Drupal 7 site that is making heavy use of Panels to build pages.

I have a page where a view will be added to a content pane.  For various reasons, the view cannot be its own page.  This particular view has a Contextual Filter on it, Content: Has taxonomy term ID.  View works great with numeric arguments.

I would like my panel page to use the term name as the argument for the view instead of the term ID.  And, for various reason, I cannot use the taxonomy/term/%taxonomy_term override that comes with Panels.

If I set up the context option for the page (Settings / Arguments) to use Term Name, I can get the argument to work.  My problem is that the vocabulary I need to use has terms with lots of capitalization and spaces in it.  So, the URLs end up unreadable.

We have a custom ctools arguments plugin that can handle pathauto-style term names, where the term is lowercased and spaces are converted to dashes, but it was done for Drupal 6.  Before I spend the time to rework it for Drupal 7, I wanted to see if there is a better and/or existing solution.

In summary,

I have a panel page with path foo/!term
Panel page has a view with a taxonomy term ID argument, where the view argument should be based on the URL
I would like to have URLs like foo/apple-beet-carrot instead of foo/Apple%20Beet%20Carrot
I cannot use the system override for taxonomy/term/%taxonomy_term

What is the best way to go about this with Drupal 7, Views 3, ctools, and Panels, short of making a new ctools argument plugin?

There may be better routes out there, but I am going to suggest the one I have in mind right now.

You could create your own custom block - that wraps around the Views block display that you already created. Why? Because that way you have full control of the arguments.

Wrapping a Views block display with your own custom block:

Implement hook_block_info() and hook_block_view().
Inside your hook_block_view() call the View display programatically. The View display should be a block (it looks like you got it already configured).
While instantiating the View display, you can grab the arguments from the URL using the arg() function. Since this is your own code, you can do anything that you want with those arguments. For example, you could load a term using an nid-based argument, get the term's proper name, URL-decode it if needed, and then feed it to your display.
Execute the View display, retrieve the results, and return them as the output of your block.

Then instead of embedding in the panel the block that was provided by your View, you embed the one that you created in your custom module. Again, since you called the View programatically, you had full control of the arguments that were passed to it.

It sounds complex, but it's really easier than you think. Here's a plain example of how to call the View (you could modify it for your needs):

$view = views_get_view('my_foobar_view');
$result = $view->execute_display('block_display_baz');
$term_id = arg(2); // Get the term from my-panel/foo/<term id>
$view->set_arguments(array($term_id));
$view->execute();
if(!empty($view->result)) {
  foreach($view->result as $result) {
    // Do something with $result...
  }
}

This G.D.O. document can provide you with more examples on how to programatically embed Views.


How does the batch API work internally? I ran into a timeout issue using migrate the other day and started to wonder how the Batch API works internally.

The way I understand it is that in its simplest form you'll pass an array of values (nids for example) and a function to operate on those values.
The batch API then processes a fixed number of those values with each request until it's finished.

When a batch is running the page seems to use Ajax requests to show the progress of the batch operation (% done and messages). I assume it waits until the request has finished to update the progress and then start the next request immediately afterwards?

If the page with the batch request is closed does the batch processing stop? Will it restart when the same URL is opened again? The migrate module sometimes continues but it's probably using queues?

This is how batch works (Based on my Understanding)

1. Initialize

Initialize the batch processing. Based on the clients(Browsers)  configuration on whether JavaScript is enabled or not.
JavaScript-enabled clients are identified by the 'has_js' cookie set in   drupal.js. If no JavaScript-enabled page has been visited during the current  user's browser session, the non-JavaScript version is returned.
If JavaScript enabled Batch uses ajax request the keep the connection alive across the request.
If JavaScript is not enabled Batch uses sets a meta tag in html to make regular refresh  intervals to the keep the connection alive across the request.

(This is how the progress bar is updated on the progress of the Job Done.)

Batch Process

For starting the process, Batch creates a Queue and adds all the operations(functions and arguments) that you define in the batch array like,

$batch = array (
'operations' => array(
  array('batch_example_process', array($options1, $options2)),
  array('batch_example_process', array($options3, $options4)),
  ),
'finished' => 'batch_example_finished',
'title' => t('Processing Example Batch'),
'init_message' => t('Example Batch is starting.'),
'progress_message' => t('Processed @current out of @total.'),
'error_message' => t('Example Batch has encountered an error.'),
'file' => drupal_get_path('module', 'batch_example') . '/batch_example.inc',
);

Additionally it also assigns  a batch id which is unique across the batches.
Now Batch calls claims the Queue items one by one and executes the function defined with the arguments that are defined in it.
This is a crucial part, The function(Operation) that implements the batch operation should chunk the data and process the data very efficiently keeping in mind of PHP's Memory limit, Time out. Failing to do so will end up in your problem.

  I ran into a timeout issue using migrate the other day and started to wonder how the batch API works internally.

The Batch Function

The functions that implement Batch should take of the following things very carefully,

Number of Items within the operations to process like,

if (!isset($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
}

Limiting the number of items to process in one function call like setting up a limit,

// For this example, we decide that we can safely process 5 nodes at a time without a timeout.
$limit = 5;

Update on the process to post-processing like,

// Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $node->nid;
    $context['message'] = t('Now processing %node', array('%node' => $node->title));

Informing the Batch engine whether the Batch is completed or Not like,

// Inform the batch engine that we are not finished,
// and provide an estimation of the completion level we reached.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
 }

Most of the Above Points are taken care of the Drupal's Core batch operations if it is Missed in the Implementing function. But it is always best to define in the implementing function

Batch Finished callback

This is the last call back called when defined in the batch array Usually a report of how much processed etc...

ANSWERS

  If the page with the batch request is closed does the batch processing
  stop? Will it restart when the same url is opened again? The migrate
  module sometimes continues but it's probably using queues?

Yes, Ideally it should restart the batch and as said above it is based on the function you implement.

To solve your problem of PHP Time out use Drush batch which is available in migrate module, But first dig out migrate's batch functions and try to chunk your processing data.


Appropriate filters' setting I've custom content-type with several fields, e.g. rozdzielczosc1, rozdzielczosc2 and rozdzielczosc3. There are references to the term.

I'm creating the search. Now, I've several filters

My question is about third group of filters. I created exposed filter for field_rozdzielczosc1 and filters for field_rozdzielczosc2 and field_rozdzielczosc3 inherit values from filter for field_rozdzielczosc_1. When user set the filter value for field_rozdzielczosc1, filters values for another filter (field_rozdzielczosc2 and field_rozdzielczosc3) is the same. It works.

My search

In my description I ignore the two first group of filters. They work.

When user set "Rodzielczosc" in the search I'd like to choose contents whose field_rozdzielczosc1 or field_rozdzielczosc2 or field_rozdzielczosc3 is equal choosen value.

When user set "Rodzielczosc" and fill in the "title", I'd like to choose what above but only if title of content includes given "title".

When user doesn't set anything I'd like to choose all contents.

As you've seen, I tried something, yet it doesn't work.

Create separate Group of filters and move a "title" filter there.

Maybe also check all OR and AND (but they seems fine for me...)


What do I do with the list of blocked IP addresses I have a growing list of blocked IP addresses on my Drupal 7 site. I've installed the following modules: Honeypot, Captcha questions, Captcha, reCaptcha, and Hidden Captcha. They all work fine and there are no more bogus users or posts created but there are still a lot of bots that try to intrude with scripts. Is there something I can do with the collected IP addresses from this path: admin/config/people/ip-blocking to help perhaps others or the community as well?

We've all been there and felt that.

This is time consuming.  You could report the abuse to the abuse@domain.xyz email by looking up the Whois record for each IP.  This email address and investigation are required by ...

  The 2013 Registrar Accreditation Agreement (RAA) requires
  ICANN-Accredited registrars to provide abuse contact information and
  take steps to investigate reports of abuse. This includes:

  Maintaining an abuse contact to receive abuse reports involving domain
  names sponsored by the registrar, including reports of illegal
  activity, and publishing an email address to receive reports on the
  home page of the registrar's website;

  Taking reasonable and prompt steps to investigate and respond
  appropriately to any reports of abuse;

  Establishing and maintaining a dedicated abuse point of contact to
  receive reports of illegal activity filed by law enforcement or other
  similar authorities designated by the government of the jurisdiction
  in which the Registrar is established or maintains a physical office.
  The registrar should review such reports within 24 hours of
  submission. This includes a dedicated email address and telephone
  number that is monitored 24 hours a day, seven days a week;

  Publishing on the registrar's website a description of its procedures
  for the receipt, handling, and tracking of abuse reports; and

  Providing an abuse email address and telephone number in Whois
  results.

  The full abuse contact requirements are provided in Section 3.18 the
  2013 RAA.

CleanTalk.org and abuseipdb.com  will accept the IPs and emails you find as spam.  One at a time though so start with the biggest offenders.

  When you sent a report, the IP or Email address with malicious
  activity will be added in our blacklist database with status
  "Suspicious". If we will receive other abuse reports so the status
  will be changed to BlackListed.

Spamcop.net will take spam emails you find then sends "warning information to the internet service provider responsible for hosting the services used by the spammer (web sites and email sending sites)."

Rather than "a growing list of blocked IP addresses", have you considered blocking by country or region or IP range?  You can do that through the .htaccess file or Drupal modules.

I hope this gets you started in your crusade for a better world.


Changing a user password through phpMyAdmin Hopefully this should be a quickly resolvable query:

If I only have phpMyAdmin as a means of changing a password - e.g. say I can't login and need to change the Admin password (and Drush is equally not available etc) should I be able to reset a user's password using the following query:

UPDATE drupal_users SET pass = SHA2( 'the_password', 256 ) WHERE uid = 20

where the drupal tables are prefixed with "drupal_"

I have tried the above query in order to change the password for a user, but when using the password specified in the above sql statement I am still unable to login.  This makes me think I am missing something here.

Anyone got any ideas how to change a drupal 7 user password via PhpMyAdmin using SQL?

Drupal 7 uses a hash salt (see your settings.php) in addition to several other bit of information in order to create a SHA2 of the users PW. You should really use drush to change a user's pw if you need to.


Omega template.php form alter I'm trying to edit default user login block.

I successfully changed it by creating custom block--user--login.tpl.php inside omega-starter/templates, but I don't want to write whole block code. I only want to change certain fields.

I tried to use this code in template.php :

function omega_starter_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user-login-form') {
    //dpm($form);
    $form['actions']['submit']['#value'] = t("Custom login button!");
  }
}

It doesn't make any changes. Please suggest a solution.

Sorry I checked your code again and found the answer , change your code to this :

function omega_starter_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user_login_form') { //form ID was changed
    //dpm($form);
    $form['actions']['submit']['#value'] = t("Custom login button!");
  }
}


Alternatives to creating a large number of one-use, page-specific blocks? I'm working on a relatively large site using Drupal 7, and find myself creating a large number of one-use, page-specific blocks in order to embed custom content on some of the pages in this site. Is this the best way to go about doing this, or are there other alternatives?

I've used the Views module for a few things, but it is not always able to meet my needs.

You should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting Bean permissions, it should give you a lot of flexibility about how exactly you want to use this (great) module.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

A rising star ...

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.

I'm not aware (yet) of any other contributed module that "only" started in D7, and made it right into core in the very next major Drupal release ... If there are other modules with a similar track record, I doubt there would be many of them ...


How do I get the result from a database and show it? I have a database table with the following fields: name, company_name, geo_loction. I want to get those fields using the following query.

$zip_code = db_query("SELECT * FROM data_set WHERE id = 1", array(":city" => $city))->fetchObject();

Is that the correct code? How do I show the result?

//here $id value is hard-coded to 1, you can use your own logic to get the value.
$id = 1;
$result = db_query("select name, company_name, geo_location from {data_set} where id=:id", array(':id' => $id));

//To iterate over each row of the resultset use foreach
foreach($result as $ind_data) {
  echo "name is " . $ind_data->name . "
";
  echo "company name is " . $ind_data->company_name . "
";
  echo "geolocation is " . $ind_data->geo_location . "
";
}


When using features to manage deployment, should I break my functionality into many little features or one big feature? I'm relatively new to the features module and I've read contradictory recommendations online regarding whether it's easiest to maintain A) one big feature or B) several smaller features and then a "feature-controller" type module that lists all the smaller features as dependencies.

A bit about my specific situation: I'm using a local development -> dev server -> staging server -> live server workflow.  This particular site will almost certainly be the only one of its kind that I ever develop; I do not intend to use the features I create for this site on any other sites.

This makes me lean toward doing everything in one big feature because I've had problems in the past where I accidentally defined the same rules in multiple features and gotten into trouble.  However, in terms of structure this seems wrong to me-- there are different features/functions so they ought to be divided into separate features.  On the other hand, I feel like by doing this I may just create additional work and overhead for myself that won't benefit anyone.

Which approach is easier to maintain in actual practice-- one big feature or many smaller ones?

Make several little Features, split by conceptual layer.

Advantages:

Granularity when reviewing Overrides and performing Reverts — so you don't have to revert everything at once.
Modularity — even if you don't plan to reuse individual components, breaking things down into discrete modules will help with maintainability.

For deploying a single site from development to test to production, we use the following taxonomy (where "site" is replaced with a unique machinename for the site) —

site_types Feature — declares Content Types, Fields, ImageCache settings, User Roles
site_structure Feature — declares Contexts, Views, Menus and Menu Links, Blocks, User Permissions, Variables

depends on site_types Feature

site_content Feature — declares Nodes

depends on site_structure Feature

If there are multiple distinct site sections (for example, Public vs Private), consider splitting things up further:

site_types Feature
site_structure Feature — declares structural components common to both Public and Private

depends on site_types Feature

site_public_structure Feature

depends on site_types Feature

site_public_content Feature

depends on site_public_structure Feature

site_private_structure Feature

depends on site_types Feature

site_private_content Feature

depends on site_private_structure Feature


How to find Image URI in Kint via .entity in the node tree I am working on Drupal 8 finally and using the replacement for Krumo which is Kint. It packs a lot more information in than Krumo did, and came with a bit of confusion.

While trying to get the image uri of an image that was rendered via a content type, the uri was not listed. I did however find an answer here Get Image URL in Twig .

And I saw that my reference needed .entity.uri.value prepended to it. This worked, but after further inspection of my node tree in kint I could not find anything the led to .entity as a reference. So how do I found out what to appended to my node tree reference if it is not listed?

Every image in Drupal 8 is a file entity.

You can try in template_preprocess_node():

$image_file_id = $variables['node']->field_image[0]->target_id;
$image_file = \Drupal\file\Entity\File::load($image_file_id);
$uri = $image_file->uri->value;


Drupal 7: hook for comments placeholder How can i implement a hook in my theme template that will display a placeholder in my comment box? I am using drupal 7 and zen sub theme. Thank you, in advance.

You could use the hook_form_FORM_ID_alter to modify your comment form.

Also have a look at How Theme Comment Form Drupal 7 wich will tell you exactly how to achive this.


How to configure EU cookie compliance module for only Google Analytics I have installed and configured the EU cookie compliance module, but it only displays the message when I log into admin section. I use Google Analytics and I must show the message for all the site.

I think that the issue is that Drupal doesn't set any cookie and that's why it doesn't display the message (the GA cookie is external to Drupal).

How can show the message when I use only the GA cookie?

In the permission page (admin/people/permissions), check "Display EU Cookie Compliance popup" for the anonymous user.


how to validate minimum age in webform I've got a question about webform and webform validation.

I'm in D6.19 with webform 6.x-3.4 and webform validation 6.x-1.3

I'm adding a date field to capture age, and I need to validate that the age of the user is at least 13 years from current date.

Does anyone know how I can do this?
Thanks
Stephanie

You can do it using the hook_webform_submission_presave() exposed by the Webform api in a custom module.

Another alternative is to make use of this sandbox project

  This module provides a way to calculate values for Webform components
  and/or to add custom validation code without the need for creating
  custom modules that implement hooks. It offers a PHP-like macro
  scripting language to use instead.

  Differs from Webform PHP in that there is no eval() evil and macro
  code has no direct access to Drupal environment or functions, i.e.
  macro code is contextually jailed.

  Differs also from Webform Calculator in that it permits logic-driven
  calculations and also integrates with the Webform Validation module.


Saving values using variable_set through an array I have used variable_set to save one value. How can I save multiple values through an array using variable_set?

It's the same:

The variable_set function saves the variable to database serializing it. variable_get takes the variable from $conf where the variable is already unserialized.

Example:

$var1 = array(
 'key1' => 'value1',
 'key2' => 'value2'
);
variable_set('var1', $var1);
print_r variable_get('var1');

Output

Array
(
    [key1] => value1
    [key2] => value2
)


How to create a list of nodes that the anonymous user has created and limit it by the current session (SID)? Is there a way to create a list of nodes that the anonymous user has created and limit it only by the user's current session?

Basically I want the anonymous user to create a node under a specific content type and give that user a list of nodes (maybe using views) that he or she created only during the his or her current session on the site.

Anybody willing to help? I've been trying this the whole day and can't seem to get it done.

You should be able to use hook_node_insert to grab the nid of the node that is being created. Take the nid and add it to $_SESSION. Then create a View that accepts NIDs as contextual arguments. You'll need to do some additional coding to grab those NIDs from the session and pass it to the View.


Downloading from private directory corrupting some file types We have set up a private file system on a website based on drupal's guidelines. We are using Drupal 8.

We have setup the private file directory outsite of /var/www at /var/privatefiles. When downloading certain types of files - specifically docx - files are being corrupted. pdfs and other common types seem to be working fine.

File upload is working correctly as I am able to scp the files directly from the server and they are intact.

Additionally, on a test server made from a copy of the server we set up the private files inside the siteroot and that works without problem. This solution is not ideal however as we do not want the files to be accessible directly from the web.

I cannot find anything that discusses this issue, surely I am not the first person to set up a private directory this way and have docx files break?

UPDATE:

Further testing indicates that what is occurring is that drupal or php are adding 3 newline 0a characters to the start of every file served from the private file system. It has np effect on some formats but all MS files - docx,xlsx etc - are broken.

How do I fix this?

We have finally solved the issue and in case it is of use will put the answer here.

Based on this php issue we realised the issue could be a closing php tag somewhere else on the site.

In the end we found three small modules - one animated a set of banner images on the site; one made some api calls for a search feature; and another created some custom blocks from an external api call.

Each of these had ?> at the end of their .module files. Removing them fixed the problem.

Why this problem went on to affect all files served I do not know.


Transforming a Webform upload field into a single Attach button I want to transform the entire "Browse No file selected Upload" to a button like "Submit" nellens.com/home/content/contact, using CSS, I don´t know if this is possible. It is made with Webforms!

I found these 2 tutorials, with this I can manipulate the upload field only with CSS, without touching the PHP code:

http://jsfiddle.net/gabrieleromanato/mxq9R/

http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

With this, it creates the link based on an image as background that imitate the form of the button.

Thanks again to @Mołot for helping.


Cron job and Access Denied function I have a custom module which implements  hook_node_view() and checks certain conditions to decide whether a user can view the content or not. The code snippet is:

    if( ! user_is_logged_in() && $node->type == "abc") {
        drupal_access_denied();
        module_invoke_all('exit');
        exit();
    }
    else {
        //do nothing
    }
}

The code works fine for me but the problem occurs when drupal's cron runs as Anonymous user. The only message I get is Attempting to re-run cron while it is already running. Could you please give me your suggestion to handle this.

hook_node_view() shouldn't be used for access checks, there's hook_node_access() for that sort of situation:

function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if ($type == 'abc' && $op == 'view') {
    return $account->uid > 0;
  }
}

That'll handle the access check for the node gracefully, and shouldn't stop cron running halfway through.


How to use Dompdf with Entity Print without composer? I'm trying to make Entity Print work but I'm having issues with configuring the module.

The project I'm working on is two years old and for some reasons, I can't use composer and the module folder is at the project's root. The modules that have been created manually are in modules/custom, those downloaded are in modules/contrib

I downloaded and unzipped dompdf 0.8.1 in my vendor directory, and did the same in modules/contrib for Entity Print.

However, after the installation, when I try to make the module work, I get the message

  "Dompdf is not available because it is not configured. Please install with: composer require "dompdf/dompdf 0.8.0".

I have the choice between TCPDF (v1) that gets a PHP error when activated, that makes me need to reinstall the module if I want to get back to the configuration page, and Php Wkhtmltopdf that can't reach the server X even though I installed every related libraries I could find.

One coworker told me that he managed to make Entity Print work with DomPDF, but he couldn't remember how, even though it had something to do with the autoload.

I can't manage to make the couple solutions I found, and I don't really know what I'm looking for.

Please tell me if you need to see a file's content, I don't really know what I can show you for now.

Thank you in advance

I have been using the same module and was able to get it setup with Dompdf. Here are the steps in detail I used.

Summarized steps:

composer require drupal/entity_print (this automatically downloads the dompdf dependency for me)
On the content type, I enabled the custom display setting of PDF
Followed steps in "From your theme" to create the print.css and twig templates
composer require dompdf/dompdf (in case #1 doesn't download it)

Alternative: Ludwig module


Set node to flagged by default I'm using flags on my site as a way of filtering content through views, when a user views a certain node content type, I have a rule setup which resets the value of my flag and sets it against that user for that node, the views will reference this information and change their output accordingly.

The problem I have at the moment is what happens when anonymous users enter the site for the first time, they have no flag set, and thus none of the views show anything, until they travel to one of these special nodes.

What I'm looking for is: is it possible to set a flag to a default value, so that everyone has this node tagged until it gets changed?

You need to use another flag to identify anonymous visits.
Flag value is always boolean , true or false. So you cannot have a default value to identify whether it's visited by anonymous.

What you can do is use a rule

Check visitor is anonymous
If yes set a flag called "anonymous_visit" to that particular node
Use above information in your views to display nodes

Above rule sets flag on view of a node, If you want to add flag by default to a content then your rule event should be on node create add xx flag to node...

You can also use flag api with node api hooks to achieve above.. See flag api below example..

Flagging or Unflagging an item
You use the $flag->flag() method to either flag or unflag an item. Example:

<?php
$flag = flag_get_flag('bookmarks') or die('no "bookmarks" flag defined');
// Flag node #456:
$flag->flag('flag', 456);
// Unflag node #456:
$flag->flag('unflag', 456);
?>
The signature of this $this->flag() method is:

<?php
function flag($action, $content_id, $account = NULL, $skip_permission_check = FALSE)
?>


Add value to existing field value db_update How can Add value to existing value of field using db_update ?

I have a field in custom table amount which will be incremented by a function

I think you mean something like this:

db_update('custom_table')
  ->expression('count', 'count + 1')
  ->condition('id', $id)
  ->execute();


Simple jquery instructions attached on form is not executeing I have a very simple js attached to a form, and I cannot see why it is not executing.

(function ($) {
    alert("test");
    $('#field-ai-event-date-unique-add-more-wrapper').hide();
    $('#field-ai-event-date-range-add-more-wrapper').hide();
})(jQuery);

The alert is popping up as expected, the jQuery instructions are not executed. They work fine in the console and hide the form elements as expected.

What is the problem here?

jQuery 101: If you want to manipulate an element in the DOM, the DOM needs to be ready first.

(function ($) {
  $(function() {
    $('#field-ai-event-date-unique-add-more-wrapper').hide();
    $('#field-ai-event-date-range-add-more-wrapper').hide();
  });
})(jQuery);

See jQuery.ready().

If you can convince yourself never to forget this small fact, life will be a lot easier :)


Drupal 7 View tab on user profile empty as default? In a default Drupal 7 installation where no custom fields were been added to user profiles is it the normal behavior that the user profile tab View is empty? I would expect to see for example the registration email. Thank you all for help

The user view tab should include the default user entity_view information as per

user_view and
user_build_content

Normally that's information such as the history / length of time since registration and other default content.


Comments field displays only plain text I have a Drupal 7 site where people might want to put code snippets in a comment.  I have the geshi module set up for syntax highlighting.

I have an article node set to the Full HTML text format, and some code snippets.  The article is displayed properly, the code is highlighted.

I have created a comment on the article with the text format also set to Full HTML, and some code snippets.  The comment displays the literal html code, as if the text format is plain text or something.  I have BUEditor and Ajax markup installed, and the preview they give me shows it highlighted.  But Drupal's preview is consistent with the real output.

I've tried googling for this problem, but between most people wanting the opposite and the term comment being on pretty much every webpage these days, I couldn't find anything.

I was doing the following:

    <csharp>line1
    line2
    line3</csharp>

Those extra 4 spaces in the beginning made Markdown put that in a <pre>, and then geshi still processed the csharp block.  Taking out the spaces in the beginning made it work correctly.


Award user points for selecting an avatar? I'd like to award my happy little users when they select an avatar.

Anyone know of a module that melds User Points and Avatar Selection?

Both modules are awesome, but I can't find a way to combine them into thanks-for-making-your-profile-pretty goodness.

I don't think there already exists a module for this.

What you need to do is implement hook_user_update() and check if the user now has a picture assigned but didn't before. If so, use userpoints_userpointsapi() to grant the user the number of points you want.

Something like this:

<?php
function yourmodule_user_update(&$edit, $account, $category) {
  if (!empty($edit['picture'] && empty($account->picture)) {
    $params = array(
      'uid' => $account->uid,
      'points' => 10,
      // You probably want to provide additional arguments,
      // refer to the API documentation.
    );
    userpoints_userpointsapi($params);
  }
}
?>


How to work with caching and conditional rendering in a template? I've added a custom module function to allow the is_front conditional to work inside of a block template. The purpose is to display the site slogan on the homepage, but not across the rest of the site. The rule works correctly, but the site's cache is causing it to render incorrectly. If I clear the cache from the front page, the slogan displays sitewide. If I clear the cache from another site page, then the slogan doesn't display on the front page.

I'm presuming it is because the block's display is being cached in some way. Is there a simple way around this other than adding a second instance of the block?

Here are some solutions I can think of:

Solution 1: Use CSS (easiest)

Make sure the slogan has some classname you can refer to. Example: site-slogan. Use body classes to change slogan visibility. Here's some rough CSS to get you started.

/* Hide slogan for all pages */
#block-site-branding .site-slogan {
  display: none;
}
/* Show slogan for front page */
body.path-frontpage #block-site-branding .site-slogan {
  display: block;
}

Solution 2: Use 2 block instances (not recommended)

Setup one block instance, say block-site-branding-front for the home page and configure it to show the slogan. Make this block visible only for <front> page.
Setup another block instance, say block-site-branding-inner for the inner pages and configure it to hide the slogan. Make this block visible for all but <front> page.

You can also define a custom block in a custom module, but that would be an overkill. I think the first solution should do the trick.


Read only version of node form for anonymous users? Use case: a site that accepts applications for courses. Users need to register first before they can create an application (for security, spam etc.) - however the registration process might put them off; can anyone suggest a way to preview the form?

Requests to '/node/add/application' obviously get Access Denied when not logged in, because Anonymous Users don't have the "Application: Create new content" permission.

can anyone suggest a way to preview the form?

The no code way would be to use screen shots (images).

Alternatively, you could check if the user is logged, it they are not then unset the submit button via a hook_form_alter.

  prevent someone from circumventing it by submitting the form manually

Better yet, if user is anonymous, you alter the callback function of the submit button by unsetting the existing one and adding a new custom callback.


Drupal Views: Contextual Filters for certain fields I'm having a little trouble understanding contextual filters on Drupal Views and was wondering if I could have a hand solving this problem.

I've got a content type and which allows me to add a Title, Body and a Featured Image. I want this featured image to be displayed through a Drupal View, but only when it matches the current node. If I view the Product 1 node, I only want to show the Featured Image for Product 1 and not all the other products too.

I've got a Featured Image view set up as a Block and I can successfully display this block for my allocated content type. It reads the Content: Title and the Content: Featured Image fields where the Title field is excluded from display.

How do I configure the contextual filter to restrict the Featured Image only where the currently viewed node matches the Title. Is this possible?

Sure - that's a lot easier in Drupal 7 / views 3 than it used to be. You're displaying this block on a node page, correct? All you need to do is add a contextual filter of 'Content: Nid' and then add a 'default value' of type 'content id from url'.

That will pull the node id from the current url and pass it as an argument to this filter, restricting the output of your view.


Content dependent on the IP of the viewing user Is there any drupal module for implementing such behaviour?
I want to display content especially selected for the user, based on her localisation/IP.

Can you propose some solution?

For example, for a side bar I would like to have a set of filters:

in case of IP in mask xx.xx.xx.xx display side bar A
in case of IP in mask yy.yy.yy.yy display side bar B
in case of any other IP display default side bar

I think that this depend that you are looking for. See this information if you want to hide a block according certain conditions http://drupal.org/node/134425 (you can custom your php using $_SERVER['REMOTE_ADDR'] to get IP address)

If you want to show or hide whole sidebar, I think that you can make this in template.php (in your theme), adding with php your IP condition, and according the result of condition, set (and/or unset) regions. See this for more/related information http://drupal.org/node/539488


hooks inside template.php Everytime I use drupal hooks I always take the custom module route and call the hooks from there. I'm basically talking about all the hooks in drupal -- hook_form_alter(), hook_page_alter(), hook_menu, hook_user(), hook_nodeapi(), hook_init, etc. etc. etc. etc.

On the other hand, I have never actually delve into writing hooks inside my template.php so I was wondering:
- If this is possible?
- Is it going to work exactly the same as it does when called in a module?
- Are all drupal functions available as well through template.php?
- Are there any notable differences in code implementation?
- In which scenario I would choose custom module over theme.php?

Please note any D6 and D7 difference.

Please advice. Thank you.

Some hooks you can call inside template.php, but not all hooks - it really depends on what you're doing. If you keep it mostly theming related (altering data output, adding CSS, form alters, etc), you should be okay. A hook like hook_search_api_query_alter wouldn't work.


Linux distribution suited for a clean and easy Drupal 8 install I am experiencing a series of issues trying to prepare a server on my professional environment for running Drupal 8. By default, the IT team will install CentOS 6. More precisely, we are running CentOS 6.7.

The issue here is that the default versions of PHP and MySQL on that version of CentOS won't match the minimum required versions for running Drupal 8, which requires us to use repositories. As we are not Linux ninjas, we are facing several problems with the repos. I have two versions of libmysqlclient on the system, but the system will only 'see' the old one which doesn't support the MySQL version required by Drupal. The thing is really getting cumbersome.

So my next approach would be to suggest the IT team to go with the ideal Linux distribution which wouldn't require us to use the repositories, one that can deliver the cleanest install of PHP, Apache, MySQL, phpMyAdmin and Drush.

Based on your experience installing Drupal 8 on Linux servers, what is your preferred setup (Linux distribution), requiring minimum effort from server administrator, to install the appropriate versions of PHP, Apache, MySQL, phpMyAdmin and Drush that will work 'out of the box', discarding the use of custom repos? Thanks in advance.

Now that is released, Ubuntu 16.04 LTS with php 7.0, perfect for drupal 8.


Adding prefix/suffix HTML to View field I have a view that renders its contents as three fields, and based on the layout markup I received from our Front-end developer, two of these fields need to be wrapped in a container div so they can be floated as a column, with the first field and its encapsulating div serving as one column in itself.

However, I can't think of any way to theme these fields without creating a tpl.php, unless there's a prefix/suffix setting inside the Views setting i'm not seeing, and if not, what are my options for theming the field output?

The output generated is printed below.

Health

Donec consequat sem urna, quis posuere felis
      tincidunt sit amet ongue vestibulum

Check this Post to learn about re-writing results in views

Add a new field called global:text in views and Choose Exclude from display in all the other fields you use
Now edit global:text and check rewrite result to add your mark-up there


How do I import attributes with the feed mapper? I have a Drupal 7 instance with Ubercart 3, and I'm also using the Ubercart Feed Mappers module to map out the importing of product fields. I have all the fields, images and categories working well, but not attributes.

I've searched high and low for an answer or a short how to for importing attributes and multiple attributes for each product but with no success. How can I achieve it?

You need 'UC Feeds Product Importer' a sub module built to import all the product related fields.

check this: https://drupal.org/node/1802908

Create an importer (at admin/structure/feeds/create). Or try my default importer module, which creates a csv importer from all Ubercart fields - including attributes - automatically. If you use it, please leave feedback on the issue!
Download the template from the import page (if you use the default importer above, it will be at /import/uc_feeds_product_importer/template)
Fill in the template. For each attribute option you want enabled, fill in at least one of the cells for weight, price, or cost (a zero value works). If you fill in at least one of the three, any unfilled will default to zero. If you leave all three blank, that option will not be enabled on the imported product.
Import the completed csv at /import/uc_feeds_product_importer (if you're using my module above), otherwise go to /import and choose the importer you created.


Download Update's fail (Unix File Permissions on /tmp directory) When I goto admin/reports/updates/update select all and then hit the "Download these updates" I get the following  error message

  The specified file temporary://filewq3Nao could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.
  http://ftp.drupal.org/files/projects/ctools-7.x-1.0-alpha4.tar.gz could not be saved to temporary://update-cache/ctools-7.x-1.0-alpha4.tar.gz.

File System Settings can be found here: admin/config/media/file-system

/tmp is setup with 777 and I get NO errors on this page.  I attempted to create a /tmp2 with 777 and that directory would fail the security checks.  I am on shared hosting.  There are directories in /tmp called analog, awstats, cpbandwidth, webalizer, webalizerftp which I assume are CPannel utilities:)

You probably have your own tmp directory, which is not /tmp but /some/path/to/your/directory/tmp. You wouldn't be allowed to create /tmp2 for sure :)

To find that out, go to admin/reports/status/php and look for _SERVER["DOCUMENT_ROOT"], that will tell you where Drupal is located and from there, you should be able to build the path to your tmp directory.

Then set the temporary directory to that.


Add bootstrap.inc to file to programatically save nodes In Drupal 6 I would add these two lines to my code so that I could programatically import fields without having to create a module for it

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

However, trying to do this in D7, I am getting all types of errors from defined constants not being defined.  What is the proper way to do this in d7?

I have my script ready, and I do not want to spend another several hours writing code just so this can fit nicely into drupal as a module.  Thoughts? thanks!

Drupal 7 uses the DRUPAL_ROOT constant that is set to the Drupal root directory path. If you look at the code of the index.php file, you will notice the following code.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

The constant is also used from Drupal functions, such as module_load_include().

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      return $file;
    }
  }

If you have to write, for any reason, a function similar to module_load_include() you should use DRUPAL_ROOT to get the Drupal root directory.

Supposing that in your case Drupal is not in the current directory, you can use the following code.

define('DRUPAL_ROOT', 'the directory containing Drupal');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Search and Replace Scanner not publishing nodes after search? I'm using the handy Search and Replace Scanner module to do a basic sitewide search. It's working well... except that it's not publishing the nodes after the it does the replace. It's making new unpublished revisions. This is quite annoying because then I have to go to all 50+ nodes that were changed and publish them all.

Is there any way around this? Ideally, I'd like the nodes to just be published after the replace.

It's a node setup thing. Adjusted Workflow/Revision settings to auto-publish, and we're all good.


Get text_long field value with EntityMetadataWrapper I am trying to get data from a text_long type field using EntityMetadataWrapper, and from what I'm seeing on the interwebs, I should be using something like this:

$wrapper->{$field}->value();

or

$wrapper->{$field}->value->value();

However, if I use the first one, I get an array with format and value keys, but if I try the latter, I get an Call to a member function value() on null` error.

Do I have to use $wrapper->{$field}->value(); and manually get the value from the array? Or is there a more direct method? I've looked through the class, I don't see another method that gets the value data.

Since the long text field is an array in the entity Metadata wrapper (due to fact that long text fields can have an input format applied to them),  you should decode the text.

See the Drupal.org entity Metadata documentation and search for the example
$wrapper->body->value->value(array('decode' => TRUE));
Also, check out this similar post about handling the formatting of long text fields when extracting with entity Metadata wrappers


How to add blog preview to home page? I've got a blog set up on my site, with a separate page holding all the blog posts.
I've created a custom content type for making the individual blog posts so when a new post is created a preview is displayed in a list under a 'view', like any normal blog.

I would like to know how can I also list the blog previews (or teasers) on the home page as well as the main blog page?

I would like to know how can I also list the blog previews (or teasers) on the home page

You can do this using views in both D7 & D8. If you go at Structures/Views, you will find the view name Front page, you can enable that view which by default works as front page in Drupal. So as per you need, you just need to apply filter for blog content type and in view mode you can set it as teasers.

as well as the main blog page?

Same way you can make new view and give new path/url to that view and set it as main blog page.

Illustrations of above details:

1. Default front page view at Structures/views

2. Front page view setting page: I have changes the filter parameters so it will show only blog posts at home-page.

3. Output image: HOME page showing only blog previews.


Programmatically add new role to group member Trying to update a group membership to add an additional role, but cannot find any help on how to do this.

I want to add the role of "manager" to all owners of "client" type groups, using the following code:

// Get the group owner
$owner = $group->getOwner();

// Get the membership details of the owner
$membership = $group->getMember($owner);

// Get the roles of the owner
$roles = $membership->getRoles();

// Check whether the owner has manager role
if (!isset($roles['client-manager'])) {
  // No, so add the manager role to the membership
  // >>> The following doesn't work, but I hope you get the idea <<<
  $manager = new GroupRole();
  $membership->addRole($manager);
  $membership->save();
}

Any help or advice with this problem appreciated.

I was using hook_group_user_roles_alter(), but this has been removed in the latest release (8.x-1.0-beta5), so now need to implement a db update function to set it permanently.

I was eventually able to find the correct process.  The working code follows:

// Get the group owner
$owner = $group->getOwner();

// Get the membership details of the owner
$membership = $group->getMember($owner);

// Get the roles of the owner
$roles = $membership->getRoles();

// Check whether the owner has manager role
if (!isset($roles['client-manager'])) {
  // No, so add the manager role to the membership
  // Get the group_content entity
  $group_content = $membership->getGroupContent();
  // Set target group role
  $group_content->group_roles->target_id = 'client-manager';
  // Save updated entity
  $group_content->save();
}

Thanks for your help.


How config the single page site module I have installed the Single Page Site module and I was follow the instructions but still don't works for me.

the module conf:

Menu: main

Menu class/id = #block-mainnavigation

Menu item selector = ""

Title: "Home"

Tag: h2

check: homepage

I have one item of my main menu called : "servicios", link to #servicios"

In my page--front.html.twig

i have a section with a element
Nuestros Servicios

but don't works

any idea?

Well, i found a best way to do a one page menu , using link attributes for add exceptions to the any menu item, and i used jquery one page nav than with a simple reference to the menu, works perfectly.


How to apply Image Style with no effects and lazy load image? We have two content types (Articles and Basic Page) that use the same Image (field_image) field. We are using the lazysizes js library where you need to add class="lazyload" and data-src="image-url.png" on the <img> tag.

For the Article Content type only we want to be able to lazyload the images, but we want to do in a way that does not impact the Image field on the Basic Page content type.

We initially thought that the best way to do this was to assign an Image Style with no effects and then use the mytheme_preprocess_image hook to do the following below.

Is this the correct way to modify the <img> element the way we need to? The goal is to be able to lazyload the original image without modifying it (no scalling, resizing, cropping, etc.).

function mytheme_preprocess_image(&$vars) {
  $lazy_loading = [
    'lazy_load_image_style' // Machine name of Image Style.
  ];

  if(in_array($vars['style_name'], $lazy_loading) {
    // Copy src into data-src.
    $vars['attributes']['data-src'] = $vars['attributes']['src'];
    unset($vars['attributes']['src'];

   // Add css class.
   $variables['attributes']['class'] = 'lazyload';
}

It may be easiest to use Blazy or Image Lazyloader.

If neither of those suit your needs, I would create a new field formatter class. In your custom module create a new formatter src/Plugin/Field/FieldFormatter/LazyImageFormatter.php that extends Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter.php.
 You'll need to use the same annotation that formatter has, but then you'll only need to implement the viewElements method. Begin the method by calling $elements = parent::viewElements($items, $langcode);. Traverse $elements afterward and update the render array similar to how you have done above. Make sure to return $elements; when you're done.

This will give you a formatter on the manage display screens that you can select on whichever image fields you want on any view mode of any entity. You can even get it to work with any image style selected via your new formatter.

If you've never extended a Drupal 8 plugin check out the plugin api. Once you know how to create and extend one plugin type it's very similar process to create or extend others and you'll quickly find that the world is yours.


Is there an alternative to the Node reference, and the Feeds modules? I am using Drupal 7, Reference Module (references-7.x-2.x-dev), and Feeds Module (feeds-7.x-2.x-dev).

I created 2 Content Types: Address Book, and City. The Address Book content type has a node reference to nodes of the City content type; the CSV file is imported to "City" content type with success using Feeds Module.

I am unable to import to a node reference using the Feeds module. With it, I created an importer, and mapped 2 fields for AddressBook content type:

Name:  Target is Title
City:  Target is NodeID

The CSV file looks like the following:

  Name,City
  COK,1230

Executing this import gives me unfavorable results, where the City field does not get populated.

Is there an alternative module that may be used or another method that may be recommended?

Please advise where further clarification is needed.

There is a patch in the works that adds Feeds support for Entity reference fields.

References will most likely be deprecated in favour of Entity Reference in the near future, so this is a good option once it gets finalized.


Organizing uploaded files in folders created by date This could be very trivial, but I haven't been able to find a good solution.
I have an image field associated with a content type called article, and I wish to organize the files uploaded during content creation in a way that they go to a sub folder (within files/article) which uses the day's date as name.
For example, if the article is created on April 15, then the associated images (the ones added through the image field) go to files/articles/15-04-2011/filename.jpg; the articles created the day after will have their associated files in files/article/16-04-2011/filename.jpg.

You can use the Filefield Paths module to automatically rename uploaded files according to a scheme defined by tokens. The node creation date is one of the available tokens, so that module should be able to do what you want to achieve.


Not all fields of node are present in content I've set up a custom content on my multilang site type with several fields that are all configured to be translatable. But when I try to theme that node I only habe a subset of the field available, although all the other field are saved in fieldDefinitions array. How to have all the fields available in fields array?

I have a node template node--products.html.twig Therein I access the values with {{ content.field_content_rating_level }} which works fine for the 4 fields in the fields array above, but not for the rest of theme even thought the share the same type of field. All fields are editable without any error in the backend. All fields are filled and translatable.

I use some of the missing fields in views and they work.

The {{ content }} variable within node templates contains all fields configured to be visible within your content type's display settings. If you experience fields missing, they are most likely disabled within your display.

Head over to your administrative backend's Structure > Content types > [Your content type] > Manage display settings and ensure all fields you are trying to access are enabled for your current display mode.

You can always access disabled fields within your node templates by accessing the original node entity. The node entity along with its fields and some limited accessor methods are available within the {{ node }} variable of your templates.

Use e.g. {{ dump(node|keys) }} for debugging the available properties of the node within your template.

Comprehensive documentation about the variables within node templates can be found within it's header's comment block.


Any way to have "Path Will Be Viewed" trigger? I would like to restrict certain roles from visiting certain pages, ideally by using Rules.

I am able to do this with Nodes, however for Pages such as a Views Page, I can't see any way of triggering this redirect?

If you simply want to restrict the access to the View, you should alter the settings for the View.

Under the access settings, select Role instead of Permission, and select the appropriate role.

However, if you have to use Rules for some other reason, I would create a rule that triggered every time Drupal is initializing. And then, add a condition with custom PHP code. You could do something like

global $user;
$rid = 1;
return ($_GET['q'] == 'my/forbidden/path' && isset($user->roles[$rid]));

and then add an action that redirects the user to another page.


Can I create a form with a route like this /rooms/{node.alias}/booking? I'm working on a booking project and I have to create a form for reservations.

I have created the accommodation content type and the url_alias for this is: /rooms/[node:title]

Example:

/node/1 = /rooms/1-accommodation-example
/node/2 = /rooms/2-accommodation-example

I need to know if I can do this:

booking.booking_form:
  path: 'booking/{url_alias}'
  defaults:
    _form: '\Drupal\booking\Form\BookingForm'
    _title: 'Accommodation booking'
  requirements:
    _access: 'TRUE'

Is this possible? path: 'booking/{url_alias}' or path: '{url_alias}/booking'

What happen next, if you try yo go to this route:

/booking/any-text-asdasdas = the form page is loaded.
/booking/rooms = the form page is loaded.
/booking/rooms/1-accommodation-example = page not found.

I tried but I don't know how to find information about this way of routing.

I don't know if I have explained what I need well, any information will be very helpful.

Thanks,STF

Is this possible? path: 'booking/{url_alias}' or path:
  '{url_alias}/booking'

path: '{url_alias}/booking' paths can never start with a slug/placeholder.

You'll have to use path: 'booking/{url_alias}'

In your form:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $url_alias = NULL) {

    // Some DB query to check if $url_alias is the 2nd path of an alias.
    // In other words, check if "/rooms/$url_alias" exists.

    if ($db_query == false) { // if $url_alias is not the 2nd path of an alias.
       throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
    }

    // Your Form code goes here

    return $form;
  }


How do you go without hierarchical taxonomy filters, when the site heavily relies on content browsing(multiple filters and sorting)? I'm building classifieds site with drupal and got stuck on one major issue: I have 1 taxonomy vocabulary with parents, children, grandchildren and great-grandchildren, and can't find a way to build browser which would not restrict user's choices.

Over few days I found many drupal users stuck in the same place waiting for hierarchical taxonomy filters in views. this simple hierarchical select  almost solves it, however in views it does not show child nodes when parent term is selected.

So what are the ways to go around this issue in drupal? Anyone built a site with hierarchical taxonomy vocabularies?

This is unfortunately a big pain point with Drupal 7.  On my site, I handled this with Views and Panels.

In my case, the hierarchies with places generated by the Location taxonomize module in the form of country / state / city or country / city.

To give you a rough idea of how I approached it: I overrode the taxonomy term path using Panels/Page Manager.  I then added two variants in the following order:

a variant containing a content pane that aggregates countries and shows only those countries with 1 or more entries
a variant containing a content pane that takes a country as an argument/contextual filter and shows users having that taxonomy term as well as  a list of states using the special Panels related terms (show children) block

Depending on the structure of your taxonomy and what you are trying to show, this can be an extremely complicated setup, but it is possible even without direct support from hierarchical select.


Drupal 7 timestamp insert into mysql error i get error when i want to insert current time to my table-field date,

  i get this error PDOException: SQLSTATE[22007]: Invalid datetime
  format: 1292 Incorrect datetime value: '1345724717' for column 'date'
  at row 1: INSERT INTO {users_history} (uid, nid, points, date, reason)
  VALUES ('31', '107', '2', '1345724717', 'session'); Array ( ) in
  points_node_insert() (line 57 of
  /home/www/live_project/htdocs/sites/all/modules/custom/points/points.module).

i have table like this:

uid int
nid int
points int
date datetime
reason enum

this is my query(this query works fine if i delete date field)

  $date = time();
    db_query("INSERT INTO {users_history}
       (uid, nid, points, date, reason) VALUES
       ('$uid', '$nid', '$points_for_post', '$date', '$reason')");

The 'datetime' value assumes the "YYYY-MM-DD HH:MM:SS" formatting, if I got it, you're trying to insert a 'timestamp'


How to alter a field within an unlimited field collection? I am trying to set the #access attribute to FALSE on a field that is within an unlimited field collection - so it is hidden from users. I am relatively new to Drupal so I'm not sure how to handle this. I tried to use hook_form_alter and some basic CSS - but I couldn't get either of the solution to work properly because of the unlimited field cardinality.

Here's what worked for one row in the field collection in a custom module:

$form['field_my_field_collection']['und'][0]['field_myfield']['#access'] = FALSE;

How do you alter a specific field in a field collection with unlimited values? Thanks in advance for any help - the Drupal community is awesome.

Since Drupal 7.8 you can leverage hook_field_widget_form_alter. You can alter any field widgets provided by field_collection before the form_alter of the main form.

function my_module_field_widget_form_alter(&$element, &$form_state, $context) {
  if ("field_my_field_collection" == $element['#bundle']) {
    if ("field_my_field_collection" == $element['#field_name']) {
      $element['#access'] = FALSE;
    }
  }
// dpm(array($element, $form_state, $context), "field_name: " . $element['#field_name'] );
}


"This view has been automatically updated to fix missing relationships" - fields removed from a working view for no reason I have a site built on Commerce Kickstart 1 - Views 3.7.
I have a standard cart, to which I wanted to add photos of the products. It is a view that includes a relationship to Commerce Order: Line items and  a contextual filter by Order ID.

Now, I added a reference to the product in order to be able to access the photos.     The view works OK, all the initial elements and the images are there, but when i try to edit it, all the relationships are gone and I receive the "This view has been automatically updated to fix missing relationships" message. Both the relationship I added and the default relationship to line items are gone.

RELATIONSHIPS
Commerce Order: Line items
(Line Item) Commerce Line item: Product

FIELDS:
(Line Item) Commerce Line item: Display path
(Product) Field: Image (Image)
(Line Item) Commerce Line Item: Title
(Line Item) Commerce Line item: Unit price
(Line Item) Commerce Line Item: Quantity text field
(Line Item) Commerce Line item: Total
(Line Item) Commerce Line Item: Delete button

To me it looks like a bug in Views? There is a discussion of a similar issue https://drupal.org/node/1860380 (the last post is actually mine). Maybe I am wrong, though, maybe it's me who's doing something wrong?

EDIT: It turned out after all that this behaviour was related to the "Administration Language" module https://drupal.org/project/admin_language.
Disabling it made the problem disappear for good.
It seems as its is related to access permissions.
A similar problem was encountered in creating product views in drupal commerce. If you want to relate to the fields of the referenced product, you have to grant the View permisssion to all products (non-node enitities of DC). Otherwise the users without permission to view the product enitities will see an empty view (see Views results empty for unprivileged user when using Relationship: Content: Referenced Product). What makes it especially difficult to track that the problem does show up only when one uses Relationship & "Fields" display. A similar view with content / teaser etc renders the same content without problems.

Now, I wanted to add an image of the product to the cart view. I referenced the Image field of the product in the cart ((Line Item) Commerce Line item: Product), and put the image field from there.

I understand that the permissions problem prevent the view from functioning properly. It seems to be that it's a bug that
a) the view itself functions well
b) that the problem appears in the Views UI
c) that the error message is not informative.

It seems to me that this behavior is just a side effect of a number factors in how the Views work.


Display random value from multi-value field in Views I have an image field that allows unlimited values, and I need to use Views to display a random image from a node's image field. The View should display a random image from that node's field each time the page is reloaded. How can this be accomplished?

Example:

On page load, display image "1" from Node A's multi-image field.
Reload page, display image "3" from Node A's multi-image field.
Reload page, display image "2" from Node A's multi-image field.
Reload page, display image "3" from Node A's multi-image field.

Thanks!

Re-querying with Views for information you already have is excessive. I think a better option is to use something like
 Single Image Formatter which can display a random value from a multivalue image field.


Boost won't work after configuration of .HTaccess Preliminary data

It seems I've configured .HTaccess right, as required by the following guide to installing Boost, But it also seems the module doesn't work.

What I did was to copy my .HTaccess auto generated rules from admin/config/system/boost/htaccess/generator and paste it exactly instead of the sentence "-------paste the rules right here--------" mentioned above, but I don't know if that was the true intention of the author...

Anyway, the final outcome is this:

# RewriteBase /

### BOOST START ###

# Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
RewriteRule .* - [E=boostpath:normal]

# Caching for anonymous users   # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [S=3]

# GZIP
RewriteCond %{HTTP:Accept-encoding} !gzip
RewriteRule .* - [S=1]
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz [L,T=text/html,E=no-gzip:1]

# NORMAL
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

### BOOST END ###

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

Why I'm assuming a problem?

On one hand, Drupal's CRON tells me Boost installed correctly, should be working if properly configured. On second hand, while surfing from another browser anonymously, I checked page source (CTRL+U), But didn't the famous message (as HTML note):

  Page cached by Boost @ YYYY-MM-DD HH:MM:SS, expires @ YYYY-MM-DD
  HH:MM:SS, lifetime X hours

Therefore, I assume a problem. Now, as Shawn instructed in the comments below, I turned on the Boost debugger, went to Reports > Recent log messages, and then saw two interesting errors:

First error:

Array
(
    [cache_this] =>
)

Second error:

This error is to long to be pasted here, but it seems to do something with Drupal's Autocomplete mechanism.

You can verify Boost is working by browsing a page as an anonymous user (e.g. using your browser's Incognito/Private Browsing mode) and looking at the source code of the page. If Boost is working you should see a HTML comment at the bottom of the document that looks like this:

<!-- Page cached by Boost @ YYYY-MM-DD HH:MM:SS, expires @ YYYY-MM-DD HH:MM:SS, lifetime X hours -->


Filter users in views with a mandatory role and another role that is optional Suppose I have a Role A and Role B.
As per my requirement The Role A is mandatory for a user and the Role B is a good to have role.
I want to filter out the users in the views. So If a user has only Role A, he should be listed. If the user has both the roles he too should be listed but if the user has Role B only he should be restricted.
Please Suggest.

You can put condition in View's criteria.

Go to your view and step ahead to filter.
Put first filter as. For example you have role as category A and category B.

Add following filters which can be helpful as per your scenario.

   Select content:role (condition : is one of A and B)
                    OR
   Select content:role (condition : is one of A)
                    AND
   Select content:role (condition : is none of B)

Don't forget to add OR and AND condition in between filter fileds.

Hope this will be helpful.


Overriding fields from one content type which inherit from another content type Imagine we have 50 different professions in the same domain (medicine for example). In a region, we can have 5 doctors who have the same addresses, and in another region we can have 15 doctors in different addresses. We want their information to be stored in the database (e.g. addresses, telephone number).

So I decided to do this:

Content type 1 (general information): title, field_region, field_tel, field_email, etc.
Content type 2 (specific information): title, field_region, field_inherit_from, field_tel, field_email, etc.

Thus, when we want to add specific information to a profession X from region Y, we have to create a new content of content type 1 and then create content type 2 which will override specific fields from content type 1.

Keep in mind that a same region may have 10 professions who have same phone number, same email address but 7 professions have its own email address for instance.
Also, keep in mind that there is more than 15 different fields (so 10 different type of information about the professions).

How can I do this? I just don't know what the best way to do it is.

I am not sure if you are using D7 or D8, so will take a high level approach.

I would suggest that you will need to use an entity reference field on Content Type 2 (Person) to reference the item of Content Type 1 (Profession template) that will provide the default values for fields that are not filled in. They might even be the same content type if all the fields are the same, and all can accept default values (though if so watch out for recursion in the next step).

Now using a custom module, on node load, you can check for empty fields and replace their values with those of the referenced node.


Problem sorting events by Term Reference Hi I created an Event Calendar in Drupal 7.3 I have a content type set up with term ref everything works great when i click on an event I have at the bottom display the term Ref
you can see it here  http://www.ofmq.com/content/pain-falls-major-injury-mcalester

at the bottom of the Event there is a link to the term ref in this case it is Nursing Home
when you click it you get a list of all events that have Nursing Home as a term
my problem is how can I sort the list generated by event start date?
Any help would be appreciated
Cheers
DEW

It would seem like your link is simply rendering the taxonomy term usage page (that comes standard with Drupal). What I would recommend is creating Views with Contextual Filters (the filter could be the name of the taxonomy term, in this case nursing-home).

Once you have your Views with Contextual Filters built (with a set link, such as /events/) then you can simply rewrite the result of the term field (i.e. display it as plain text and then rewrite) using tokens for the machine name of the term and provide it as a link.

Does this make sense?


_locale_import_po passing in a file I am trying to use _locale_import_po($file, $langcode, $mode, $group = NULL).  I want to point it to a local file in my Drupal site (e.g. drupal-7.23.fr.po').

However, when I try to do this I get the following error:

  fopen(): Filename cannot be empty locale.inc:693

I am using the following code to initialize the $file variable passed to the function.

  $file = new stdClass();
  $file->filename = 'drupal-7.23.fr.po';
  $file->filepath = drupal_get_path('module', 'mymodule') .'/'. $file->filename;

I have the file in sites/all/modules/mymodule/drupal-7.23.fr.po.

Line 693 of locale.inc is

$fd = fopen($file->uri, 'rb');

So you need to provide your file path on the uri member of the file object, instead of/in addition to filepath.

There are a bunch of different things done with that file object throughout the process you're calling, so there may be more you need to add as well.


Exec JS after flag ajax result In my portal I need to use "flags" module to create a simil twitter "follow/unfollow". I have installed and configurated this module. All works, via AJAX too.

Now I need to exec some other JS function after that the flag module has completed his call. I think that I need to add (on the backend) some "commands" before flags return "commands" to execute in the frontend.

How I can I do this ?

Thanks, M.

here is API https://www.drupal.org/node/336122

The two events

The flagGlobalAfterLinkUpdate event

This event is triggered immediately after a flag link has been updated. (Flag links appear in two flavors: "Bookmark this!" and "Unbookmark this!", and when we speak of "update" we mean this change in appearance).

The flagGlobalBeforeLinkUpdate event

This event is triggered just before a flag link is updated. As will be explained later, the existence of this event is for cosmetic reasons only: it allows us to carry out actions while the throbber () is still visible.

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  alert('Object #' + data.contentId + ' (of type ' +
    data.contentType + ') has been ' + data.flagStatus +
    ' using flag "' + data.flagName + '"');
});


programmatically add class name to fields I want to add custom class name to fields in user login form other than default class name.
For example,

user-name-field for Username field
password-field for Password field
click-me-button for Submit button
creat-account-link for Create new account
request-password for Request new password

how to do this programmatically?

Alter the login form using hook_form_alter(). And use #attributes to add custom classes to fields.


Show only text in a form I just want to show the status of an item on one AJAX call. I cannot find any form element that allows me to only output text. I don't want a textfield form, since that would allow the users to enter a value.

How do I show text only in a form created with the form API?

If you want to show only text, use '#markup' form element, with syntax like this:

$form['status'] = array(
  '#markup' => '<p>' . variable_get('status', t('Off')) . '</p>',
);


Dynamically generated radio buttons share name foreach ($questions as $question_index => $question) {

      $form['questions'][$question_index]['answer'] = [
        '#type' => 'radios',
        '#title' => '',
        '#default_value' => 1,
        '#options' => $options,
      ];

    }

I am generating a form like this, but the radio buttons share the same name. I find that weird since I am wrapping it in a dynamic wrapper.

I know that I could add something along: [$question_index]['answer_' . $question_index]

But, is it possible to make it rely on the grouping/container instead?

You can try using #tree:

$form['#tree'] = TRUE;

Or you can add it to only your questions element:

$form['questions']['#tree'] = TRUE;


How to add content type as a menu item child without displaying the link in the menu? I recently found menu block module, which displays my submenu very nicely. Here's the menu hierarchy:

Home
About
News & events
-- News
-- Events
Contact

So when I go to the News & events page and from there to the News page the submenu displays just fine. But when I open a piece of news in the News page (which is a view displaying content from the News content type) the sub menu disappears. I'd like to show the submenu like the piece of news I just opened would be a child of News menu item. The problem is how to this without actually displaying all the news links in the menu. I know that there's a way to disable menu links but haven't found a way to disable them by default when adding new content.

What would be the best way to implement this kind of hierarchy?

If your path aliases are something like, e.g., example.com/news/node_alias, you could use the menu trail by path module. That way, you don't have to add the nodes to the menu to achieve this: the News item remains active on subpaths of /news/*.


How do I add a span class to form item title in register form? '#title' => t('I have read and agree to the') . " terms of service",

How do I add a span class to the whole title, so It would end up like so:

 I have read and agree to the terms of service

You can use the following code:

'#title' => '' . t('I have read and agree to the terms of service', array('@terms' => url('terms'))) . '',


Delete in lieu of truncate? If my DB user doesn't have permission to truncate a table - would using delete instead without any parameters be equivalent?  So like -

 $this->db->delete('data')->execute();

in lieu of

 $this->db->truncate('data')->execute();

I've never used the delete command this way in the Drupal DB API.

Logically a truncate and a delete statement are very similar. They work a little different which allows truncate to be faster in many cases. For the specific code in question, it might be a little slower but it should perform the same purpose and the code should work fine.

However, if your site lacks the ability to TRUNCATE then it also lacks the ability to DROP tables. It's possible to run Drupal on sites like that for very specific purposes, but there are several Drupal features that will not work without the ability to DROP tables.


Is there a way to know the type of output inside a template file? I am making a website for both WAP and smartphone browser, and I am using two themes to display WML and HTML. Now I have a problem to show a <anchor> link. The pseudo-code for the code I would use in the template file is the following one:

if (HTML_THEME) {
  print 'BACK';
}
else{
  print '<anchor>BACK<prev/></anchor>';
}

Could anybody tell me how to implement this?

I think you're looking for the $theme_key global, which gives you the:

  Name of the active theme.

You can use it like so:

global $theme_key;
if ($theme_key == 'mobile_theme') {
  // ...
}
else {
  // ...
}


Within a View, How do i paginate the content found inside a single Multiple file field, i.e. inside one node Hopefully someone can help.

I am using a file field and allowing unlimited files within a single content type field called "Video", handled by Media Module. I have created a view per "gallery" of multiple files inside the node, it's already set-up contextually using the nid. Paginating the media files list from this one node result isn't easy to do with what is out there. I have tried infinite scroll but it didn't work out, i have also tried CCK Pager with no luck and the limit settings available are just that limits which don't paginate. Any ideas?

Just to be clear i am not trying to paginate a view of nodes, its a view of files found within a single node.

I am using Drupal 7.63

There are two obvious ways to solve this, the easier one is through your existing Content views, and the other is through creating a new File type view.

Content type Views

It is true that the Views type determines what will go into each new row in views results, and Pager is acting on views rows.

But if you have a multi-value field it is possible to make it display each value in a separate views row, making the same node appear many times in the views results, as many times as there are field values.

Here's how you do it:

Edit your "Videos" field and under Multiple field settings make sure you don't have the Display all values in the same row option enabled.

This will make the same node repeat as many times as you have videos, and although the Pager will still work on node rows, it will look like it's working on field values (if you're only showing that one field and not revealing the node Title, for example).

File type Views

To get the Pager to actually page through individual files you have to create File views. There are some steps how you can make that views pull data from one content type and field:

The File views starts by displaying file names of all the files on the system. To make it aware of where the file is being used (you want only the Videos) add a Relationship File: Content using Videos and make it required. This will filter out only the files that are in the "Videos field", and it will make available various Content related Fields and Filters.
Add the "Content: Videos" Field and set it so it doesn't display all values in the same row. You will still see the files repeated in the results.
Don't add any File Fields
Under Query settings enable Distinct and Pure distinct. This will make each file display only once.
Add the Contectual filter for NID, it will be available because of the Relationship you added and it will use it by default.


commerce cart block with drupal theme I want to overwrite the block generated template drupal commerce "commerce cart" using the bootstrap theme.
What I need is the name with which overwrite block.tpl.php theme for that specific block bootstrap

Edit your cart view and under Advanced, Theming: Information, click on Information and you will see this:

For template file name you want to use the last suggested name, (which I underlined for you) that way it only affects this specific view and not others.

Now that you have a name, click on the blue link and copy all the code in there and paste it into your template file and modify as you wish.

Remember to flush the cache to see changes or you could click the Rescan template files button


Display paragraphs items in comma-seperated series I have a series of paragraphs items representing two different types of contributors to a publication: staff (user link) and non-staff (text).  (See How to control the display of a user account connected via entity reference)

According to Paragraphs preprocess paragraphs handles building the render array for its items in the same way as nodes, comments, etc, so maybe my question is much broader, but here's what I'm trying to do:

I want to send up with a basic comma separated list of items:

Person 1

or

Person 1 and Person 3

or

Person 1, Person 2, and Person 3

with links on the items that should be links.  I guess I just am not getting render arrays and the theming functions well enough yet, that I understand how to do it.

The paragraphs preprocess question makes me think maybe I should be overriding the fields_formatter, but what I've been working on up to this point is theme_preprocess_paragraphs_items().  That seems like it should allow me to do what I want, I can see that I could loop through $variables['element']['#items'] or maybe the integer keys of $variables['element'], but how to change those so that they append ', ' or ', and ' or whatever as appropriate (outside of the link on link items is escaping me).  (I do understand how to determine what should be appended, just not where to append it to make drupal output what I want.

append ', ' or ', and ' or whatever as appropriate

You can use CSS to accomplish this
HTML

    Editor:&nbsp;

            Person 1

            Person 2

            Person 3

            Person 4

      Author:&nbsp;

                  Person 4

    Translator:&nbsp;

            Person 5

            Person 6

CSS
.paragraphs-items { /* start each field on a new line*/
    clear: left;
}

.paragraphs-items div { /* eliminate the blocky results of div hell (eliminate some extra spacing in the process)*/
    float: left;
}

.paragraphs-items .entity-paragraphs-item .content:after { /* default to putting commas after every value … */
    content: ", ";
}

.paragraphs-items .entity-paragraphs-item:last-child .content:after { /* … except the last one */
    content: "";
}

.paragraphs-items .entity-paragraphs-item:nth-last-child(2) .content:after { /* The last two items in the series should be separated by a ", and " … */
    content: ", and ";
}

.paragraphs-items .entity-paragraphs-item:nth-last-child(2):nth-child(2) .content:after { /* … unless there are only two items, in which case it should be " and " */
    content: " and ";
}

EXAMPLE DEMO
Note in content: ", " since it won't pick up the empty space (by pressing the space bar) I used the ALT+0160 trick to make the empty space.


What is the actions table for and can I delete orphaned actions? I just ran

$ drush cc all -v

and it tells me I have orphaned actions. I'm curious to what the actions table is for in Drupal 7 and if it's safe to just drop all the data in the actions table?

There is no button or link or even an indication that orphans exist when going to /admin/config/system/actions.

I don't really get why, but when I visit /admin/config/system/actions/orphan the orphaned actions are removed.  I'm watching the Drupal log when I go to that path and it systematically removes all the orphans.


CORS setup with ReactJS Fetch API I have a ReactJS app that fetches an external API URL with the following structure.

fetch(url) // or fetch(url, {mode:'cors'})
  .then(response => response.json())
  .then(data => {

In my browser, when it tries to render the component, I am getting the following error message

  Failed to load https://XXXXX/jsondata: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8080' is therefore not allowed
  access. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

So I research how to enable CORS in Drupal 8 and doing trial and error for different configurations didn't work.

This is my current cors.config under services.yml file

  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', 'access-control-allow-origin','x-allowed-header','*']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*'] // or ['POST', 'GET', 'OPTIONS', 'DELETE', 'PUT', 'PATCH']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['https://XXXX/','*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: true // or false
    # Sets the Access-Control-Max-Age header.
    maxAge: false // or 1000
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: true // or false

I have tried to install a Chrome extension that is amazing that removes this error but of course this will only be working in my device.

Im not entirely sure but is this something to change Drupal CORS config or allowing Access-Control-Allow-Origin on the API URL side (https://XXXX)?

I would just like to answer my own question. After reading more documentation about how CORS works, I found out that, to allow Drupal access other site/server, CORS must be enabled in the other party not in Drupal site itself. Some basic explanation found here too. https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work/10636765#10636765


Content translation of paragraphs I'm trying to translate paragraphs in Drupal 8. According to this bug report, which is marked as fixed, it should work.
#2543258: Entity references of untranslatable fields are not displayed in the correct translation is supposed to be fixed as well.

I don't know if this has anything to do with it. Right now, I'm stuck and I even don't know if this really should work or not.

I'm doing the following:

In hook_preprocess_page there is $vars["node"] (as usual available via argument $vars)
On this node (could in fact be any arbitrary Node object, I guess) I will call $node->getFields()
One of the fields is a pararaph node ("field_sidepane")
I call "$field->view()" on this field to render the whole field (i.e. everything that's in the sidepane) at once. view() doesn't seem to support a second argument for the langcode or anything.
The sidepane contains multiple paragraphs (Cardinality=-1). One of these paragraphs contains a field "field_body" of type "text_long".
This field is marked as translatable (under the Paragraphs section of the config page). field_sidepane by itself (appearing under the Content section of the config page), however, is not marked as translatable.
Apart form the minor glitch, that these paragraphs are wrongly labeled as "All languages" (which I think is https://www.drupal.org/node/2463575) everything works great during edit-time. I can edit text separately for the different languages etc.
On the page, however, only the primary language is ever shown.

I thought it would be straightforward but I turns out to be surprisingly difficult. In the class Drupal\Core\Entity\Entity\EntityViewDisplay I discovered the following section:

      // The language of the field values to display is already determined
      // in the incoming $entity. The formatter should build its output of
      // those values using:
      // - the entity language if the entity is translatable,
      // - the current "content language" otherwise.
      if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
        $view_langcode = $entity->language()->getId();
      }
      else {
        $view_langcode = NULL;
      }

I've found that if I set $view_langcode to NULL, it seems to work. Obviously, it gets the language from the main entity. But I don't know how I can change this in any way (either programmatically nor via the UI). Even if I explicitly use $node = $node->getTranslation("en"); and call getFields() on the result, it doesn't seem to work. I could find no way whatsoever to render the field in the translated language.

Yes, that API doesn't support passing in the language.

I would recommend you use a view mode for what you are doing. You can click that together in the UI, configure the fields you want to see there and then just call $node->view('your_view_mode'). That should just work.

You could also use the Entity View block provided by ctools module, then you can place your sidebar as a block in a region and don't need any custom code at all.


Zen subtheme region templates not being used? In a subtheme of Zen, I've got a templates folder that has region.tpl.php and region--footer.tpl.php that are copied from the main Zen theme. However, the custom region file is not being used for the regions of my theme; I even changed the contents of the region--footer.tpl.php file to just be <?php exit("Hi!"); to see if it's being called at all, and it appears to not be.

I've cleared the theme cache (it's set to clear every page load); what am I missing to get that custom region template to actually apply?

A few things to check on that might be causing your error:

Is the footer region populated with a box or content? If no, the region won't show.
Have you edited the region--footer.tpl.php of the main Zen theme or your subtheme? Editing the wrong one won't show the result.
Is the footer properly actived (not commented) in your subthemes's .info file? (regions[footer] = Footer)


sub directory multisite just redirecting to default after first page I have a sub directory multisite setup on a sub domain. (locally with mamp everything is running fine), but on my live server, i can only reach the first (home) page of the multisite site, and when going anywhere (q?=user/login), i get directed to the default site.

site is dev.mysite.com/www.example.com

i have softlink in the drupal root - www.example.com -> ./

in sites.php i have

$sites = array('dev.mysite.com.www.example.com' => 'example.com',);

and of course the structure is sites/example.com

nothing like a cookie address in the settings... i dont know what else could be wrong. Using the same htaccess, the default, that was working locally for me.

i did notice something interesting that could be a clue. I have a logo image embedded in the page template. (img src="<?php print base_path().path_to_theme(); ?>/img/logo.png")

so locally the source prints as:

img src="/www.mysite.com/sites/example.com/themes/example/img/logo.png"

and on the server it looks like

img src="http://dev.mysite.com/www.example.com/sites/example.com/themes/example/logo.png"

Any caching turned on? (varnish/memcache/...)

If using memcache make sure to separate the memory buckets in each site's config.

$conf['memcache_key_prefix'] = 'Example_Memcached_Key';


Access denied when I try to delete the user menu How can I delete a user menu in Drupal 7? It throws me an access denied error, though I am logged in as user #1. What's wrong with it?

You cannot delete any of the following menus; they come with the core. You can delete any menu you created yourself.

To disable them from displaying go to admin/structure/block.


Group Audience field in Group Content does not show any values other than None I am a OG newbie and followed examples and created a new content type called "Team" and a new content type called "Item" and associated it as a Group Content Type for "Team".

I created a new "Team" called "Team 1" and when I try to create a new "Item", in the Group Audience field I only see "None" as an option.  When I change the Group Audience field setting in "Item" to "Select List" instead of "OG Reference", I see the "Team 1" as part of the list.

The problem is that this workaround is not sufficient because I want to get the "Create Item" link in the Team's page using Entity Reference Prepopulate module.  However, not having it as "OG Reference" causes issues with using entity reference pre-populate field setting for the Group Audience field (getting an AJAX 500 error when I select entity reference pre-populate checkbox).

Any idea what I am doing wrong?  I am using OG 7.x-2.7, Entity Reference 7.x-1.1 and Entity Reference Prepopulate 7.x-1.5

Making sure the Group is published solved the issue for me.


Drupal Commerce Paypal WPP Programatically Create a Transaction I stumbled on a thread over at: https://drupal.org/node/1867768 and I am trying to do a similar integration with a "one page checkout" where the customer selects the product, puts in shipping information and cc information all on one page and I'm capturing that info using drupal's form api submit callback. I can programmatically create the order, add the profile type to the order but I'm getting a little stuck when it comes to the transaction. By the looks of it Ryan had mentioned that each payment gateway has a different way of declaring the transaction. I'm using Paypal Payments pro also know and Website Payments Pro (WPP) and was wondering how to go about creating a WPP transaction programmatically and seeing if anyone had dealt with this before?

Thanks,

I was able to solve this issue.  Instead of retyping it, the answer can be found on drupal.org at this link: https://drupal.org/node/1867768#comment-8755925