Install multiple apps on a Bitnami stack I am currently transitioning from my Ubuntu 16..04 LAMP Server to a Bitnami 7.59 Drupalstack. However, I discovered that Bitnami does NOT provide instructions / FAQ on how to install multiple Drupal apps onto a single Bitnami Drupalstack, while "snubbingly" providing an instructional FAQ on how to add multiple Joomla Apps onto a single BitnamiJoomlastack... :0

(I am using an Ubuntu 16.04 host with Virtualbox5.1 and Ubuntu16.04 guest to run Bitnami drupalstack7.59)

Therefore, for all you hardcore drupalers I would like to write my own set of docs on how to add multiple Drupal apps onto a single Bitnami Drupalstack.

One Problem:

How do I actually install multiple Drupal apps onto a Btinami Drupalstack?

I was told by Bitnami Community folks that I should simple exchange "joomla" for "drupal" and follow this FAQ which of course did not work.

Along the way, I created my documentation but troubleshooting back-end Bitnami servers is out of my league.

Below are my own configuration notes, derived from attempting follow the bitnami joomla instructions  (i feel dirty..)

Can anyone troubleshoot where I am going wrong?

All I get is error code 404 when I try to visit the newly configured Drupal App... http://127.0.0.1:8080/drupal1/

My Steps To Create Additional Drupal Apps in Bitnami Drupal7Stack

New Document Root  /opt/bitnami/apps/joomla1/htdocs  translates to /home/username/drupal7stack/apps/drupal/htdocs/

Rename default drupal app

sudo mv /home/username/drupal7stack/apps/[drupal-site-name] /home/username/drupal7stack/apps/[drupal1-site-name]

Modify config file located at /home/username/drupal7stack/apps/[drupal1-site-name]/conf/httpd-prefix.conf

gedit /home/username/drupal7stack/apps/[drupal1-site-name]/conf/httpd-prefix.conf

FILE CONTENT{truncated}:

Alias /drupal/ "/home/username/drupal7stack/apps/[drupal1-site-name]/htdocs/"
Alias /drupal "/home/username/drupal7stack/apps/[drupal1-site-name]/htdocs"
Include "/home/username/drupal7stack/apps/[drupal1-site-name]/conf/httpd-app.conf"

Modify the .httpd-app configuration file at /home/username/drupal7stack/apps/[drupal1-site-name]/conf/httpd-app.conf to use the new path:

File Content {truncated}:

    Include "/home/username/drupal7stack/apps/[drupal1-site-name]/conf/banner.conf"

Include "/home/username/drupal7stack/apps/[drupal1-site-name]/conf/htaccess.conf"

Modify the Apache .htaccess file at /home/username/drupal7stack/apps/drupal1/conf/htaccess.conf to use the new path:

File Content {truncated}

RewriteBase /drupal1

Change the name of default db to via phpmyadmin accessible at http://127.0.0.1:8080/phpmyadmin/   (use root login).  Also, create username/pwd of site specific drupal installation

N/A  phpmyadmin GUI

Adjust the settings.php file found at /home/username/drupal7stack/apps/[drupal1-site-name]/htdocs/sites/default/settings.php to the db specific user created in step five

sudo gedit /home/username/drupal7stack/apps/[drupal1-site-name]/htdocs/sites/default/settings.php

restart the drupalstack (apache/mysql), then view new site at http://127.0.0.1:8080/[drupal1-site-name]

For drupalstack use ~/drupal7stack$ ./manager-linux-x64.run , then visit new website

This is not a direct answer to your question. If it wasn't long I'd post it as a comment.
Since you mention configuring a server is not your forte, I'd like to recommend you and other Drupal developers at any level of expertise, an alternative development environment to manage multiple instances of Drupal, and other websites in a Vagrant virtual environment:
Laravel's Taylor Otwell also created Homestead:

Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!
Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 7.2, PHP 7.1, PHP 7.0, PHP 5.6, MySQL, PostgreSQL, Redis, Memcached, Node, and all of the other goodies you need to develop amazing Laravel applications.

It certainly targets the Laravel developers, but I've been using it for most of my local development needs, whether they are Laravel, or Drupal (6, 7 or 8), or any other PHP website.
It makes it much easier to manage any number of websites with different PHP versions, different database needs, and custom hostnames in a single configuration file, to your liking either YAML, or JSON file.
I should mention that I'm not affiliated in any way with Laravel or its creator. I just really like my experience with Homestead so far, and wanted to share.
Go ahead and read its documentation, and install it globally on your machine. Set up a couple websites and give it a try. My guess is you'll have your sites up and running before you can resolve the issues with current Bitnami instance you have.


How to make Drupal 6 search result URL have ".html" at the end? I want the search result URL become

http://www.site.com/search/node/Search for something.html
http://www.site.com/search/node/cars.html

I've looked into custom_url_rewrite_outbound() but there is not much I can understand

custom_url_rewrite_outbound() is not the only function you need to place in settings.php; you need also custom_url_rewrite_inbound(), which converts back the URL to the one known by Drupal.

For those functions, you can use code similar to the following one:

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  if (preg_match('|^search/([^/]+)/(.+)|', $path, $matches)) {
    $path = 'search/' . $matches[1] . '/' . $matches[2] . '.html';
  }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  if (preg_match('|^search/([^/]+)/(.+)\.html$|', $path, $matches)) {
    $result = 'search/' . $matches[1] . '/' . $matches[2];
  }
}


How to add SUM() in Views Like in the given picture

I would like to find and print the sum along with view results. How can I do that?

Try the Views Calc module

This module adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

Image from module page


private file downloads don't work with IE8 only when using hook_file_download I am trying to allow files that are within the /sites/default/files/private/ directory to available to users with correct role and this is working correctly within all browsers (including IE9) except for the IE8 browser.  It does not appear to be a particular file type since it does not work with either .pdf's or .doc's extension.  It their something special that I need to do to the "mime type" so that IE8 will successfully download these files?
I have listed below hook_file_download which determines when a requested file download is allowed based on a combination of the page $url and the requesting users role and I highlighted in bold the bottom of the function where it determines the mime type that is returned.

function atf_retirees_file_download($uri) {
  $user = $GLOBALS['user'];
  $roles = $user->roles;
  $pos_inside_atf_alias = stripos($uri, '/inside-atf/');
  $pos_nibin_alias = stripos($uri, '/nibin-user-area/');
  if (($pos_inside_atf_alias === false && $pos_nibin_alias === false) || ($pos_inside_atf_alias !== false && !(in_array('ATF Retirees', $roles) || in_array('administrator', $roles))) || ($pos_nibin_alias !== false && !(in_array('NIBIN User Area', $roles) || in_array('administrator', $roles)))) {
    return -1;
  } else {
    **$mime_type = file_get_mimetype($uri);
    return array('Content-Type' => $mime_type);**
  }
}

I found that if I added "'Cache-Control' => 'private, must-revalidate'" to the returned array within hook_file_download that the file also downloads for IE8 (see below section).

$mime_type = file_get_mimetype($uri);
return array('Content-Type' => $mime_type, 'Cache-Control' => 'private, must-revalidate');


How to add Login/Register link in the right header in Skeleton theme I am using Skeleton theme with Drupal 7 in my website. Below is a screenshot of it-

As you can see, the right header is completely empty here. I want to add "Login | Register" links in this block in the following manner-

Drupal has this feature where you can create menu links for user/login and user/logout and only the appropriate one will be displayed automatically. Same goes for user/register.

So create a new menu, add links "Login" (user/login), "Logout" (user/logout) and "Register" (user/register). In admin/structure/block move your new menu to where you need, and apply necessary styling.


Drupal 6 - How to programatically create a content type I am creating a module to display a dashboard that shows various stats. One section will be for adding announcements. My thought is that the best way to do this would be to create a custom content type and then pull in the latest announcements from the announcement content type submissions.

My question is how can I create that content type programatically with the proper fields? Where can I go to add those announcements once the type is created? And how can I pull the latest announcements to display on the page?

I'm new to Drupal, so I'm struggling at the moment to learn the proper way to do things.

You can use the Features module to export out the content type and the fields associated with it. Once you have done this you will have a .tar or .zip file of the export code in a functional module.

From here you are able to move that directory into your sites/all/modules directory and have a fully functional module.

Do remember to remove your content type and fields, before installing the module on your site. The new module will recreate them for you.


Trying to integrate Rate-Widget (Rate-Module) into Status-Block (Statuses/Facebook Style Status) With Drupal 7, I am trying to combine the Rate-module and the statuses-module (formerly Facebook Style Status), for my voting widget to show up in status boxes.

At https://drupal.org/node/811742 it explains to implement the hook hook_facebook_status_render_components.

<?php
/**
 * Implementation of hook_facebook_status_render_components().
 */
function MYMODULE_facebook_status_render_components($status) {
  //Only show on individual status pages.
  if (arg(0) == 'statuses' && is_numeric(arg(1))) {
    //Here, the theme function MYMODULE_voting_widget is assumed to take a "type" and "id" parameter, but it may vary.
    return array(
      'MYMODULE' => array(
        'value' => theme('MYMODULE_voting_widget', 'facebook_status', $status->sid),
      ),
    );
  }
}
?>

The README from the rate-module however describes to use the following code:

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
  print rate_embed($node, 'NAME');
}
?>

So I used this latter code and implemented the hook in the rate-module:

<?php
function rate_facebook_status_render_components($status) {
  //Only show on individual status pages.
  if (arg(0) == 'statuses' && is_numeric(arg(1)) && ($node = node_load(arg(1))) ) {
    //Here, the theme function MYMODULE_voting_widget is assumed to take a "type" and "id" parameter, but it may vary.
    print rate_embed($node, 'ratingwidget');
  }
}
?>

I deactivated the module and re-activated it, but nothing shows up.
What did I do wrong? Do I need to include any files from the Statuses-module in my rate.info-file, in order to implement hooks from one module in the other? Did I do something totally wrong and just don't understand the concepts?

Thanks very much in advance.

A couple problems here.

I assume you are using Drupal 7, and therefor this module:
https://drupal.org/project/statuses

Which is the successor of facebook_status module for D6.

Your hook is for the D6 module, and does nothing for the D7 module.

I couldn't find the replacement hook in the new D7 version:
http://drupalcode.org/project/statuses.git/blob/bc7e520:/api.php

The other problem, is that 'statuses' are their own 'entity' - for lack of a better word.  They are not actually even 'entities' in the Drupal terminology.  Just some entries in it's own DB table.

The reason this is a problem, is your code is looking to load a node from path when on a path like (/statuses/5), but a 'status' is not a node.

As far as a solution, you'll have to decide a new road to go down, but at least this helps you understand the situation.


How can I avoid this markup is filtered out from my block? I generated a widget on pinterest. The result is the following:

pinit.js is included in the theme and is available in the page.

I added a block with the following code.

When I saved the block (I used CKEditor), it cleaned. Actually, I don't know if it is cleaned by CKEditor or the full HTML filter.

How can I find out which of those is cleaned out the markup?

If it's due to CKEditor, how can I solve it? The advanced content filter is disabled.
If it's due to full HTML filter, how can I configure it so that only this non compliant syntax is allowed?

NOTE: In the full HTML filter, the checkbox Correct faulty and chopped off HTML is NOT checked.

I've had the same issue with CKEditor removing classes in the past, Full HTML is not the issue.

Add the below code to the end of your CKEditors config.js file, which is found within the CKEditor library code.

CKEDITOR.config.allowedContent = true;

You might find that the file is called ckeditor.config.js and that this is the file that needs to be changed rather than the default config.js. This file can be found in the root of the CKEditor module.


How to know where the value of a field is being stored in I have a field_date in a content type.

I want to do something like this on a tpl.php:

$date->____________ (where the value of the field is being stored)

How can I know this?

Sounds as if you are asking how to see what's available to you in a variable.

Install the Devel module, and just use the dpm() function:

dpm($variable);

It will use Krumo to represent the data you pass and display it on the page. If it's an array, it will show you all the elements, same for objects and so on.


How to display external data using custom form in a Drupal page? I have created a form custom module for get data from an external url.

$requestType = drupal_http_request('http://www.example.in/php/example/getSampleType.php',$options);
$loomType =drupal_json_decode($requestType->data);

This is my Form

Using this result I have created checkboxes and select a value from checkbox then submit the data.

function myForm_form_submit($form, &$form_state) {

$form_state['rebuild'] = TRUE;
$url='http://www.example.in/php/example/exampleSort.php';
//$data1 = http_build_query($form_state['values']['check'], '', '&');

$checked = array();
foreach($form_state['values']['check'] as $key => $val) {
array_push($checked, $val);
  }
$mychecked=checking($checked);

$checkedType = array();
foreach($form_state['values']['checktype'] as $key => $val) {
array_push($checkedType, $val);
  }
$loomType=checking($checkedType);

$datas=array("sampleMachine"=>$mychecked, "sampleType"=> $loomType);
$data =json_encode($datas);
$option = array(
            'method' => 'POST',
            'data' => $data,
            'headers' => array('Content-Type' => 'application/json'),
    );
//$headers = array('Content-Type' => 'application/json');

$response =drupal_http_request($url,$option);

echo "<pre>";
print_r($response);
echo "</pre>";

}

I got some result. Now I want to display those results in my drupal page. How can I do that..I am using Drupal 7.

I want to display this in Drupal page in specific format

Not sure why you want to create a custom module for this, since ... there is a module that can "*display JSON results in a Drupal page" ... i.e. the Views JSON Query module. Some details from its project page:

  JSON Query is a Views 3 plugin that adds native JSON query generation. It allows you to parse JSON using Views' graphical query builder.
  It works much like Views XML Backend but with JSON.

And a screenprint from that same page:

For more details, read about it in the article about "Show external JSON data in Drupal Views".

PS: Similar solution if your input format is XML (instead of JSON), using Views XML Backend.


Why would a field be missing from the Rules data selector? I've added a couple of fields to the standard product bundle included with Commerce, like so:

I'm now trying to add a rule (Data Comparison) based on the "Special Offer Active" field, but for some reason it's missing from the data selector:

The other field I've added ("Special Price") shows up fine.

Anyone know why this might be happening? I've cleared caches a few times and run cron to no avail.

I found the answer in the Commerce documentation:

  This is due to the fact that Rules only knows about the default fields that we tell it should function in a manner similar to entity properties. In order to access additional fields, you have to do one of two things in your conditions:

  Use the Entity has field condition to ensure the field you want to access exists on the variable you want to use it for, or
  Use the Data comparison condition to check the type of the entity (i.e. product type) to gain access to every field on the entity.


Adding form elements via ajax; input not stored in $form_state['values'] I am trying to add a date, start time, end time to a form - the user can add as many 'rows' as necessary.  The form fields are being added to the form correctly, and the $form_state['input'] is showing the correct values that were input on the form. However, the $form_state['values'] is only showing the last one, e.g. if I add three (bringing the total to 4) it only includes the last value.

Relevant code in the form builder:

$num_dates = !isset($form_state['num_dates']) ? 1 : $form_state['num_dates'];
$form_state['num_dates'] = $num_dates;
$form['date']['#prefix'] = '
';
$form['date']['#suffix'] = '
';
for ($i = 1; $i <= $num_dates; $i ++)
{
  $form['date']['calendar_date' . $num_dates] = array(
    '#title' => 'Date',
      '#type' => 'textfield',
      '#maxlength' => 15,
      '#attributes' => array('class' => array('calendar-date')),
      '#prefix' => '
',
  );
  $form['date']['event_start_time' . $num_dates] = array(
  '#title' => 'Start Time',
      '#type' => 'select',
      '#options' => drupal_map_assoc(array(t('9:00 AM'), t('9:15 AM'))),
      '#attributes' => array('class' => array('calendar-date-times')),
  );
  $form['date']['event_end_time' . $num_dates] = array(
  '#title' => 'End Time',
      '#type' => 'select',
      '#options' => drupal_map_assoc(array(t('9:00 AM'), t('9:15 AM'))),
      '#suffix' => '
 ',
      '#attributes' => array('class' => array('calendar-date-times')),
  );
}
$form['add_another_date_time'] = array(
  '#type' => 'submit',
    '#title' => 'Add Another Date/Time',
    '#value' => 'Add Another Date/Time',
    '#limit_validation_errors' => array(),
    '#attributes' => array('class' => array('look-like-text-button')),
    '#submit' => array('exhibitorevents_form_add_date_time_submit'),
    '#ajax' => array(
      'callback' => 'exhibitorevents_form_add_date_time',
        'wrapper' => 'form-date-wrapper',
        'method' => 'append',
        'effect' => 'fade',
    ),
);
    $form['submit'] = array(
  '#title' => 'Submit',
  '#type' => 'submit',
  '#value' => 'submit',
  '#weight' => 100,
);

And the callback functions:

/**
 * Ajax callback for add more dates/times
 */
function exhibitorevents_form_add_date_time($form, $form_state) {
  return $form['date'];
}
/**
 * Submit handler for add more dates/times button
 *
 * Increments num_dates +1
 */
 function exhibitorevents_form_add_date_time_submit($form, &$form_state) {
   $form_state['num_dates']++;
   $form_state['rebuild'] = TRUE;
 }

I have added the $form_state['input'] & $form_state['values'] array here: http://pastebin.com/nL3DWHm8 for reference.  This particular example, I added one date 'row', making 2 total.

You should add the $form['#tree'] so that all the values are passed.


Broken file derivatives when creating an article I recently installed Drupal 8 to familiarize myself with this platform. I've noticed that, whenever I create an Article, and attempt to upload an image for that article, the styles created from that upload don't work and result in broken links.

The image uploads work just fine. Consider the image below:

In the Article view under Add Content, I have uploaded a small 312 KB file.

The thumbnail preview (red) does not work here, nor elsewhere, and attempting to visit the link generated for this thumbnail results in a 403 Forbidden result: mysiteurl.com/sites/default/files/styles/thumbnail/public/2015-12/Untitled.gif?itok=Y40Z0DEa
The link to the image uploaded (blue) works just fine. Clicking that link displays the image: mysiteurl.com/sites/default/files/2015-12/Untitled.gif
Last detail: I see that this error extends to the Styles configuration screens as well, where the default image on the left side displays fine whereas the right-hand, style-applied preview is broken (and attempting to display the image in a new browser tab, just like the preview in the Article screen, results in a 403 Forbidden result).

How would I go about resolving this? I don't think it's GD, following the directions outlined in a troubleshooting page on Drupal (I cannot post more than two links, due to reputation) I see in the Configuration area for my site that I have a writable file system, and GD installed - bundled (2.1.0 compatible).

I may be coming from left field here, but might the 'Styles' directory be the culprit? If there's some way I can have this folder get regenerated by Drupal, I wonder if that would resolve these errors.

Change the ownership of file folder to www-data:www-data and give permission to 755 in recursive way.


How to display a list of users tagged with taxonomy term, but taxonomy term already used in another display I have a taxonomy vocabulary . I already have a view set-up that displays each committee's page using the '/taxonomy/term/%' display. This works great.

Committee:
   - Committee #1
   - Committee #2

My issue is that I would like to have another display that shows committee members (set up as drupal users) that have been tagged with a committee using the term reference field.

Committee #1

Committee #1's Users

Committee #2

Committee #2's Users

How would I get this work. I can't use the path '/taxonomy/term/%' again.

Thank you in advance for any help!

I you just want a view you can use any path you desire, as long as you have the correct contextual filters. Clone the existing view and adapt the path and whatever else you need.


Role cannot create or edit book content I feel like I am missing something obvious that I just can't quite put my finger on.

As an administrator, I see "Add Content > Book page" and "My Workbench > Create Content > Book page" in the admin menu, and I see tabs to create and edit drafts when viewing a book page.

My "book author" role does not see any of this though, despite seeing controls for 3 other content types just fine. The node permissions allow book authors to "Create new content" for the book page type. The 3 other content types also have "Create new content" and no edit permissions, and they all work fine.

For the 3 working content types, if I remove the "Create new content" permission, the admin options disappear from the menu and tabs aren't shown, and the menu and tabs reappear as soon as I recheck "Create new content". So it's just this Book module content type that's giving me problems.

This is a Drupal 7 site, with a few contributed modules that affect content access, such as Workbench Moderation and Organic Groups. I have also tested out some other content access modules in the past, such as Workbench Access and Domain Access. All these modules have long been disabled, however, and I have rebuilt permissions several times since. I suppose it should be noted though that I only just recently enabled the Book module, while the 3 working content types were all in use when I was experimenting with Domain Access, Workbench Access, et al, so maybe there are some lingering settings in the database?

I'm not quite sure why this started working, but all went right with the world when I added the "Book page: Edit own content" and "Book page: Edit any content" permissions for the "book author" role.

Two odd things with this though:

I'm sure I tried this at least once before earlier today
I immediately disabled both permissions again to see what would happen, and nothing did, i.e. the book author role is still able to create and edit draft Book page content... which is good, but weird


Get webform submissions filtered by data value I have 2 webforms set up, one form collects the user email address and emails the user some info, the second form collects their email address again and needs to select the previous form's submitted data from the database and forward this onto a selected user.

Is there an efficient method for selecting webform data filtered by a field, rather than nid or sid, (in my case it would be an email address)?

The $filters parameter on webform_get_submissions() can be used for field filtering. The function's code loops over the filters and adds them as conditions.

foreach ($filters as $column => $value) {
  $pager_query->condition($column, $value);
}

So something like:

$old_form_submission = webform_get_submissions(array('email_field_name'=> $provided_email));


When should I not use Views for listing content? Views is the most popular module of Drupal 7. I don't doubt it's the best solution for listing content on Drupal, as one of the Drupal strengths.

However, Views is not used everywhere. For example, this video shows how to create a product catalog in Drupal Commerce using Taxonomies and Menus.

This question is to ask for the cases where Views shouldn't be used, and why.

That's quite a subjective question, but generally speaking, use Views if

You need it done quickly
You need to allow flexible UI edit access
You don't mind a slight performance hit
You need Views for some other module integration ( VBO, views_data_export etc.. )

Otherwise, you can use custom page callbacks

If you don't mind taking a bit longer to build
You don't need UI edit access
You want the fastest performance.
You want to do something Views can't do, or that is much easier to do custom.
You are a capable developer.


Custom taxonomy page that lists content In Drupal 7, I'm trying to create a page that shows all terms in a specific taxonomy, along with node content that uses the taxonomoy.

What I'm hoping to do is create what's essentially a grid of views, where each term in the taxonomy displays: an image associated with the taxonomy term (the image field was added to this particular taxonomy), and then below it a list of nodes tagged with that term, ideally with each list having its own mini pager (although a complete listing or a partial listing with a "more" link would also work if a pager is not achievable).

I'd also like to do this without Panels, since I'm not using it anywhere else on the site.

Can someone point me in the right direction as to how I should approach this?

The quickest way I know of is by using Views.
I would create a special "content type" with a special image field, a text field to describe the meaning of the Tag, and a Term Reference field to include the applicable tag later. Then I would enter one image + text for each existing tag and assign it to the tag itself. Later with the help of views I would customize display-views like the one you have mentioned which would take just a few minutes to do.


This works as a module, but think it should go in my .theme file instead This is some code which we're using to merge together content types into the body of an article:

<?php

function remove_p($string) {
  $first_p=substr($string,0,3);
  if($first_p=="
") {
    $string=str_replace('
','',$string,$temp=1);
  }
  return $string;
}

function custom_press_release_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node_array = $build['#node']->toArray();
  if ($node_array['type'][0]['target_id'] == 'press_release' || $node_array['type'][0]['target_id'] == 'article') {

    // Get the location entity ID
    $field_name = $entity->get('field_office_location')->getValue();

    $location_id = $field_name[0]['target_id'];

    // Get the location name
    $term_object = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($location_id);

    if(is_object($term_object)) {
      $term_array = $term_object->toArray();
    }

    // Generate output like - December 5, 2017
    $new_time_format = date('F d, Y', strtotime(substr($build['created'][0]['#markup'], 0, -7)));

    // Body text from Drupal
    $old_body = $build['body'][0]['#text'];

    $body = '
';
    if (is_array($term_array)) {
      $body .= $term_array['name'][0]['value'] . ', ';
    }
    $body .= $new_time_format . ' – ';
    $body .= remove_p($old_body) . '
';

    // Modified body text
    $build['body'][0]['#text'] = $body;

  }

}

I think that this would be better done in my theme file, but we weren't able to call the functions we needed within the theme.

Did we just miss something, or is this something that just needs to be done as a separate module?

What you missed is, that you can achieve all that output manipulation by just using the admin UI and view modes. It has the benefit of you being able to adjust the output order and available fields without having to touch any code. And gives you more power and flexibility to administer how content is displayed.

By incident, your solution matches a question answered just recently here: How to modify the value of a taxonomy field of a node using hook_node_view()?

Please have a look to my answer there, which describes how to show a field of the the taxonomy terms on the nodes by using the UI.

You can easily adjust the proceedings by e.g. creating a dedicated display mode for your content nodes instead and adding the required fields there.

Additionally, you like to show the formatted created time, which you can either preprocess within a theme's hook_preprocess_HOOK() (so for example yourtheme_preprocess_node()), but also have already exposed within the template variables as {{ date }} in your node.html.twig template.


How to get the data of field collections I have one field collection with 4 fields. How to get the data of field collection in views tpl file

I am trying to load data as

field_collection = entity_load('field_collection_item', array($node->field_suppliers_value['und'][0]['value']));
print_r($field_collection);

The fields in field collection are one is text field and another one is entity reference and one more is term reference and last one is date type.

I am able to retrieve the data only for text data type and for other data types it was showing as [target_id]=some number.

How can i retrieve the data for other data types except text.

These are the field data types and their column names:

Text - value
Entity Reference - target_id
Term Reference - tid

Combine that with field_get_items(), e.g.:

$items = field_get_items('node', $node, 'field_suppliers_value');

if ($items) {
  // Or $items[0]['target_id'], etc
  $fc = field_collection_item_load($items[0]['value']);
}

Hopefully that'll give you enough to go on.


Formatting output of token I have Drupal Commerce, and it sends confirmation emails after product is sold. In those emails are tokens. I have token [commerce-order:created] and I'm interested if is there any conveniant way to change a formatting of that date.

If [commerce-order:created] is a date token, then you can use [commerce-order:created:custom:<the format you want to apply>], where <the format you want to apply> is the string format accepted by date().

Otherwise, the more generic way to alter tokens implemented by other modules is implementing hook_tokens_alter().

function mymodule_tokens_alter(&$replacements, $context) {
  $options = $context['options'];

  $sanitize = !empty($options['sanitize']);
  $langcode = !empty($options['language']->language) ? $options['language']->language : NULL;

  if ($context['type'] == 'commerce-order') {
    foreach ($context['tokens'] as $name => $original) {
      switch ($name) {
        case 'created':
          // Set a value for $sanitized and $new_value.
          $replacements[$original] = $sanitize ? $sanitized : $new_value;
      }
    }
  }
}

Notice that in my code:

$sanitized is the sanitized value to assign to the token, used only when $sanitize is TRUE
$new_value is the new value for the token, used to obtain the value of $sanitized


Need multiple url paths for single node without redirecting I have the requirement on our Drupal 7 site where if we have a single node we need to be able to have multiple url paths to reach that node.

For instance lets say we have a node with id 1234
Currently we can create an alias for it:
example.com/my-custom-alias

and I can go to example.com/admin/config/search/path/add
and add a second url for this node with id 1234:
example.com/differenturl/my-custom-alias

but when I try to go to:
example.com/my-custom-alias

the browser redirects the page to:
example.com/differenturl/my-custom-alias

What I need is for both urls to resolve to the the same node and for the url to not change (or be redirected).

This is because we use Google Analytics and we need to know from which part of our example.com site our node/1234 is being accessed from.

Currently the only thing that Google Analytics will track is:
example.com/differenturl/my-custom-alias

and won't track:
example.com/my-custom-alias

Does anyone know how I can achieve this?

Decided to solve the issue by adding URL query parameter to designate where the particular page was coming from as per suggestion of leymannx and Rick Harinton.

Thanks for all your help!


Views single field themeing with custom variables How do I pass a variable from a preprocess hook to a template file for a single field, that is view files starting with

  views-view-field--

I want to know what are the preprocess functions that can be used for this purpose. Because, whenever I try to set a variable using hook_preprocess_views_view_fields it is only renderable at sytle/row level, but never at single field level.

Hope Im clear with my query. Any help appreciated.

I think it's just that there are two similarly-named theme implementations: views_view_field and views_view_fields (trailing s). Generally you can take the name of the template file before the first double-dash to find the theme implementation name, so if the template starts with views-view-field-- you'd expect the preprocess to be hook_preprocess_views_view_field(). (That naming pattern's not guaranteed though.)


How to set the size attribute of a select field? When you use a "select" field with multiple values Drupal generates this HTML:

<select multiple="multiple" name="..." id="..." class="...">

How can I inject the size="..." attribute? This will cause the box to show more values.

You might be able to do it with the #size property of the Form API. I am not sure, but you might need to also set the #multiple property to TRUE in order for the #size to be honored.

It it also not clear from the question if you are creating your own form using the Form API, modifying an existing Form API form using a hook_form_alter(), or writing your own form HTML (which I imagine - and hope - you are not doing).


Displaying fields from my content types in a module I am learning how to write modules at the moment. The following piece of code simply pulls out of the database some data and selects just the nid, title and created fields

function photo_gallery_contents($display){

$max_num = variable_get('photo_gallery_max', 3);

$query = db_select('node', 'n')
->fields('n', array('nid', 'title', 'created'))
->condition('status', 1) //Published.
->condition('type','portfolio') // Only want our photos aka Portfolio content type
->orderBy('created', 'DESC'); //Most recent first.

if ($display == 'block') {
// Restrict the range if called with 'block' argument
$query->range(0, $max_num);
} // Now proceeds to execute().
// If called by pge, query proceeds directly to execute()

return $query->execute();

}

This works fine but how do I access the other fields I created for my "portfolio" content type such as "field_image" or "field_category" both of which I added? I just cannot work out how to do this. Your help will be so appreciated!

I've written other hooks that represent this information on the page or block, at the moment I am showing a list of links to my nodes. I want them to be images with links instead:

function _photo_gallery_page() {
$result = photo_gallery_contents('page');
//Array to contain items for the page to render.
$items = array();
//Iterate over the resultset and format as links.
foreach ($result as $node) {
  $items[] = array(
  'data' => l($node->title, 'node/' . $node->nid),
  );
}

if (empty($items)) { //No content in the last 2 weeks.
  $page_array['photo_gallery_arguments'] = array(
    //Title serves as page subtitle
    '#title' => t('All photos from ever'),
    '#markup' => t('No photos available.'),
  );
  return $page_array;
}

 else {
  $page_array['photo_gallery_arguments'] = array(
    '#title' => t('All photos from ever'),
    '#items' => $items,
    //Theme hook with suggestion.
    '#theme' => 'item_list__photo_gallery',
  );
  return $page_array;
}

}

So how do I swap $node->title to show the image instead?

The best way would be to grab just the node ids from the table, and use the node_load_multiple() function to load the node objects.

The field data will be attached to those objects, and you can use other API functions to extract the data/build the display HTML (field_get_items() and field_view_field() respectively).

Some sample code that should help:

function photo_gallery_contents($display){
  $max_num = variable_get('photo_gallery_max', 3);

  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('status', 1) //Published.
    ->condition('type','portfolio') // Only want our photos aka Portfolio content type
    ->orderBy('created', 'DESC'); //Most recent first.

  if ($display == 'block') {
    // Restrict the range if called with 'block' argument
    $query->range(0, $max_num);
  }

  // Fetch the results for the nid field into an array
  $nids = $query->execute()->fetchCol();

  // Load the node objects and return
  return node_load_multiple($nids);
}

function _photo_gallery_page() {
  $result = photo_gallery_contents('page');

  //Array to contain items for the page to render.
  $items = array();
  //Iterate over the resultset and format as links.
  foreach ($result as $node) {
    // Build a render array based on the field's display settings.
    $image = field_view_field('node', $node, 'field_image');

    // Render the array down to the image HTML
    $image_html = drupal_render($image);

    $items[] = array(
      'data' => l($image_html, 'node/' . $node->nid, array('html' => TRUE)),
    );
  }
}


Best practice approach for environment specific keys I'm using encrypt/key/real_aes and lockr to create environment specific encryption profiles. Ie, prod data should never be accessible on UAT, dev, local etc.
What I'm wondering about is whether I can easily swap out field encryption profiles on specific environments, or if I can change the key being used by the environment?
Ultimately, I'd just like keys to be available to their environment only. Lockr helps by never displaying the key, but I can still request the prod key from lockr when on local, etc.
I'm not sure I can do these while keeping my site secure so I'm hoping for some best practice solutions to this.
Thanks.

So, I reached out to one of the authors of key and the lockr service to get some help.
What I learned is, if using the key module without lockr, you can change the value of the key while keeping its machine name the same.
But, if using lockr (and you should be using lockr) it will create and swap keys for you based on your environment automatically. So, your encryption profile will automatically be kept up to date. Awesome stuff.
Hope this is helpful to others, the docs are here; https://docs.lockr.io/#separate-environments


drupal generating image-styles I just wanted to know if there is some way to make Drupal 7 re-build all the images for a specific style. The image style is created after the pictures were uploaded. The module using this image style will be color box.
Even though I update, delete, re-create the style, no images are generated in the according folder on the webspace.

Do you have any idea?

You can use drush to re-build specific image styles. drush image-flush thumbnail will force the refresh of thumbnail styles; you can use drush image-flush to get a list of available styles to clear.

You can find more information on the Drush website.


Div and problem locating their CSS files I'm making my first website with drupal 8 for a university project.

I currently have 2 problems unresolved, the first one is that using the geolocation module to add a google map location is giving me problems, the width is setted at 50% and i can't find the way to change it to 100%, since I can't find the .css file that generate the style from the location page. The code from website that I think responsible is:

<div class="geolocation-google-map geolocation-processed" style="height: 400px; width: 50%; position: relative; overflow: hidden;>

but I don´t know how to change it.

The second problem I have is that just over, it generate a div ("<"div">" Location "<"/div">") with the label title, and I would like to add a .css class to hide, or simply remove it.

PS: I don't know if it's important, but I'm also using drupal 8 zymphonies theme.

Thank you very much.

1) Assuming you already have sub-themed Zymphonies theme, just add this in your sub-theme's stylesheet-

.geolocation-google-map {
width: 100% !important; }

If not, read this documentation on sub-theming and do the above. Same goes for (2)

2) You can target your div (without class or id) using :nth-child() selector

Being a title, it usually is 1st or 2nd child of the view wrapper.If so

.view-name > div:nth-child(1) {
  //styles for a div that is the first child
}

.view-name > div:nth-child(2) {
  //styles for a div that is the second child
}`

Note that the div you're targeting has to be the direct child of its predecessor


HTML markup is removed from email I am trying to send an email with a small html form of hidden fields and a submit button. I have been piecing this together from several very incomplete answers and documentation sources that take several approaches to this but no answer so far has worked for me (so please do not mark this as a duplicate).

I have a module, my_module, and in the my_module.module file I have the following hook.

function ten_sixteen_mail($key, &$message, $params) {
    if (isset($params['subject'])) {
        $message['subject'] = $params['subject'];
    }
    if (isset($params['body'])) {
        $message['body'][] = $params['body'];
    }
    if (isset($params['headers']) && is_array($params['headers'])) {
        $message['headers'] += $params['headers'];
    }
}

Elsewhere in my_module.module I send an email with the following code. I am getting the email, but without the form and button html, only the  text.

$to = "someone@example.com";
$subject = "This is an email subject";
$body = "
Here is some text.
";
$body .= '<form name="someform" action="https://www.example.com/somepage" method="post">';
$body .= '<input type="hidden" name="somecode" value="' . $somecode . '" />';
$body .= '<input type="hidden" name="something" value="' . $something . '" />';
$body .= '<input type="submit" style="padding: 10px; background-color: #d42c2c; border: 2px solid #cccccc;" value="Click This" />';
$body .= '</form>';
$params = array(
    'headers' => 'Content-type: text/html',
    'subject' => $subject,
    'body' => $body,
);

$message = drupal_mail("my_module", "my_module", $to, language_default(), $params, "serviceaccount@example.com");

I have Mail System and Mime Mail installed and enabled.

I'm pretty confused about the config options for both modules. For Mail System I have set the 'theme to render the emails' to my custom theme, though I really don't require any theme-ing of the email it was not an option to disable this.

I have created a new module and key setting with the key my_module for the module my_module.

Mime Mail is set to use the Full HTML Email format.

What am I doing wrong that is preventing my html form from coming through in the email?

The hook_mail headers need to be like this:

$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';


Add prefix / suffix to field by using template_preprocess_field I remember in Drupal 7, this was possible. I need to add some HTML before a field and I don't want to edit it in the Twig file. Is it somehow possible to add prefixes / suffixes by using the template_preprocess_field function?

I already tried something like that, but with no success:

function MYTHEME_preprocess_field(&$variables, $hook) {
    $element = $variables['element'];
    if ($element['#field_name'] === 'field_genre') {
        $element[0]['#prefix'] = '
';
    }
    if ($element['#field_name'] === 'field_duration') {
        $element[0]['#suffix'] = '
';
    }
}

to prefix a paragraph field, this needs to be put into mytheme.theme .

function mytheme_preprocess_paragraph(&$vars) {
  if (isset($vars['elements']['#paragraph']) && ($vars['elements']['#paragraph']->getType() == 'hp_dean')){
    //kint($vars);
    $vars['content']['field_hp_dean_title']['#prefix'] = '
';
    $vars['content']['field_hp_dean_more']['#suffix'] = '
';
  }
}

you can adjust this to your specific hook, like hook_preprocess_node and similar .


Debugging a module upgrade In "Status report" I have message saying that some modules have database schema updates to install. However, when I run update.php nothing happens. I just get the standard error message that "Some of the pending updates cannot be applied because their dependencies were not met."

Reports -> log messages does not have anything relevant.

How should I debug this?

It is possible that a module that you just updated now has a new module dependency. Go to your module listing page and see if any enabled modules now have a dependency listed as missing. Download the missing dependencies, enable and run update.php


Any easy way of implementing a mega menu? Im wondering if there is a easy way to implement the following dropdown menu(ive added a before hovering on a list item, and after):

If i had to do it right now, i would use a bootstrap dropdown, and basically have to create an entire module around making the paths to point in the right directions.

Do you guys know of any existing menus or any easier way of doing this?

thanks

(not a complete answer, but too much for a comment)

The main characteristic of a "mega menu" is that the contents of the menu are not limited to a simple list or tree of menu links. In your own example you have links with descriptions / subtitles, you have a picture, you have multiple columns that probably have nothing to do with a menu tree structure.

This is why you should use tools other than menu links system, for the contents of each megamenu box.

The first step is to forget you are creating a menu, and instead imagine you would be creating custom pages or blocks. How you create these, is a question for itself.

I have heard of someone who used nodes (possibly with pragraphs module), where every megamenu page is a node.

Another option would be to do something with panels.

The next question is how to anchor the megamenu contents to the actual menu items.

The person who used nodes for the megamenu pages (if I remember correctly) used a field where people specify the menu link path. Then when displaying the menu, the contents from the matching node are inserted as submenu.

You could also completely give up on the links being menu links, and instead just display node titles as toplevel items (sorted by whichever criterion), and then the rendered node as "submenus". This could be done with views, if you use a ul/li list as the style plugin (with custom classes) and a special view mode + layout for each item with its megamenu page. The special html you need would be in the custom layout.

Special attention should be given to multiple language versions, and possibly access checks for links. Maybe you use different paths in different languages?

This still requires some creativity in putting everything together.

But the main idea should be to look for solutions outside the menu links system.

EDIT:
I should add: You may want to think about doing something with ajax, to let the contents of the pages load after the main page contents. If I remember correctly, the person I talked to did this somehow, I just don't remember how exactly.

Credits to https://twitter.com/rachel_norfolk


Credit card type in drupal commerce I need to find out what credit card type was used when someone purchased something from my website.

Is it possible to find this out? I was looking through the database tables and couldn't find anything in there. I also looked in the orders payment tab and still couldn't find anything.

Thanks

Drupal commerce does not provide anything for this. Actually it must not do it since payment companies require (and often make it completely impossible) to know the credit card properties.

Your only hope is what might be stored in the commerce_payment_transaction table by the payment gateway. Often additional data is stored as a serialized PHP object in the payload filed.

If you don't find anything there, you might have to dive into the specification of the payment getway company and check whether they provide this information via the API. If you are lucky this might be integrated into the appropriate drupal commerce payment getway.


How to get select option id value in form api Hi hello please help how to get dynamically selected option id value (i.e #options=>0=>'bala',1=>'kumar')

for example
how to get selected value of ID value in form api in drupal

$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

the selected value store in $key value, please help me how to do....

$key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

is this correct???

You can get the value using:

$form['field_name'][#options][$form_state['values']['field_name']]


Pager with EntityQuery how can I make a pager with the pager class? I could not find anywhere how to do this with the EntityQuery class. I have a pager(10) that displays the last 10 items. I want to make a pager with numbers like
< 1, 2, 3, 4, 5, 6 >.

This is the code I have now:

class NewsArchive extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Query for newest articles and return max 3 results.
    $query = \Drupal::entityQuery('node');
    $news = $query->condition('type', 'news')
      ->condition('status', 1)
      ->sort('created', 'DESC')
      ->pager(10)
      ->execute();

    // LoadMultiple News in $nodes variable
    $nodes = Node::loadMultiple($news);

    $path = base_path();

    // Return $nodes variable with name items to the module.
    return array(
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    );

  }
}

I have read somewhere that this was possible with the following code:

      $build['pager'] = [
        '#type' => 'pager',
      ];

How does this build pager (render) fit into my code? Can someone show me how to start?

Add the pager to the build array in which you return the results:

  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    ],
    'pager' => [
      '#type' => 'pager',
    ],
  ];

Or extend the theme with a variable #pager if you want to theme this in one place:

  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
      '#pager' => [
        '#type' => 'pager',
      ],
    ],
  ];

Then you can print the pager in twig:

{{ pager }}


my module template_preprocess is not called I can't figure out how to correctly implement the theme mechanism in my module. The hook just doesn't get called, after flushing registry ofc.

My mymodule.module contains a function (this function gets called, no problem, I give it just for illustration):

function mymodule_node_view($node, $view_mode) {
  ...
  $node->content['mymodule_tocteasers'] = array(
    '#markup' => theme('tocteasers', array('tocteasers' =>  "whatever")),
  );
}

As I understand the theme mechanism, in order to render tocteasers hook, the module should implement it. Here is my module's implementation, which is not called at all, ever:

function template_preprocess_tocteasers(&$variables) {
  $variables['content'] = "something!!!";
  dsm($variables); print "hello";
}

^^I also tried function mymodule_preprocess_tocteasers(&$variables) without success

In addition, I have a file named tocteasers.tpl.php in my module directory, containing:

<div>
  <?php print "!!"; ?>
  <?php print $content; ?>
</div>

This also does not get printed or called.

Can someone plese advise me, how to make this implementation so that the tocteasers.tpl.php file is used and gets the $content variable as intended?

What you don't report in your question is the hook_theme() implementation, which is necessary for Drupal to know the theme functions a module implements. In your case, the array returned from hook_theme() should be something similar to the following (supposing that your module defines just a theme function).

  return array(
    'tocteasers' => array(
      'variables' => array('content' => 'the default value'),
      'template' => 'tocteasers',

      // Use it only if the template is not in the same directory the module is located.
      // This path should be relative to the Drupal root directory.
      'path' => 'the directory where the template file is located',
    )
  );

Notice that:

You call the theme function with theme('tocteasers', array('tocteasers' =>  "whatever")), but the template file is not using $tocteasers.
The template filename must be the same used for the theme name; in your case as the theme function is tocteasers, the reported template filename must be "tocteasers". The extension ".tpl.php" is not used, as it is automatically added by Drupal when it looks for the template file. The only allowed difference between the theme name and the template filename is that the template filename can use "-" where the theme name uses underscores. This is because the "-" character is not allowed in a theme name, which must use the same characters used in a PHP function name. (This means it cannot start with a number, for example.)
If you are altering the code of an existing, enabled module, Drupal caches the data returned from hook_theme(); the result is that you had a theme function that was not using a template file, and that has been modified to use it, Drupal will not use the template file because it still referring to the old definition. hook_theme() is called in some specific cases, such as when a module is disabled, enabled, or updated. To force Drupal to update its cached data, you should disable and re-enable the module from the administration interface.
dsm($variables) could not show anything, if it is called too late, i.e. when the messages set with drupal_set_message() (the function used from dsm()) are already rendered. For those type of debug messages it's better to use watchdog(), which saves the message in a database table. Drupal allows to see those messages in admin/reports/dblog, and defines WATCHDOG_DEBUG for this very purpose.
Both template_preprocess_tocteasers() and hook_preprocess_tocteasers() are used, the difference is that template_preprocess_tocteasers() is defined from the module implementing the theme function, and it is called before hook_preprocess_tocteasers(). The purpose of the preprocess functions is not printing anything, but altering the variables passed to the template file, or the theme function. As consequence, the following code doesn't work as expected (i.e. "hello" is not in the output of the theme function).

function template_preprocess_tocteasers(&$variables) {
  $variables['content'] = "something!!!";
  print "hello";
}


How to pre-generate image styles after image is uploaded Is there  a quick way in Drupal 7 to generate image styles straight after the image is added to the image field?

You can look into Image Style Pregenerate module to generate images.


How to redirect user when new node save by ajax in advance form block drupal 7? I have a website in drupal 7. I used advanced form block module to create add form block. Advanced form block module create block for form to edit and add new content. All node saved by ajax submission.

I want to redirect the user when new node save by this form. I used rules and form[#redirect] method in my hooks, but these are not working.

Can any one help me to figure out this?

Thanks

A form[#redirect] will not work in an AJAX form.

You can use an AJAX redirect command from CTools: ctools_ajax_command_redirect

To do this, you should probably have to alter the form and use your own callback function returning the ajax command (along other needed data). I don't know advanced form block module so I can't say how difficult it is.

Example from http://dropbucket.org/node/1236:

  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  $commands[] = ctools_ajax_command_redirect($path);
  print ajax_render($commands);


How to change the target of a file for a multiple file field in drupal 8? I have a content type with a file field: field_document.

It contains multiple files.

I chose Generic file as display format in manage display setting.

I need to change the target attribute of the files that drupal generates for me. How can I do that?

So instead of this

OUTPUT from 'core/themes/stable/templates/field/file-link.html.twig'

  Test Document

I would need this: target="_blank"

  Test Document

You can do this in a hook, but also in a custom file-link template in your theme. Check if the file link has a class specific to a pdf file and then set the target attribute:

file-link.html.twig

{% if attributes.hasclass('file--application-pdf') %}
  {{ link }}
{% else %}
  {{ link }}
{% endif %}


Subtheme media query CSS in Omega Kickstart subtheme I want to build a site based off of Omega Kickstart which is a subtheme of Omega.  Of course I want to layer in my changes sparsely so I made a subtheme of Omega Kickstart.

All the guides out there for doing this assume that you only want one global CSS file in your new subtheme.  That seems crazy to me -- I want to follow the same mobile-first pattern in my subtheme and individually override each targeted CSS file i.e. alpha-default.css, alpha-default-narrow.css, etc...

Is this possible?  To have both omega-kickstart-alpha-default.css and MYTHEME-alpha-default.css?

Everything I try seems to want to override omega-kickstart*.css with MYTHEME*.css.  And it seems to defeat the whole purpose of subtheming to copy omega-kickstart*.css over to MYTHEME*.css.

I had similar issues like this. I ended up simply overriding the CSS file in my template.php. I created a helper for me to do this. Simply run hook_css_alter and replace the file you are targeting with your own. In this case, the omega theme's grid file is here:

sites/all/themes/contrib/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-24.css

And I am replacing it with:

sites/mysite.com/themes/my_theme/css/grid/alpha_default/wide/alpha-default-wide-24.css

This is the code in my template.php

/**
 * Implements hook_css_alter().
 */
function my_theme_css_alter(&$css) {
  $themePath = drupal_get_path('theme', 'my_theme');
  $newCSS = array(
    'sites/all/themes/contrib/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-24.css' => $themePath.'/css/grid/alpha_default/wide/alpha-default-wide-24.css'
  }
  _my_theme_replace_file($css, $newCSS);
}
/**
 * Helper function to replace an existing file with a new path
 */
function _my_theme_replace_file(&$files, $newFile) {
  foreach($newFile as $oldpath => $newPath) {
    if(isset($files[$oldpath])) {
      $files[$newPath] = $files[$oldpath];
      $files[$newPath]['data'] = $newPath;
      unset($files[$oldpath]);
    }
  }
}

The helper function _my_theme_replace_file simply loops through the array, finds the old path and replaces it with the new one.

I hope this helps.


How to display the recent user revision in a views block with contextual filters? We are having a Setup where we need to be able to display User Revision Fields via Views Blocks. We are using the User Revision Module and even fixed a Bug on the Contextual Filter Plugin of that Module.
Lets say the Url is /user/abc/revision/123 everything with a Contextual Filter for the VID on the Path works fine.
The Problem comes when we want to display the last Revision trough the same View because it has not the Revision Url pattern. it is only user/abc
Do i have to write a custom Contextual Filter which can differentiate the Url ? And what is then used instead of the VID ?

I ended up using PHP Code in the contextual filter:

$cpath = explode('/',current_path());
$path_uid = $cpath[1];
if (array_key_exists(3, $cpath)) {
  $path_vid  =  $cpath[3];
  return $path_vid;
}
else {
  $result = db_query("SELECT vid FROM {user_revision} u WHERE uid = (:uids) ORDER BY vid DESC LIMIT 0,1", array(':uids' => $path_uid))->fetchField();
  return $result;
}

Would be nice to put this in a custom module so if have to make changes and do not have to touch every display of the view.


Arguments of hook_file_download_access_alter() function hook_file_download_access_alter(&$grants, $field, $entity_type, $entity) {
  // For our example module, we always enforce the rules set by node module.
  if (isset($grants['node'])) {
    $grants = array('node' => $grants['node']);
  }
}

The arguments $field, $entity_type, $entity are not used in the  implementation. What are these arguments used for, when the function is called?

You do not need to use $field, $entity_type and $entity in your implementation of hook_file_download_access_alter(), if you do not want to.

You should use theses arguments if you need to handle files differently depending on which field of which entity they belong to.

For example, node_file_download_access() restricts access on files to people that can view the node. If you want to remove this restriction for nodes of a specific type foo, you would have to check whether $entity_type == 'node'and whether $entity->type == 'foo' and grant access if this is the case.


Move, style or remove title in taxonomy template I would like to remove the title from rendering in the natural taxonomy page template so that I can add it in the teaser and reorder the fields. Currently, the title shows first, and then the other fields in the teaser display. When I view the "Manage Display" for the teaser view mode, the title field is "hidden" and if I show it, it ends up appearing twice. I would like to unhide it, define a specific class reorder the fields.

Can this be done without an added module? I have already played around with taxonomy view but am asking for an alternative that doesn't require using the taxonomy view, which I have disabled for the time being. E.g. If I need to edit the template, which template would it be and what specific way does it need to be edited to remove the title? My site is complex with a bootstrap theme and a sub-theme that I purchased as well as my custom modifications.

See screenshots below for a visual.

Teaser with title hidden

Shows title at the top without defined class

Teaser with title shown and class defined

Shows title twice

I want to make the one at the top go away or show it where the other one is with the proper class.

Bonus:
I really want to add author and date information like in the screenshot below to the taxonomy template, which I pulled from my taxonomy view version before I disabled it.

Option one might be to change the template tpl for your taxonomy page. You can also create a new view for your page.


How do I forcefully uninstall any module having content? I want to uninstall the Field module, but this module can not be uninstalled; when I try, I get the following message.

  Field API to add fields to entities like nodes and users. Machine
  name: field Version: 8.0.6 Required by: TextNodeAdmin ToolbarAdmin
  Toolbar Extra ToolsFileOptionsAggregator (disabled) ImageAccelerated
  Mobile Pages (AMP) (disabled)Custom BlockBook (disabled)Text
  EditorCKEditorCommentInterface TranslationConfiguration Translation
  (disabled)

How do I forcefully uninstall any module that is having dependency or content inside, for example the Node module, the Views module, or any entity having content in it?

I tried using \Drupal::service('module_installer')->uninstall(['admin_toolbar']); but then my site breaks.

For example, I made any custom content entity type and add content
  into it. Now I can not uninstall my custom module until and unless I
  delete all content or truncate module specific db table – Sugandh Khanna.

Unfortunately, in Drupal 8 you can't disable a module, like you can in Drupal 7.

In Drupal 7 you need to disable the module first, which means all module related code stays in DB. Then, if you wanted, you Uninstall to remove everything from DB.

In Drupal 8 the only option is to uninstall the module, which means you have to destroy all traces of your module from the Database. You cannot just disable the module anymore.

Also, to uninstall Flag (as in your comment here), you have to uninstall dependencies first, then and only then, it will allow you to uninstall Flag. Because if module X depends on Flag and somehow you removed flag, it will totally screw up module X, X becomes useless, module X is nothing without Flag. Therefore you need to remove module X first, then and only then it will allow you to remove Flag.

For more info: Why can't I uninstall modules in Drupal 8? (Explained)

Issue: Disabled modules are broken beyond repair so the "disable" functionality needs to be removed


Custom Gallery images showing in one column In Drupal 7, I have created a custom gallery, but all images are showing in only one column.

I have Bootstrap theme for Drupal. I'm using the modules Views (Bootstrap), Colorbox, Multiupload Imagefield Widget, Multiupload Filefield Widget (both for multiimage uploads).

Steps I took:

I created a new content type Gallery
Added an image field to the content type and selected multiload (to enable upload of several images at once)
Removed body field as I only need images.
Image display has been set to Colorbox (I previously created different image styles - preview, full, etc.)
In Views, I created a new page Galleries, which contains all galleries that I have on the site. I had no problems putting those Galleries in a 4 column layout. So basically this is a Albums view.

My problem is that when I click on Album name, a new page (of content type Gallery) opens. It contains all the images of the particular album. However, all the images are shown in only one column.

I have tried to change the layout with panels and display suite, but as Images are considered as one field, the end result stays the same. Is there any way I could change the steps I took and do this differently, so I could have the Gallery with listed Albums as I have now, and then when I click on albums the images are shown in 3 or 4 column layout?

Thanks

Its has multiple ways to do that but I recommend you to do it with views.

Create a new views as block view and follow the following steps:

Add image field in fields
Add filter criteria
You can change the FORMAT of the views as you like (according to your requirement you should select Grid type) to display images in multiple columns.
Add a contextual filter with nid (node ID) field and set it like this
Save the views and go to admin/structure/block and enable your block
Don't forget to hide the image field in the manage display of Gallery Content Type, path is admin/structure/types/manage/CONTENT-TYPE/display

Image as Example

For more details, click here


Linked entity references in a content type I am unsure if this is possible in Drupal 7, but here is my problem: I have 3 content types, A, B and C.

B and C refer to A through a field field_A (entity reference).

C refer to B through a field field_B.

When creating/editing B, I want the user to select one node A1 of type A, and then, select some node of type B that refer to the node A1.

For example, let's say I have these nodes:

- A1, A2
- B11, B12 referring to A1; B21, ..., B24 referring to A2

A user creates new content of type C, and selects A2: I want the user to be able to select items of type B among the list B21, ..., B24.

I started to use an entity reference view to populate the list of B in C, but then was stuck because it is not possible (or I could not manage to do it) to refer to a field of the edited content type.

Thanks for any help!

Actually, while looking at the hierarchical_select module, I found a module which is (almost) working - the "Dynamic dependent fields" module.

It does not work yet with multiple values though.


How to download file upon submitting a form? I have a form with the submit button.
And I have a file in '/sites/default/files/tmp/my_doc.docx'
I'm trying to download the file upon submitting the form.

Here is my code

public function submitForm(array &$form, FormStateInterface $form_state){
   $filename = '/sites/default/files/tmp/my_doc.docx';
   $response = new BinaryFileResponse($filename);
   $form_state->setResponse($response);
}

But it doesnt't work properly.

That is, the file is being downloaded but has the same name that name of php file containing this code.

Could you clarify me, what have I done wrong ?

You need to set the filename with setContentDisposition, as the constructor only takes the file, but doesn't set the name itself:

$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'my_doc.docx'
);

Don't forget to add use Symfony\Component\HttpFoundation\ResponseHeaderBag; at the top of your file.

There is quite a bit more you can do with BinaryFileResponse as well, so check out some of the methods.


How to exclude some keywords from a search with Search API? I can't find how to do boolean search, and ignore some keywords from a search.

I would like to do a search like "house+garden" - parking, which return all the nodes containing house, and garder as keywords, but not parking.

How is it possible?

I believe the "custom_search" module can do that. http://drupal.org/project/custom_search

Although I don't know whether the exact boolean syntax is used, I know the module offers two ways to search in the way you want:

With three different text fields (one for OR, one for AND, and one
for WITHOUT)
With one text field (By using some kind of syntax like
you described)


Force user to fill in at least text area or file A registered user is creating a node with a body and file field. I want to force the user to either fill the body with 300 chars or select a file. At least one needs to be selected/filled.

How can I do it?
Can I do this using the Rules module?

I don't know how you could achieve this with rules. You could however create a small custom module that adds a form validation function to the node edit form. The validator would check that the appropriate conditions are met.

Edit: something like this would work I think for content type page.

/**
 * Implements hook_form_FORM_ID_alter for page_node_form.
 *
 * @see module_validate
 */
function module_form_page_node_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'module_validate';
}

/**
 * Form validator for page_node_form.
 */
function module_validate($form, &$form_state) {
  // This strips HTML tags - to disable, remove the filter_xss() call.
  $body_length = drupal_strlen(filter_xss($form_state['values']['body'], array()));

  // We're assuming the field is called 'file' and we're checking the first file.
  $file = $form_state['values']['field_file'][0];

  // Rather than checking against 300, we should perhaps call node_get_types()
  // and find the configured word limit.
  if (body_length < 300 && !$file['fid']) {
    form_set_error('body', t('Please ensure that you either enter 300 characters into the body field, or upload a file.'));
  }
}


How to output a screen from a submit handler? (D7) Based upon a form's values In my submit handler I build the output screen and display it with a drupal_set_message();. I'm trying to figure out how to display the information on a page. I can't find any examples. I've created a theme, which is probably unnecessary, but again, I don't know how to display it.

You want output form values after form on submit?

function mymodule_myform($form, $form_state) {
  $form['mytextfield'] = array(
    '#type' => 'textfield',
    '#title' => 'My Textfield',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  if (isset($form_state['values'])) {
    $form['page_output'] = array('#markup' => 'Submitted value: ' . $form_state['values']['mytextfield']);
  }
  return $form;
}

function mymodule_myform_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


How to add html to the "My user points" page (user points module) I am building a Drupal 7 site using the User Points module.

I have some issues that I am not able to solve, you can see the issue here.
I can go around these issues if I will be able to edit the HTML of the "my user points" page (the page that every user can see the points he got and the reason he got them).

Mainly, I want to add a link in this page, that will link to another page on my site.
In addition, I want to add some text beneath the title of the page (original title).
Third thing I want to do is make sure the output on the "Reason column" will be longer, and won't cut off and be too short with "..." in the end.

How can I achieve that?

Where and how I can find the HTML of this page, and edit & add some HTML code?

You can find the menu path defined for " My User Points " page in userpoints.module file in hook_menu implementation..

  $items['myuserpoints'] = array(
    'title' => 'My !points',
    'title arguments' => userpoints_translation(),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('userpoints_list_transactions'),
    'access callback' => 'userpoints_access_my_points',
    'file' => 'userpoints.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu',
  );

As you see above..

Page callback drupal_get_from with arguments "userpoints_list_transactions" is defined in "userpoints.pages.inc" file...

/**
 * Displays a detailed transaction report for an individual user.
 *
 * @param $account
 *   For which account to display. Defaults to the current user.
 */
function userpoints_list_transactions($form, &$form_state, $account = NULL, $tid = NULL) {

  // If this is an AJAX request, update $_GET['q'] so that table sorting and
  // similar links are using the correct base path.
  if ($_GET['q'] == 'system/ajax') {
    $q = 'myuserpoints';
    if (!empty($account)) {
      $q = 'user/' . $account->uid . '/points';
    }
    $_GET['q'] = $q;
  }

  if (empty($account)) {
    global $user;
    $account = $user;
  }

  $settings = array(
    'show_user' => FALSE,
  );
  $header = userpoints_get_transaction_header($settings);

  $query = db_select('userpoints_txn', 'p')->extend('PagerDefault')->extend('TableSort')
    ->fields('p')
    ->condition('p.uid', $account->uid)
    ->orderByHeader($header)
    // Enforce consistent sort order.
    ->orderBy('p.txn_id', 'DESC')
    ->limit(variable_get(USERPOINTS_REPORT_LIMIT, 10));

  if (module_exists('taxonomy')) {
    $query->leftJoin('taxonomy_term_data', 't', 'p.tid = t.tid');
  }

  $unapproved_query = db_select('userpoints_txn', 'p')
    ->condition('uid', $account->uid)
    ->condition('status', USERPOINTS_TXN_STATUS_PENDING);
  $unapproved_query->addExpression('SUM(points)');

  $values = userpoints_filter_parse_input($form_state, $tid);
  $active_category = userpoints_filter_query($query, $values);
  userpoints_filter_query($unapproved_query, $values);

  if (isset($active_category)) {
    drupal_set_title(t('!Points for @username (%category category)', userpoints_translation() + array('%category' => $active_category, '@username' => format_username($account))), PASS_THROUGH);
    $total_title = t('Total !points (%category category)', userpoints_translation() + array('%category' => $active_category));
  }
  else {
    drupal_set_title(t('!Points for @username', userpoints_translation() + array('@username' => format_username($account))));
    $total_title = t('Total !points', userpoints_translation());
  }

  $rows = array();
  foreach ($query->execute() as $transaction) {
    $rows[] = userpoints_get_transaction_row($transaction, $settings);
  }

  // Store context in the output array so that modules have access to it.
  $output = array(
    '#account' => $account,
    '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'userpoints') . '/userpoints.css',
      ),
    ),
  );

  $output['form'] = userpoints_filter_form($account, $values);

  $output['list'] = array(
    '#type' => 'container',
    '#id' => 'userpoints_list_wrapper',
  );
  $output['list']['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No !Points earned', userpoints_translation()),
    '#weight' => -5,
    '#attributes' => array('class' => array('userpoints-myuserpoints-list')),
  );
  $output['list']['pager'] = array(
    '#markup' => theme('pager'),
    '#weight' => 0,
  );

  // Fetch pending (not yet approved) points according to the category filter.
  $pending = (int)$unapproved_query
    ->execute()
    ->fetchField();

  // Display both pending and approved points in a simple table.
  $output['list']['summary_table'] = array(
    '#theme' => 'table',
    '#header' => array(
      array(
        'data' => $total_title,
        'colspan' => 2,
      ),
    ),
    '#rows' => array(
      array(
        'data' => array(t('Approved !points', userpoints_translation()), userpoints_get_current_points($account->uid, isset($values['tid']) ? $values['tid'] : 'all')),
        'class' => array('userpoints-myuserpoints-total-approved'),
      ),
      array(
        'data' => array(t('Pending !points', userpoints_translation()), $pending),
        'class' => array('userpoints-myuserpoints-total-pending'),
      ),
    ),
    '#weight' => 10,
    '#attributes' => array('class' => array('userpoints-myuserpoints-total')),
  );

  // For simplicity, the generated output is passed to a custom alter function.
  // This would also be possible through hook_page_alter(), but that hook is
  // hard to use.
  drupal_alter('userpoints_list_transactions', $output);

  return $output;
}

In the end you can see generated output is passed to a custom alter function

  drupal_alter('userpoints_list_transactions', $output);

By implementing hook_TYPE_alter()  in your custom module you can able to change the output..
i.e YOURMODULENAME_userpoints_list_transactions_alter function you need to implement..

/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
}

$output is a form variable.. You can add a new element to $output ..

/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
  $output['custom_text']['my_link'] = array(
    '#markup' => l("LINK", "Your Link"),
  );
  $output['custom_text']['my_text'] = array(
    '#markup' => 'Blah Blah',
  );
}


Sorting with Voting API I know a lot has been written on this issue already but I found no clear answer.

Here it is:

With the Voting API and another module such as Fivestars or Rate, how do you rank the results within results?

Let me give an example: With views, I can have a proper display of all the nodes that have received, say, 5 stars followed by all those that received 4 stars and so on. So the nodes are grouped properly.

But to rank the nodes within each group (i.e.: The 5 star node that have received the most number of votes being displayed first followed by the 5 star node that come in second position, etc. How does one set that in views?

At the present, I have no sorting within each star group so a node that has received one 5 star vote comes before one that has received three 5 stars, followed by one with that received two (1-3-2.)

My setting are:

Relationships: Content: Vote results -- Value type: No filtering -- Aggregation function: Average vote.
Sort criteria: Vote results: Value (desc.)

It looks like I need an additional sorting mechanism but i can't find it.

Any one has an answer for this? I am not a programmer but a site builder. :)

Thank you. :)

Never mind I think I finally found the solution:

In addition to the settings above, I added a second relationships: Content: Vote results. It's the same relationship as before but instead of "Average vote" in the Aggregate function, I have "Number of votes." So as to avoid confusion, I also changed the identifier to: "Vote results (rank in group)"

So, I have two relationships, almost identical except for the Aggregate functions.

Then, in addition to the sort criteria described above, I added the same criteria again except that I chose the second relationship ("Vote results (rank in group)") instead. Order is also descending.

And that gave me the desired results: Nodes are properly ranked within the groups.

You can test this by enabling  Text to display under the stars: Both user's and average vote in the rating field.

:)

Hope that helps.


views use the same css class for both sidebar and article, blocks me from resizing main content I have a front page view of articles that are displayed as trimmed as well as a sidebar block. This is all fine I have my layout all good. The issue is, if I click on an article to go to it's full page view then the article retains the css class from the front-page so I am stuck with a 70% full page article.

The main issue is that both my articles and latest articles (sidebar) use the same class name "content". I tried to edit templates in order to override this but to no avail. All blocks use the "content" class which makes it uneditable!

edit in fact every block I have uses the class="content"!

Any help would be appreciated!
Cheers!

Surely you can either define different classes for the teaser and fullpage views of your content type using templates, edit the views template or define your css using the class .front or .node-type-article ?

For 1) create a node--content-type-name.tpl.php file and use the if (!$page) { // teaser view switch to output a different class or template.

For 2) create a views-view-unformatted--view-name.tpl.php file and wrap it in a different class

For 3) use the built in drupal classes that are outputted into your themes body tag in your themes html.tpl.php file with <?php print $classes; ?>. Edit your css to specify your style usinf .front .article {} .not-front .article {} etc ..

Or edit your block.tpl.php file and remove the class .content


Endless Redirection of Drupal on IIS I just transferred a Drupal 6 website from an Apache-based dev environment to an IIS-based production environment. Now I am getting a "too many redirects" error.

What could be causing that and how do I fix it?

Need more info! The Devel module has an option for interrupting page redirection and displaying the page you're about to be forwarded to - very handy for debugging redirection. Common redirection issues stem from Rules, Context, Delta, and even just the URL Alias system within Drupal itself.

The transition from Apache to IIS is an interesting hint though - any chance we can take a look at your .htaccess and web.config files to check for differences? Something else to watch for could be trailing slashes and the difference in server handling, as well as the user that PHP is running as under a possibly different CGI.


How can I hide the Organic Groups Audience selection? I don't want the OG audience selection to appear on a custom content type I have created for groups.  I'm only providing the link to create the custom content within a group so the group they are in is pre-selected and it makes no sense to display it.  I can't believe there is not a OG option to turn this off so how can I accomplish this?

You can set #access to FALSE to hide elements like this:

/**
* Implements hook_form_alter()
**/

function yourModule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'yourFormId':
      // We should remove the group check box from users, Its always going to be
      // checked for project content type.
      $form['group_group']['#access'] = FALSE;
      $form['group_access']['#access'] = FALSE;
      break;
    }
}

Above I removed the check box that says "group" and group audience.


What to use for node_prepare in Drupal 7 I am converting a module from Drupal 6 to Drupal 7. I have come across a Drupal 6 functional call named node_prepare and I am not sure what needs to be done to make this work with Drupal 7. What should this function be replaced with?

Thanks.

You don't need to replace it with anything as it happens, you can just remove it.

All that function does is prepare the node body for display. Since the body is a field in Drupal 7, all that processing is done elsewhere, and it's not something you need to invoke manually any more.


Can't save location when posting node through services module I am using services module to post nodes using rest/json. The nodes also contain images and location. So far I can upload the image and save the node, but the location is not saved. I receive no errors in logs.

Any ideas? Is there something I have to add,maybe permissions, in order to be saved?

This is the json that creates the article but doens not save the location.

{
    "title": "some title",
    "type": "article",
    "language": "el",
    "body" : {
          "und": [
              {
                  "value": "some text"
              } ]
    },
    "field_tags": { "und": "9" },
    "field_image": {
        "und":
          [{
            "fid": "1364"
          }]

    },
    "locations":{
        "und":[
                {
                  "country":"gr",
                  "latitude":"55.7046601",
                  "longitude":"13.191007300000024",
                  "name":"TEST LOCATION",
                }
            ]
    }

}

How are you storing the location? Node location? Location CCK field?
take a look at:

https://www.drupal.org/node/906968

If you are using a CCK location field you should disable node location module.

Or if you aren't you could switch to a location field.

As a last option you could put latitude and longitude in their own text fields (like field_latitude and field_longitude) since gmaps module can take lat and lng from text fields.

  you can use CCK location which allows you a geolocation field, it
  comes with location module:

  https://www.drupal.org/project/location


Form API Ajax trigger callback with size of input I use the API Form of Drupal 8 to create my form.
I had an ajax callback on a field:

$form['association']['numero'] = array(
        '#type' => 'textfield',
        '#title' => t('foo'),
        '#size' => 10,
        '#maxlength' => 10,
        '#suffix' => '

',
        '#ajax' => [
            'callback' => '::fetchApiData',
            'event' => 'change',
            'prevent' => 'click',
        ],
    );

with my callback function :

public function fetchApiData(array $form, FormStateInterface $form_state)
{
    return 'foo';
}

It's all working fine, but i want to trigger the callback when the user writes 10 characters precisely. Does anyone has a solution for that?

You can do this:

1) Decide on an event name. In this code, the event name will be 'overminlength'

2) In the form element being defined using the Form API, set your #ajax as normal, but set the #ajax 'event' to the event name chosen in step 1:

'#ajax' => [
  'wrapper' => 'some_wrapper',
  'callback' => 'some_callback',
  // Set the custom event here:
  'event' => 'overminlength',
],

3) Create a custom JS file and attach it to the field

'#attached' => [
  'library' => ['mymdodule/mylibrary'],
],

4) Add a $.keyup() listener to the field.

In the callback, count the number of characters in the field
If it's more than X characters, call $.trigger(), and trigger the event from step 1

(function($, Drupal) {

  "use strict";

  function fieldwatcher(context) {
    $(context).find("#edit-myfield").once("fieldwatcher").each(function() {
      $(this).keyup(function() {
        // Change '3' to the number of characters after which you want to
        // trigger the ajax.
        if ($(this).val().length > 3) {
          $(this).trigger("overminlength");
        }
      });
    });
  }

  Drupal.behaviors.testScript = {
    attach: function(context) {
      fieldwatcher(context);
    }
  };

}(jQuery, Drupal));


how i can reset the page num to 1 when i change to another exposed filter option? Now,i have a view page with exposed filter(filter option:filterA,filterB) and full pager

when i go to the 3rd page of  filterA , change the filter option to filterB ,i find the page redirect to the 3rd page of filterB ,what can i do to let it redirect to 1st page of filterB

Create new filter group in the "Filter Criteria" section of view and add move both the exposed filters in the new group and than apply the "OR" operator between them as below:


How to pass argument to php file using a drush command? I've small php script in my public folder called sample.php. I run this file using drush command drush scr sample.php.

I want to know how to pass argument to php file using drush command and how to get arguments in php file?

This is explained quite nicely in drush topic scripts.

Your script should start with:

#!/usr/bin/env drush
<?php

Then, you may call your script directly. For example, if you have saved your script in a file called myscript, then you would call it via:

$ myscript a b --flag=bar

Drush provides a method called drush_shift that allows you to access you one at a time:

$first = drush_shift();
$second = drush_shift();

In the above example, $first will be a and $second will be b.  You may access your options via drush_get_option() as usual.

$flag = drush_get_option('flag');
$other = drush_get_option('other', 'default');

In the above example, $flag is bar and other is `$default'.

Note that you can use $argv as suggested in the other answer, but if you do this, your arguments and options will be mixed together, and you will need to parse them yourself.  Using drush_shift() and drush_get_option(); is more convenient.


How do I disable fields for a user account? The site I am developing has 2 type of profiles: the main account, and the alternative account associated with it. The alternative user gets blog posts, forum posts, under its own name. "He-man" and "Frodo" could be two examples.

The main accounts have signature, and image fields that never apply to them because the system always defaults to the alternative account for these things.

Since alternative accounts, and the main accounts both have different roles/permissions, how can I hide these fields using permissions?

I see that http://drupal.org/project/user_picture_field can be used to hide the picture field by setting permissions. How can I hide more than just the picture?

With the Field Permissions module you can hide fields per role.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


Is there an easy for my authenticated users to search other authenticated users? I would like to allow my authenticated users the option to search through other authenticated users profiles (like when you allow people to change the filters on a view of content).

I've been searching through modules and documentation for a while now and can't seem to figure out how to solve this problem.

I was hoping that maybe their would be someway to create a view of users? Is that possible? If not, how can this be achieved?

There is a default user search. You can go to "your_site/search/user" to try that out. You can set the permissions at "admin/people/permissions" to allow only authenticated users to use this search.


Using chinese character in drupal_mail_send() generates unreadable character I am using code similar to the following one.

$message = array(
  'id' => 'named_fund',
  'to' => $email,
  'subject' => '恭喜您！',
  'body' => '恭喜！',
  'headers' => array('From' => 'Company Name <example@example.com>', 'Content-Type' => 'text/html; charset="utf-8";'),
);

drupal_mail_send($message);

When I use Chinese characters for the "From" header, I get strange characters. Why?

Try this:

drupal_mail_send(utf8_encode($message));

As Oswald implied, this is a character encoding issue.

If any data is coming from, or going to be stored in, the database, also make sure your database character encoding is utf8_general_ci.


Rule to create a Node from a Webform Submission Using Rules with Webform Rules enabled, how would I make a new node after a webform submission and use the submitted values as field values in the node?

In short, how do I turn webform submissions into nodes using Rules.

I've set up the Rule like this:

Where do I go from here? I can't seem to find a way to move webform submission values into the node's fields.

Please note: I have read "Using webform rules to create node after webform submission" and "How to create a node with submissions of a webform?". Unfortunately, neither address my question.

Below is something I learned about using webform data in Rules, which may help you to get this to work ... (assuming this question is about D7).

You have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So try to use similar tokens.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform).
the 2nd attempt explains what to do in case of Webform.

Note: if your target field is a multi value field, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "Add item to a list".


Creating JS file on the fly I have a code that generate a big bunch of javascript code and I would like to create a .js file on the fly and include the code in it.

The code would be reconstructed at each cache destruction. The file would be used by all visitors.

Any ideas what I could use to make this possible? Or there's no "drupal way" to do this?

thank's!

I would do this in this way:

function YOUR_MODULE_init(){
    drupal_add_js('path/you/want/to/use/to/include/javascript.js');
}

function YOUR_MODULE_menu() {
    $items = array();
    $items['path/you/want/to/use/to/include/javascript.js'] = array(
        'title' => 'Generated js',
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name'
    );
    return $items;
}

function your_function_name() {
    $js = ... your code that composes js here ... ;
    print $js;
    exit;
}


if function getValue() on null return nothing I looked around, but am not exactly sure how to ask this question.

Is there a means of not erroring out on "function getValue() on null". Basically I'd like to return nothing and move on if getValue is being called on something that doesn't exist.

You can check if a field is empty or not before asking for getValue() with:

if (!$entity->get('field_name')->isEmpty()) {
  $value = $entity->get('field_name')->getValue();
}


Products with Vehicle Fit Guide I'm in the process of developing a website for vehicle cargo boxes and adventurous vehicle accessories, and the client has requested a fit guide.

What I need is a jumping off point:  Do I build a taxonomy list of vehicle makes/models/year first and then ask vendors such as Yakima and Thule for their products? Do I ask the vendors first for their products and incorporate the vehicle list later?

I'm ultimately looking to host all vendors products within the site itself, and not have any iFrame solutions or link to vendor cart solutions.

I've searched for days now and have found multiple pre-built databases for vehicle's but am still wondering where to start...

Start wherever it makes sense to you. Your project sounds iffy if your not hired directly by any of these entities to promote their products.

I'd recommend a content type or entity as Accessory and then taxonomy terms for Make Model and Years of cars which will facilitate searching.

Start with that site structure, if it doesnt work for you then change it later.