Accessing sub-array data from theme_field__custom_content_type($variables) This is a mix of a PHP and a Drupal question.

I created a custom function...

theme_field__custom_content_type($variables)

I have the DEVEL module installed and have been using it profusely. I'm trying to modify the layout/look of a custom content through a childtheme I'm developing. I'm running into an issues that is leaving me scratching my head.

I have a custom content type [netrunner_card] and it has several fields that are taxonomy references. One field in particular is [field_card_subtype]. A card can have multiple subtypes... "Location," "Seedy," "Cloud," etc. What I want to do is to take those subtypes and place them next to another field like so:

field_card_type : field_card_subtype[0] - field_card_subtype[1] - etc

So that you would see output like:

Operation : Location - Seedy

ICE : AP - Trap

etc.

What I am doing is the following...
Yes, I am creating custom variables for this as it helps to collect everything in an easy to use package.

$blinksFieldName = $variables['element']['#field_name'];
switch( $blinksFieldName )
{
    case 'field_unique_card':
        $variables['card_is_unique'] = $variables['element']['#items'][0]['value'];
        break;
    case 'field_card_subtype':
        $variables['card_subtype_list'] = implode( " - ", $variables['element']['#items']);
        break;
    ...
}

When I kpr( $variables['card_subtype_list'] ) I get a string of the word 'Array'. I think that's because the breakdown of the variable in question is more like:

$variables['element']['#items'][0]['#title']

I'm very confused how you reach that level of the array when one of the placeholders is the array index... I had thought to do a for-next but I can't figure out how I would word it? Any help would be greatly appreciated.

I think I get what you're doing...you won't be able to straight implode the items array if it's a sequential set that you're using to build up a list of key/value pairs...

There are probably a few different ways to do that loop, I'd try something like this:

$keys = $values = array();
$count = 1;
foreach ($variables['element']['#items'] as $item) {
  if ($count++ % 2 == 1) {
    $keys[] = $item['#title'];
  }
  else {
    $values[] = $item['#title'];
  }
}

$output = '';
for ($i = 0; $i < count($keys); $i++) {
  $output .= $keys[$i] . ' - ' . $values[$i] . '<br />';
}
$variables['card_subtype_list'] = $output;

Hopefully someone will propose a better solution, that's not exactly elegant. Apologies if I've misunderstood.


How can I theme the outgoing contact mail? I want to theme the outgoing mail from the contact module, because the standard output looks horrible. Where can I do this? It's the one starting with admin (http://example.com/user/1) sent a message using the contact form at http://example.com/contact.

I was able to get Berdir's answer working in Drupal 8.1.0. But I had to do a number of things to get it going.

Install mailsystem, swiftmailer, contact_storage, and contact (core) modules
Setup a custom contact form, configure it and add fields as needed.
Configure swiftmailer message settings (/admin/config/swiftmailer/messages) to use HTML.
Configure swiftmailer transport settings (/admin/config/swiftmailer/transport) to preferred transport type
Configure mailsystem default mail system settings to use swiftmailer for both formatter and sender plugins. I assume you could also configure per module in the later section if you like, however I did not try it.
Under /admin/structure/display-modes/view add a new view mode for Contact message, setting it's namespace to mail. This is the view mode that will be used when sending the email (somewhere this is hardcoded from what I can tell).
If you want a pretty display of the Contact message nodes on the site then you will also want to create a full view mode and configure that too.
Configure your view modes under the custom contact form you created. The Display Suite module really allowed for customizing the markup with it's field templates made available in display suite extras.

Note, I also have Berdir's MessageViewBuilder override in a custom module but I am unsure it is any longer necessary. I have not attempted to remove it yet.


Feeds: How to import images using CSV Node Import? I try to use Node Import clone with an extra image field to import nodes with images attached.

Without success, I try to upload content from a local file (s).

I use CSV parser and Node Processor.
My content type has a image field called Photo I mapped to the csv format using the mapper.

I am using Windows as a local feeds source and Drupal 7 as a server.

How to import images using CSV Node Import ?
What should be exactly the image file path in the csv file ?

I don't think it will work based on local files. The way I understand it, feeds is made to work off CSV data, with files that are already on the server.

It will take a bit of playing around on your part, but your best bet is to upload a single product/node with an image.  Find the path to that image. Once you find the folder where your image is being stored, upload your images to that folder.

Then give the direct path to the image on your server in your CSV file, in the image section. The path will probably look something like this, depending on the how you configured the image field. This example is from a Drupal Commerce site:

example.com/sites/default/files/styles/uc_product_big/public/image-you-want-to-use.jpg

If your server runs some sort of post processing (image-resizing, cropping, scaling), and then saves in multiple folders, I'm afraid you're out of luck with this method.


Bullets and numbers not visible in CKeditor When I edit something in CKeditor and insert a list, the bullets or numbers are not rendered in the result.
Is it possible to correct it?

CKeditor uses CSS from either your default theme or it's own stylesheet. If you are are using your site theme maybe it is set to hide the bullets and numbers.


How to show a block on pages with a path like '/member/*' but not 'member/*/likes'? I want to show a block on a member's profile page (member/*) but not on member/*/likes.

It doesn't seem I can do this without PHP in the block settings, does it?

Try restricting visibility to this URI:

member/*/

(trailing slash!)

Alternatively, you can download the Context module and position the block using a new context, and negate the member/*/likes path in your context configuration.


hook_menu() custom URL with argument I am working with a 300K records dataset and I am having some performance issues. I try creating a node for each of the records on the dataset, but even the simple path translation query is taking forever (over 50ms to execute) to get the node ID from the page and the rest of the queries on the page make it insanely slow to load a single page. The server has all the capacity it might need and it even has memcached working, PHP-FPM, NGINX, etc.

I decided to have each page coming from that dataset as simple as possible to avoid having to load all those objects and so on. The question comes when I want to use the url:

http://www.example.com/item-ABBC

ABBC is the argument that will hit the database to perform a search, but I can figure out how to accomplish this with the hook_menu:

function mymodule_menu() {
    $items['item-%'] = array(
      'page callback' => 'mymodule_abbc_view',
      'type' => MENU_CALLBACK,
    );
    return $items;
}

I am trying to avoid hitting the path table as much as possible that is why I wanted to use the MENU_CALLBACK instead of a regular menu item.

Is this possible at all?

The way Drupal works out of the box, you need to separate your arguments with /. So your URL should be 'item/%'.


How to add permissions and configure links to a module in the /admin/modules page? I created a custom module and when I go to /admin/modules page it looks like this (no links):

How can I add the configure and permissions links to my custom module, just like Devel does?

Configure is the configure key in yourmodule.info.yml, containing a route name, usually your primary settings form/page.

Permissions link automatically shows by having permissions defined in your module.


Make a "Taxonomy Term" Appear in search field What my requirement is to display taxonomy terms in search results when someone searches for anything related/similar to it.
For example: I have a taxonomy ABC, and articles 1,2,3,4 related to it. So when somebody searches ABC, along with article 1,2,3,4, ABC should also be visible there.
I suppose i would have to edit the .tpl.php file of 'search display' and also add the required fields in the taxonomy fields(like image and description) which are required by the articles when searched.Where and how can i add fields in taxonomy terms.

If you have Views installed, use the Views to create a new searchable page. Views has the "Expose", which allow user to change them. All you have to do in View, is to add the "Taxonomy term: Name" on "Sort Criteria" and check the "Expose this sort to visitor, to allow them to change it". See below screenshot for details.


Form input returns "1" instead of real value On this page I have an select list with values from a file directory. This works. Only after submitting it doesn't get the value of it. It makes it "1". Normally with a "normal" select list this should work I guess.

Problem: $form_state['input']['edit']['ios_cert'] doesn't return selected value.

Code (in hook_form):

$files = array();
foreach(glob("C:/wamp/www/drupal2/sites/default/files/*.pem") as $filename) {
   array_push($files, substr(strrchr($filename, '/'), 1));
 }

$form['replace_textfield']['edit']['ios_cert'] = array(
    '#title' => t('Select right certificate file'),
    '#type' => 'select',
    '#options' => $files,
    '#default_value' => $ios_key,
    '#weight' => 45,
  );

Code (hook_submit):

$ios = $form_state['input']['edit']['ios_cert'];

$query = db_update('push_notifications_api')
->fields(array(
'app_id' => $app_id,
'GCM' => $gcm,
'ios' => $ios,
'ios_mode' => $ios_mode,
))
->condition('app_id', $oldid)
->execute();
drupal_set_message(t('@title has been updated succesfully.', array('@title' => $title)));
dsm($form_state);

Result:

And it should be something like "Filename-djfklasjklf.pem"

thanks in advance!

I already got it.

I added this:

foreach ($files as $record){
    $options1[$record] = $record;
 }

And then use $options1 as '#options'


How can I theme the markup for the labels in a set of radio options on a specific form item? Given this form item defined in a custom module;

$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet // array of options pulled from a data source
];

How can I modify the label of each option to include a small image to the right of the text? In my case, the image is stored in the same dataset alongside each label.

I'm going to guess this has something to do with adding a '#theme' attribute, but I haven't been able to determine the entire process for setting that up.

You'll need to massage the $optionsSet array so it's structured like this:

$optionsSet = [
  'option1' => 'option 1',
  'option2' => 'option 2',
];

$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet,
];


Code Problem in my template.php Hello i have an awful feeling im just simply doing something fundamentally wrong. I think they are both the same function possin;y Can anyone tell me how to get it all together possibly? thanks

<?php

function ukf2_preprocess_page(&$vars) {
 if (isset($vars['node'])) {
$vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
}
}
// Finish copy Template for Content type

function ukf2_preprocess_page(&$variables) {

if (!empty($variables['page']['sidebar_first'])) {
    $variables['content_column_class'] = ' class="col-sm-10"';
  }

 else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

if (!empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class2'] = ' class="col-sm-8"';
  }

 else {
    $variables['content_column_class2'] = ' class="col-sm-12"';
  }

}

You just need to put all that logic into a single function:

function ukf2_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
  }

  if (!empty($variables['page']['sidebar_first'])) {
    $variables['content_column_class'] = ' class="col-sm-10"';
  }

  else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

  if (!empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class2'] = ' class="col-sm-8"';
  }

  else {
    $variables['content_column_class2'] = ' class="col-sm-12"';
  }

}


Custom module with custom theme/template I have tried to get this question answered in the past, but I was never given a satisfactory response.

I am building a custom module. I do not want the module to inherit the current theme being used by Drupal core; it should have its own themes/templates. This is the code I have written.

myApp.module

// $Id$
require_once ('myApp.theme.inc');
function myApp_menu()
{
 $result = array();
 $result['myApp'] = array(
    'title' => "My App",
    'page callback' => "myApp_home",
    'access callback' => true,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

 return $result;
}

function myApp_home(){
    $output = theme('myApp_home', array('data'=> ''));
    return $output;
}

myApp.theme.inc

function myApp_theme() {
    $path_to_theme = drupal_get_path('module', 'myApp')."/theme/";

    $themes = array();
    $themes['myApp_home'] = array(
    'template' => 'myApp_home',
    'path' => $path_to_theme ,
    );
    return $themes;
}

myApp_home.tpl.inc

Hello World

The problem is that the module still resides within the Drupal core. I want to have it be a full page web application.

I am new to this, so if anyone could provide an explanation of the best practice, and example code, I would really appreciate it.

As Clive said, you can simply return HTML instead of the render array, e.g.

function myApp_theme() {
    $html = "Hello World;
    return $html;
}

A more general way is to modify the page.tpl.php in your theme and add a wrapper around the normal styling.  E.g.

<?php if ( $plain_page ) { ?>
  <?php print render($page['content']); ?>
<?php } else { ?>
Normal stuff
<?php } ?>

Then in your module, use the template_preprocess_page hook to set the $plain page variable.  E.g.

my_module_preprocess_page( &$vars ) {
  [ check if it's a page you want as plain ]
    $vars['plain'] = TRUE;

You will only need the content for the  tags as the html.tpl.php template handles that.


Drupal as mobile application backend What I try to achieve is create a simple Form where I will be able to add new content (like "Question" objects for instance) and access the information through Services 3.x. My problem is that I am new to Drupal and some guidance will be very helpful. I have tried to create a new custom content type, but as I need grouping of the fields, I used the "field collection" module. The problem there was that when using the node service I couldn't get the content of this field collection. So I am actually stuck now. The following questions appear in my head now:

Do I need to write my own module to be able to extend the NODE object or I can achieve it by creating custom content type?
Can I customize a service to return only desired properties (like only the id and the title of a node without returning all other properties like createddate, modifieddate, etc.) or should I create my own module to achieve this?
If I need to create a custom module, can you point me to an example? (I have read the Drupal article for creating a resource for Services 3.x, but there they using a new custom object and not the NODE object)
How can I have both a form to enter content and a service resource for the basic CRUD operations in one module? Using hooks?

Basically my point is to skip writing code for CRUD operations if it is possible and just use the ones from the NODE, but expose to the mobile app only some of the NODE properties and have a form where I can enter new content.

I am using Drupal 7.

I want to apologize for the messy post, but it really represents the thoughts in my head...

That's 4 questions in one ;-)
For #2 checkout my previous question that has just been answered. Services Views would be another solution to do it without code.


Where is the content of the pop up bubble in my form validation coming from? I use the Clientside Validation module for my webforms.

I get a "Please enter an email address" pop up bubble next to the email text field when an incorrect email is entered. I am not quite sure where this is coming from.

I would prefer this functionality instead:

  Submitting the form with an empty email field displays a different
  error message to when an invalid email is entered eg.
  http://validation7.ubu001.attiks.com/node/1?utm_medium=atix&utm_source=cv7b

Can anyone shed some light about it?

In our instance we used clumsyfingers's code but with parsing fix:

novalidate cannot be "1". It has to be either:

no value
empty value
value = attribute name

like so:

function mymodule_form_alter(&$form,&$form_state,$form_id) {

  if(strstr($form_id,'webform') !== FALSE) {
    // prevent html5 validation, i.e. on input type="email" fields
    form['#attributes']['novalidate'] = 'novalidate';
  }

}

CSE HTML validator was returning this message:

  The "novalidate" attribute for the "form" element has an invalid value
  "1". This is a boolean (true or false) attribute. The presence of a
  boolean attribute represents true and absense of the attribute
  represents false. Setting a value is not necessary, but if a value is
  set, then it must be an empty string or be a case-insensitive match
  for the attribute's name. NOTE: Never use the values "true" and
  "false".


How to display article metadata in a custom div? Metadata (publication date, author's name...) is normally displayed in the "Content" part between the "articles" tags. I have created a new region "titre d'article" in which I would like them to be displayed with the title of the article.

I was able to add the title block when the blocks were formatted. For metadata, I created a "Post metadata" view with a "custom text" field to display them.

But when I create a block with this view and add it to my region, it displays metadata for all published articles when it should display for the read-only article.

I don't know what I'm doing wrong. Yet I had already done it and it worked. I have to do it again because I'm going to lose the data from my old computer.

So basically, I want to hide or delete the default position of the metadata (that I can do easily) and display them in a custom div created using a region.

Please tell me if there's any mistake in what I did.
Or if there's another way to do it more simply, I'd be delighted.

Thanks to help me

"Read-only" usually means a file or an item that cannot be changed/edited, you can only view it. I'm guessing what you actually mean is "current, the one being viewed right now".

You have to add a contextual filter to your Views that would filter the results to only the node you're currently viewing.

Here are the steps to configure Views to show only the current node's results:

Expand the Advanced area in your Views
Under Contextual filters click on Add
Add the ID filter from the Content Category and configure it:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Article
Hide View if the argument doesn't validate, or some other options that make sense to you.
Place the Block on article pages in your theme region (your have this already), adjust Node from URL and other Block options.

The Views Block will only show on article pages, and it will only display output related to the current node.


The directory sites/default/files is not writable on Mac OS X I had my website developed by someone else and it is currently working with no issues on our web server.  I'm trying to set the same site up on my Mac OS X 10.6 using the preinstalled Apache server, MySQL, and PHP5.  Also, it's Drupal 6.22 we're using.  I copied all of the website files (including Drupal and the .htaccess file) and put them in /Library/WebServer/Documents/website.  I then did a mysql backup on the server and imported that file on the local machine with phpMyAdmin.  I configured the settings.php file and everything else to work nicely so it can connect to the DB, etc.

Most of the site works as expected, however, there is a couple of nodes that won't work at all.  Instead I get this message when I go to them:

"The site is currently not available due to technical problems. Please try again later. Thank you for your understanding."

The weird part is if I enter in the URL to go to the edit page for that node it works, but I still cannot view the page.

When trying to search for problems that only issue I found anywhere is in the "Status Report" page it says the file system is not writable.  I get this message:

"The directory sites/default/files is not writable."

I checked the permissions and that folder has drwxr-xr-x set for it.

Any ideas as to what might not be set properly would be greatly appreciated.

The files directory in your site must be writable by the webserver. In the finder, do a Get Info on the files directory and assign read & write permissions to staff. (Make sure that this applies to any directories inside files as well.) Alternatively, in the terminal you could "chmod -R 775 my-site-path/sites/default/files" to take care of files and any contained subdirectories.


How do I get the email of the one submitting contact form in the "reply to"? Drupal 8 site. I'm using the core Contact module for basic "Contact Us" form.

How can I get the email of the person submitting the form to be in the From field? And a follow-up: How do I get the email of an authenticated user to show in the body along with the username?

Site and users:

The site is an association website. There are about 100 user accounts.

Domain and email:

The site domain is not the same as the email domain in account settings: the site is theirsite.org and the email is theiremail@gmail.com

From & To in email

When the email came in from authenticated user or anonymous user, the From and the To are both showing theiremail@gmail.com - the site email.

What shows in body of email:

The email from the authenticated user does not show in the body of email; only the user name and the link to their user account /user/[user-number]

When I submit a form as an anonymous user the email does show in the body.

P.S. I do not want to use the Webform module.

If the person submitting the form is an anonymous visitor the form will be empty and the visitor will have to fill in every field.

If the visitor is logged in (authenticated user) the name and email address are already pre-filled from their user profile.

Are you sure you're not testing this while being logged in as an admin account that has the same email address as the site? Then it's expected to see that email there.

Try to login as a different user, and also test as anonymous to see that the email is now from that different user/empty respectively for those two cases.

If you're constantly seeing the site email as From in all three cases then it's a bug and you should try to see where it's coming from. I haven't seen any problems with the Contact module, it's showing the correct "From" value every time.


restrict visiting user/1 path for all users except admin I would like to add a condition that users are not able to visit admin profile using user/1 in url. (not even if url contains alias).
What would be the easiest way of doing that? I do not want to install additional module just for this task. Thank you.

You can do this in page.tpl.php

global $user;
global $base_url;
$uid=$user->uid;
if(agr(0)=='user' && arg(1)==1)
{
if($uid!=1)
{
drupal_goto($base_url);
}
}

OR

function YOURTHEMENAME_preprocess_page($vars) {
  if ($_GET['q'] == "user/1")
  {
    $usr = user_load(arg(1));
    if(!in_array('administrator',$usr->roles) ){
         drupal_goto("ANY PAGE"); //Example <front> for the homepage
    }
  }
 }

Hope this will work


How do I post JSON data on a remote resource? I'm working to integrate a Drupal 8 site's content into a 3rd-party search tool. To get our data, the 3rd party requires us to post JSON to their API.  Having never done this before, what is conceptually needed to accomplish this in Drupal 8?  The site in question is around 5-6k nodes.
My initial thoughts are a custom module with a route that calls a controller function that creates an http client. The client gets its data from a json View. So when I visit the route, it pushes the data to the endpoint?  That is my rough guess and any insight is much appreciated.
Thanks!

Quite a few ways to do that, but here's one approach using the queue api, for async processing:

Add the items to a queue on save.
Add a queue worker to process the queue and send the items to the remote service.

If you use a cron queue, you can process them automatically via cron.
More info:

https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.8.x
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Annotation%21QueueWorker.php/class/QueueWorker/8.8.x


Drupal Commons on D6 - Visibility of 'Group members' and 'Latest group activity' blocks Out of the box the 'Group members' and 'Latest group activity' blocks on the main page of a group are visible to all users regardless of whether one is a member of that group or not.

How can both blocks be displayed only when a user is a member of that group?

Thank you,

Alex

I had an urgent need to fix this issue quickly so I added a few lines of code to one of the Drupal Commons files directly. Once I have more time I plan to extract the functionality into a custom module. Until then this was my fix:

Open file /profiles/drupal_commons/modules/features/common_core/commons_core.blocks.inc
Locate functions '_commons_core_group_activity_block_view()' and '_commons_core_group_members_block_view()'.
Add the following lines before the if statements:

//Determine group nid
 $url_parameter = explode("/", $_GET['q']);
 $group_nid = $url_parameter[1];

//Determine group membership, exclude Admins
 $is_group_member = og_is_group_member($group_nid,$include_admins = FALSE);
Add && ($is_group_member != '') as second condition to each if statement

If you know a better way please share.

Alex


Undesired toggle effect with #states and checkboxes I'm working on a patch for the Login Disable module, and on the settings page, I want to have two mutually exclusive options so that when one is checked, the other is unchecked. Using the FAPI #states value, I have the following code:

function login_disable_settings_form($form, &$form_state) {
  $form = array();

  $form['all_users'] = array(
    '#type' => 'fieldset',
    '#title' => t('All Users'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['all_users']['login_disable_is_active'] = array(
    '#type' => 'checkbox',
    '#title' => 'Prevent user log in',
    '#description' => t('When active the user login form will be disabled for everyone. For roles granted bypass rights they must use the access key defined below.'),
    '#default_value' => (bool)variable_get('login_disable_is_active', FALSE),
    '#states' => array(
      'unchecked' => array(
        ':input[name="login_disable_individual"]' => array('checked' => TRUE),
      ),
    ),
  );

  $form['all_users']['login_disable_key'] = array(
    '#title' => t('Access key (optional)'),
    '#description' => t('For added security, a word can be required to be added to the URL.'),
    '#type' => 'textfield',
    '#size' => 10,
    '#default_value' => variable_get('login_disable_key', 'admin'),
  );
  if (!empty($form['login_disable_key']['#default_value'])) {
    $form['login_disable_key']['#description'] .= '<br />' . t('The URL to use to log in is: @url', array('@url' => url('user/login') . '?' . $form['login_disable_key']['#default_value']));
  }

  $form['all_users']['login_disable_message'] = array(
    '#title' => t('End-user message when login is disabled'),
    '#description' => t('The message to display to users when login has been disabled.'),
    '#type' => 'textfield',
    '#size' => 80,
    '#default_value' => variable_get('login_disable_message', t('Member access has been temporarily disabled. Please try again later.')),
  );

  $form['individual'] = array(
    '#type' => 'fieldset',
    '#title' => t('Indivdual'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['individual']['login_disable_individual'] = array(
    '#type' => 'checkbox',
    '#title' => t('Disable on user profile'),
    '#description' => t('Checking this box allows disabling individual logins on user profile pages.'),
    '#states' => array(
      'unchecked' => array(
        ':input[name="login_disable_is_active"]' => array('checked' => TRUE),
      ),
    ),
  );

  $form = system_settings_form($form);

  return $form;
}

So as I see it, my code should just uncheck a checkbox when the other checkbox is checked. I also want the option that neither is checked.  However, what's happening is that they are working as a toggle, in that if I uncheck one, the other one is being checked, which is prohibiting the third option of neither of them being checked. Can anyone tell me why I'm getting this effect?

Thanks.

Form API states act in both directions. Suppose you set an element to be unchecked if a condition X is true. Then it gets unchecked when X becomes true, and gets non unchecked (i.e. checked) when X becomes false. See the example code and its demo at drupal.org.

You need some custom jQuery in the case.


Submit button to filter data from table select by selecting on list select i'm new on drupal, i've create a module that shows a form (with tableselect, list select and a submit button) the tableselect shows data from the database, but i want to filter what i want to see on the table by selecting what i want from the list select and submit. i've create the submit function (it contains the query with condition) and when i use dsm($form['tableselect'] everything works (filter works), but how can i show the result's select on the tableselect ? because it doesn't change

here's my form :

$form['options_state'] = array(
    '#type' => 'value',
    '#value' => array (
        'all'=>t('All'),
        'Valid'=>t('Valid'),
        'published'=>t('published'),
        'not published'=>t('not published')

        )

    );

$form['state_book'] = array(
    '#type' => 'select',
    '#title' => t('state :'),
    '#options' => $form['options_state']['#value'],
);

// filter submit button

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

and this is my table select (the first one shows all records) ;

$header  = array(
    'book_title' => t('title'),
    'book_state' => t('state'),
);

    $sql = db_select('field_data_field_title','ta');
    $sql->join('field_data_field_state','st','st.entity_id = ta.entity_id');

    $sql
        ->fields('ta', array('field_titre_en_arabe_value','entity_id'))
        ->fields('st',array('field_state_value'));
        $result = $sql->execute();

    $rows = array();

foreach ($result as $res){

$rows [] = array(
        'book_title' => l($res->field_title_value, 'node/'.$res->entity_id),
        'book_state' => $res->field_state_value
      );

}

$form['table1'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty !'),

);

return $form;

}

table1 works, but it shows all records (book published and not published)
now here's my submit function :

function book_form_submit($form, &$form_state){

$cond = $form_state['values']['state_book'];

$header  = array(
    'book_title' => t('title'),
    'book_state' => t('state'),
);

$sql = db_select('field_data_field_title','ta');
$sql->join('field_data_field_state','st','st.entity_id = ta.entity_id');

$sql
    ->fields('ta', array('field_title_value'))
    ->fields('st',array('field_state_value'));

    $sql->condition('st.field_state_value', $cond, '=');

$quer = $sql->execute();

$rows2 = array();

foreach ($quer as $q){

    array_push($rows, array(
        'book_title' => $q->field_title_value,
        'book_state' => $q->field_state_value,

    ));

}
$form['table2'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty!')
);
}

Now how can i put result of submit on table1 to show what the query returns ??

Thanks

Digging in, and trying to run some pseudo code it looks like there may be a problem with AJAX callbacks and tableselect fields regarding Drupal Core.

https://www.drupal.org/node/1458824 (7x and 8x)

I would consider using the Views module with exposed filters.

You could fairly easily create a view that displays 2 articles, which exposes a state drop down list.  You could use a page or block view for the front end.

If you update your question with what you are ultimately trying to accomplish I can try to put together a more appropriate Views setup.


Add inline style to render array attributes, without XSS filtering I wish to use an inline style to add a dynamically generated background image URL to a div, e.g.

  $build[0] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'thumbnail-image',
      // the example below is a YouTube thumbnail, to be cropped using other CSS
      'style' => sprintf('background-image: url("https://img.youtube.com/vi/1234567890/sddefault.jpg");', $video),
    ]
  ];
  return $build;

The XSS filtering silently drops style attributes.  Can I disable that for an individual render array, or otherwise work around it?

Note: this is generating output for a Field Formatter, used in a view.

The official advice is:

  If your markup needs any of the tags not in this whitelist, then you
  can implement a theme hook and/or an asset library. Alternatively, you
  can use the key #allowed_tags to alter which tags are filtered.

Things tried:

1) using a theme hook and a template

Here's my template:

Sample output

It's working, except the style attribute is still being stripped out.

2) #allowed_tags (but it's not a tag, it's an attribute):

'#allowed_tags' => array_merge(\Drupal\Component\Utility\Xss::getAdminTagList(), ['style']),

Successful workaround:

This code is in a field formatter for views, so I overrode the default views template. The views templates allowed a style attribute to pass through as I would have expected.

Initially I made a template for one specific field, but the problem was I needed to access the values of a separate field too and it was proving hard/impossible to retrieve them with the row._entity variable.

So then I decided to use views-view-fields.html.twig instead, which gives access to all the fields. This took rather longer, but as my code had a couple of conditionals and some variables used more than once, on balance the end result is cleaner than doing everything in the UI. (It's worth leaving yourself a note in the view UI admin comment and any docs that the view field is overwritten.)

I'd use '#type' => 'inline_template' for this: You can do everything what you can do in a regular .twig file, just inlined in code:

  $build[0] = [
    '#type'       => 'inline_template',
    '#template'   => '
{{ bar }}
'
    '#context' => [
      'foo' => $youtube_thumbnail
      'bar' => $whatever
    ]
  ];
  return $build;

Here is a complete list of render elements / #type 's for render arrays. (For Forms API, here is the sub-list of FormRenderElements)


Passing an array of object from custom module to template in drupal 8 Follow this about passing an array to template. But my array is array of object so I'm getting some errors on the page, this is the one of them:

  User error: "0" is an invalid render array key in
  Drupal\Core\Render\Element::children() (line 97 of
  core/lib/Drupal/Core/Render/Element.php)

This is my code :

Controller

  public function content() {
      return array(
        '#theme' => 'my_page',
        '#text' => "Lorem Ipsum",
        '#myvariable' => array('key' => $myArrayofObjects),
      );
  }

mymodule.module

function my_page($existing, $type, $theme, $path) {
  return array(
    'my_page' => array(
        'variables' => array(
            'text' => NULL,
            'myvariable' => array(),
        ),
    ),
  );
}

my-page.html.twig

Test twig template!

{{text}}

{% for key, value in myvariable %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

This is the array :

Array
    (
        [0] => stdClass Object
            (
                [name] => User1
                [user_id] => 1
                [email] => user1@website.com
            )

        [1] => stdClass Object
            (
                [name] => User2
                [user_id] => 2
                [email] => user2@website.com
            )

        [2] => stdClass Object
            (
                [name] => User3
                [user_id] => 3
                [email] => user3@website.com
            )
     )

How the best way to pass an array of object from module to template and render or loop it using twig engine?

In your controller why you are using like this

'#myvariable' => array('key' => $myArrayofObjects),

Change it as

'#myvariable' => $myArrayofObjects,

and in my-page.html.twig

Test twig template!

{{text}}

{% for key, value in myvariable %}
  Key : {{ key }}
  Name : {{ value.name }}
  User ID : {{ value.user_id }}
  Email : {{ value.email }}
{% endfor %}


How do I detect the language using node alias I know to get the current language of a website:

$current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

However, given that I have a node alias

$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);

How do I get the language of that $alias node?

To get the path alias of specific language try with:

$current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
/** @var \Drupal\Core\Path\AliasManager $aliasManager */
$aliasManager =  \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/node/10', $current_lang);

If you want to get the language code from alias try with:

$aliasArray = \Drupal::service('path.alias_storage')->load(['source' => '/node/' . $nid]);
$lang_code = $aliasArray['langcode'];


Adding field input to a field I am creating a custom content type with the following fields:

  Name
  Offices(can be many)
  Address(offices address)

Question is, how can I be able to add address field to each office names?

Sounds like you want Paragraphs or Field Collection.

Basically, the idea with these modules is to group two fields (office + address) as a set within an entity and then embed that entity in your content type.

For Drupal 8, Field Collection recommends using Paragraphs, so that's the module I would use.  For Drupal , I would use Field Collection.


How can i access variable inside body node(input format:php) from my own module please can you help me.

I make own simple module and storing actual variable like this:

.
..
...
function getip_preprocess(&$vars) {
  global $get_specific_ip;
  $vars['get_specific_ip'] = get_client_ip();
}
...
..
.

If i call this variable from page.tpl.php, or node.tpl.php., it works.....

But if im trying to get this variable from inside of body content area, result is empty... If i call function get_client_ip(), i will get solution i need to see, but im trying to get it as a variable, like $user.

I tried to make global variable from it ( $GLOBALS['get_specific_ip']; ) , but it aint works.

Please help me how to do it.

Thanks a lot for your answer.

Regards Stein

Some comments on your code and question:

global $get_specific_ip; and $GLOBALS['get_specific_ip']; are both the same  thing. For more info see http://php.net/manual/en/language.variables.scope.php
global variables and the template $vars array are different, so
global $get_specific_ip;
$vars['get_specific_ip'] = get_client_ip();
won't actually set a global variable because you're never setting $get_specific_ip to anything, it will only set the $vars['get_specific_ip'] variable, which will make $get_specific_ip available in all your templates but not as a global variable.
The getip_preprocess() does not seem like the best place for this code. IP address is not specific to theme templates and would be best as either a global variable or attached to the existing global $user object. In either case gettip_preprocess() is not the optimal place because it isn't a global solution.
If the function get_client_ip() is a custom function of yours you should name space it to your module to avoid possible conflicts with other functions. For example, call it getip_get_client_ip().
The variable name $get_specific_ip is a little strange because it sounds like an action or function name but it should describe what is stored in it. For example $client_ip. That however could also run into name spacing issues so would be better as $getip_client_ip or something like that.
Note that there is a Drupal function ip_address() that might possibly be useful to you.

If you really want this available everywhere then you could use hook_boot() like this:

/**
 * Implement hook_boot().
 */
function MODULENAME_boot() {
  // Set the user's IP address to a global variable for use elsewhere.
  global $get_specific_ip;
  $get_specific_ip = get_client_ip();
}

Then you can use global $get_specific_ip; from anywhere on the site to get that variable.

The use of hook_boot() means it will run even on cached pages, which is a must for IP detection because you want your code to run and get the current user's IP even if they are getting a cached page.
The other side to that is that you need to be careful to try not to use resource intensive code in there because it will always run on every page load.

It's worth noting at this point that whenever doing something with dynamic data like IP address make sure to properly test cached pages to make sure they always function as you would expect.

One last thing is that Drupal core already makes the user's IP address available to you in the global $user object.

So you can also get the IP like this:

global $user;
$ip = $user->hostname;

So unless you are doing something special in your get_client_ip() function it might be better to use that.


How do I make computed fields visible when other fields are presented? I have been spinning my wheels for hours.  I added a computed field to a content type and it simply wouldn't show up in the result.  I made an all new content type with nothing in it and the computed field showed up fine.  Once I added an additional field, the computed field vanished.  Is this a bug or a feature?

No reason why it shouldn't show up just because there are other fields in that content type. Are you sure there is data to show?


Entity form in ctools modal popup, whilst passing in values from current node I need to open an entityform in a modal popup. I have got this working using 'Modal operations' and 'Modal forms' modules following this guide: http://julian.pustkuchen.com/en/comment/reply/599. My link looks like the following:

<?php print t('Apply') ?>

The problem now is that I need to pass certain data (e.g. the nid) of the currently viewed node into the entityform.

I am happy to use hook_form_alter or similar, but obviously hooking the entityform has no knowledge of the currently viewed node. My other, pretty hacky, idea was to grab data with javascript and put it in that way, but I need some sort of popup event to work from, which I don't think exists.

Is there another approach to this I could be using, or am I going down the right track?

If anyone's interested in the answer, I just appended ?nid=5 to the end of the link url. Then I could just hook_form_alter to get the nid:

if($form['#id'] == 'whatever-entityform-edit-form'){

        $nid = $_GET['nid'];
        $node = node_load($nid);

        $form['field_whatever'][LANGUAGE_NONE][0]['target_id']['#default_value'] = "$node->title ($node->nid)";

    }

Might not be the best way, but it works.


How to change the user-facing label for a Commerce payment option? I'm using Commerce Braintree as a payment method, which accepts both credit cards and PayPal. Currently it looks like this, which some users are getting confused by since it's not clear that the PayPal button is an alternative to the credit card info options:

I'm getting worrying confused customer comments like "But I don't have a PayPal credit card number", so I'd like to edit this label so that it informs the users that they are being presented with two options (PayPal or credit card), but I can't find any way to:

There's nothing in the UI
The feature request to enable it was rejected, a follow up request is incomplete
A suggestion to use hook_form_alter doesn't work with all payment methods
I don't want to use string overrides because it's too blunt a tool, replacing "Credit card" everywhere would have unfortunate consequences elsewhere

How do I this be done?

I wasn't expecting something so basic to require an entire extra module, but apparently it does:

Download and install Commerce Payment Alter
Set new labels at the admin page admin/commerce/config/payment-methods/alter

Don't forget to document for administrators that they need to go to a whole different page if they want to rename a payment method's user facing label.


Newly contributed theme not showing in Project Application issue queue I have contributed a theme (Auro) in Drupal.org and assigned for "Needs review" but the project not showing in Project Application issue queue.

Why doesn't my theme appear in the Project Application queue? What did I do wrong?

It doesn't appear because you didn't create an issue in the Project Application issue queue, but in the issue queue for your theme.
To create a issue in that queue, go to https://www.drupal.org/project/issues/projectapplications and click on Create a new issue.

Since I am a Drupal.org webmaster, I have already moved the issue in the correct queue; you don't need to do anything more.


Clearing the cache changes the nice menu every time Maybe this isn't a cache problem, but I am using Drupal 6, I have cache disable and I am editing a custom nice menu CSS file.

I didn't see changes right away to my nice menus, so I cleared the cache in the performance page, and the menu would revert back to old changes. When I cleared the cache again, it randomly found new settings for Nice Menu.
I then installed Devel, and cleared the cache, but it didn't help. Clearing the browser cache didn't help either.

Do you have any idea?

If you have turned CSS file aggregation off, changes take effect immediately unless you have an external cache like Varnish of the css file. If you are not seeing changes after checking this, maybe your CSS file is not included or the rules implemented is overridden by other CSS rules.


Images problem after migration I have a strange problem.
Today I moved a site from staging to production and the site work fine but I cannot se the images.

I can see in ftp the picture but drupal do not serve it in the page.
I already tryed to clear cache.

In the reports log I there is a lot of

Unable to generate the derived image located at public://styles/ensemble-small/public/anne ristorcelli s.png.

errors but I do not understand what I can do.
The GD tookit works fine.. I checked it.
I tryed to re-upload some images but do not work and I can't see they in the editing page too.

Can someone help me to solve this?

UPDATE:
I tryed to delete the images generaten in the staging server to verify the correct working of the images modules. The images was ok.
So the problem is in server request?

If I try to see the image directly I have this error:

    Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, postmaster@ensemble05.it and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

I fixed this problem going to sites/default/files/.htaccess file and commenting

# Options None
# Options +FollowSymLinks

After that I had some other broken images but there are some wrong address in the nodes  tags linked to
/subdirectory-of-staging-server/sites/default/files
instead
/sites/default/files

Thank you for all the comment who help me to debug the error ^^


How to set up a question/assignment pool for a course website? I have done quite a bit of Drupal work in the past, but am a bit stuck on this one.  The basic idea is that the site will offer 1-on-1 tutoring to students.  There will be there levels of users: Course Admins, Tutors, Students.  What I am looking to do is the following:

A course admin can create a pool of "readings."  A reading consists of something to read, and an arbitrary number of questions to be answered (currently a text-field entry with unlimited number of values.
A tutor, can now create an "assignment" (another content type), for a student that has been assigned to them.  To create an assignment, the tutor would simply select from the list of available readings (The tutor doesn't create any questions, readings, etc.. on their own, they must choose from the pool that has been created by course admins).  I am envisioning the assignment content type as a cloned reading, with the addition of answer fields for the student to fill in.  I believe the reading should be cloned, so that if a course admin updates the questions in a reading while the student is working through answering the questions, their answers will correspond to the old questions.

Any thoughts on how this might be done?  Will it require me to write a custom module, or can something like this be accomplished through the basic content type creation + some rules?  Any thoughts would be greatly appreciated.

You might want to start from the Answers module. Here are some details about it (from its project page):

  Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

Question.
Answers.

The Answers module comes with integrations with other modules such as:

the Rules module, to add all sorts of business logic to fit your requirements.
the Userpoints module (and supports voting).

Here is a summary of how I'd implement what you're looking for:

the Questions and Answers are 2 content types, implemented via the Answers module.
Implement the Readings as a (3rd) content type, in which you add Entity references to the various Questions that would fit.
Implement the assignment as a (4th) content type, in which you add Entity references to the appropriate readings.

Not sure if it would be a requirement here, but I can imagine you also might want to add the Group module. Some more details about that:

you can organize the various students that attend a selected course (with group type = Class, or Training), and with each specific course implemented as a "Group".
the Group roles that would make sense in this case are:

course admin.
tutors.
students.
outsiders (= anybody else who is not (yet) involved in a specific class, but for which you want to show them something about such classes, to create awareness).

Disclosure: I'm a (co-)maintainer of the Answers module.


How to hide the inside page for anonymous user? I have a view named Search User.

LINK: www.example.com/search-user

If any anonymous user directly open this link then this page shown.

How can I hide that View page for the anonymous user.

Go to your view. and set Role permissions like follows

Click on Permissions

Select Role

Check all roles except anonymous user.


Copy url in link to webform I would like to know if it is possible to set up a link on a node to open a webform and copy the url from the node where the link sits to a field in the webform when it opens. If not, maybe copy some text in the link to the webform?

Probably the easiest way to do it would be to pass the path in a GET variable and use a token.

So on your node page edit the webform link to include the path like so

Webform link

Then on your webform for that textfield use [current-page:query:yoururl] as your default value.

Obviously replace yoururl with whatever you want to name the variable.


Reuse/sync view mode display settings across entity bundles? Assuming I have a number of entity bundles (e.g. node types) with a similar structure and behavior. Now I want to show a list of such entities/nodes. I want to use a view mode, e.g. "teaser", to display each node.

I could now configure the "teaser" view mode for all 4 node types, optionally with Display Suite. But the settings should be all the same.

So, which solutions do exist to have the same settings across entity bundles, and keep them synced?

Also, when exporting to a feature, I would prefer to avoid redundancy.

As far as I know, this is not currently possible with view modes in Drupal 7, due to how this feature works. But I am curious for out-of-the-box solutions that do the job.

Disclaimer: This is a question I repeatedly was asking myself in the past. At the time I am writing this, I already created a solution that works for me. I am posting this as a Q/A to share it with others. meta

Multiple solutions, pick what works best for you..

View modes

If you really want to work with view modes, there might be ways to copy the settings around between bundles. This still leaves you with lots of redundancy. So maybe not the preferable solution.

Views fields

If you work with Views, you can use views fields instead of view modes. These have their own advantages and drawbacks. You cannot use a layout (afaik). And now you cannot reuse the fields configuration across views.

So..

views fields: reuse across entity bundles, but not across views.
view modes: reuse across views, but not across entity bundles.

Ctools content panes / panels

Panels configurations can be reused in different places.

I personally do not use them as much, so I am sure someone else could write more about it.

Entity display plugin / Renderkit.

You can use EntDisP, to configure an entity display from multiple components. (This is using components from Renderkit.)

The module gives you a views row plugin, and a views field handler. So you can create an "entity display" for the entire row, or you can combine it with views fields.

It also gives you field formatters for entityreference, taxonomy term reference, paragraphs, and field collection.

You can configure the entity display in the place where you use it, so it will be stored as part of the view, field formatter, etc.

Or you can configure it as a "preset" with CFR Preset, so it will be stored independently and can be reused in different places. Such presets can be exported as features.

You can embed view modes in entity displays.

You can also embed entity displays in view modes using EntdispFieldUI.


Form alter not working I used custom module to alter comment form.in that module i write below code to remove required option for fivestar rating field. but it is not working.

$form['field_rating_comment']['und']['0']['value']['#required'] = FALSE;
$form['field_rating_comment']['#required'] = FALSE;

both are not working.

If it's an entity then you can remove the required property from manage fields option in comment.

$form['field_rating_comment']['und']['0']['rating']['#required'] = FALSE;


When is it appropriate to run a drupal_bootstrap? I have a static site with a drupal blog in a subfolder and I want to bring the latest posts into the homepage. I can run a drupal_bootstrap and then load the nodes I want. Is this an ok strategy? When is it appropriate to use drupal_bootstrap?

In order to bootstrap Drupal from another PHP script, you can use below code:

 define('DRUPAL_ROOT', '/path/to/drupal');
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

When ever you would like to call Drupal Functions or features outside of Drupal root you can use above code..


Retrieve create node form. Why cant save send values? I want to add a custom page for creating "blog post". Ive got a node blog. So I write something like this:

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

    $items['user/%/edit/blog/add'] = array(
            'title' => 'Add blog post',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('module_add_blog',1),
            'access arguments' => array('createBlog'),
            'type' => MENU_CALLBACK,

    );
return $items;
}

And then in module_add_blog callback:

function module_add_blog(&$form_state, $arg) {
    $form = array();

    $id = intval($arg);
    if ($id == 0){
        drupal_set_message('ID must be an integer.' , '$error');
        return;
    }

    $user = user_load($id);
    module_load_include('inc', 'node', 'node.pages');
    $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog');

    $form = drupal_retrieve_form('blog_node_form', $form_state, $node);
    drupal_prepare_form('blog_node_form', $form, $form_state);
    return $form;
}

Form is rendered in path user/1/edit/blog/add but when I send data it is NOT SAVED.

Any ideas how fix it? Thanks

I think you're confusing Drupal by having a form within a form so-to-speak. I think it would be a lot easier to define a proxy function for the node form so you don't need to worry about doing so:

function module_menu() {
  $items['user/%/edit/blog/add'] = array(
    'title' => 'Add blog post',
    'page callback' => 'module_blog_form_proxy',
    'page arguments' => array(1),
    'access arguments' => array('createBlog'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function module_blog_form_proxy($uid) {
  // Validitiy checks etc...

  $user = user_load($uid);
  $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog');

  module_load_include('inc', 'node', 'node.pages');
  return drupal_get_form('blog_node_form', $node);
}


How do you get the last star to be only star shown in a rating? The out of the box process with fivestar will show star 1,2,3,and 4 highlighted (it will show all stars up to the actual vote). I need stars except the actual vote to be the neutral or the unselected star.

Say for example, someone votes 4 out of 5. How do I show ONLY 4th star highlighted while all the others are either the neutral or unselected star?

EDIT: After reviewing fivestar.js, I believe the code that handles highlighting is the following;

$container.find('.star:lt(' + index + ')').addClass('on');
      $container.addClass('fivestar-widget-' + ($options.length));
      $container.find('a')
        .bind('click', $this, Drupal.behaviors.fivestar.rate)
        .bind('mouseover', $this, Drupal.behaviors.fivestar.hover);

      $container.bind('mouseover mouseout', $this, Drupal.behaviors.fivestar.hover);

      // Attach the new widget and hide the existing widget.
      $select.after($container).css('display', 'none');
    });
  },
  rate: function(event) {
    var $this = $(this);
    var $widget = event.data;
    var value = this.hash.replace('#', '');
    $('select', $widget).val(value).change();
    var $this_star = $this.closest('.star');
    $this_star.prevAll('.star').andSelf().addClass('on');
    $this_star.nextAll('.star').removeClass('on');
    event.preventDefault();
  },

I haven't used Fivestar but if you use rate it has an option to show the users vote. Rate has a fivestar widget as well.


AJAX HTTP error 200 when using Views Bulk Operations on Files I am attempting to use VBO's "Lock Files" operation to prevent some files without file usage records from being randomly deleted (it happens). I am open to alternate means of doing this as well as a solution to this specific problem.

VBO has never worked great. Particularly the options to "select all on this page" or "select all on all pages" almost never show up. Every once in a while it will but there seems to be no rhyme or reason there.

Whether I select multiple files or a single file from the view preview results, when I attempt to execute the "lock file" operation, on the "confirm" step, I get a js alert box pop up with this error:

  An AJAX HTTP error occurred
  HTTP Result Code: 200
  Debugging information follows.
  Path: /admin/structure/views/ajax/preview/files_check/default
  StatusText:
  ResponseText:
  window.NREUM||(NREUM={}),__nr_require=function(e,t,n){function
  r(n){if(!t[n]){var o=t[n]={exports:{}};e[n][0].call(o.exports,function(t)
  {var o=e[n][1][t];return r(o||t)},0,0.exports)}return t[n].exports}
  if("function"==typeof__nr_require)return__nr_require;for(var o=0;o
  Performing Lock selected files on the selected items...

This does not appear to be the complete error, but since the error is in the alert box instead of the console there appears to be no way to access the full error.

After I clear the alert box I still have the confirm button and cancel link. When I click confirm I just get the error again. When I click cancel I return to my preview but now the "select all..." options are visible. All further attempts still generate the same error though.

This is the query output by my view

SELECT DISTINCT file_managed.fid AS fid, file_managed.timestamp AS file_managed_timestamp, file_managed.filename AS file_managed_filename, file_managed.uri AS file_managed_uri, file_usage.count AS file_usage_count
FROM
{file_managed} file_managed
LEFT JOIN {file_usage} file_usage ON file_managed.fid = file_usage.fid
ORDER BY file_usage_count ASC, file_managed_timestamp ASC
LIMIT 10 OFFSET 0

I have tried this by setting the advanced "Use Ajax" option to both yes and no with the same result.

Drupal (7) core and all modules are up to date.

I'd be happy to provide any additional information needed. Please advise.

200 means that a response was returned successfully, but the response is not something your code can work with, which is why you are getting the error. It looks like the response is returning a script, rather than whatever is expected (likely JSON).


Views - Custom Field Layout? I'm looking for direction on how to format the field layout of a view.

Here's the layout I'm looking for:

--------------------------------------------------
| Field1     | Field2      | Field3              |
| Field4     | Field5      |                     |
--------------------------------------------------
| Body                                           |
|                                                |
|                                                |
--------------------------------------------------

Using the "column" selection in the table settings, I'm able to "combine" fields into a single column (i.e. Field1 and Field4), but I'm stuck on how to display the Body under all the other fields in a cell that spans the whole table.

Suggestions?

I realize there are many ways to achieve my goal, in fact I've found this video that seems to be exactly what I'm looking for, but is this an overkill?

For precise control over views markup I usually take a departure from typical Drupal methods.   I set the view to be a table format,  then create my own view template.  The reason I use the table format is that it's really easy to work with and has a simple loop through each row of the results returned from the view.   From there, you can create your own markup using just the field values from each row.

Check this link:
https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7

Here's some shortcuts to get you started quickly. In your theme's directory, create a file called:
views-view-table--NAME-OF-YOUR-VIEW.tpl.php

Inside that file, start by pasting the source from this (click View source on the page):
https://api.drupal.org/api/views/theme!views-view-table.tpl.php/7

Then, clear your site's cache. Your view will now be using that new template and you can edit as required.


How to programmatically set a value to a node attribute I have a node named let's say "group" to which I added a field called "foo".

How would I programmatically give a value to this "foo" attribute?

I would like to do this when a user is joining a group. This joining process does not involve a saving of the current node, it just add data to a custom table i made. So Hooks don't apply here.

I am guessing i would have to:

1-load the node
2- add data to my attribute
3- resave the node

I am still trying to figure out how to do that, so if anyone has experience to share that'd be much appreciated..

Thanks

Actually very straight forward, here is how i have done it:

$group = node_load ( $nid );
$group-> foo = 'bar';
node_save ($group);

That's it.

Hope that' ll help anyone.


How can I create a patch using Git? I have found an issue on drupal.org that I would like to submit an solution for. How can I create a patch using git so that I can submit it as a possible fix?

Every Drupal.org project has a tab title 'Version control', click on it and it will take you to a page with Git instructions, including a section titled 'Creating a patch'.

See here for an example: http://drupal.org/project/wysiwyg_fields/git-instructions

Code below is copied from the D.o. instructions.

git checkout -b [description]-[issue-number]

Make your changes. Note the change in syntax for issue-related commit messages. See the Commit messages page for details.

git add -A
git commit -m "Issue #[issue number] by [comma-separated usernames]: [Short summary of the change]."

Roll the patch.

git status
git fetch origin
git rebase origin/6.x-1.x
git format-patch origin/6.x-1.x --stdout > [description]-[issue-number]-[comment-number].patch


RDBMS-independent way to get table primary key? Let's assume we have Drupal instance with second database connection. Tables in that second database are shared between many systems and thus was not created using Drupal's schema functionality. How do I get the name of the primary key, in a universal way that doesn't dependent on the RDBMS? Is there a way that will be equally good for all databases?

For MySQL I can use db_query and:

SHOW INDEX FROM {table} WHERE Key_name = "PRIMARY"

and for SQL-92 compatible ones:

SELECT pk.TABLE_NAME, c.COLUMN_NAME primary_key
  FROM information_schema.table_constraints pk
  JOIN information_schema.key_column_usage c
    ON c.table_name = pk.table_name
   AND c.constraint_name = pk.constraint_name
 WHERE constraint_type = 'primary key'

Thanks to T I's answer on stackoverflow.

What happens with Oracle or Apache Derby? I know I can find specific solutions, but I wonder if there is a Drupal way. I couldn't find one outside schema.

For non-Drupal tables

I don't think there is a cross-db drupal way to do this currently.

It would have to be added to the database schema class for each database type.
For example, see the mysql database schema class and look at something like addIndex.

Something similar could be done for showIndex().
If it is added for all the different database handlers, it would then be able to be safely used.

Then a database API function would have to be added for easy calling.

For example you would need a db_show_index() function in database.inc like db_add_index().

For Drupal defined tables

You can use drupal_get_schema() and get the schema for a table; then, get what you need from that. It will return a schema as defined in hook_schema().

You might also be interested in some of the other schema API functions.

The schema will only be what was defined in hook_schema though. It won't pick up anything that has been added or changed outside of that.


What function/method can I use to redirect users to a different page? In Drupal 7, I use the following code.

function my_goto($path) {
  drupal_goto($path, array(), 301);
}

What code should I use in Drupal 8?

This is the code that should be used in Drupal 8. See change Record for more info.

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_goto($path) {
  $response = new RedirectResponse($path);
  $response->send();
  return;
}


How to view and inspect a Commerce Billy invoice pdf template as HTML, before it's passed to the PDF generator? I'm trying to customise a Commerce Billy pdf invoice template. I've seen  Custom PDF template in Commerce Billy which tells me what I need to know about which files to edit to do this.

What I can't see how to do is, see the template as rendered by HTML before it's converted into a PDF. I need to do this to see what CSS classes are being applied where, and because testing changes to the HTML and CSS layout is much easier in HTML and CSS using inspect element tools than constantly re-generating PDFs.

How can I see a Commerce Billy PDF template as it is rendered as HTML before it is passed to the PDF generator? Right now, I'm just guessing about how the rendered PDF will look when I make changes, then repeatedly re-rendering PDFs, which is an inefficient way of working. I'd like to be able to try different CSS changes using developer tools in a browser, then apply those changes to a file and check they apply cleanly, then generate test PDFs.

If you check the page callback of PDF URL (i.e. "invoice-pdf/%commerce_order"), the HTML output of Invoice PDF is generated using commerce_billy_pdf_html($order) function. Same function is used by Print Invoice URL (i.e. "invoice-pdf/%commerce_order/print") to generate Printable output of Invoice. Since print page render HTML output you can inspect the output easily.

So for example, if your order number is 1 and your Invoice PDF URL is "invoice-pdf/1", then you can see the HTML Structure of PDF Output by going to "invoice-pdf/1/print" page.

Hope this helps.


How do I render a  tag? I am using the following code.

public function buildForm(array $form, FormStateInterface $form_state) {
 $appDir = take_control_app_dir();
 $extpath = take_control_fb_ext_client_path();

 $validationString = take_control_random_string(20);
 $fbpath = take_control_client_path(drupal_get_path('module', 'fb') . '/fb.html?extpath=' . $extpath);
 $form = [
   'example one' => [
     '#markup' => ''
   ],
   'take_control' => [
     '#markup' => '
iframe
',
   ],
 ];

 return $form;
}

The  tag is not rendered.

Is there any way to make it render?

Probably iframe is filtered in #markup. Use an inline_template instead:

  'example one' => [
    '#type' => 'inline_template',
    '#template' => '<iframe src="{{ url }}"></iframe>',
    '#context' => [
      'url' => 'www.google.com',
    ],
  ],


Modify form values before creating node I would like to use user-submitted data from one form field and add it to anther field, then submit the form to create a node that has my custom data. I'm having a hard time doing this. Any help is appreciated.

This is what the node api hooks are good for.

From the docs:

  The node passed validation and is about to be saved. Modules may use
  this to make changes to the node before it is saved to the database.

You don't specify D6 or D7

In D6

hook_nodeapi() $op == 'presave'

In D7

hook_node_presave()

You can modify values in your implementations of these hooks and they will be saved.

edit

If you need the NID you have to use hook_node_insert, but you will have to save to the DB directly.


How to allow anonymous users to view page? I would like to make a new page, before publishing it I'd like to send it to other people to review/approve the content without having to log in.

Is this possible?

I think it is hard to achieve.
However, using Access Unpublished module, maximum you can do is you can provide the specific URL to anonymous user(which includes all), so they can see the unpublished node with that specific URL(So, this way you are hide content from all other users, as they have not that URL), however they can not edit. For Editing option you have to set the separate user role, hence it ends up with login.


How to pass pagination value to drupal view programatically? I have a view with contextual filter and I render the view through program as below
$args=[$id];
$view = Views::getView('schedule');
$render_array = $view->buildRenderable('rest_export_1',$args);
$rendered = \Drupal::service('renderer')->renderRoot($render_array);

The view is paged with 5 results in each page. How do I pass the value to get results from the second page of the view?

I found setCurrentPage more suitable for my use case
$view = Views::getView('schedule');
$view->setCurrentPage($pageNum);


Make a div clickable using a render array What is the (best) way to make a div clickable using a render array in code?

I am creating a module that outputs a title in a rounded box, so I use the markup type and specify a class with #prefix and #suffix and apply some css on that class. This gets me a box, but I want to make the box clickable with a different url for each box. What would be a good way to do this?

I could put an onclick in the prefix or put  in the prefix and  in the suffix. But both are not very pretty.

I'm using Drupal 7 and would like not to use additional modules like views.

It sounds like you want to create an Accordion, I would look at Views Accordion because it sounds like what you want. I would try to stay away from custom javascript and html and attempt to theme views_accordion as you want it to look.


Shared subset of users in a multi-site instance Can I have a shared subset of users in a multi-site instance? In other words, I have the same list of administrators across all sites. Can these administrators be admins for all sites through a shared database rather than producing the same list of admins for each site?

I am aware that each site in a multi-site instance has its own database, which contains content and users specific to said site.
I am aware that content and users can be shared by configuring a shared database. However, I only want to share administrators among sites and keep content and other users with site-specific roles and permissions specific to its respective site.

As you mentioned yourself you can share users across multiple site but that are all users. So you need an external 'database' for your admin users that magically exists for all sites.

For this you could use https://www.drupal.org/project/ldap which could contain you administrators.

Normal users can login as normal aka without use the LDAP directory.

Note LDAP can work with MS Active Directory too.


Returning an array of all content types in a folder I exported all my configuration files to config/sync.
Now i'm trying to get all the content types from that folder into an array.

Its a bit like what this code does:

$manager = \Drupal::entityTypeManager();

$manager->getStorage('node_type')->loadMultiple();

But that returns all the Installed content types on my drupal.
I just want the ones from my sync folder because i'm making twig templates from them.

If you mean node types, every node type generates (amongst others) a file called node.type.NODE_TYPE_MACHINE_NAME.yml when exporting to config/sync


drupal_add_js() won't work with footer scope i 'm trying to add a file to end of body via template.php in mytheme_preprocess_page.
this is the line i have:

drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/file.js',array('type' => 'file','scope' => 'footer'));

why i can't see file.js in view source? -if i change footer scope to header file.js add to head tag -

doc says:

  Possible values are 'header' or 'footer'. If your theme implements
  different regions, you can also use these

i tried to add footer region to page.tpl.php but it doesn't work.

what do means footer scope?

Make sure you're printing $page_bottom in html.tpl.php.

In Drupal 6, it looked like this:

<?php print $closure; ?>

In Drupal 7, you now want all 3 of the $page_top, $page, and $page_bottom variables which correlate to the header, content, and footer scopes. Here's a sample (and simple) html.tpl.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<body>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>


Render updated node data during views render I have a view page which display node titles?

I'm also using workbench moderation module. During views rendering I check nodes and on certain condition I'm publishing the node from draft state using workbench_moderation_moderate($node, 'published');.

So is there any views hook Where i can use to set a revision of a node to publish and then views fetch the node's updated data?

I have tried hook_preprocess_views_view(&$vars) but it moderate the node to publish but then display the updated data on 2nd page referesh.

Assuming this is Drupal 7.

hook_preprocess_views_view() runs after the query is performed. You could try using hook_views_pre_view() or hook_views_query_alter(), both of which happen before the query runs, and save the nodes at that time. Of course the results of the view will not be available to you then, so you would have to select the nodes in some other way.

Also neither of these hooks work in themes, you would have to use a custom module.

https://api.drupal.org/api/views/views.api.php/group/views_hooks/7.x-3.x


product display image not showing drupal I have a question about Drupal Commerce (I'm using Drupal 7). I've added a number of products and created a multi-product display for them. I added a product image (it's common for all these products) to the product display. I also have a view of all product displays with images. But when I click and go to the product price and add to cart form, the product image does not show up. What am I missing??? (I did the same on the localhost before and everything worked fine, but probably I forgot to configure something)

I believe you need to add a relationship to your view between the node and the product display.

Hope this helps...


Views date filter by year - only one select list for the year I have a content type "news" and a views page to list the news. The views contains a exposed filter (category and year).

How can I realize the select list "Year" with the follwing options as exposed filter:

All
2016
2015
2014
2013
2012

When the user selects '2015' the list below is updatet (ajax) and only news entry form 2015 are listed.

How can I realize this?

Add filter criteria of Year field.
Now expose this field by selecting 'Expose this filter to visitors, to allow them to change it' option from field setting.
For Ajax behaviour, choose Use AJAX from advance view section.


How to use set() on a field within a field collection? I have a custom entity type, and I'm defining its form, which extends ContentEntityForm. During my save() function, I want the form to conditionally unset fields based on the values of other fields. (example: unset the value of a list select field if a certain checkbox is checked off)

I can't seem to accomplish this with $form_state->setValue() or $form_state->setValueForElement(), in both cases my code is seemingly ignored and the select widget is not unset upon finishing saving (although a var_dump of $form_state->getValues() at the end of the function shows that the values array is indeed being modified the way I want it to be).

However, the following code seems to work nicely for the title field (defined via baseFieldDefinitions(), is not inside a field collection):

$entity = $this->getEntity();
    $entity->set('title', array(array("value" => "aaaaaaaa")));
$entity->save();

My title for the newly saved entity does indeed show up as "aaaaaaaa"

Is it possible to target fields inside field collections in this way using this $entity object? Or is this the totally wrong approach?

It's not really clear to me why you don't change the values on the entity, but save() is too late.

The entity is built in buildEntity()/copyFormValuesToEntity(), if you want to change how it is build based on form_state values, you have to change them by overriding those methods and doing your changes first.


How to rearrange EVA fields in profile2? I augmented a profile2 profile with two Eva views.

Now, I would like to re-arrange them. For that, I would like to see those fields in the Manage display tab. I tried to explicitly create those missing fields, looking in vain for an Eva view type.

Anyone having met this problem ? Thanks.

I installed Profile2(7.x-1.3) and Entity Views Attachment(7.x-1.2) on Drupal 7.34.

When you create two eva fields in your respective views and set "Entity type" as Profile and Bundle as "Your profile name" as shown in the following figures: Entity Type - Profile, Bundle - Custom. "Custom" is the name of the profile I created.

After saving the views with their respective eva fields , the fields for display automatically appear in the "Manage Display" tab of your profile as shown below(note the fields with prefix EVA) :

Here you can reorder EVA fields with ease.

And this is how the views are rendered in the user's profile page :

I included above screenshots, in case you have missed some settings. If you still can't see the required fields, then create a new issue here for EVA or here for Profile2. Hope I could be of help. Please excuse me for my late reply as I am new to Drupal.


How to loop over OG group members from comment I'm trying to set up a Rule to send a privatemsg to all group members when someone posts a comment on the group node itself.

One approach I've tried using existing options provided by the OG module:

**Events**
After saving a new comment

**Conditions**
Entity is a group
  Parameter: Entity: [comment:node]

**Actions**
Get group members from group audience
  Parameter: Group content: [comment:node]
  Provides variables: List of group members (group_members)
Loop
  Parameter: List: [group_members]
  List item: Current member (member)
    **Loop actions**

This method fails to find any members. I'm guessing this is because the "Get group members from group audience" function expects its parameter to be a node posted on the group rather than the node representing the group itself.

Another method I've tried is to define a new Rules action in a custom module:

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_get_og_members' => array(
            'label' => t( 'Get OG members from group node' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'nid' => array(
                    'label' => t( 'Group node NID' ),
                    'type' => 'integer',
                ),
            ),
            'provides' => array(
                'group_members' => array(
                    'label' => 'List of group members',
                    'type' => 'list',
                ),
            ),
        ),
    );
}

/**
 *
 */
function mymodule_get_og_members( $nid )
{
    $node = node_load( $nid );
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    // user_load_multiple indexes by UID which might be confusing the Rules loop. Reindex!
    $members = array_values( $members );
    dpm( $members ); // This works!
    return $members;
}

In Rules UI I've added this custom action followed by a loop. The loop suggests the provided members-list variable to iterate over and everything looks fine, yet when the Rule is run I get errors like this:

Unable to get variable group_members, it is not defined.

Unable to evaluate loop.

I've asked an overlapping question here: https://www.drupal.org/node/905632#comment-10893894

Similar posts that I've read:

How to loop over a list of Organic Group users using Rules

I can't access a provided variable in rule action

https://drupal.stackexchange.com/a/170922/58279

I found a work-around by implementing all of the desired functions in the custom action provided by my custom module:

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_comment_notify_og_members' => array(
            'label' => t( 'Notify OG members of comment' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'comment' => array(
                    'label' => t( 'Comment entity' ),
                    'type'  => 'entity',
                ),
            ),
        ),
    );
}

/**
 * Notify relevant OG group members of a new group comment
 *
 * @param   object (entity metadata wrapper)    $comment
 */
function mymodule_comment_notify_og_members( $comment )
{
    //~ dpm( $comment->getPropertyInfo() );

    // Get the nodes we need from the comment entity metadata wrapper
    $node = $comment->node->value();
    $author = $comment->author->value();

    // Get all active group members
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    foreach( $members as $member )
    {
        if( $member->uid !== $author->uid )
        {
            // We're not notifying the author of his own comment

            $subject = format_username( $author ) . ' commented on ' . check_plain( $node->title );
            $body = '';
            $body .= 'Hi ' . format_username( $member ) . ',';
            $body .= '' . l( format_username( $author ), 'user/' . $author->uid ) . ' just commented on the ' . l( $node->title, 'node/' . $node->nid ) . ' group.';
            $body .= '' . l( 'View the comment', 'node/' . $node->nid, array( 'fragment' => 'comment-' . $comment->cid->value() ) ) ;

            privatemsg_new_thread( array( $member ), $subject, $body, array( 'author' => $author ) );
        }
    }
}


jquery is not adding a class On my Drupal site, I have a simple jquery file attached to the theme. This file is added in preprocess_node. The whole content of the file is as follows:

(function ($) {
  console.log("hello world");
  $('li').addClass('hello');
  $('div').addClass('hi');
})(jQuery);

Here is what happens when I run any Drupal page:

no javascript errors
the console shows "hello world "
in Chrome debug, div's do not have class "hi" and li's do not have class "hello"

I ran the same (without wrapper function) on jsfiddle for some basic html and the result was as expected, classes were added to div's and li's and can be seen in Chrome debug. So why is it not working in Drupal?

You need to utilize Drupal's JavaScript Behaviors functionality in order to ensure that your javascript is run after the DOM has loaded and that it will not conflict with other javascript in Drupal.

Try changing your JS file's code to this:

(function ($) {

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    console.log("hello world");
    $('li').addClass('hello');
    $('div').addClass('hi');
  }
};

}(jQuery));


Drupal 7 menu translation and url aliases I am building a multilingual site with Drupal7 and enabled i18n and menu translation module. I can translate menu items and it is working fine with only one little problem:

If the menu item points to an internal page (i.e: /user) everything is OK, however if the menu item points to a node, the title is translated but I can only specify one path.

I.e.: I have an English page "About us" which is node/1 and have the URL alias /about-us

I have the Hungarian translation of this node "Manunkról" under node/18 and URL alias /magunkrol

I see the correct titles in each language and I get the correct language versions when I click them. BUT on the English page, the link has /about-us in the HREF, but on the Hungarian page it has node/1 (the node path of the English version). The link gets redirected but this is not an ideal solution in regards of SEO. Is there a way to display the URL alias in the HREF for each language?

Setting up a menu per language (as stated in other answer) seems to me more like going around the problem rather than fixing it. I created an issue for it at https://drupal.org/node/2051041 and attached a patch.

Using that patch you don't need to the unnecessary hassle of setting up tons of menu items per language just because the href doesn't render as expected.


Drupal behind a SSL offloading reverse proxy -- is this config correct? We are transitioning an existing drupal installation to run as a SSL-only site behind a SSL offloading proxy. Drupal itself has no SSL and is running on port 80 on apache.

We've got what we think is a pretty successful configuration:

On the nginx end of the world it looks like:

server {
    listen              80;
    server_name         staging.example.com;
    return              301 https://staging.example.com$request_uri;
}

server {
    listen                  443 ssl;
    server_name             staging.example.com;
    ssl_certificate         $chained_cert_path
    ssl_certificate_key     $private_key_path;

    location / {
        proxy_pass          http://$backend_ip;
        proxy_set_header    Host $host;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_set_header    X-Forwarded-By $server_addr:$server_port;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_redirect      http:// https://;
    }
}

And in the drupal site's config we are running:

// reverse proxy settings and such
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array($proxy_ip);
$base_url = 'https://staging.example.com';

As I said this seems to be passing all tests, but my spidey sense is saying this was too easy and there is a fugly problem waiting somewhere in some part of drupal we don't understand well enough -- manually paving $base_url just isn't sitting right with me. Are there landmines here?

You don't have to indicate $base_url = 'https://staging.example.com'; , you can have something like this:

server {
    listen              80;
    server_name         staging.example.com;
    return              301 https://$host$request_uri;
}

server {
    listen                  443 ssl;
    server_name             staging.example.com;
    ssl_certificate         $chained_cert_path
    ssl_certificate_key     $private_key_path;

    location / {
        proxy_pass          http://$backend_ip;
        proxy_set_header    Host $host;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_set_header    X-Real-IP $remote_addr;
    }
}

and in your Drupal settings:

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array($proxy_ip);

// from http://devblog.more-onion.com/using-drupal-behind-reverse-proxy
if (
  isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' &&
  !empty($conf['reverse_proxy']) &&
  in_array($_SERVER['REMOTE_ADDR'], $conf['reverse_proxy_addresses'])
) {
  $_SERVER['HTTPS'] = 'on';
  // This is hardcoded because there is no header specifying the original port.
  $_SERVER['SERVER_PORT'] = 443;
}


CDN module enabling "Far Future expiration" breaks whole site theme drupal 7 CDN module
Version:    7.x-2.6
component -- Origin Pull mode — Far Future expiration

I am using CDN module on drupal 7.22. We are using custom theme where adaptive theme is as base theme for all other users and "seven" theme for admin.
As soon as i check the "Far Future expiration" and save, whole site theme is breaking except admin theme.

And without checking "Far Future expiration" Iam facing http://drupal.org/node/1993600 issue.

These modules might help you out (quotes added here are from their project pages):

Advanced CSS/JS Aggregation:

  On demand generation of CSS/JS Aggregates. If the file doesn't exist it will be generated on demand.
  Stampede protection for CSS and JS aggregation. Uses locking so multiple requests for the same thing will result in only one thread doing the work.
  Fully cached CSS/JS assets allow for zero file I/O if the Aggregated file already exists. Results in better page generation performance.
  Can add JS to any region of the theme & have it work and be aggregated.
  Combine CSS files by using media queries.
  Prevent more than 4095 CSS selectors in an aggregated CSS file (IE 6-9 limitation).
  ...

Imageinfo Cache:

  ... will generate image styles right after an image is uploaded and also on entity save. This will help with front end performance as the needed image style will already have been generated; thus the end user doesn't have to wait for the image to be generated. This can also mitigate some issues with image style generation if your CDN is configured incorrectly as the images will be generated without the request going through the CDN.


Modules for media management I am looking at the ability to management off and online video content.
I need to be able to add media using text filters and to search for media within the cms.
What is a good module for a modal style background when playing video?
I need to arrange videos into playlists by artists and create gallerys.

On my research I have come up with the following:

Media
Searching Media
http://drupal.org/project/apachesolr_media
http://drupal.org/project/apachesolr
http://drupal.org/project/apachesolr_file

http://drupal.org/project/media (for managing media)
http://drupal.org/project/media_gallery (for managing galleries of images and videos) http://drupal.org/project/mediaelement (for local files) http://drupal.org/project/multiform

More info:http://www.slideshare.net/G_N/drupal-7-media-modules

If you can give me any more information that would be great.

You also needs views and taxonomy to build the lists.
I'll add also shadowbox or colorbox to play videos in a modalframe.


Using views in a clever way? I would love some help to think here, I need to create one or several views (I'm hoping one)

I have a site that will present different groups and they will each have their own page/view with:
- a slideshow
- some nodes
- a contact form
- a block with Facebook posts from their Facebook pages
- some social links (like google+, Facebook like etc.)

I will start with a few but I want it to be easy to add more in the future, hopefully without creating a new view for each group. Note that this is not a social site, the content will be added by one person and the page will simply be a presentation of these groups in a standardized way.

I'm thinking views with EVA and maybe I could use taxonomy to "group" them? I don't want to put a specific term if I don't have to as that would exclude any new groups and also would force me to make a separate view for each group. How would I go about to set it up in such a way that it recognizes what to show in one view?

Thankful for any insight and suggestion!

Drupal 7
(Multilingual site)

I will try to explain better.

Let's say I have several products that I want to present in a standardized way: a slideshow, text with images, a contact form, content from a specific Facebook page, content from a specific twitter feed etc.
This will be presented in a view.
I have several products and I want to easily be able to add more, preferably without having to create a new view each time.

How do I go about it? If I use taxonomy to mark what belongs together I will still have to create a new view every time I add a new product. If I use content types I have to create a new content type for each product (which would be even more work).

What I see here is a typical Panels situation, with Taxonomy.

Create a vocabulary "groups",
Create two content types : slideshow item , nodes (with term relationship field to the vocabulary "groups", of course)
Three fields to the terms themselves (taxonomy terms have "cck-like fields" in core since Drupal7) : email adress, Facebook widget, etc.
Create views for each use: the slideshow, the nodes...
Enable the "taxonomy term page" panel, and insert in it your views showing your content associated to that term, and the fields of your term (Panels has the out-of-the-box interface for that) : contact form, FB block, and so on.

That's the simpliest I see :)


Site name is not changing in When I change the site name in admin/config/system/site-information it has no effect on the site name between the title tags. It always shows "Drupal" as the site name.

I'm using the Basic theme with the same implementation as in the core themes:

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

I already checked the translations and the site name is also not hard coded in settings.php

I had same problem, and I solved it after reading this article:

Source : https://www.drupal.org/node/2844755

you can do it step by step :

Change the default language to English.
Delete the other language.
Clear the cache.
Change the site name.
Add the other language and set it back to default.

It works after adding new language again


All links point to the old site after migration I migrated a Drupal 7 site from 1 server to another. Let's call the old site URL http://oldsite.com and the new site url http://newsite.com. I have copied over the code base and the database. The site displays correctly on http://newsite.com, however all the links point to http://oldsite.com. The only way to access the links are to type the URL in the browser (e.g. http://newsite.com/admin).

I have read lot of forums and done the following:

Set the $base_url in settings.php
Cleared cache in Config > Development > Performance
Cleared the cache table in DB
Ran update.php
Disabled clean urls

Nothing has worked. Someone suggested changing an entry in system table. Don't know which entry they were talking about.

Can anyone suggest the correct steps and perhaps an explanation of why I keep getting the redirects?
I have also referred to Moving a site, links/admin do not work.

For sites being localized, you have to edit every language:
/admin/config/regional/language
It's because there's a "domain" field that is left with the wrong URL in the database.
That solved my case of moving from subdomain beta.mysite.com to www.mysite.com