How to add css class to these form fields? I wan to be able to add certain css class to all the text fields in my content edit forms. here is a picture of what i can see using Devel:

Those arrays under the "Und" are for the fields I want to add the class. I have tried to do this with the following:

function iclub_form_article_node_form_alter (&$form, &$form_state) {
dpm($form);
$form['field_body']['und']['0']['#attributes']['class'][] ='addRecactor';

foreach ($form['field_paragraph']['und'] as $i) {
    if (is_numeric($i)) {
        echo $i .'</br>';
        $form['field_paragraph']['und'][$i]['field_myparagraph']['und']['0']['#attributes']['class'][] ='addRecactor';
        foreach ($form['field_paragraph']['und'][$i]['field_myparagraph']['und'] as $y) {
            if (is_numeric($y)){
                $form['field_paragraph']['und'][$i]['field_myparagraph']['und'][$y]['#attributes']['class'][] ='addRecactor';
            }
        }
    }
}

but this does not work for all the fields and I think it is not the solution as it is not robust.

How may I be able to add the class to these fields?

You should write a statement that first check the form element type then add class attrubutes to it,
something like
//in form_alter

foreach($form as $form_elem){
if($form-elem['#type']=='textfield'){
    $form[$form_elem]['#attributes']['class'][] = 'myclass';
   }
}

(this is not the exact solution,I just want give you idea)

another way is using hook_preprocess_field

and the final and easy way is using js to add class, because drupal set default class for his textfields,you just need one line jquery code to add you

   $('.form-text').addClass('myclass');

if you don't want this js not load in all page, I suggest you add your js with drupal_add_js conditionally in hook_form_alter, it means that

    //in hook_form_alter
     $des_forms=array('node_add_page','node_add_prodcut');
    if(in_array($from_id,$des_forms)){
    drupal_add_js('your js'); //you also add it inline,but I suggest you put it in js and add it as file
}

again I tell you because I have no time in this moment I just suggest you some solution idea, I hope could help you


Menu Block - How to make a new menu automatically available? How to automatically set a newly created menu as available so that it can immediately be used when configured for "the menu selected by the page"?

I've tried setting the 'menu_block_menu_order' variable through code, upon a new menu creation, but haven't figured it out.

What's the best way to automatically set a new menu , or all menus, as available?

I'm not very familiar with the Menu Block module, but this seems to be the proper way of setting the menu_block_menu_order variable when a new menu is created:

function mymodule_menu_insert($menu) {
  $menus = variable_get('menu_block_menu_order', array('main-menu' => '', 'user-menu' => ''));
  $menus[$menu['menu_name']] = '';
  variable_set('menu_block_menu_order', $menus);
}


File added programaticaly are not deleted when node is deleted I'm creating a node programmatically with one image field. Nodes are Created without any problem.

But if I delete the node the file is marked as "used in 0 place" but never deleted (I run the cron).

If I edit the node and delete the file of the image field, the file is still marked as "used in 1 place".

I want the file be deleted instantaneously like if I create the node using the node form.

/**
 * Create a new book from google data
 *
 * @param array $booksData
 * @return \Drupal\Core\Entity\EntityInterface\static
 * @throws Exception
 */
function book_market_create_book_node(Google_Service_Books_Volumes $booksData) {

  // Google_Service_Books_Volumes object automatically iterate, this will get data from the first book
  $bookData = $booksData[0];

  if (empty($bookData['modelData']['volumeInfo']['title'])) {
    throw new Exception('book data are incomplete');
  }

  $bookNode = Node::create([
    'type' => 'book',
    'moderation_state' => 'published',
    'title' => $bookData['modelData']['volumeInfo']['title'],
    'body' => $bookData['modelData']['volumeInfo']['description']
  ]);

  $imageLink = $bookData['modelData']['volumeInfo']['imageLinks']['smallThumbnail'];

  if (isset($imageLink)) {
    $data = file_get_contents($imageLink);

    $transliterator = new Drupal\Core\Transliteration\PHPTransliteration(NULL, \Drupal::moduleHandler());
    $fileName = $bookData['modelData']['volumeInfo']['title'];
    $fileName = str_replace(' ', '_', $fileName);
    $fileName = $transliterator->transliterate($fileName, 'fr', '_') . '.jpeg';

    $field_cover_settings = $bookNode->field_cover->getDataDefinition()
      ->getSettings();
    $destination = $field_cover_settings['uri_scheme'] . '://' . $field_cover_settings['file_directory'] . '/' . $fileName;
    $destination = \Drupal::token()->replace($destination);

    $file = file_save_data($data, $destination, FILE_EXISTS_RENAME);

    $bookNode->set('field_cover', [
      'target_id' => $file->id(),
    ]);
  }

  $bookNode->enforceIsNew();
  $bookNode->save();

  return $bookNode;
}

I think that file will be delete when you run cron. File can't delete because temporary file have time life. You can see code in file_cron.
function file_cron() {
  $age = \Drupal::config('system.file')->get('temporary_maximum_age');
  $file_storage = \Drupal::entityManager()->getStorage('file');

  // Only delete temporary files if older than $age. Note that automatic cleanup
  // is disabled if $age set to 0.
  if ($age) {
    $fids = Drupal::entityQuery('file')
      ->condition('status', FILE_STATUS_PERMANENT, '<>')
      ->condition('changed', REQUEST_TIME - $age, '<')
      ->range(0, 100)
      ->execute();
    $files = $file_storage->loadMultiple($fids);
    foreach ($files as $file) {
      $references = \Drupal::service('file.usage')->listUsage($file);
      if (empty($references)) {
        if (file_exists($file->getFileUri())) {
          $file->delete();
        }
        else {
          \Drupal::logger('file system')->error('Could not delete temporary file "%path" during garbage collection', array('%path' => $file->getFileUri()));
        }
      }
      else {
        \Drupal::logger('file system')->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', array('%path' => $file->getFileUri(), '%modules' => implode(', ', array_keys($references))));
      }
    }
  }
}

You can see line if($age) and line ->condition('changed', REQUEST_TIME - $age, '<'). It's logic when run cron delete file.
And you can go admin/config/media/file-system to see time life of temporary file. Default are 6 hours.


Do I need to give a complete copy of my site's source code to a themer? I want to get my sites themed from expert themers ( for example at Freelancer etc). I need node, views etc be themed along with site look and feel.

I've done little themeing till now and I tested with my site source.

What I want to ask is it necessary to give complete site source code to the themer which i don't want to do? What minimum they'd need?

The minimum they need depends on what you are having them theme.

Basically they have to have everything they need to do their job.

If you exclude something that affects any visual part of the site it could impact their ability to do their job.

If they are making the whole theme for your site I feel you really should give them everything, because if you don't it is possible that some things will not get themed.

If I was the one implementing the theme and I was not given the whole code I would definitely specify that any problems with the theme that relate to not having all the parts are not covered by warranty.

In the end though it depends on your specific site and what you are having themed.
Maybe on your site there are pieces of functionality/code that could be excluded without impacting the parts of the site being themed.

If your worry is them seeing your code, because there are specific things regarding your code that are very sensitive then you either need to find a themer you can trust, and have them sign legal NDA agreements or whatever else is required.

If you are worried about them doing bad things to your code, use version control.
Have everything in version control before you give it to them so that when you get their work back, you can see exactly what has been changed, so if they are changing things they shouldn't be you can more easily know about it.

You could also try to get someone to review their work (or you review it yourself if you have the knowledge).

Another thing you could do is host the site somewhere on the internet where the themer can work on it, but only give them access to the theme directory. So they are allowed to FTP to the theme directory only, and not have access to the rest of the site, but they still get to use the fully functioning site.

The harder you make things for them though, the more chance you have of getting an inferior result or having the work take longer than expected.


Validating node creation / edit form I'm using form_alter to play with the node form for a specific content type. This content type has many different fields and I'm also using Field Collection module to organize all these fields & logic, if that makes any difference.

Apparently, there are some incompatibilities between the Field Collection & Field Dependencies modules so I thought I might be able to build a similar field dependency functionality with my own module.

I've created a validation function for the form. My problem is that I'm trying to access $form_state values that users insert in the form in order to validate these values but I think I'm doing something totally wrong here:

function _mymodule_my_validation_function($form, &$form_state){
    $short_field_name = $form_state['values']['long_field_name'];
    if (empty($short_field_name) || $$short_field_name == '') {
        form_set_error('error','That field cannot be empty!');
    }
}

Unfortunately this validation script doesn't work. To be more exact, I

dpm($form_state);

in my form_alter and $form_state doesn't even contain 'values' (shouldn't it be present but empty?).

Is there a different best practice for validation node form fields instead of dealing with the $form_state['values'] array?

Also, I need to be able to see the values submitted by users each time the node form is submitted. Currently, I dpm($form) in my form_alter function and everything is returned on the node/%/edit page as expected. But how can I catch submitted values on the node/% page after submitting the node form??

Update:
When I call dpm($form_state) within my validation function I get what I need if the form doesn't validate (as we still are on the same node edit page). But how can I receive the (new/changed) values that users entered in the form fields in case the form is submitted successfully and user is directed to content list page?

For custom forms
The preferred way is to call hook_form_validate for hook_form but you can use $form['#validate'][] = 'custom_validate_function' to call validate function

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

$form = array();

// write your custom fields here..........
return $form;

}

function hook_form_validate($form, &$form_state) {
 $short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');
    }

}

For built in forms by creating content type

function hook_form_alter($form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form_state['#validate'][] = 'form_1_validate';
    $form_state['#submit'][] = 'form_1_submit';
  }
}

function form_1_validate($form, &$form_state) {

$short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');

}
}

function form_1_submit($form, &$form_state) {

//To get the user selected or user submitted values you should look into code below
$field_name_values = $form_state['values']['field_name'];

}


Why are there two default image options in an image field When you create a field of type image in Drupal 7, there are two default image fields.

One is in settings and the other is in field settings. There is a message with each of those two settings, but I still don't understand how they are different. In each case, they upload to the sites/default/files/default_images folder.

What is the difference between the two settings fields?

One is the default image information for that field as a global entity, while the other is specific to that instance of the field. Fields can be re-used across different content types, so the global default would apply to every content type that used that field, unless those content types override that behaviour with their own specific default.


An alternative for pathauto and token I'm considering alternatives to pathauto module for automatic URL alias generation.

The reasons I want to stop using it are the following:

Most of the aliases are [node-type]/[node-title] so I do not need all other functionality.
Token goes wild and takes too much resources on pages where it needs to display the available tokens. I have 16 content types and quite a lot of fields and certain pages take considerably more time to load due to the large list of tokens.
I do not need token module for anything else
I would have 2 big modules less - pathauto and tokens, which would have impact on performance

I checked some similar discussions on drupal.org, but none of them offered really an alternative.

I'm now looking into optimizing the fields as each content type has its own set of fields (meaning they are not shared); this was done because of the performance but ironically I ended up with performance issues on the other end.

Setup: D7 with all latest modules.

Did you have similar problems? How did you solve them? Any words of wisdom?

Thanks!

[UPDATE]

For anyone looking for something similar, here is an article which explains how to handle that through a custom module.

The main performance problem with tokens is the token UI/token browser. You can disable that by overriding theme_token_tree() and returning an empty string. What I once did on a site is replace it it with a link that was able load the browser using ajax, but even that didn't help anymore on a site with ~300 fields and lots of references.

Pathautho/Token don't depend on entity.module?


Hook for csv export view - flag exported items I am using Views data export to export view with exposed filter, is there any hook or another way to run an action over these filtered items?

My goal: set "flag" (boolean field) for these exported items so I will know, they have been exported.

Views Data Export isn't transactional and so if you're looking for something, you'd likely need to wrap up Views Data export with your own code that loops over the results and sets the flag then.


Handle formatting of longtext value for entity wrapper So I have a working setup where some code pulls in the latest Wikipedia extract of a page.  I then use Entities to handle a node creation, adding the contents of the extract to the longtext value of the generic body field:

$body = array();
$url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles='.urlencode($item['name']);
$result = @file_get_contents($url);
if ($result){
  // Oh yes!
  $decoded = json_decode($result, true);
  foreach ($decoded['query']['pages'] as $page){
    if (array_key_exists('extract', $page)){
      $body[] = t($page['extract']);
    }
  }
} else {
  // Boo, nothing found.
}

// Doesn't exist, we have to make it first. (Using Entities)
$node = entity_create('node', array('type' => 'article', 'uid' => 1));
$entity = entity_metadata_wrapper('node', $node); // $node->nid is probably better here
$entity->title->set($item['name']);
if ($body){
  $entity->body->set(array('value' => $body[0]));
}
$entity->save();
// Woo got our nid!
$nid = $entity->getIdentifier();

The problem is, I can't seem to control the output of the body at all.  It renders surrounded with paragraph tags, using html line breaks for each paragraph.  I want to surround each paragraph with paragraph tags.  I've tried using preg_match to catch newlines (\r\n) but anything I replace it with just gets rendered exactly - making paragraph tags show up in the extract text when viewing the node.

What's the best method of doing some formatting to the extract?

You just need to specify a format for your text value:

$entity->body->set(array('value' => $body[0], 'format' => 'full_html'));


Advice on CSV import with taxonomy for data sanitaztion i have a situation where users will be uploading csv files of the same format/columns but
the data is not consistent...for example in the "state" field, one office might use "NC" and another might use "North Carolina". another might have "N. Carolina". misspellings are common too in some fields.

how do i let them upload this data but sanitize it at the same time so that i know that "NC" == "North Carolina" == "N. Carolina"...etc?

my thought is to use a vocabulary for each column and force the user to map any data that doesn't match up before the csv is processed and nodes are created.

so i'm thinking the process would be as follows:

user uploads csv
user gets a form/table showing the data they uploaded along with a vocab drop down for each cell that needs to match up to a term. (each cell in the state column would have a drop down)
user manually maps any data that did not match up to a term.
user hits "process csv" and nodes are created.

so if i uploaded a csv that had "Nrth Car." in the state column...i would have to select "North Carolina" from the drop down before the csv can be processed.

*would also be cool if i could store these variations as synonyms so that next time they upload a csv they won't have to map the same variations again. ("Nrth Car." would automatically be mapped to "North Carolina" the second time around.)

thoughts?

Store the list of states as a taxonomy and add a text field to the taxonomy called aliases. This would be an text field with unlimited values.

Now when checking if a term exists you can use:

function taxonomy_load_term_check_aliases($name, $vid) {

    // load term by name (not using taxonomy_get_term_by_name() as I want to pass in vid, not machine name)
    $tid = db_query('SELECT tid FROM taxonomy_term_data WHERE vid = :vid AND `name` = :name', array(':name'=>$name, ':vid'=>$vid))->fetchField();

    // no match - see if an alias exists
    if(!$tid) {
        $bundle = db_query('SELECT machine_name FROM taxonomy_vocabulary WHERE vid=:vid', array(':vid'=>$vid))->fetchField();
        $tid = db_query('SELECT entity_id FROM field_data_field_aliases WHERE field_aliases_value = :name AND bundle=:bundle',
            array(':name' => $name, ':bundle'=>$bundle))->fetchField();
    }

    $term = taxonomy_term_load($tid);

    return $term;
}

If you can't find a match then add an additional alias. As you list of aliases builds up it will become more and more automated.


user_roles with features When I use user_roles() when there are roles added by features, the feature roles are not returned. How can I get a list of all roles on my site included those defined in features?

Is the Role listed on admin/user/roles?  If not, your Feature might not be defining a Role, or the Feature might be overridden.

Roles defined by Features do actually show up in user_roles().  I created a simple Feature defining a single role, then enabled it:

% drush php-eval "print_r(user_roles())"
Array
(
    [1] => anonymous user
    [2] => authenticated user
)

% drush pm-enable yayfeature
The following extensions will be enabled: yayfeature
Do you really want to continue? (y/n): y
yayfeature was enabled successfully.                                                                                [ok]

% drush features-revert yayfeature
Do you really want to revert user_role? (y/n): y
Reverted user_role.                                                                                [ok]

% drush php-eval "print_r(user_roles())"
Array
(
    [1] => anonymous user
    [2] => authenticated user
    [5] => yay
)


How do I programmatically check if a context is active? How do I see which contexts are active on the page?

I can't find any ContextManager object in hook_preprocess_page().

I figured it out: The Context module defines a service for getting the ContextManager object, which has getActiveContexts(). You can obtain it using the following code.

$activeContexts = \Drupal::service('context.manager')->getActiveContexts();

I need to read Service Container.


Replace a word in a custom block or paragraph with a token related to a content type field value I have a content type with a mix of paragraphs and custom blocks.
Most custom blocks (content) are the same on all pages except for one word that needs to be replaced by an other one.
I would like to replace that word with an other one related to a field on the content type page.
I thought it could be done with Token Filter (https://www.drupal.org/project/token_filter) but that is not an option.
EDIT 2: explain with example
I have a content type 'CMS page'. It has a field 'field_brand_name'. This field is used to replace a string in paragraphs or custom blocks that exists on the content type page.
If I create a page for Magento and a page for Drupal and a page for WordPress. The only that needs to be replaced is the brand name in the text (Magento, Drupal or WordPress) on all custom blocks or paragraphs that I have used on that specific CMS page ... That could be resolved by a Token if there was a context for it, but there is no ... so the token is not replaced. Is that clear enough?

First create your own module.
In mymodule_tokens.module insert below:
<?php

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */

function mymodule_tokens_token_info(): array
{
    $type = array(
        'name' => t('My Module Tokens'),
        'description' => t('Custom tokens to solve use-case problems for the website.'),
    );
    $node['brand'] = array(
        'name' => t("Brand name from node"),
        'description' => t("Brand name to replace in text, custom blocks, paragraphs, ..."),
    );
    return array(
        'types' => array(
            'mymodule_tokens' => $type,
        ),
        'tokens' => array(
            'mymodule_tokens' => $node,
        ),
    );
}

/**
 * Implements hook_tokens().
 */

function mymodule_tokens_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata): array
{
    $replacements = [];

    if ($type == 'mymodule_tokens') {
        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'brand':
                    $node = \Drupal::routeMatch()->getParameter('node');
                    if ($node instanceof \Drupal\node\NodeInterface) {
                        if ($node->hasField('field_brand') && !$node->get('field_brand')->isEmpty()) {
                            $brand_name = $node->field_brand->value;
                            $replacements[$original] = $brand_name;
                        } else {
                            $replacements[$original] = null;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    return $replacements;
}


Restrict language content for a given role I have a multilingual site (spanish/english). I created 1 role: translator.

I need the anonymous users to ONLY see the contents in english language and the translator users to see both.

How can I accomplish this?

A way to achieve it can be this.  Note I am assuming you are using the standard node-based translations, and not entity-based translations.

Suppose the content is a node-type one and the content-type is called Page_en_es.  Give permissions at /admin/people/permissions:

View own unpublished content, Page_en_es: Edit any content etc to translator users
View published content to anonymous users.

Then, whenever a translator edits or creates the Spanish content, s/he will set it (=node) to be not published.  And the Spanish version won't be seen by anonymous users.


File Upload in Selected Location I have file field in a content type to upload files. I have also created a drop down which has different values like folder 1, folder 2, folder 3 and so on.

I want file field to upload my files on location based on that drop down value.

for example if I have selected folder 2 in the drop down then the files should upload in folder 2

please provide some help on this issue.

Try using File Path Module

  Adds the ability to use node tokens in destination paths and
  filenames.


How can I set up RNG Conflict with a multi day event I'm loving the RNG module and the conflict functionality, but I'm a little confused regarding how to set up my seminars and events.

My current use case is I have a simple four-day event with one optional seminar every day.

Initially, I created one registration type "spring seminars", and one event type "Registration". Then I created the four seminars as content, and couldn't figure out how to allow people to register for more than one, as conflict made the other three days unavailable as soon as a registrant registered for one day.

Then I went back and created four different event types, "spring seminar day 1, spring seminar day 2, etc." Then I recreated the four seminars, one per event type, and it allows registrants to register separately. This allowed registrants to register for more than one, but doesn't allow me to keep all sessions under the same seminar [event type] and doesn't work well with calendar if I decide to have more than one seminar per event per day [when I would like to keep them all under the same event type]. It also seems like I was missing a simple "no conflict" option when all four seminars were under the same event type.

Here's the basic layout of the two seminar [registration type?] & session [event?] types the Kobe Education Commission puts on;

3-5 day seminar > 1 timeslot per day > 1 session per timeslot
Registrants can register for any of the events as there is no conflict with either timing or with having specific topics for different groups of registrants. I'd like these to be the same registration type "spring seminar" if possible.
1 day seminar > 5 timeslots per day > 3-5 sessions per timeslot
Registrants can only register for one seminar per timeslot, and there may be specific sessions that a group of registrants isn't eligible for.

This is my interpretation of your multi day seminars:

I think for your first scenario where there is no conflicting sessions, there is no need to enable RNG Conflict.

For the second scenario where you have multiple (3-5) sessions potentially running at the same time. You should have some field on the event nodes that uniquely identify each. You could do this by:

Adding a integer field representing the timeslot number (timeslot 1, 2, 3 etc). Or,
Add a date field on each event with the start datetime for each session. Then set RNG Conflict to use one of these options.

You may also want to add a field representing the overarching seminar. Resulting in something along the lines of:

Your site only needs a single event type (a node type, etc), and a single registration type no matter how many seminars you have. If you are customising your registration form then you may want to add more registration types, but this would be unusual.


Automatically Subscribing Nodes to Organic Groups based on Taxonomy Term Use Case:
We want to automatically add nodes to groups based on existing taxonomy terms. So when we create a new group it is populated with existing site content such as case studies and white papers that may be relevant.

I was hoping the rules module would allow this but it is not immediately obvious as I was thinking you could set up a series of rules to run that have a logic of if node has taxonomy term x then place in Organic Group Y. This would be nice as removes error and also means editors do not have to add taxonomy terms and then also decide which groups to post into.

Custom module will help. I would use node_insert() and node_update() although we have used submit handlers for this in the past also.

Code to add a node to a group is:

$form['group_audience'][LANGUAGE_NONE]['#default_value'] = $group_audience;

I have read that og_group() can set a node type entity as group content, but the api looked like it changed to us.

The taxonomy_access module might provide another way of thinking of this that suits your needs.


Link to download pdf from webform email I have created a webform, after the submession the customer is sent the registration confirmation e-mail.  How do I include in this email a link to download a pdf ?

If we are talking about a webform, then under the "webform" tab on the webform node there will be an "email" section. You can add it directly to the email text. The link will be /node/[nid]/webform/emails .

The "registration confirmation" part is a bit ambiguous. There is a user registration confirmation also, but I'm guessing that you are referring to the webform being a type of event registration form? In the case of user registration, there is a section under /admin/config/people/accounts where you can modify the emails.


Is there a modules "wish list" anywhere? I'm new to Drupal, and right now my job consists mainly of site-building. But I'm a PHP developer, and I'd like to get into module development. The problem is, anything I could think of to do has most likely already been done! Is there any kind of wish list maintained somewhere (on drupal.org) of modules that people wish would be written?

Check out the Contributed Module Ideas group on groups.drupal.org.

The Google Summer of Code group can also be a good source of inspiration. Some of the ideas may not be big enough to sustain a student for the entire summer, so they don't get picked up otherwise.


What is the variable format to reference Views field data in a Global PHP that resides in a footer/header? Currently its annoying to have to manually parse through the views results data by either doing a print_r() or a dsm() via devel. Does anyone know how to reference a field via PHP when you put in a Global PHP field in either the header or footer of the View?

To reference a Views field result here's the format of the variable when using a PHP Global in the footer/header in a Views display:

$results[0]->field_**<FIELD NAME>**[0]['raw']['**<VARIES DEPENDING ON TYPE OF FIELD>**']

This is in reference to a taxonomy id (tid) reference:

$results[0]->field_field_device_type[0]['raw']['tid']

This is in reference to a text field called full_name:

$results[0]->field_field_full_name[0]['raw']['value']

The [0] represents each result row and the last array value usually changes depending on the field type (text,reference,image, etc.) So its better to dsm or print_r() if you really need to reference something that your not sure of.

Here's a sample output of the array structure so you can get an idea of how its laid out:

Here's a better view of the array output of a view's result when you do a print_r() within the header. I had to apply this to another view and forgot how to reference the variables. So here's the full output when you do a print_r($result[0]->field_field_machine_type): (keep in mind it has to be "field_field" when you reference a field.

     Array
(
    [0] => Array
        (
            [rendered] => Array
                (
                    [#markup] => Tablet
                    [#access] => 1
                )

            [raw] => Array
                (
                    [tid] => 105
                    [taxonomy_term] => stdClass Object
                        (
                            [tid] => 105
                            [vid] => 9
                            [name] => Tablet
                            [description] =>
                            [format] => plain_text
                            [weight] => 0
                            [vocabulary_machine_name] => machine_type
                            [rdf_mapping] => Array
                                (
                                    [rdftype] => Array
                                        (
                                            [0] => skos:Concept
                                        )

                                    [name] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => rdfs:label
                                                    [1] => skos:prefLabel
                                                )

                                        )

                                    [description] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:definition
                                                )

                                        )

                                    [vid] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:inScheme
                                                )

                                            [type] => rel
                                        )

                                    [parent] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:broader
                                                )

                                            [type] => rel
                                        )

                                )

                        )

                )

        )

)


access denied preferred over no view How can I make it so roles that are denied access to a page can still see overview of page i.e. title and description but get an access denied message if not granted access?

I have tried different combinations of per node access along with content access but because in permissions there is only a view published content for all content which if deselected renders every page access denied regardless of content or node access...my only option it seems is the invisible page for no content access which is not at all preferable.

You can try using Premium content  Module..

Project Page Says

  This is useful on a news or membership site where teasers are
  available to the general public but the full body is only available to
  privileged users. Premium nodes appear in listings with full title and
  teaser available to anyone. If a user does not have adequate
  privileges, the default behavior is to show a simple message, but you
  can use Panels or theme overrides to do more custom things.

Found this article in D.O which will be useful for your issue.


how to post an article by jquery using REST service of Drupal? i want to create an article by rest services of drupal ?
as given in the documentation on Drupal Post docs link

but it gives an error Reference error : Drupal is not defined

in the following line of code jQuery.get(Drupal.url('rest/session/token'))

here is my code based on docs

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

function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://localhost/dr/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken

    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

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

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

You need to enclose your javascript

(function ($, Drupal) {

  ...

})(jQuery, Drupal);

to access Drupal and the usual $ for jQuery.


Show exposed filter entry with match number I want to have some view filter like this one for example.

I want a list of option [a select..] with the number of results they provide.

Can I do this in some way?

It can be achieved with the help of hook_form_alter().

You just need to override the $form['type']['#options']

Example

An exposed filter with content types and the number of nodes attached to each select option.

/**
 * Implements hook_form_alter
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form['#id']) {
    case 'views-exposed-form-[YOUR-VIEW-NAME]-page':
      foreach ($form['type']['#options'] as $option => $name) {
        if ($option != 'All') {
          $query = "SELECT COUNT(*) amount FROM {node} n "."WHERE n.type = :type AND n.status=1";
          $result = db_query($query, array(':type' => $option))->fetch();
          $name.= ' (' . $result->amount . ')';
          $form['type']['#options'][$option] = $name;
        }
      }
    break;
  }
}

If you don't want to run the query every time when the filter is being displayed, then you need to create a variable with these numbers. The query might be then performed only once, during your module installation, and the variable would be updated only when the node will be created, updated or deleted.

An example with the custom variable

Custom function to create or update our custom variable.

function update_node_numbers() {
  $node_numbers = array();
  $node_types = node_type_get_types();
  foreach ($node_types as $type => $object) {
    $query = "SELECT COUNT(*) amount FROM {node} n "."WHERE n.type = :type AND n.status=1";
    $result = db_query($query, array(':type' => $object->type))->fetch();
    $node_numbers[$object->type] = $result->amount;
  }
  // set variable
  variable_set('node_numbers', $node_numbers);
}

The function should be fired only during administrative tasks (install module, create, update or delete node)

/**
 * Implements hook_install.
 */
function YOURMODULE_install() {
  update_node_numbers();
}

/**
 * Implements hook_uninstall.
 */
function YOURMODULE_uninstall() {
  variable_del('node_numbers');
}

/**
 * Implements hook_node_insert.
 */
function YOURMODULE_node_insert($node) {
  update_node_numbers();
}

/**
 * Implements hook_node_update.
 */
function YOURMODULE_node_update($node) {
  update_node_numbers();
}

/**
 * Implements hook_node_delete.
 */
function YOURMODULE_node_delete($node) {
  update_node_numbers();
}

Now we can alter the form with the help of our custom variable, without using any query.

/**
 * Implements hook_form_alter.
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form['#id']) {
    case 'views-exposed-form-[YOUR-VIEW-NAME]-[DISPLAY-ID]':
      $node_numbers = variable_get('node_numbers');
      foreach ($form['type']['#options'] as $option => $name) {
        if ($option != 'All') {
          // some options may have been just created.
          if (!isset($node_numbers[$option])) {
            $node_numbers[$option] = 0;
          }
          $name.= ' (' . $node_numbers[$option] . ')';
          $form['type']['#options'][$option] = $name;
        }
      }
    break;
  }
}


allow user to sign up for different role I am new to drupal, so any help would be appreciated in advanced. My requirements are as follow.

1 happened in signed in user environment.
1 :" there must be groups. and they will be assigned under one user (role: manager) only he can manage the user (create,update,read and delete)" - need to be solved

* There will be a user with (admin permission) will be able to manage groups including manager * solved**

in home page : guest environment
2: "User must be able to choose which group they wanna go in: But they might need to be approved by group manager or admin before they can use their account"

for 1: i found some modules like organic group/sub-user

for 2 : i found some modules like multiple registration/ advanced registration (i don't think that gonna make it)

So please, Drupal masters, if you happens to know how to full fill those requirement with drupa stuff like Field, views or whatever. Do let me know. THANKS!!

Organic groups can do it however it requires a legthy process form the user. Eg. a manager must create a group (the creator of the group is also the manager of it by default). Then users that wish to join the group must go to the page of the group and request to subscribe. The good thing with og is that it also supports the concept of og content. That is you may create a content type and denote it as og content of a specific group. Then only the members of this group will have permissions to a node of this content type.

Another option is to use a plain old field in the user registration form that will be a list with the desired role. You can do this by going to the user configuration page. Then you can add a rule to automatically grant the requested role to every new user (a simple value comparison in rules) or create a manager view so the manager can see which user wants a role and grant it. The vbo module can help the manager in the later case.


Multiple (bulk) upload with the media browser widget I'm using Media 7.x-2.0, and I would like to be able to upload more than one image/media at the same time with the media browser widget. How can I do this?

I know about Plupload but I just need HTML5 support and don't want a special widget.

There is also Multiupload Filefield Widget, but I want to keep the media browser widget.

You will need to use https://drupal.org/sandbox/fangel/1652676 to be able to upload multiple images and still be able to access the media library.


Send reminder to referenced users day before event date in cck date field I have a node type called event.

An event has a "Event Date" date field, and a "Staff" user reference field.

I need to send a reminder emails to all referenced users, 1 day before the event date to remind them they are working.

I'm getting lost in Rules trying to work out what actions I need it to react on, and how to get the users emails to send the message to.

My problem is pretty similar to "How to send notification for an event for users that have signed up with the list of events for that month?" which was asked 3 years ago and didn't get a reply.

Can someone who is an expert with rules help me out?

UPDATE:

I have it working for one user reference field now. Added relationship "User: Duty Manager (field_duty_manager) - reverse" and contextual filter "(field_duty_manager) Content: Nid" with "Hide view" when filter is not available. I can type in "55" into the perview, and it only lists the Duty Manager, perfect.

My next struggle is to get this to work for the mulitple user reference fields. Am i going to have to clone the rules for each individual field?

I will show you how to do it when a new event is created. You must in addition provide for when an event is updated (by deleting the scheduled event and rescheduling it) and when an event is deleted (by deleting the scheduled event). If an event does not exist and you delete it it won't throw an error, so it is acceptable to do it.

You need the following additional modules installed: Views and Views Bulk Operations, reason being you will use views to obtain the list of emails and VBO is needed to interface it with Rules.

STEP 1
Start by adding a view (don't select page or block in wizard as we only want a master) of type 'Users'. Remove the sort and pager as it is not necessary.

Add a relationship 'A bridge to the Content entity that is referencing User via field_staff' and make it required.

Add a contextual filter of nid: 'The node ID.', make sure the relationship created earlier is selected, and Hide view when filter value is not available.

Add a field 'Bulk operations: User' and accept the default. This is the important field and technically the only field needed.

Test the view by typing a known node id in the preview field.

STEP 2
Create a Rules component of type 'Action Set' and call it 'Send Notification'. Add a Variable of 'Entity: Node', give it a label and machine name of 'node'.

Add an action to this component: 'Load a list of entity object from a VBO View'. Select the view you created earlier. Set its argument to '[node:nid]' and leave the provide variables at default. Note the variable name of the List of entities: entity_list.

Add a loop to this action, and select 'entity-list' as the Data Selector. Note the default name of the current list item: list_item.

Add an action to the loop (note: add it to the loop and not the component) of 'System: Send Mail'. In the to value select '[list-item:mail]'. Fill the rest out the way you want.

STEP 3
Add a new rule and call it 'On new event', to react on 'Node: After saving new content'. Restrict it to type 'event'.

Add an action to this rule, 'Rules schduler: schedule component evaluation', and select the 'send notification' component you created earlier.

Set the evaluation date to node:field-event-date.

Add an offset: -1 days

Add an identifier of 'node-[node:nid]-event' and note its pattern as you will be using it to delete events.

Select the Node as 'node'

That should be the gist of it.


Redirect does not work on nginx I'm migrating an old site to Drupal (using migrate module), and I've managed directly in code all old urls to redirect to new Drupal urls using redirect module, for example:

www.mysite.com/UserProfile.php?user=5

Redirects to:

www.mysite.com/it/community/peoples/mr-max

This works very fine on my dev environment with apache, but doesn't works on live environment with nginx.

At first try with old url, I received a blank page with the message "No input file specified."

So I've changed virtual host conf from:

location ~ \.php$ {
  #fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $request_filename;
  fastcgi_pass php-fpm;
}

to:

location ~ \.php$ {
  #fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME index.php;
  fastcgi_pass php-fpm;
}

RESULT: no more "No input file specified." blank page, but redirect doesn't works and my front page is shown for all old urls.

Here's other settings from my virtual host, if can help:

location ~ \..*/.*\.php$ {
  return 403;
}
location ~ ^/sites/.*/private/ {
  return 403;
}
location ~ (^|/)\. {
  return 403;
}
location / {
  try_files $uri @drupal;
}
location @drupal {
  # For D7 and above:
  # Clean URLs are handled in drupal_environment_initialize().
  rewrite ^ /index.php;
}
location ~ \.php$ {
  #fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME index.php;
  fastcgi_pass php-fpm;
}

What kind of setting I have to change/add to the above conf to make redirect working correctly?

Finally, someone redirected me to the right place

Here's the missing code that does the trick:

location ~ \.php$ {
            error_page 418 = @rewrite;
            recursive_error_pages on;

            fastcgi_split_path_info ^[^=](.+\.php)(/.+)$;
            include fastcgi_params;

            if ( $uri = /index.php ) {
                    break;
            }

            if ( !-e $document_root$fastcgi_script_name) {
                    return 418;
            }

            #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
            fastcgi_read_timeout 240;
            fastcgi_pass  127.0.0.1:9000;
}

Source: http://wiki.nginx.org/Drupal

(link suggested in https://groups.drupal.org/node/405038)


How can I get my WYSIWYG editor to stop *#@&%^ing up my HTML? I've tried every combination of "CLEANUP AND OUTPUT" settings that might conceivably prevent munging my HTML, but nothing works.  No matter, what, my HTML gets flattened or in some way rewritten, mainly with whitespace being trimmed off that I want to leave in.

I would suspect CKEditor (version 3.6.4.7575) except that when I tell WYSIWYG to "Apply source formatting", CKEditor doesn't prevent that, so it seems that logically this problem is in the WYSIWYG module.  "Apply source formatting" simply causes the HTML to be screwed up differently.  Some linebreaks are left in place, but spaces at the beginning of the line are left in place.

How can I prevent this, and still use a WYSIWYG editor?

I had just run into this problem of wysiwyg editors reformatting the html source into a minimized blob of contiguous html.

The solution I found was to use TinyMCE editor with WYSIWYG and to add an additional module called wysiwyg-codemagic.  With this module, you place the codemagic plugin for TinyMCE in the TinyMCE library's plugins (Follow the instructions in module's Read.Me).

Now, when the author of the node content drops into the html source, as occasionally needed, the source is very readable and presented correctly.

This was an old post, but I thought this new info would help for the others of us that still run into this problem


How to create an Orbit slide show based on the zurb foundation? I stubbornly tried to create an Orbit slide show based on zurb foundation 6 framework.

I followed all the steps on the instruction page:Orbit Slide Show.

I added everything needed for this type of slide show and included below CSS and Java Script classes in theme library:

motion-ui.css
foundation.css
foundation.js
jquery.js

The template code I used is here: Orbit SlideShow Problem

But unfortunately all images display vertically below each other (one image below another) and the Previous / Next button does not work properly, see below image:

I would be happy to hear what the problem is, share your experiences and guide me to know what is the right way to load that slideshow?

After many days searching for cause of this problem in throughout of the web resources, forums and reading variety of article, I fond that this issue for this that I don't
keep the Priority of foundation Files Structure in my library, According to the  Zurb Foundation documentation in this page: Installing JavaScript

  It's important that you Make sure "Foundation.js" (or
  Foundation.min.js) files loads after "jQuery.js" (or jquery.min.js).


How to make Views sorting case-sensitive? Ascending alphabetical sorting in a Views string field works like this:

1
2
3
a
A
b
B

But I want it like this:

1
2
3
A
B
a
b

Is there any way to do this?

What you're want to do is a sort by a character's byte value. MySQL has a function for this, BINARY(), which you could use in your ORDER BY criteria (e.g. ORDER by BINARY(title)).

Drupal Views doesn't have any default sorting handlers that use this function, so the only way to do it in views is by creating your own custom sort handler.


How to import rules on site install? When I go and export my rule, I get the following:

{ "rules_vote_points" : {
    "LABEL" : "Vote points",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "userpoints_rules", "voting_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "3",
          "tid" : "0",
          "entity" : [ "node" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "approved"
        }
      }
    ]
  }
}

Where could I put this to import it in the site install? E.g. I am importing views with a hook_views_api hook in my module and a module.views_default.inc file that searches through the views folder and imports the views, and content types are created with hook_install in .install files in my modules. But how do I import the following?

Assuming this is for D7, try this code (which includes a copy of your exported rule):

function my_module_default_rules_configuration() {
  $configs = array();
  $rule = '{ "rules_vote_points" : {
      "LABEL" : "Vote points",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "userpoints_rules", "voting_rules" ],
      "ON" : [ "voting_rules_insert_node" ],
      "DO" : [
        { "userpoints_action_grant_points" : {
            "user" : [ "node:author" ],
            "points" : "3",
            "tid" : "0",
            "entity" : [ "node" ],
            "operation" : "Insert",
            "display" : 1,
            "moderate" : "approved"
          }
        }
      ]
    }
  }';
  $configs['rules_vote_points'] = entity_import('rules_config', $rule);
  return $configs;
}

PS: have a look at the code of the Answers Userpoints module for an example where this technique is used also (contained in answers_userpoints.rules_defaults.inc).


jQuery csv file export fires multiple times I have a custom form, and I just want a button in the form that fires a jQuery plugin that generates a csv file for download. The problem I'm having is that it seems to fire multiple times for some reason, and I haven't been able to figure out why. I've tried both a button and a link, but I keep getting the same result.

Here's the form button:

$form['export_csv_button'] = array(
  '#type' => 'button',
  '#value' => t('Export to CSV'),
);

And here's my jQuery behavior:

(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

Is there something obvious I'm missing that is making this happen?

Thanks.

Try this:

(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").once().click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

I added the jQuery.once() method.


Creating a Home Page Template The index page of a site I am building is to be a video and nothing else which clicks through to the site.

I have read about page templates and seen some modules called 'front page' but I would like to to do this within the code.

Is there a best advised / standard way to do this?

I have tried setting an if statement for $front_page but this seems to happen for every page.

The variable you wish to test is $is_front, which is only true for the front page.

You can find a list of the variable available for page.tpl.php here.


Custom date formats in webform emails I have a webform that sends an email. The webform has a date field and I need to format that date field.

I have tried:

[submission:values:date_field:CUSTOM_FORMAT]
[submission:values:date_field:long]
[submission:values:date_field:value:custom:d-M-y]

Both result in a blank date.

How can I format the date in a webform email using a non-default (which appears to be short) date format?

I had to create a custom hook_tokens function:

/**
 * Implementation of hook_tokens().
 */
function MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'submission' && !empty($data['webform-submission'])) {
    $node = isset($data['node']) ? $data['node'] : node_load($submission->nid);

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'values:date_field:custom_format':
          foreach ($node->webform['components'] as $cid => $component) {
            if ($component['form_key'] == 'date_field') {
              $replacements[$original] = format_date(strtotime($data['webform-submission']->data[$cid][0]), 'custom_format');
            }
          }
          break;
      }
    }
  }

  return $replacements;
}


Exporting a view from one site to another I'm a Drupal beginner with a problem.

I'm gonna do some updates on a live site which requires some new views to be created, and with that some new content types and blocks. I'm working off my local dev site doing these changes there first and then I'd like to be able to export these views as a package with the content types and blocks that they handle. Is this possible?

Of course I could just export my local database and import it on the live site, but the problem is that the live site is very active so the database is always changing. And my updates will take at least a week to do, so I can't keep up.

Any suggestions?

By Default views have option to import and export. By using that we can do it.

In drupal7 views3.x has option of import link in this url admin/structure/views

With this image you will get clear view of how to import and export a view.


Ajax replaced elements not available in form submit callback I have some elements in a form as below:

$form['provider'] = array(
    '#type' => 'select',
    '#title' => t('Provider'),
    '#required' => TRUE,
    '#options' => $some_options,
    '#ajax' => array(
        'callback' => 'my_callback_func',
         'wrapper' => 'tests-div',
         'method' => 'replace',
         'effect' => 'fade',
     ),
);

$form['tests'] = array(
    '#type' => 'select',
    '#title' => t('Tests'),
    '#required' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => array(''),
    '#validated' => TRUE,
 );

When the provider select box value is changed, the callback my_callback_func checks the chosen value of the select box, and returns a modified version of tests select box with some new options set.

function my_callback_func($form, &$form_state) {

    [snipped code which reads form data and calculates $some_new_opts ]

    $form['tests'] = array(
          '#type' => 'select',
          '#title' => t('Tests'),
          '#required' => TRUE,
          '#prefix' => '
',
          '#suffix' => '
',
          '#options' => $some_new_opts,
          '#validated' => TRUE,
    );

    return $form['tests'];
}

So far so good - when I change the value of the provider select I can see the Ajax event firing, the new options appear in the tests checkbox and I can select from them. But then when I submit the form using

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'go for it',
    '#submit' => array('my_post_submit_function'),
 );

none of the Ajax supplied values are visible in either form or form_state within my_post_submit_function. Instead, the original value (the empty array) is always shown in $form['tests']['#options'], and $form_state['values']['tests'] is null ("").

What am I doing wrong ?

Updated 4th Sept

I'm still trying to solve this problem.
I've looked in a debugger at what happens when I click the submit button.

index.php and menu.inc direct control to form.inc, where drupal_get_form makes a call to drupal_build_form.

At this point $form_state seems to be being reconstructed from somewhere (the cache_form table?) as it certainly doesn't contain the settings I made to it during my earlier processing. (for e.g. I set $form_state['foo'] = "bar"; which has now disappeared.)

Does anybody know how this works in more detail? Does form caching mean that it's impossible to submit Ajax-modified data to the submit handler?

I received some help on Drupal.org about this... Jaypan's helpful reply is at https://www.drupal.org/node/2563045. I've posted a comment there to show how I got this working eventually.


How to add OG to the menu? I have Organic Groups installed within Drupal 7 and I am attempting to get the groups to display in the menu. For all authenticated users I want the group(s) they belong to show up in the menu (could be the user menu).

Addition:

The picture below shows how far I have gotten. This is within the edit view window. The closest window shoes the fields that can be added. The only group-specific fields I found are Group: Group permissions and Group: Group user roles and for the filter there aren't any group-specific choices. Is there some roundabout way to add them or a specific permission I may be missing. I have given my administrator (currently logged in) all of the permissions listed for the groups.

Do you need this in an existing menu?

Personally I would do this with Views. If you have it installed try the below.

Create a new view
Add a Block Display
Set Access to Authenticated Users
Change the Basic Settings > Style to "Table"
Add Fields for Node Title & Organic Group Post count
Add Filters for Organic Group Member "True"

This will now display a table with the titles and a "new" post count. You can make it look more like a traditional menu by changing the view settings further.


How do I add JavaScript specific for a view? I have a view in my site that has a specific class name. I want to know, inside the template.php file of a theme, how I can know if a view with specific class name is available in the requested page.

This is very important for me because I need to include specific JavaScript and CSS, when a view with a specific class name (such as image-gallery) is used in a page.

You could use the template_preprocess_views_view() hook to do this:

function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'your-view-name') {
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'your-theme') . '/your-js.js');
    // add needed stylesheet
    drupal_add_css(drupal_get_path('theme', 'your-theme') . '/your-css.css');
  }
}

Note that you could also check the specific display of the view using:

if ($view->name == 'your-view-name' && $view->current_display == 'your-display-id') {
  // include javascript & css here
}

You should be able to check for a custom css class like this:

if ($view->name == 'your-view-name' && $view->display[$view->current_display]->display_options['css_class'] == 'your-css-class') {
   // include javascript & css here
}


Theme the login page for Maintenance mode I've created my theme as subtheme of ZEN, and I have created my maintenance page template, which works when I enable the maintenance page.

If I try to visit example.com/user, the login page is shown with the standard template, and not with the maintenance-page template.

How do I make Drupal 7 use the maintenance page template also for the login page?

If you want the login page to look different when you are in maintenance mode you theme it by checking the maintenance mode variable like this:

if (variable_get('maintenance_mode', 0)) {
  // Do something because it is maintenance mode.
}

For example, in your page template you could do this:

/**
 * Preprocess variables for the page template.
 */
function THEME_NAME_preprocess_page(&$variables) {
  if (variable_get('maintenance_mode', 0)) {
    // Add a template suggestion for pages that are not the maintenance
    // page, while the site is in maintenance mode.
    $variables['theme_hook_suggestion'][] = 'page__inmaintenancemode';
  }
}

Then you could make a page--inmaintenancemode.tpl.php file, that could be used to theme any pages that are visible while in maintenance mode.
Be aware though that this will then affect all pages you see when you are logged in during maintenance mode, so you might want to change the line that check for maintenance mode to:

if (variable_get('maintenance_mode', 0) && user_is_logged_in()) {

You can do the same check in hook_form_alter() or in other template preprocessors, or anywhere else you are modifying content.


How do I use CkEditor layout on textfield input? I have a content type with a "Text (formated)" field. When I try to write something in it, all my HTML is ok. But I want to use the buttons of ckEditor to make it more "user friendly". I don't want to always have to write all my tags manually.

On "Text, long (formated)" field, there is no problem.

You can see what I mean in this screenshot.

I already tried to switch text format under my field. Nothing changed, except I got more tags allowed.

CKEditor only works on a textarea, you can’t attach an instance to a textfield.

You could implement hook_form_alter and change it from a textfield, but it’s hard to see what the point would be.

If you need long text, just use a long text field. It was designed for your use case, so will always work as expected.


Problem rendering paragraphs field - advanced but still not working I am working on a site with one special page layout (lets call it originally "two columns"), which has basically two columns: The left one showing page contents and the right one an unlimited number of paragraphs.

There is still one problem:

1) The twig tries to show also the paragraphs in the end of left column not following the without-filter. If I show the field title (content type Manage display) it shows the title in the bottom of the left column but no other output is generated of the field_aside paragraphs

2) I can't get the right column to show anything from the field_aside, whatever I try.

The crucial code comes here (the best idea what to do so far, tried a multitude of alternatives with zero results)

    {{ content.body }}

    Aside...
    {{ bamboo_render_field('field_aside', 'node') }}

The page is using a Bulma based theme but I'd reckon it has nothing to do with the problem.

I have Bamboo Twig and Bamboo Twig Loaders enabled.

The field_aside should render the corresponding paragraph texts.
wbr

hank

I am sorry, there was just a dumb error in the paragraph template that I used in testing. So, never mind...


Add a trademark to a word everywhere on a site I've tried a few different techniques now but I can't get one to work reliably across all content. What I need to do is have all instances of the business name include a trademark symbol:

ie -> DinosaurCakes  becomes DinosaurCakes&tm;
or
Would you like some DinosaurCakes? becomes Would you like some DinosaurCakes&tm;

The javascript version I was trying to do was looping through the page on load and replacing the string with the function I found here-> http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/
But it isn;t digging in to all of the child nodes for some reason and so some versions of the string don;t get replaced.

I then tried to do it in Drupal via hook_page_alter with:

function dinosaur_page_alter(&$page) {
    // attempting to add the DinosaurCake (tm) marks using page_alter
    // find all '#markup' and then scan for terms
    function display_array(&$your_array){
      foreach ($your_array as $key => &$value){
        if (is_array($value)){
          display_array($value);
        }
        elseif (is_string($value) && $key === "#markup") {
          $value = str_replace(array('DinosaurCakes"), array('DinosaurCakes&tm;'), $value);
        }
      }
    }
    display_array($page);
}

However, using this method, it doesn't work on headings and does apply to title attributes and pathnames which of course breaks everything.

Any ideas on the best way to attack this?

You can use "String Overrides" (http://drupal.org/project/stringoverrides) module to accomplish what you want to do and it will work even if JavaScript is disabled and the changes will be cached as well by the Drupal cache.

Note: This will work with content pass by the t() function, if you have the word hard coded on the theme or module it will not work. Also it is CaSe SeSiTiVe.


Comment.tpl.php how to add a link back to the node In the comment.tpl.php I've shown the comment parent node title by:

$node->title

I need to make this title link back to the parent node:

$node->$node_url

But this doesn't work. How should I do that?

You can use the entity_uri() and l() functions, similar to how it's done in template_preprocess_node():

$uri = entity_uri('node', $node);
$link = l($node->title, $uri['path'], $uri['options']);


Possible to access source database in prepareRow() in Migrate module? I'm doing a D2D migration that requires a mapping table to map tids from the source site to the destination site. In prepareRow(), I need to check the tid for a certain vocabulary and get the corresponding tid for the destination site. For a couple reasons, this mapping table is kept in the source site. However, the problem is that the default db connection that is being used in prepareRow() is the destination db, not the source db any more, so running my query throws an error. How can I switch the connection to use the source db so I can access this table and cache it? The short term method would be to copy this table to the destination site, but this will be an ongoing migration, and I don't want to have to update the table manually in the destination site every time the table is updated.

Thanks.

2 simple approaches:

You call the other DB explicitly like you do any other place to talk to it from drupal.

// Method #1
$query = Database::getConnection('default', 'for_migration')->select('source_table', 'st');
// $query = ....

// Method #2
db_set_active('my_other_db');
// ... code here ...
db_set_active();  // switch back to normal DB connection in-use. This is important.

Method 1 is outlined here: https://www.drupal.org/node/1014558
Method 2 is outlined here: https://www.drupal.org/node/18429

Your other option is to not do it in every prepareRow() explicitly. Think outside the box :P. Why re-query this information within every prepareRow() -- that just slows down your migration. You can define this custom $tid_map lookup array in your Migration class's constructor as a data member to the migration class itself. You only query it's value a single time (on migration startup). prepareRow then just checks the stored array whenever needed. You may or may not have to use a static variable to assure the value is saved and preserved throughout the Migration lifetime ... I'm not sure.


How to point parent menu item to a link and sub menus too Hi I have a main menu named Home and there a sub menus in it. When I click any of the menu item of sub menu the content of the sub menu displayed. But After that I can not go to home by clicking home menu  as it contains sub menu and it does not point to home link hence its non clickable. My issue is that I want parent item to points to a link and sub menus too. Is it possible?. I am using bootstrap theme.

You can do this by using below modules :

Path Breadcrumb

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

Menu Breadcrumb

  By default, Drupal 6+ use the Navigation menu for the breadcrumb. This
  module allows you to use the menu the current page belongs to for the
  breadcrumb.


Drupal 7 Error 324 (net::ERR_EMPTY_RESPONSE) I am working on a new Drupal 7 site and I am randomly getting connection errors to my server.

I am getting "Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data." in Chrome and Connection reset Errors in firefox. They are sporadic and tough to replicate. I call my service provider (MediaTemple) and they are unable to replicate the problem.

I am honestly at a loss and will look into any ideas given.

I found something else as well. It turns out that I was using a beta version of a module that was spitting out so many error messages that it was crashing apache.

Best advice I can give is to stick to trusted and tested modules.


What does Drupal do when registering a user? I'm relatively new to Drupal.
I like to understand what Drupal does programatically when a user is being created?

More specific I like to know if any file is being created?
Or is it just a database transaction?
Where is the database changed? Which tables?

Because I would like to build a 3rd internal party to create acct from 'behind' so I need to understand what it does so my 3rd party app can mimic the same and at the end the new user login seamless.

No file is being created (unless you count the user avatar), only a database row in the users table.

You should check out the user_save function in the Drupal docs.


That's a session encoded string (different from a PHP serialized string). There's no built-in way to decode it directly into a variable, so you'll have to use a custom function.

Here's one nicked from the docs page for session_decode().

function unserializesession( $data ) {
  if(strlen( $data) == 0) {
    return array();
  }

  // match all the session keys and offsets
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();

  $lastOffset = null;
  $currentKey = '';
  foreach ( $matchesarray[2] as $value ) {
    $offset = $value[1];
    if(!is_null( $lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset );
      $returnArray[$currentKey] = unserialize($valueText);
    }
    $currentKey = $value[0];

    $lastOffset = $offset + strlen( $currentKey )+1;
  }

  $valueText = substr($data, $lastOffset );
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}

It works well with the example in your question, returning a nested array of values.


Block template suggestions Is there a way to use a custom template for each block by title? For example, if I named my block "test1", and it is in the region "left1", I want to use the following template suggestions:

block-left1-test1.tpl.php
block-left1.tpl.php
block-test1.tpl.php

Is there a list of template suggestions for blocks?

The Drupal theming system has a concept called "template suggestions". When a theme hook is invoked, Drupal checks if the theme hook is implemented as a template or as a function. In case of a template, All preprocess functions for that theme hook are invoked. This means that every module or template can add its own data to the variables that will be made available to the template. Those variables are passed around as a large array, $variables. This array can contain a list of template suggestions as a nested array called $variables['template_files']. Drupal will later reverse that list and use the first existing template it can find. See the documentation on drupal.org for more details.

Now what you can do is:

Add a function to your theme's template.php named [themename]_preprocess_[themehook] (eg. function mytheme_preprocess_block(&$variables) {} )
In that function, construct the desired template name suggestions
Add those suggestions to the $variables['template_files'] array

By the way, if I'm not mistaken you cannot use the region name in the template suggestion, because at the time the block is rendered, it is not yet known in which region the output will be shown.

PS 1: It helps if you tell us which Drupal version you're using.

PS 2: I'm voting for this question to be moved to https://drupal.stackexchange.com/


How to add new items to existing menu using custom module Is there any way to add new items to an existing menu using custom module in Drupal7.

For Drupal 6 you do use menu_link_save:

$item = array(
  'link_title' => 'Menu title',
  'link_path' => 'menu/path',
  'menu_name' => 'menu_name',
  'module' => 'your_module',
);
menu_link_save($item);


hook_theme_registry_alter caches this function caches the output, so it doesnt work if I want to change dynamically between two template files. For example user-profile.tpl.php and user-profile-project.tpl.php

Code:

function hook_theme_registry_alter(&$theme_registry) {
  $tmp1 = arg(0);
  $tmp2 = arg(1);
  $tmp3 = arg(2);

  if ($tmp1 == "user" && is_numeric($tmp2) && !$tmp3) {
    $user = user_load($tmp2);
    $roles = $user->roles;
    if (in_array('project', $roles)) {
     $theme_registry['user_profile']['template'] = 'user-profile-project';
    }
  }
}

So how can I do this differently?

Implement hook_user_profile_preprocess() and add your template suggestion as last entry of $variables['theme_hook_suggestions']. Instead of using arg() as you are doing, use menu_get_object('user', 1).

hook_theme_registry_alter() is not good because:

Drupal caches what it gets from hook_theme_registry_alter()

  // _theme_registry_build()
  if ($cached = cache_get('theme_registry:build:modules')) {
    $cache = $cached->data;
  }

It is never invoked for each page request Drupal gets; so you could not for which user the user profile is.

Then, the Drupal way would probably be to check the user has a specific permission rather than a specific role.

if ($account = menu_get_object('user', 1) && user_access('your permission', $account)) {
  $variables['theme_hook_suggestions'][] = 'your template suggestion';
}


Create View to display users with same select list value to each individual user When a user registers on my site, he/she chooses the college he attended and the course he/she studied from select list fields i created using the profile 2 module

Is there a way to create  a View that displays to each user the people who attended the same college & studied the same course.

Thank you.

You can do it creating using Views with a contextual filter.

Profile2 has integration with views, and if you create a view's page display with a path like yoursite.com/user/[username/id]/users-with-same-college url. You get it!

Hope it helps.

Regards.


Lightbox doesn't show images loaded by entity_metadata_wrapper There is a field collection in a content type, it's name is field_jeld. This field collection has an image field, it is field_image. I also defined an image style called book_mini. I need to load the images using lightbox, to do so I set the following image format in manage display of every display mode:

I have to load the images in the front page so I used entity metadata wrapper, this is my code:

$nid = "A NID GET FROM SOMEWHERE ELSE";
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node',$node);
$jelds = $wrapper->field_jeld->value();
foreach ($jelds as $jeld){
    $item_id = $jeld->item_id;
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $item_id);
    $photo_field = $fc_wrapper->field_image->value();
    $image = theme('image_style',
        array(
            'style_name' => 'book_mini',
            'path' => $photo_field['uri'],
        )
    );
    print $image;
}

This code prints the image in book_mini format very well but the problem is, when I click on it, it is not loaded by lightbox and no popup is shown, in fact the image is not a link. How do I can solve this problem?

UPDATE1

I also tried this

$nid = "A NID GET FROM SOMEWHERE ELSE";
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node',$node);
$jelds = $wrapper->field_jeld->value();
foreach ($jelds as $jeld){
    $item_id = $jeld->item_id;
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $item_id);
    $photo_field = $fc_wrapper->field_image->value();
    $image = theme('image_style',
        array(
            'style_name' => 'book_mini',
            'path' => $photo_field['uri'],
        )
    );
    $name = $photo_field['filename'];
    $url=  $base_url."/sites/default/files/image/".$name;
    print "".$image."";
}

I'm sure the $url points to the right file, after clicking the browser opens the lightbox but it doesn't show image, only white screen!

UPDATE2

The only solution I found is to use filed collection views and Views. I created a View called loadcover and selected field_jeld as a field. I also created a View of field collection views, called fc_jeld, and selected the required fields. This is the Formatter configuration of field_jeld :

Then using this code

print views_embed_view("loadcover","block",$nid);

it worked ! sounds the lighbox works with field collection only in the Views not the node!!!

In the lightbox configuration settings it allows you to define a certain class, so it popups whenever an image has that certain class. So all you have to do is to find a way to add a class to your image.

Perhaps you could use the Image URL Formater module. Set your image field format to url. (So when it prints, it will print the image url instead of the actual picture)

then concatenate a string to add html to your code.

print '<img src="' . $image . '" class="lightbox">';


Drupal 8 Custom Composite Entity Select Field Does anyone have an example of how I add an Entity Select (Specifically a term reference) to a custom composite?

Here's the code I've tired. The field with the title shows up but no select.

$elements['test_tax'] = [
  '#type' => 'entity_select',
  '#title' => t('Test Taxonomy'),
  '#target_type' => 'taxonomy_term',
  '#selection_handler' => 'default:taxonomy_term',
  '#selection_settings' => [
    'target_bundles' => [
      'my_terms' => 'my_terms'
    ],
    'sort' => [
      'field' => 'name',
      'direction' => 'ASC'
    ]
  ]
];

I'm a front-end guy so I'm a bit out of my element in php...

I think you just need to change...

'#type' => 'entity_select',

...to...

'#type' => 'webform_entity_select',

In the Webform YAML source editor we are hiding the 'webform_*' prefixes, within custom code they have to included.

@see https://cgit.drupalcode.org/webform/tree/src/Element/WebformEntitySelect.php


Include a third party library using namespaces, dependencies I made a library to access to the Taleo data ( https://github.com/Polzme/Taleo ).
I tried to follow the best practice to do it.
It's using composer ( http://getcomposer.org/ ) to resolve dependencies to Monolog and Guzzle.

Now, the big question is, how to use my library 'Taleo' in a Drupal module ?

I tried with xautoload ( http://drupal.org/project/xautoload ) and composer_autoload ( http://drupal.org/project/composer_autoload ) without success.

I also tried to include the file 'vendor/autoload.php', but it doesn't works (and it works well in the demo.php file: https://github.com/Polzme/Taleo/blob/master/demo.php)

Before including each file manually, I would like to know if there is a working solution available for Drupal 7.

Thanks!

It is indeed possible with xautoload.

Here is some explanation what initially went wrong:
https://gist.github.com/4018045

As a general guide:

function hook_libraries_info() {
  return array(
    'Taleo' => array(
      'name' => 'Taleo PHP Library',
      'xautoload' => function($api) {
        // $api already knows the library path.
        // 'src' is relative to that.
        $api->namespaceRoot('Taleo', 'src');
      },
    ),
  );
}

The $api object is explained here:
http://drupalcode.org/project/xautoload.git/blob/refs/heads/7.x-2.x:/lib/InjectedAPI/hookXautoload.php


Create hook menu with custom module (child/%) In my custom module I want to create menu with the name "child/%" is it possible. When I create menu "child/test", whenever I load the page http://localhost/project/child/test it gives error page could not found. so if I run http://localhost/project/%E2%80%8Bchild/test like this it is working.
Its confusing, Kindly clarrify.

Thanks,
John.

try to follow this code

<?php
/**
 * Implements hook_menu().
 */
function example_menu() {
  // In this example, the third parameter will be passed.
  $items['admin/example/%'] = array(
    'title' => 'Example of first parameter being passed',
    'description' => 'This has a page arguments index of two because the wildcard occurs at the 3rd parameter',
    'page callback' => 'one',
    'page arguments' => array(2),
    'access arguments' => array('access administration pages'),
  );
  // The third and fourth parameters are being passed, hence we need to create an array with values 2 and 3 for the page arguments key
  $items['admin/example/%/%'] = array(
    'title' => 'Example of multiple parameters being submitted',
    'description' => 'Example of multiple parameters being submitted',
    'page callback' => 'two',
    'page arguments' => array(2, 3),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

/**
 * One parameter being passed.
 */
function one($one) {
    return $one;
}

/**
 * Two parameters being passed.
 */
function two($one, $two) {
    return $one . ' ' . $two;
}

Thank You.


Why has my security shield for my new module on Drupal.org been removed? I have recently managed to create a module on drupal.org, by following the entire process from Sandbox->Project Application->Module Publish.

However after few weeks my module lost the security shield, and am getting this message instead:

  This project is not covered by the security advisory policy.
  It may have publicly disclosed vulnerabilities. Use at your own risk!

I have gone through some of the documentation (Security advisory process and permissions policy), but I couldn't find suitable explanation.

Here is a screenshot of how it looks like now:

My questions:

Why has my module been tagged with this message?
How can I resolve it, or how can I find what is wrong in my module?

Only full releases get the security shield. Your screenshot only shows a dev version. I don't think the shield was removed from your module, as it wouldn't have had one in the first place since you don't have a full release.

To get the security shield, you'll need to release a full version (one not suffixed with -dev, -alpha or -beta).

** EDIT **

I have just discovered that an additional step needs to be taken in addition to creating a full release. Until recently, if a module was given a full-release, it automatically received the security advisory. However, I just promoted a module I've got from RC to a full release, and it did not receive the security advisory. Editing the module page now has an option that requires to module maintainer to opt into the security advisory.

Even having done so, my module still does not have the advisory shield, so I assume it now goes under some review from the security team before receiving it. This issue seems to support that assumption: https://www.drupal.org/node/2666584

--- Edit 2 ----

It turns out their was a bug in the system. I am already able to promote modules to drupal.org rather than the sandbox. With existing modules, when upgrading from D7 -> D8, modules were automatically given the shield when I released a full version. However the module I mentioned above did not have a D7 version, and when I promoted it to a full release it didn't receive the shield. After waiting two weeks for approval I finally contacted the security team, and they looked into it and found a bug in the caching system, and fixed it.

So it appears that the original information I gave - that you just need to release a full version, and have opted into security advisory coverage, is correct.

Here's a screenshot of the module edit page.


entityQuery condition for users without a role In Drupal 8 - Is there a way to do a 'NOT IN' in a user based entityQuery?

$uids = \Drupal::entityQuery('user')
      ->condition('uid', 72)
      ->condition('status', 1)
      ->sort('created', 'ASC')
      ->execute();

This query ^ yeilds results

$uids = \Drupal::entityQuery('user')
  ->condition('uid', 72)
  ->condition('roles', ['testing_user'], 'NOT IN')
  ->condition('status', 1)
  ->sort('created', 'ASC')
  ->execute();

This query ^ does not. User 72 doesn't have the role 'testing_user'

Your original code is correct. The problem is condition of 'not in'. It doesn't give result of users who has no roles. If you give roles to each user you are good to go.

More reading

You can get deeper understanding from class file
   https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Condition.php/class/Condition/8.2.x

Also there is a Drupal 7 API documentation about conditional-clauses
https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses


Missing my custom ajax field values by image field in node form alter I have created new content type and added two taxonomy reference field (select list) both referenced to same vocabulary "car" and one Image field with cardinality = 6,

In car vocabulary listed brands and models like:

Brand 1
- model 1
- model 2
- model 3
...
Brand 2
- model 1
- model 2
....

In my content type, first reference select list depth setting is 1, so displays only brands,
In Second reference select list (Models) content_taxonomy_opt_groups => 1,

I have created simple module, for altering on node form and creating custom ajax on Brands and Models select list,

When select a brand, models field displays only models of selected brand...

My ajax has worked

Problem is: when upload an image (Ajax upload) and click Publish this error is shown:

An illegal choice has been detected. Please contact the site administrator.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function car_info_form_car_info_node_form_alter(&$form, &$form_state, $form_id) {
  $brand_options  = $form['car_brand'][LANGUAGE_NONE]['#options'];
  $selected_brand = isset($form_state['values']['car_brand']) ? $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] : key($brand_options);

  $form['car_brand'][LANGUAGE_NONE]['#default_value'] = $selected_brand;
  $form['car_brand'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'car_info_dependent_model_callback',
    'wrapper' => 'dropdown-model-replace',
    'effect' => 'fade',
  );

  $form['car_model'][LANGUAGE_NONE]['#prefix'] = '
';
  $form['car_model'][LANGUAGE_NONE]['#suffix'] = '
';

  if ($selected_brand > 0) {
    $model_options  = _car_info_get_model_dropdown_options($selected_brand);
    $selected_model = isset($form_state['values']['car_model']) ? $form_state['values']['car_model'][LANGUAGE_NONE][0]['tid'] : key($model_options);
    $form['car_model'][LANGUAGE_NONE]['#options'] = $model_options;
    $form['car_model'][LANGUAGE_NONE]['#default_value'] = $selected_model;
  }
  else {
    // Remove default options (All models of brands) if brand not selected
    $form['car_model'][LANGUAGE_NONE]['#options'] = _car_info_get_model_dropdown_options('');
  }

  // $form['#validate'][] = 'car_info_form_car_info_node_form_validate';
}

function car_info_dependent_model_callback($form, $form_state) {
  return $form['car_model'];
}

function _car_info_get_model_dropdown_options($brand_id) {
  if (isset($brand_id)) {
    $car_models_tree = taxonomy_get_children($brand_id);

    $models[''] = t('Select model');
    foreach ($car_models_tree as $model) {
      $models[$model->tid] = $model->name;
    }
  }
  else {
    $models[''] = t('First select brand');
  }

  return $models;
}

function car_info_form_car_info_node_form_validate($form, &$form_state) {
  $car_brand = $form_state['input']['car_brand'][LANGUAGE_NONE];
  $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] = $car_brand;
}

If I dont add image or add image without click on upload button (upload handled when clicked on publish directly) in both way my form is submitted correctly

But if click upload button in image field (Upload handled by ajax), this issue is happened and $form_state['values']['car_brand'] is empty when using ajax image upload.

In your form an AJAX call is made when your car_brand element is changed but also when upload image button is clicked. Your problem is the AJAX call that is made when upload button is clicked. In that call car_info_form_car_info_node_form_alter() is called, and probably is modifying the allowed options array for the model select element in a wrong way.

In your form altering function check for the element that fired the AJAX call  modifying the select element options only when your first select (brands). You can check for that element in the $form_state['triggering_element'].


In which template file is a node title supposed to be? I have to add a Title field to each content type to ensure a title appears on the node view.

This makes me wonder: Maybe I'm missing the title variable in my implementation of page.twig.html or something, but I don't see a title variable anywhere in the default page.html.twig.

In which template should my title variable be displaying?
What should the code in the template look like to display the title?

Page title is now a block

  The page title is now provided by a block so it can be easily moved
  without editing the page template.

  The markup for the page title can be edited in page-title.html.twig,
  and template_preprocess_page_title() can be used in conjunction with
  the template

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


Change view css based on field value? the view shows a simple article, i want to show the view in rtl direction if a specific field value is YES for example, if the value is NO, then the view will be displayed as ltr.

I have a hidden field that have two values, Yes or No, based on them i need to change the VIEW. only the view, everything else in the page must stay the same.

How to achieve that please

It is easily achievable with drupal_add_css in a hook_preprocess_views_view.

An example of it can be found in the last comment here.


Automatically show one selection of a field based on the selection of another field in a view Sorry if this is a repeat question but I'm stuck!

Ok, I have a content type named 'Media' that is basically a bunch of videos, pictures, podcasts as well as a small write up that explains what it is. I have a view that lists these media files according to most recently added. My problem is that in this view, I display an icon according to whichever type of media it is (a camera logo for videos, and podcast logo for podcasts, etc.) but I have to choose which one it is every time I create a new 'Media' content type.

I have a field called 'icons' within this 'Media' content type, which is just a term reference with a select list widget. The taxonomy terms are the file types (video, podcast, picture) and they are linked to the correct image/logo/thumbnail whatever you want to call it.

What I want to do is have it so that when I am adding a new 'Media' content type, it will automatically figure out the correct image/logo to display once I select the type of Media it is (the 'type' is a list(float) field and also uses a select widget). I hope this makes sense!

Take a look towards conditional fields module. Hope this will helps to solve your issue.
(https://www.drupal.org/project/conditional_fields)


What is the correct way for a Drupal 8 custom theme to override the JS collection renderer? I would like to implement a custom theme, and in my theme, I need to change the way that JavaScript is rendered. By default, Drupal 8 will use the Drupal\Core\Asset\JsCollectionRenderer class, and create a bunch of html_tag render arrays.

I want to change this to allow returning just the name of the JS file, so I can present it in a different way using Twig.

It would appear that I need to define a ServiceProvider class that can register a change to asset.js.collection_renderer (core.services.yml), and implement a custom class to replace JsCollectionRenderer's behaviour.

However, it looks as though I would need a custom module in order to get the ServiceProvider's register() method to fire.

If possible, I wanted to avoid needing a custom module just to have a custom theme, because that seems like needless overhead, so I'm wondering if there's a way to fully encapsulate this behaviour in a single theme, or whether my approach is misguided in some way and there's a better way to handle this.

Themes have no mechanism to provider or alter services. A custom module is needed.


Why don't links use https:// when I access the site using that protocol? The Problem

Accessing my site over https (the only protocol allowed) I get the content, but none of the CSS, images etc.

Drupal is creating pages in response to https requests that include http links to these resources, but it should be using https.

What I've done

I have copied a site to a dev server. The site loads and basically works fine - I can log in etc. It's just that all the links drupal generates are http. The site I've copied it from also runs over https. The site does not exist on http (it would just get a Forbidden error). I've drush cc all.

So Apache's working - I can access the site. .htaccess is working (clean urls work, for example).

I'm using SNI to access the site because the server has other vhosts too, but I'm only accessing the site using the latest Firefox (and as it's a dev site and I'm the only dev, nobody else will use it).

I've done this dozens of times and am quite stumped! Why does Drupal not notice that the request came over https?

The fix

Turns out that .htaccess has this to say:

/* Base URL (optional).

If Drupal is generating incorrect URLs on your site, which could
be in HTML headers (links to CSS and JS files) or visible links on pages
(such as in menus), uncomment the Base URL statement below (remove the
leading hash sign) and fill in the absolute URL to your Drupal installation.

Sure enough, putting $base_url = 'https://example.com'; fixed it.

But why is this necessary?

I had a similar problem and ended up using $base_url = ''. It fixes the problem with static content. Drupal will generate relative URLs instead of absolute which is the right thing to do anyway. However, this breaks update.php for some reasons (running 7.38).


how to reference a field in a field collection in a page.tpl file I have added a field to the basic page content type (a field collection field, to be exact). I want to be able to pull out the content of each field and display it in different format. How can I do this? Which variable contains this data? I am using an override of page.tpl.php.

EDIT:
I did try dpm($node) and I see the field collection field. However this is the structure I see - field_call_to_action['und'][0]['value']  which is equal to 231. I still don't see the actual values of the fields in the field collection.

You may use entity_load. I have a project in which I use Field Collections as you, and this is a fragment of code in my module. I hope it helps you.
The key is the use of entity_load.

    foreach($node->field_imagenes["und"] as $value){
                $a = entity_load('field_collection_item',     array($value["value"]));
                $prefered = false;
                if(isset($a[$value["value"]]->field_prefered_image["und"][0]["value"]) ...