Panels not working with page manager? I'm testing page_manager on a fresh install of Drupal 8 (V 8.1.8).

I installed :

Layout Plugin 8.x-1.0-alpha22
Panels 8.x-3.0-beta4
Page Manager 8.x-1.0-alpha24 (with page_manager_ui)

When I try to create a Panel variant in a custom page, I've got no option to insert a block...

My UI appears like that :

Where can I add content in this page ?

Panels and Page Manager in Drupal 8 are under heavy development, so probably it's a temporal problem.

In Drupal 7 Page Manager is a submodule of CTools, but in Drupal 8 is a standalone module. The reason for this is Page Manager tasks (configuring UI) are very important but Panels wants to remain independent from the UI. This makes sense, as each module focus on its duty (Panels on doing its magic, Page Manager in configuring Panels through the UI).

To be more accurated Panels in Drupal 8 can be implemented. Currently, Page Manager and Panelizer implement panels.

So now they are not working together, but eventually they should, that's the target.


How to get fetchField using db_query? I wrote db_query in two ways, I followed the drupal documentation to write safe db_query, one of them doesn't work, I want to know what I'm doing wrong in the code below.

// Worked perfectly
function custom_get_user_account_id() {
  global $user;
  return db_query("SELECT `field_account_target_id` FROM {field_data_field_account} where `entity_id`=:user_id and `bundle` = 'user'", array('user_id' => $user->uid))->fetchField();
}

// doesn't work
function custom_get_user_account_id() {
  global $user;
  return db_query("SELECT field_account_target_id FROM {field_data_field_account} fa where 'fa.entity_id = :user_id and fa.bundle = :user' ", array(':user_id' => $user->uid, ':user' => 'user'))->fetchField();
}

You could achieve this by either one of the following:

By using db_query():

function custom_get_user_account_id() {
    global $user;
    return db_query('SELECT field_account_target_id FROM {field_data_field_account} WHERE entity_id = :user_id AND bundle = :bundle', [
        ':user_id' => $user->uid,
        ':bundle' => 'user',
    ])->fetchField();
}

Or by using db_select():

function custom_get_user_account_id() {
    global $user;
    return db_select('field_data_field_account', 'fa')
        ->fields('fa', ['field_account_target_id'])
        ->condition('entity_id', $user->uid)
        ->condition('bundle', 'user')
        ->execute()->fetchField();
}


How to add basic page content I wanted to add basic page content but I cant see in add content  why it is? can anyone tell me how to create it now please?

You need enable the basic page link in admin/structure/menu/manage/navigation. I think this might be the problem


Restricting view of nodes on taxonomy aggregation pages? I have a taxonomy vocabulary that I use in many different content types.  I want to restrict, programmatically, access rights to specific content types.  As in, a specific role is not able to view particular content types unless they directly authored the item.  This includes any view of a particular node (full, teaser, etc.).  I've implemented hook_node_access as follows:

function progress_reporting_node_access($node, $op, $account) {
  if ($account->uid == 0) {
    return NODE_ACCESS_IGNORE;
  }
  if (_is_tagged($node,$account) && $op == 'update') {
    return NODE_ACCESS_ALLOW;
  }

  $records = _non_viewable_records();
  if (is_object($node) && in_array($node->type,$records)) {
    if ($op == 'view' && $node->uid != $account->uid) {
      drupal_set_message('Sorry, you cannot access this page. Click here to get back home.','error');
      return NODE_ACCESS_DENY;
    }
  }

  return NODE_ACCESS_IGNORE;
}

The only thing that I didn't realize is that this affects a user only when they try to view the full node.  So, when a user navigates to a taxonomy term's aggregation page, all the teasers of all the content that the term is referenced in shows up, regardless of the logic I applied in hook_node_access.

I need to somehow apply the same restrictions to all node views.  In other words, when they navigate to the taxonomy term aggregation page, they don't see teasers that they're not supposed to see.

How can this be done, programmatically, exactly?

You're looking for hook_node_access_records:

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access_records/7


How to create a eCommerce site products slideshow using views Environment: D8 with commerce module.

I am working on a eCommerce website. I created a view to display the products as unformatted list. How can I change it to a slider/slideshow view? Each slide should have 5 products info. Each product of the slideshow should contain title, list price, catalog image, short desc.

Current view:

How the view should look like with the slider:

How can I modify the view to make it a slideshow like the above design?

--

Update 1

You can use view_slideshow module

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

Before installing read README.html file present in the module. you can achieve the required output.

If you need more customization in the slider, you can use

https://owlcarousel2.github.io/OwlCarousel2/  also...if above one does not satisfy your requirement.


Taxonomy view to display all terms I am using the default taxonomy view that comes with the views module and everything is working as expected. The one problem I have is that I cannot figure out how to display a page showing all nodes under my parent vocabulary term.

Vocabulary = videos

-Term 1
--Term A

-Term 2
--Term A

-Term 3
--Term A

So with the example above if I go to any of the terms I will get the terms and children associated with them. Ex: www.site.com/videos/term-1. That works.

But I would like to have a view listing ALL of the nodes when a user goes to www.site.com/videos.

It's gotta be pretty simple, but I am missing it. Thanks!

You can create a view of taxonomy terms with a contextual filter of the type Taxonomy vocabulary: Machine name

Add relationship called Taxonomy term: Content with term and use that relationship to add the contents.


Video streaming cloudfront I am administering a drupal 6 website for a small company. We want to offer our customers restricted streaming video content on the drupal site.

What I heard it is a good idea to place these type of media files on a cdn service, everybody keeps recommending amazon s3 / cloudfront.

Is it possible to have the files on amazon, but have a restricted area on my website, where the user needs to enter some login information and after being authenticated can view the content?

If it is possible, how, what are your recommendations?

I am not familiar with using cdn, so sorry if I ask something very simplistic (:

The Video module supports storing videos on Amazon S3. Restricting node access can be done by creating a special content type for your videos and only giving view access for that content type to a role that you assign to some users, possibly by using the Content Access module.


Values disappear in $form_state['values'] I have some tableselect in a form which I can click a button and update from a database. When I update it, I need to be able to access those values in my submit function. But those values aren't available in $form_state['values'] if I have updated the tableselect via AJAX. How can I make those available, or are they not available before the form is submitted?

Here is the AJAX function:

function module_data_table($form, &$form_state) {

  $tableselect_header = array(
    'id' => t('ID'),
    'row_id' => t('Room number'),
    'start-end' => t('Start date - end date'),
    'sum' => t('Sum'),
    'type' => t('Type'),
  );

  foreach ($form['data_tableselect'] as $data => $val) {
    if (is_int($data)) {
      unset($form['data_tableselect'][$data]);
    }
  }

  // This function just gets the data from the database and returns it as an array
  $lines = module_data_from_database($form, $form_state, true);
  $form['data_tableselect'] = array(
    '#type' => 'tableselect',
    '#tree' => 'true',
    '#attributes' => array(
      'id' => 'data_tableselect'
    ),
    '#header' => $tableselect_header,
    '#options' => $lines,
    '#multiple' => true,
    '#empty' => t('No data to show.'),
    '#parents' => array('data_tableselect'),
    '#default_value' => '',
    '#weight' => 14
  );

  $form['data_tableselect'] = form_process_tableselect($form['data_tableselect']);

  $commands = array();
  $commands[] = ajax_command_replace("#data_tableselect", render($form[['data_tableselect']));

  return array('#type' => 'ajax', '#commands' => $commands);

}

And here is the relevant part of the hook_form_alter function where I defined the button that triggers the above function. The code that defines the tableselect there is much the same as that above:

$form['data_get'] = array(
  '#type' => 'submit',
  '#value' => t('Import data'),
  '#attributes' => array(
    'class' => array('col-sm-3', 'col-xs-4')
  ),
  '#parents' => array('data_get'),
  '#limit_validation_errors' => array(),
  '#ajax' => array(
    "callback" => 'module_data_table',
    "wrapper" => 'data_tableselect',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Importing...')
    ),
    "event" => 'click'
  )
);

You have to move the code for changing form elements from ajax callback to form build (which includes hook_form_alter()). The form build is executed for every ajax request before the callback function is called. In the callback you are not allowed to change the form array. Put only code there to return form elements.

More information: Ajax Forms in Drupal 7

Quote:

  Changes to the form must only be made in the form builder function
  (ajax_example_autocheckboxes() in the example here), or validation
  will fail. The callback function must not alter the form or any other
  state.


theme_hook_suggestions for string wildcard I need to create a copy of page.tpl.php using page--fixed_arg_0__variable_string_arg_1__fixed_arg_2.tpl.php as pattern. For example, if the URL is http://example.com/models/model-title/special-offers, model-title is the variable. I only want one template file instead of 10 or more.

Any suggestions?

What you'd need to do use the theme suggestions. So you'd have 1 template file e.g. page--fixed.tpl.php

Then in template.php you could have an if statement e.g.:

function THEME_preprocess_page(&$variables) {
 $arg1 = arg(1);
 $arg0 = arg(0);
 if($arg0 == 'models' && ($arg1 = 'model-names' || $arg1 = 'anothermodel')){
  $variables['theme_hook_suggestions'][] = 'page__fixed';
 }
}


CCK fields disappears I get informed that webforms didn't work anymore. I switched recently to a new server copying database and druapl installation folder to the new server.

What happens is that when webforms using, the fields (dates, numbers, etc) do not come up. I noticed that in the modules list are some incomplete entries like above:

I checked the CCK modules folder and reinstall the folder (cck-5.x-1.12), still the same.

I use CCK too for some fields in content types and it still works for creating and editing content, but when I create a new content type with a CCK field, it fails.

This site is scheduled to migrate to version 7, but meanwhile with version 5 should work.

Any idea where to search for reason that the (sub)modules are blank and propably won't work ?

The issue you're running into sounds as if the file permissions are messed up; here's a checklist of things to go through:

Open .info files of those modules and verify that they exist and have all regular information (name, dependencies, version, etc.).
If they exist and have all info, check if they have some weird file access permissions; this could prevent Drupal from reading the content. See file permission instructions for Linux servers, specifically the commands which ensure that the proper permissions are in place:

[root@localhost]cd /path_to_drupal_installation
[root@localhost]chown -R YOUR_USERNAME:www-data .
[root@localhost]find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
[root@localhost]find . -type f -exec chmod u=rw,g=r,o= '{}' \;

Try replicating the issue on a clean install AND on a clean install with the same installation files.
If the above steps don't tell you anything and you still have the issue - hack the core, specifically _module_parse_info_file() function in includes/module.inc and do a var_dump() or print_r() on the $info variable once it parses the file. Maybe the formatting is off, encoding or something else. This might get you a step further if everything else fails.

Hope this helps.


How do I change the default theme with Drush-master I've installed a premium theme in a Drupal 8.1.0, and now each time I log into the site It crashes with the error "An unknown error has occurred" (even though the site itself works fine). I thus try to change it with Drush.

I've tried drush vset bartik in drush-master to change the non-admin theme back to bartik in Drupal 8 but then came the error:

  [error]Command variable-set requires Drupal core version 6 or 7 to run.
  [error] The drush command 'vset bartik' could not be executed.

Try this:

drush config-set system.theme default bartik

You might need to clear or rebuild your CSS/JS and theme caches (drush cr).
If the problem still appears, check that it has not been forced in your
settings.php file.

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


Theme webform using custom module I know I could easily theme a webform using the webform-form.tpl template.

However, I want to do this on the module level where the tpl is located inside the custom module folder or coded directly into the .module file?

I tried looking in to these hooks and nothing seems appropriate for my need:
http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/group/webform_hooks/7

I guess you can put near the file your_module.module. Also your can put it into a nested folder. Keep attention: webform-form.tpl.php and that template engine is invoked at the last moment. It overloads all module templates.


How do I query for content that has not been updated (no revisions)? I am creating an API endpoint that serves as a content Feed that pulls in content according to some rules.

One group of content that I want to pull is articles that have been updated and that have been approved to be included in the feed. My approach for this was to include a boolean field for including it in the feed, and query for the number of revisions.

$firstGroup = $query->andConditionGroup()
    ->condition('type', ['article', 'video_game'], 'IN')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('field_include_in_feed', 1)
    ->condition('revision_uid', '1', '>=');

$nids = $query->condition($firstGroup)->condition($secondGroup)->execute();

Based on this page from the documentation, I thought revision_uid would be a valid field, but I get an error that it is not. Likewise I get an error, if I use revision as well.

The error is a Drupal QueryException with the message 'revision_uid' not found.

What is the best way to query for content (with entityQuery) that has been updated if I can't use the revision fields?

Content that has not been updated would only have one revision, so you could count the number of revisions and use a having condition.

First you'll have to join the node_revision table to the node table

$query->leftJoin('node_revision', 'r', 'n.nid = r.nid');

Count the number of revisions

$query->addExpression('COUNT(n.nid)', 'revision_count');

Filter rows with a revision_count higher than 1

$query->havingCondition('revision_count', 1, '<=');


How to get all pages of a custom content type to be displayed using a custom view? In Drupal 8, how can I get all pages of a custom content type "MyPage" to be displayed using a custom view "MyView"?

Structure -> Views -> Add a view (`/admin/structure/views/add')
View Settings: Show Content of type MyPage.

I suggest reading the Views documentation.


Should I use the theme layer or a module to create a complex, static page? We have a few pages like the following on my site, everpurse.com: https://everpurse.com/home

They contain moderately complex markup and CSS. My approach to creating these pages is to create a module that uses hook_menu() to create a menu callback. The callback itself returns a render array containing something like:

return array(
  '#theme' => 'ep_homepage',
  '#attached' => array('css' => array(...)),
);

The module provides an ep-homepage.tpl.php template file that contains all the markup, including language, HTML, etc. The #attached CSS file styles everything.

It seems, though, that the proper "Drupal way" to do something like this is to put all the CSS and markup in the theme directory, and all the language inside of t(), and expose the language via preprocessed variables in the module. But there are a number of reasons I don't like this approach:

Some of the language is very markup-heavy. There may be sentences like Available now for a limited time only. Putting this into the module mixes module concerns with theming concerns.
The CSS in the theme gets aggregated, which means it will be loaded on every pageload—including pages that don't use it. (That is, by putting page-specific CSS into the theme, you sacrifice the benefits of using #attached.)
Even when putting all the markup into the theme, the page callback has to return something. But if the theme is taking care of all the markup, what should the page callback return? Just theme('ep_homepage')? This would mean the module should create an empty implementation of the ep-homepage template, and allow the theme to override it with a template of its own, right? This seems like such a silly workaround and a bunch of extra work, just to meet Drupal best practices.

So, I guess my question is: what is the Drupal best practice for a page like this? (And I'd rather not use Page Manager/Panels, since the markup is so complex that I'd rather edit it in a Git-controlled template file than via the Panels UI.)

The "Drupal way" would be to NOT create a module to hold content, and NOT create a module for a specific page(s). "Drupal way" would likely be to (1) put all of the language/content w/markup into a node, (2) put other outside-of-content markup and styles into *.tpl.php files and css files, (3) put any PHP functionality that isn't available already in contrib into a custom module, and (4) NOT put any content/language into a theme or into a module.


Execute reaction rule programmatically I want to run Commerce rule "Create a new account for an anonymous order" from code. I can create user with user_save and etc, but I like this rule and want to reuse it.
After a hour I finished with this code:

// Load reaction rule by name.
$rule = rules_config_load('commerce_checkout_new_account');
// We need $state for 'evaluate' or 'fire'.
$state = new RulesState();
// Add 'commerce_order' parameter to state.
$state->addVariable('commerce_order', $line_item_wrapper->order->value(), array('type' => 'commerce_order', 'label' => 'Commerce order'));
// Execute rule.
$rule->evaluate($state);
// How can I get created user account from $rule?
// Now I have to do user_load_by_mail().

It works but I don't think it is the best way.
I especially don't like  to create RulesState manually. I know there are setUpState() and lots of other methods. I want to find the best solution without creating new Rules component.

As a related solution, it's much easier to execute a Rules Component programmatically. They're designed for that.

For example, consider a Rules Component (type "Rule") that accepts a $commerce_order parameter.

In this case, it happens to process a queued order item from a cron queue, pushing the order to a remote system via an API.

function MODULE_queue_iwi_push_instant_sale($item){
  try{
    if($order = commerce_order_load($item['order_id'])){
      // Invoke the rules component programmatically
      // passing the $order parameter
      rules_invoke_component('rules_iwi_push_instant_sale', $order);
    }
  }catch(Exception $e){
    watchdog_exception('my_module', $e);
  }
}

I like to think of Rules Components as similar to functions that can be called, passing parameters and potentially returning a value. They can do other magical things as well. See rules_invoke_component

Reaction rules on the other hand are event driven, triggered by some event such as node_save and passed the relevant parameters. See rules_invoke_event

More info on Rules Components here: https://drupal.org/node/1582182


How do I modify the email maximum length to 320 characters? I want to overwrite the maximum charcater limit to 320. It is defined in /core/lib/Drupal/Core/Render/Element/Email.php
Can anybody tell me how to overwrite it?

You can using hook_element_info_alter.
mymodule.module
/*
 * Implements hook_element_info_alter().
 */
function mymodule_element_info_alter(array &$info) {
  if (!empty($info['email'])) {
    $info['email']['#maxlength'] = 320;
  }
}

Flush all caches so hook gets pickedup.
As Neograph734 pointed out, the mail column's VARCHAR length will also have to be increased in the DB.  See Resizing Fields in Drupal 8 Without Losing Data to learn how you can accomplish that.


A simple field to hold date value For a content type, I need a field holding the value of a certain date in history. The content type will be used to hold some historic events and when the current date matches (September 17th, for example) the node will be displayed.

I know that the date module can handle such things but it is quite comprehensive and I will not be using calendars or event content types. All I need is to hold a date value and compare its day and month part with the current date's.

Is there a simple solution?

The Date module will store date time in this format: "2012-05-25 hh:mm:ss" . Using PHP's date_parse function you can extract all those values. What easier thing do you need?


Numbering table rows Views are normally formatted as unformatted list. I would format a view as HTML list, and choose between <ul> or <ol> markup.
Since I use the DraggableViews module, I need to format the view as table. I would like to have some automatic numbering for the view's table rows, similar to the HTML list, which uses <ol> and <li> markup.
How could I get each row in the view table to have a number that is automatically increased?

You can add the global view result counter field to the view, whose description in the Add fields dialog box is the following.

Displays the actual position of the view result.


Programmatically log in a user I am trying to authenticate users as below. I don't get any error, but it doesn't log in users.
autoLogin.php is located in the root folder. Visiting http://example.com/drupal8/autoLogin.php shows me the Login required page every time.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

$uid = 1;
$user = Drupal\user\Entity\User::load(1);
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);
$response->send();
$kernel->terminate($request, $response);

The code shown in the question would throw an error about user_login_finalize() not being defined. The code isn't loading the User module and the DrupalKernel class doesn't load any module.
I generally use the code shown in authorize.php as guideline on how to bootstrap and programmatically log in a user. In this case, to programmatically log in the user whose ID is 1, I would use the following code.
use Drupal\Core\DrupalKernel;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;

$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();

  // A route is required for route matching.
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  $kernel->preHandle($request);

  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');
if ($account = User::load(1)) {
  \Drupal::currentUser()->setAccount($account);
  // Add your code.
  $response->setStatusCode(200);
  $response->send();
}

Since it seems you are trying to access a specific page after logging in the user #1, it's probable you need to change the two lines following the A route is required for route matching. comment and use a different route name.


Drupal Commerce, behaviour when you disable order status There is possibility do disable order statuses with "hook_commerce_order_status_info_alter"
but I am wondering what happens then. Example is. Alipay has many pending statuses. I would summarize them into few or just one. But wondering what would happen then when Alipay returns some status which is not available or disabled?

I dig in a bit and run some custom code.

$order = commerce_order_load($order_id);
$order_status = 'payment_received';
commerce_order_status_update($order, $order_status);

and changed status. So even if status is disabled, it still is changed. Only way is to remove the status, unset it in

hook_commerce_order_state_info for whole parent state
or
hook_commerce_order_status_info
for particular status.

What happens then is if you try to change status to the one that is not there, status will be undefined.


Passive / light-weight / serializable translatables? So.. in Drupal 8 we have several classes that implement \Drupal\Core\TypedData\TranslatableInterface, and we have Drupal\Core\StringTranslation\TranslatableMarkup.

Each of these classes contain references to services that will actually do the translation, making them heavy on e.g. var_export() or serialize().

Is there a class to store an untranslated string plus replacements plus options, that does not contain these dependencies?

Maybe \Drupal\Core\Annotation\Translation does get close, but I think it  is only meant for annotations.

See https://www.drupal.org/node/2893029.

Ther isn't really a workaround until that is fixed.


How to give the image path in the check box field option for a content type I am creating a checkbox field in my content type and I want images to be displayed as checkboxes option.

In Drupal 7, there is a feature to add images as field list, but I am unable to give the full path for that image.

See the below screenshot for better understanding.

I cannot give my image path as http://localhost/sites/default/.. because the base path changes when we move to the Production. How can I achieve this?

Your image path needs a / before sites. Should be "/sites/default/files/test-image1.jpg"

If you don't have a / at the start, then it appends your url code to whatever page you're on. Example: node/1/sites/default/files/test-image1.jpg which is not what you want (broken image since it doesn't exist)


How to get Views Selective Filters working with Country Field from Address Field Module? When I expose the country field from the address-field module as a selective exposed filter (to only show countries that are in the results of the view), the "selection" works, which means only the appropriate countries are shown in the dropdown of the filter. But after clicking "Apply" the results are zero.

I have tried to rewrite the field but to no avail. I think the problem is, that the country is taken from the core. If i try other fields from the address field, it works.

Any help appreciated! Thanks!

EDIT: I just found out about the checkbox on the field itself called: "Display the localized country name instead of the two character country code". If this is unchecked, the view and the filter are working. But now i have a unreadable list of country abbreviations in my dropdown.

Is there something i can do about this?

I found a workaround on this. In the content-type with the address field i created a new field with a token of the country-field that is now working like a charm with views-selective-filters.


node/[nid]/edit does nothing. how to troubleshoot? I'm trying to edit a node in Drupal 6. The edit tab is visible and clickable and everything, and directs to the proper path (/node/[nid]/edit) but... nothing happens. How do I troubleshoot this? I don't see any weird edit page templates in the theme or anything. I didn't develop this site or this theme but am now maintaining it. How do I begin troubleshooting something like this?

My first step would be to watch the request with Firefox's Live HTTP Headers.  This will tell you if the request is actually going out or not.

If it is, then you need to check server logs to see if the request is being processed.  You may also need to add some watchdog() calls in the core node.module to track it down.

If the request isn't going through, then I suspect you have some rogue Javascript that is intercepting the click.  Disable JS and retest.  Another possibility could be that you have a CSS positioned element over the tab, and that is actually catching the click event.  Go through the body with Inspect Element and double check all of that.


Is it possible to show Poll results as a table in Views? I want to show the results of a Poll (core module) in Views.

However, the only way to show any Polls in Views is just as a full node (as they appear to a normal user).

I want to be able to display it as a table so that I can make it easily exportable to Excel (using the Views Export XLS module).

Any ideas?

Try to use below modules :

Responsive Tables
Data
FooTable


Install profile with variable default language messes up translations I'm working on an install profile for a Drupal app that can be delivered in several languages. The app was developed with English as the default language, but some installations might be in Arabic only.

The problem is that Arabic-language installations of this profile show the English menu items, field labels, etc. When I examine the strings in the localization UI, it shows the English string next to the default language, which is now Arabic. Only strings from the "default" textgroup are appearing correctly for some reason.

Now I am aware that there is an issue with default language vs source language in i18n. I would appreciate if someone could offer a workaround for my particular situation.

Turns out to be a simple solution: the variable i18n_string_source_language can be used to specify the source language of all strings, instead of the current site language.

I ended up setting

$conf['i18n_string_source_language'] = 'en';

in my settings.php. This worked.


Help with exposed filters please I have a content type called Profiles. Each profile has two filters, one is Location (East side or West Side) and the other is floor (2nd or 3rd). In the view I have set the profile to filter by location and floor. There is an employee who has an office on both the 2nd and 3rd floor in the east side and the 2nd floor on the west side but NOT on the 3rd floor in the West Side. But in the content filter I enabled all fields without thinking on one exception. How do I take care of this exception, please help

Do you have it setup with a multiselect picklist for the floors and locations they can be at? It doesn't sound like there is much of a problem, what are you choosing in the filter that is not working?

The exposed filter works on an AND logic by default so:

Show me
- Anyone at EAST AND on 2ND FLOOR
- Anyone at WEST AND on 2ND FLOOR

The employee will show up when you select EAST AND 2ND, EAST AND 3RD, WEST AND 2ND, but won't if you chose WEST AND 3RD.


How to implement jQuery? I want to add a slideshow in my Drupal website. But i dont know how to add jQuery file in Drupal.

Drupal already ships with jQuery, you don't need to add it yourself.

Drupal 6 comes with v1.2 (can be upgraded to 1.3.2 with jQuery Update)
Drupal 7 comes with v1.4 (can be upgraded to 1.5.2 with jQuery Update, higher with the dev version).


How do I use bigdump.php with Acquia Dev Desktop? I am trying to import a rather large database (~450MB) on my local machine (running Acquia Dev Desktop). To do this, I was going to use BigDump.

However, I must not be configuring bigdump.php correctly because I keep getting this error:

  Database connection failed due to No connection could be made because the target machine actively refused it.

Here's my database configuration in bigdump.php.

$db_server   = 'localhost';
$db_name     = 'testdb';
$db_username = 'drupaluser';
$db_password = '';

Do I have to edit something in Acquia Dev Desktop to allow connections?

If you want a web based solution for moving in database files, you should be using the Drupal solution for it:

http://drupal.org/project/backup_migrate

Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.

With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server, and to restore from an uploaded or previously saved database dump. You can chose which tables and what data to backup and cache data is excluded by default.


How do I include a custom module translation? I have a Drupal 8 custom module (custom_module) and a custom_module-8.x-1.0.da.po file I added to sites/default/files/translations, but my translations are not getting Imported during the module installation, even though translations are available for import in admin/reports/translations. Am I missing any step?

I don't want to put my custom_module-8.x-1.0.da.po file in sites/default/files/translations; I prefer it to be inside the module directory, if possible.

Add interface translation project and interface translation server pattern definitions to custom_module.info.yml.
You can use a custom path for your translation po file by setting the interface translation server pattern to whatever you want.


What is the deal with config collections? When manipulating configuration yaml files in config/sync, I note that if you put files in subdirectories, and run drush config:import, the files in those subdirectories are denoted as belonging to a 'collection'. (Top-level files have no collection listed)

This seems like it might be a useful organisational unit. However, it seems like configurations that are part of a collection are not acted on.

For example, if I put a node.type.test.yml in config/sync, and run drush config:import then a corresponding node type is created as expected. However, if instead I put the file in config/sync/test and run drush config:import, then no type is created.

What is the purpose of these collections? Is there some way to indicate that you want collections to be activate/inactive within the configuration? Do they serve some completely different purpose?

Collections are for configuration overrides. Mainly used for translations, but could be used for other purposes as well. You can list the available collections in your Drupal installation, starting with the default collection (empty string):

$collections = \Drupal::service('config.manager')->getConfigCollectionInfo()->getCollectionNames();

More info https://www.drupal.org/node/2268523


Database Each table Usage Where can I see the each table usage, which is getting created in default installation of a Drupal site.

Likes node table - used to store all nodes in them. For other tables where i can get the information. Any documentation for each table usage in database??

Thanks in advance.

Run below query on your database and see last column in the result table.

SHOW TABLE STATUS

See Screenshot below for example.


How do I use Features to export a custom content type to a stand-alone module This is a follow-up on, but not a duplicate of, Programmatically creating a content type with file field in a custom module.

As suggested by Tenken in a comment to the OP of that question, it is easy to do this by using the core FieldUI module to create the fields, and then then use Features to export the fields to a custom "Feature" module.

You can then install the "Feature" module as any other module that implements a custom content type, but you need to have Features installed for it to work.

I want to use the FieldUI and Features to create a custom content type module, but the module should be stand-alone (i.e. not depend on Features for (re)creation of the content type).

Is this doable? Or is Features a dead end in my use-case? I.e.: If I want a stand-alone module, I must create it from scratch.

And if it makes sense to use Features, what do I need to do in order to transform the "Features" module into a stand-alone one?

(I've searched for similar questions, but not found an answer that describes how you make the generated "Features" stand-alone.)

The features eco-system simply implements certain hook functions (like hook_field_info for example). It wraps these core api functions with import/export code.

When you export your content type using Features you can inspect what it creates -- besides a mymodule.install and mymodule.module files.

By examining the hooks the features implements for your exported content type -- there is nothing stopping you from copying/renaming these exported function definitions and migrating them to a new module's hook_install() function. Thus, creating a new content type which you used Features to create the building block(s).


How to filter taxonomy term in views from URL I am working on a travel website, and I made taxonomy with depth continent/country/city. I also have taxonomy locations restaurants, museums, nightlife... I have content types destinations and locations. I made a view from location content (all restaurants)

I would like to have locations filtered from destination taxonomy term in URL (e.g. destination/europe/france/paris to sort only restaurants from Paris, but destination/europe/france to list all restaurants from France).

Can anybody help?

The best way to do this is as follows:

Assuming you have fields in your content type for continent, country, and city: Add each of these fields separately in your view's Contextual Filters. You can leave them at the default settings for now.

Then, change your path settings for the page to one like such: destinations/% (the % will be replaced with your contextual filters).

After saving the view, you should then be able to visit a path such as destination/europe/france/paris OR destination/europe/france, granted you have content within those areas.


ordering profile 2 module profile type tabs i am using profile2 module, i create some profile types, but in profile section in admin/structure/profiles   i can't ordering them,is this profile default or this is only my problem?
i means if i add another profile type it just come below of anothers and any feature to ordering them

can i ordering them in form_alter?

function hook_form_alter($form,$form_state){
   change order of theme here ??? how
 }

Yes, by default profile2 module not cosidered any ordering of it's profile types.
if you want to change default ordering of them you have some  solution.
create a template file for user_profile .
Another way is ordering them with form alter
in your custom module

function hook_form_alter(&$form,$form_state) {
 if ($form_id == 'user_profile_form') {
     // do this for all your profile types
     $form['profile_yourprofiletype']['#weight'] = 'your optional order';
   }
 }


hook_path_update (and insert and delete) not getting called I've added the following methods to my module, saved, and flushed all caches on my site. I have double checked that my module is enabled and working properly in all other respects.

function xxxxxxx_path_insert($path) {
  kpr($path);
  var_dump($path);
}

function xxxxxxx_path_update($path) {
  kpr($path);
  var_dump($path);
}

function xxxxxxx_path_delete($path) {
  kpr($path);
  var_dump($path);
}

I want to receive notifications when content path aliases are updated so that I can store some info about them for my custom module. I just put these shell methods in place to ensure I was getting the hook calls and to double check the structure of the $path variable.

Then I edited an existing piece of content. I changed the title and saved the node. Since I'm also using pathauto, that module updated the content path alias to point to a new url based on the new title. I did not receive any of the calls.

Ok, so I figured maybe the auto generation of the alias was the problem, so I edited the piece of content, disabled the auto generation of the path alias and changed the path alias to something by hand. Then saved the node. I did not receive any of the calls to the above hooks.

What am I doing wrong? Why aren't these hooks getting called?

The hook documentation for your reference: path.api.php

sigh I flushed all caches a TON of times and it would never call my hooks. I had to completely disable my module, flush all caches, and then re-enable my module.

Then the system saw my hooks.

sigh


Include a View page in a Book Outline I have a site that heavily uses the book module to organize hierarchical documents. I would like to include a View in a Book Outline.

Here is a simplified example: The Parts Department of a company has documentation of all of its standard operating procedures. These procedures are organized using Drupal's book outline. The department also uses a content type called "Part" to individually enter descriptions of each part. A view was created to display a glossary of parts. This glossary should be in the book outline, but I cannot find a way to insert a view into a book outline.

Example: Parts Department Standard Operating Procedures

Page: Procedure 1
Page: Procedure 2
Page: Detail APage: Detail B
Page: Procedure 3
Page: Detail APage: Detail BPage: Detail C
View: glossary of parts -- NEED TO GET THIS INTO BOOK OUTLINE.

Thanks for your help.

Jordan

You can use the Views Field module, to embed a view into. Here is a quote about it (from the module's project page):

Allows field tables to be used as base tables with Views.
On a field settings form, you may select:

to expose the field table as a base table
the columns of the field table to expose (e.g., entity_type, entity_id, and delta)

Multiple "exposed" field tables may be related by a multi-column join using the primary key columns. This module provides a programmatic interface to trigger this relation. A user interface is provided by the combination of the Field Group and Field group views modules.
One use case is to generate a table using columns from one or more field tables. As the field tables are treated as standard base tables, the Field API handling of the "field" is not invoked. Thus, by default, the raw value in each column of the field table is displayed.
By relating field tables, the individual columns of each table function as if they were part of a single table.


How to list nodes that share only the first selected value in an entity reference field? I have entity reference field to a taxonomy vocabulary on a node, which is a multi value field.

In Views, how do I list related nodes that share only the first selected category?

Example: Suppose I have selected "category3" and "category4" for a node. I want to show other nodes which have selected "category3".

You should be able to set up something like what you are after with the following steps:

Create a view of content (nodes)
Add a contextual filter for NID with a that gets it's default value from "Content ID from url" (presuming the related products are to appear on the original products own page).
Add a relationship on field_category, call it something like "category", require this relationship
Add a filter of field_category:delta, value = 0
Add a relationship of "Content using field_category", require this relationship, use relationship: category, call this relationship something like "related"
Add another contextual filter that's also for NID with a that gets it's default value from "Content ID from url", use relationship: related, tick "Exclude" in the "More" fieldset at the bottom.
Now when you add your fields use relationship: related.


How to allow user picture during registration? I have the Avatar Selection module and the Register with Picture module installed.

But I can't get the file chooser to show up on the registration page.

What would be the problem?

You should be able to use the Register with Picture module.

I've never experience any problem with this module.

You install it and configure it, and it does what it is supposed to do.

  This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.

You will be given a check box at admin/config/people/accounts named "Enable user pictures on registration" and weight selection. Make sure you also check "Enable user pictures".

This is how it should look like when a new user tries to register:


Show teasers to anonymous visitors but not allow access to the body/node I want to encourage visitors to create an account by allowing them to read the teasers on the front page and know that creating an account is worth their effort to access the rest of the content.

i'm using v7.x

P.S. I also hope this will enable Search engines to see enough content to index properly

One way to do this is to use Panels.  Override the front page and the default node template; create two variants for each, one for anonymous and one for authenticated users (using selection rules).

Then, for the front page for anonymous users, only use teasers and remove the links to the full content.  For the anonymous node template, limit everything to teasers.

For authenticated users, enable everything just as you'd like them to see it.

Note: this is not a full tutorial on Panels, but should hopefully provide some hints to get you started.

Keep in mind that doing this will cut the search engines off from your non-teaser content as per Clive's comment.


Clientside-validation for form-api for field either digits or empty A particular form field can be left blank or filled with digits, with no other valid characters including dash"-"

$form['hours'] = array(
    '#type' => 'textfield',
    '#title' => t('Hours worked per week'),
    '#size' => 3,
    '#maxlength' => 3,
    '#default_value' => '',
    '#rules' => array(
      "digit",
      'length[0, 3]',
    ),
    '#filters' => array('numeric', 'trim')
  );

I have a minimum length of 0, but an empty field appears to be invalid.  I've tried using "numeric" instead of "digit" but this allows dashes.

Is there some way to do this without using a custom handler?

The way I did this was to add a custom validation handler.  I know I asked for a solution without one, but it turned out to be a fairly simple thing to do.  See the "#element_validate' array element below.

$form['hours'] = array(
  '#type' => 'textfield',
  '#title' => t('Hours worked per week'),
  '#size' => 3,
  '#maxlength' => 3,
  '#element_validate' => array('mymodule_validate_integer'),
  '#default_value' => '',
  '#rules' => array(),
  '#filters' => array('numeric', 'trim')
);

function mymodule_validate_integer($element, &$form_state, $form) {
  if (!empty($element['#value']) && (!is_numeric(parse_size($element['#value'])) || $element['#value'] < 0)) {
    form_error($element, t('"!name" must be a positive number.', array('!name' => t($element['#title']))));
   }
 }

function mymodule_clientside_validation_rule_alter(&$js_rules, $element, $context) {
switch($context['type']) {
case 'element_validate':
  if (in_array('mymodule_validate_integer', $context['functions'])) {
    _clientside_validation_set_minmax(
        $element['#name'],
        $element['#title'],
        0,
        99999,
        $js_rules,
        t('"!name" must be a positive number.', array('!name' => t($element['#title'])))
    );
  }
  break;
  }
}

I hope this helps someone in the future.


Looking for "Edit own Blocks" permission? It would be very useful for me to have something like "Edit own Blocks" permission.

As administrator (user 1) I created some blocks in a site. I also gave permission to create new blocks to other role users.

Then these user now can edit and delete my blocks. I need them to be able to create their own block but not to edit nor to delete mines.

I tried with the https://drupal.org/project/block_access modulen which does the job but it adds a lot configuration stuff in every block which I just see "too much" for what I need.

Any other way to do this?

Block are not content. They don't have an owner, revision and all that. But there is another way round. You can make some of content to be a blocks with Nodeblock or one of it's competitors:

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

That way you can create content type Block, and apply node permissions to it. All of them, including "edit own block".


How do I sort paragraph types? Hello it is possible to order the output of the paragraphs for example
Type of content Blog
I create a blog details field that calls the type of paragraphs and there I select image and description
In my content it goes in this order

1 Image
2 Description

In the view I call that field
blog details
and they appear to me
but based on the order of the node
But I don't want it to look like this

1 description
2 image

and always look in that order

I don't believe there's a way to sort the values of a field at the view level. However, you can easily get the results you want by creating a custom field formatter and then using it to render your field in the view.
You can read more about field formatters by reading the Create a custom field formatter documentation on d.o.
Create a custom formatter that extends the formatter you're using now. I'm guessing you're using the default ERR formatter so you'll want to extend Drupal\entity_reference_revisions\Plugin\Field\FieldFormatter\EntityReferenceRevisionsEntityFormatter.
You'll need to override viewElements() or getEntitiesToView() - I'd override getEntitiesToView().
protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
  // Let the parent class get all entities in the field first.
  $all_entities = parent::getEntitiesToView($items, $langcode);
  $my_entities = [];

  // Get first Description paragraph.
  $desc = $this->getFirstOfType($all_entities, 'MY_DESCRIPTION_BUNDLE');
  if (!empty($desc)) {
    $my_entities[] = $desc;
  }

  // Get first Image paragraph.
  $img = $this->getFirstOfType($all_entities, 'MY_IMAGE_BUNDLE');
  if (!empty($img)) {
    $my_entities[] = $img;
  }

  return $my_entities;
}

protected function getFirstOfBundle($entities, $bundle) {
  foreach($entities as $entity) {
    if ($entity->bundle() == $bundle) {
      return $entity;
    }
  }

  return FALSE;
}


How to create a role without some permissions an "Authenticated User" has? I have created a custom role. It automatically receives any permissions given to authenticated users. Is there a way to prevent this from happening?

What I would like to achieve is:

Authenticated user: has permission to edit email address and password

Custom role: doesn't have permission to edit email address and password

Currently on my site, users all have the permission "Authenticated user". I would like some new users to have the "Custom role".

The answer to this question: How can i create a user without role authenticated user role suggests to instead edit the "Authenticated user role" and swap the "Custom role" to being the one with more permissions.

So instead I would have to have:

"Authenticated user": doesn't have permission to edit email address and password.

"Custom role": has permission to edit email address and password.

BUT if I do this then all of the current users will no longer be able to edit their email address and password, as they will still be "Authenticated Users", and updating each user to the new role would require entering their password (which I can't do).

Note: I would still like all users to be able to edit other fields such as "First Name".

I don't think you can do that. The authenticated is the mimialist role with the lowest permissions.

You give it the Minimal permissions then make other roles with added permissions to the authenticated.


Scroll Calendar View so that it Centers (vertically) on page I've designed a calendar of events.  It uses a Next and Previous pager.  With the theme I am using, the top of the calendar displays part way down the screen when first viewed.  The user typically scrolls the screen using the mouse to bring the entire calendar into view.  This is problematic if the user needs to page to the next or prior month because he needs to once again use the mouse to position the entire calendar on the screen.

I'm not exactly clear on the best approach to resolve this.  I thought about looking into the theme code but wasn't sure if that's a good place to start.  I thought about trapping the display of each page of the calendar and trying to reposition (scroll) the page programmatically, but, that seemed like unnecessary code.

Can anyone advise me on a proper approach to solve this issue?  Ideally, I'd like the user to not have to scroll each page of the calendar when he uses the Next or Prior button.  It seems like there should be a way to ensure the entire calendar is visible.

One solution that comes to mind is to use hook_pager_link() to modify your view's pager links to include fragment/anchor that is in your view's header. This would work on the assumptions:

You have custom unique text for previous/next pager links (e.g. "previous month"/"next month").
You placed an anchor link in your view header (e.g. ).

In your theme's template.php you could override like so:

function MYTHEME_pager_link($variables) {

  // If we are looking at pager links with our custom title
  // use our modified theme_pager_link code:
  if (in_array($variables['text'], array('previous month', 'next month'))) {
    $text = $variables['text'];
    $page_new = $variables['page_new'];
    $element = $variables['element'];
    $parameters = $variables['parameters'];
    $attributes = $variables['attributes'];

    $page = isset($_GET['page']) ? $_GET['page'] : '';
    if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
      $parameters['page'] = $new_page;
    }

    $query = array();
    if (count($parameters)) {
      $query = drupal_get_query_parameters($parameters, array());
    }
    if ($query_pager = pager_get_query_parameters()) {
      $query = array_merge($query, $query_pager);
    }

    // Add our custom #calendar fragment
    $attributes['href'] = url($_GET['q'], array('query' => $query, 'fragment' => 'calendar'));
    return '' . check_plain($text) . '';
  }
  else { // Otherwise fall back to core theme pager.
    return theme_pager_link($variables);
  }
}


How do I configure facet items to remain visible when they are selected? I'm using Commerce Search API along with Search API and Facet API to provide a search for my products. For the server I'm using Search API Solr search.

I want to configure the facets for the search to remain visible when selected. As the facets are now, when I select one it disappears.

Although it seems that this should be an easy task to do, after searching around I couldn't find any information on how to successfully do this. If anyone has experience with this or an idea to make it work your help will be much appreciated.

I figured it out. Go to "Configuration » Search and metadata » Search API" and click the facets tab. Next to the desired facets you will see "configure filters" with an arrow pointing down next to it. Click the arrow. In the drop down select "configure filters". Make sure that "Do not display active items" is NOT selected. This worked for me.


Conditional code in preprocess_page function? I need to add a conditional code in a my_theme_preprocess_page function.

The conditional should be like:

if the loaded node has a field called background_image and the value for this field is not empty, then is true

I think this will work for you. Note:

It doesn't check the node type.
It adds the variable has_background_image on any page that has $vars['node'] available in hook_preprocess_page, and only on those pages.
$has_background_image will be true if the field isn't empty (that's the only check).

.

function MYMODULE_preprocess_page(&$vars) {

  $field_name = 'field_background_image';

  if (!empty($vars['node'])) {

    $node = $vars['node'];
    $items = field_get_items('node', $node, $field_name);

    $vars['has_background_image'] = $items ? TRUE : FALSE;
  }
}


Integration with Single Page Application (React) I have a specific scenario to integrate a single page application (react based) with Drupal (I use version 7) in order to achieve the following:

Utilize the CMS capabilities of drupal and provide static content some of it will be public some will be private to authorized users only.

Create a totally separate single page application with specific functionality, with react framework and will communicate with a different backend system. I want this app to expose it through drupal, as a page by selecting it from the menu. Only authorized users will be able to enter this section of the drupal app.

Being able to pass user details to my single page application, in order to use them to the communication with the backend (for authorization and other operations)

I'm fairly new to Drupal, as far as I understand I will need to develop a module and/or a theme to do that? Additionally, drupal and my application should have a common authentication mechanism,I use OAuth2 server which is provided as a separate instance from drupal and my single page application.
From my research I haven't found any concrete example/documentation on how to achieve this. What I have managed to achieve so far is to be able to utilize my OAuth2 server with the help of OAuth2 Authentication module.
My second part is now missing to integrate my single page application and pass some user details information to it.

To provide the page hosting the React SPA, you will need to implement a custom module. This module would also contains all the JavaScript code of your application. If that's the only usage of React in your site, I suggest bundling everything in the module to make it easier.

I assume you should be able to retrieve the user authentication token and any other needed info in Drupal. You can then pass it to your application using drupal_add_js() (or #attach in a render array). Your application can then retrieve it with Drupal.settings

/**
 * Implements hook_menu().
 */
function MODULE_menu() {
  return [
    'admin/APPLICATION/PATH' => [
      'title' => 'Awesome React Application',
      'page callback' => 'MODULE_application_page',
      'access arguments' => 'access administration pages'
    ]
  ];
}

/**
 * Page callback for the application page.
 *
 * @return The page as a render array with #attached JS and CSS code.
 */
function MODULE_application_page() {
  global $user;
  $app_data = clone $user;
  unset($app_data->pass);
  $app_data->token = MODULE_get_user_token();
  $base_assets_path = drupal_get_path('module', 'MODULE');
  return [
    '#type' => 'markup',
    '#markup' => '

',
    '#attached' => [
      'css' => ["$base_assets_path/css/app.css" => ['preprocess' => FALSE]],
      'js' => [
        "$base_assets_path/js/app.js" => ['preprocess' => FALSE],
        [
          'type' => 'settings',
          'data' => ['MODULE' => $app_data]
        ]
      ],
    ]
  ];
}


Fetching title of articles with taxonomy terms which are its siblings I am making a view that gives the title of an article. It has a term reference field. Taxonomy tree is somewhat like:

A

a
b
c

B

1
2
3

So I want to make a view that work in such a way that when one is on the taxonomy term page "a", he could see all the relevant title of taxonomy term 'a','b' and 'c'.

This is the query that the view has generated.

SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language, node.created AS node_created, node_counter.totalcount AS node_counter_totalcount
FROM
{node} node
LEFT JOIN {field_data_field_categories} field_data_field_categories ON node.nid = field_data_field_categories.entity_id AND (field_data_field_categories.entity_type = 'node' AND field_data_field_categories.deleted = '0')
INNER JOIN {taxonomy_term_data} taxonomy_term_data_field_data_field_categories ON field_data_field_categories.field_categories_tid = taxonomy_term_data_field_data_field_categories.tid
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_data_field_data_field_categories__taxonomy_term_hierarchy ON taxonomy_term_data_field_data_field_categories.tid = taxonomy_term_data_field_data_field_categories__taxonomy_term_hierarchy.tid
LEFT JOIN {node_counter} node_counter ON node.nid = node_counter.nid
WHERE (( (taxonomy_term_data_field_data_field_categories__taxonomy_term_hierarchy.parent = '46' ) )AND(( (node.status = '1') AND (node.type IN  ('article')) AND (node.language IN  ('en')) )))
ORDER BY node_created DESC, node_counter_totalcount DESC
LIMIT 7 OFFSET 0

But is still not working.

Can you create contextual filter in Views -> taxonomy parent term ID.
This should work.


Sublimetext 2 does not recognize .module file as php file I have seen a few posts suggesting how to customize SublimeText for better drupal development, although I did not see any mention of and not sure how SublimeText2 would recognize my custom module's .module as php file and show the various color highlighting for it.

Currently it just treats my .module file as an unknown file and does not show any color highlighting on it.

Thanks.

When you have the .module file open, go to:

View -> Syntax -> Open all with current extension as

and select PHP. This will then default all .module files to use PHP syntax.


How to redirect an exposed filter query to a views results page that lives in another panel page? My setup: Drupal 7.2, Panels 7.x-3.0-alpha3, Views 7.x-3.0-beta3, Chaos tool suite 7.x-1.0-beta1

Say I want to create a fruits directory website. In views I have a content pane "fruits" with exposed filters based on taxonomies "color". The website is supposed to have two panel pages. The first panel page displays only the exposed filter box "search a fruit" with a dropdowns for "color" and a search button. Upon choosing from the dropdown and clicking the search button the user is supposed to get redirected to the second panel page that includes the view's content pane displaying a list of fruits that match the filter (color).

The problem is: the exposed filter box on first page won't redirect to the result page after clicking the apply button. How do I set up views and panels to achieve this?

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='views_exposed_form') {
    global $base_url;
    $form['#action'] = $base_url.'/path_that_you_want';
  }
}


How do I hide the default page /node? Drupal out of the box comes with a page (which is the default homepage) that is assigned to the node path.

How do I avoid users reach it, and redirect them to the actual homepage of the site?

There is no easy way to hide that page. If you don't use it, you can implement hook_menu_alter(), and either remove it completely, or set its access callback to FALSE.


Is there a list of file/image field subtokens? Token browser does not show the options for file properties. [node:file-field:0:file:url] gets the url, but is there a list of all file options? Or is there a way to check it from sourcecode somehow?

Gathering the list:

[node:field-image:0:file:url]
[node:field-image:0:file:extension]
[node:field-image:0:file:name]
[node:field-image:0:file:size]
[node:field-image:0:file:mime]
The last thing that is still unknown to me is if there is an option to pull image width and height? If I remember correctly that data is in the db.

For file https://www.drupal.org/node/390482#token-file
https://www.drupal.org/project/imagefield_tokens
and
add https://www.drupal.org/project/filefield_paths   add this module
for {The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.}

Check this screenshot:


Is there a module which allows users to edit text together? I am building a site which allows users to upload handwritten images and transcribe them. Ideally, I would like if there were a text box type of module which updated the default value of the box each time it was written to.

Example:

Text box is created: "Default text"
Alice updates text box: "Alice was here!"
Text box now reads "Alice was here!" to all users.
Bob updates text box to "Alice was here! And bob!"

Is it possible to do something like this using modules? If so - which?

The page layout will look something like this:

[ Slide show ]
[ Transcription box ]
[ Comments ]

Ideally it would have the following functionality:

The image must appear on the page alongside the text editor (I had a WYSIWYG in mind but haven't been able to crack it yet)
Version control for text
Load 'default text'
Saving would overwrite the 'default text'

Is it possible to embed the transcription box in to the page? It is important that the user is able to view the image while editing the text box.

Thanks

Maybe you want to consider using the Paragraphs module for this. Here are some quotes about it (from its project page):

  Paragraphs is the new way of content creation!
  It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.

  Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.

  Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.

Some other questions on Drupal.SE where the Paragraphs module has also been suggested as a possible answer (which may help for more inspiration about what kind of things you can do with this podule):

Modular Drupal content-type (variable sections).
Simulating TYPO3-Template-Engine.
Alternative to Field Collection.
What is the best method to allow a user to attach dynamic, custom content sections to a node?


Setting up multilingual nodes I am trying to set up a D8 (8.7.9 to be precise) multilingual site and hitting some weird bug.

I have a node type basic page consisting of the title field and a body text field.

Initially I create the page in German (title: "test page de" / content "test content de"), then click Translate to add an english version, save it. So far, so good - the german page pops up at /de/node/12, the english one at /en/node/12, the language switcher works fine.

Then, I edit the German page to say "test page de-1"/"test content de-1", and submit. The German page shows the proper content, as does the English one, but now, when I edit the English page, I suddenly get the title set to "test page de-1" and the body to "test content de-1". What is going on here?

Found the issue: I had the language detection under /admin/config/regional/language/detection messed up - content language detection was identical to UI language detection (which was User account first, URL second). Used URL only for content language detection and now it works.


How do I get the user name of the user profile page that is being visited? I created a module and I need to use the user name of the user's profile being viewed.

How do I call/get it?

You can load a user object like this :

$current_user = menu_get_object('user', 1);
$username = $current_user->name;

Reference of menu_get_object function.


Add profile name field into the user page I have overwritten the user-profile-form with hook_form_alter.

Right now there are additional fields in the user-profile-form, so the user can add more information about him/her and these fields will be visible in /user/% page.

I'm wondering is it possible to add more details in /user/% without using the user-profile-form?

Let's say to display a field "Profile of [name_of_the_user]", so anyone who enters the user profile (Example John) in the top of the page will be displayed "Profile of John".

Is there any hook for that?

You can print the user name when a user is logged in using something like this...

<?php print t('Profile of '); print l($user->name,'user'); ?>

Which will display "Profile of John Smith". (This will only print the name of the user that is currently logged in)

When viewing another users profile, their name is printed as the page title. I haven't tried this myself, but you could just print the title again, with the additional text around it.

To do this...

Profile of <?php print $title; ?>

Should do the trick, as long as it is only printed on the /user page. You should add the code to your custom user-profile.tpl.php. This will print the name of the users page you are looking at, instead of the currently logged in user.


Show a field in table if current user is node author I want to create a view block that shows all published nodes of a certain content type. I've included an image below.

However the trick here is to only show the link Print Report if the logged in user is the author of that node. So if you look at my image above, the user Dennis Bonilla should be able to see his Print Report link but not see one for the row below for Test McTest.

Is there a module that can help me do this or some administrative trickery in the views ui? Or maybe even programmatically?

Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

Views PHP
Computed Field


Unable to change the OG membership type I'm trying to add a "restricted" group membership type to only show teasers of a content type to some members. I'm calling the following function from a Rules action; however, the membership ends up being a OG_MEMBERSHIP_TYPE_DEFAULT.

function mymodule_subscribe_restricted($account, $group) {
  og_group($group->gid, array('entity type' => 'user',
    'entity' =>  $account,
    'state' => OG_STATE_ACTIVE,
    'membership type' => MYMODULE_OG_RESTRICTED));
}

Looking at the source code of og_group(), the membership type should go through. And it's defined correctly in the db table og_membership_type.

Any quick pointers or should I just refactor the whole thing to use a separate group role instead of a membership type?

Found out this is an existing issue with OG 7.x-1.4: http://drupal.org/node/1572480.


Adjust topic title length on topic listing page (Advanced Forum) I'm trying to find the right  way of adjusting the topic title length displayed on the topic listing page generated by Advanced Forum (mysite.com/forum/[myforum]).

I tried to manipulate the title variable offered by the template-advanced-forum.naked.topic-list-view.tpl.php and the corresponding theme function but it gives me formatted HTML like this:

Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
 by Anonym » ons, 18/01/2012 - 17:05

My guess is that I need to go "further back" in the theming process somehow to get a hold of the title variable, but I must admit this is beyond my Drupal skills. Any suggestions?

I am using D7 and Advanced Forum (version 7.x-2.0-beta1).

Not sure if this is exactly what you're looking for, but Advanced Forum integrates itself with Views.

So (assuming you have the Views module), you can trim the length of the title field in the advanced_forum_topic_list view. This c done by clicking the Content: Title (Topic / Topic starter) field, going to 'Rewrite results' and checking 'Trim this field to a maximum length'.

Because the field contains HTML to insert a span tag, you'll have to add 32 to the trim count (e.g. if you want to trim to 20 chars, enter 52), and ensure 'Field can contain HTML' is checked.


Is exposing the UID a security issue? I noticed that the UID of users is exposed in the HTML code of a page on my site that authenticated users can access.

Is it a problem if authenticated users with "view user profiles" permission are able to find the UID of any non-disabled user account?

According to this post by the Drupal Security Team, it is not considered a vulnerability:

Disclosure of usernames and user ids is not considered a weakness

  Drupal's philosophy

  Usernames are an important part of online identity. Having a public username helps other users of a site to know the identity of the person they are interacting with in a forum or a blog. Drupal is primarily intended to be used for sites where identity and interaction are key elements so it is reasonable for that information to be public.

Of course, it will vary by site, depending on what that information allows other users to see.


Views Page Showing Root Title in Window (not views title + root title) My views page title is set to "The Title" but my window title shows as "Website" rather than "The Title | Website". This is only for my views. Any ideas what would cause this? I have a few other modules installed but not Page Title, that's disabled.

The title for a view does not show up in window title.   The Window's title is determined by the browser, independent of Drupal. The view title is used as the title before the body of your content in the content display area of the window provided you have configured the view to display the title.


How can I disable the node page for a specific content type? (But still use colorbox-node) I use colorbox en colorbox-node to show the content of a node but I don't want people to access the node page for that content type.

How can I disable the node's detailpage and still access all the content in colorbox-node?

In node.tpl.php you can test if node is accessed directly, and if so - redirect him to page with the same node inside colorbox. Or any other page, of course.


How to get the vocabulary terms for the current language How do I programmatically get all the terms within a vocabulary for the current language?

This is a similar question to Get translated term name, but not for a single term, but for the entire tree.

Two issues here:

Getting the current language, and
Getting the terms for the current language

1. Getting the current language

Use the global $language variable and get its language property:

$language->language

2. Getting the terms for the current language

In theory, you'd use i18n_taxonomy_get_tree, like so:

global $language;
$tree = i18n_taxonomy_get_tree(1, $language->language,0,NULL,FALSE);

but it seems that function is buggy. Instead, you can try using i18n_taxonomy_localize_terms with taxonomy_get_tree instead:

if (module_exists('i18n_taxonomy')) { // Check if the module exists
    global $language;
    $tree = i18n_taxonomy_localize_terms(taxonomy_get_tree($VID,0,NULL,FALSE));
} else {
    $tree = taxonomy_get_tree($VID,0,NULL,FALSE);
}


How do I debug my Feeds import not importing a field I have a Feeds import set up to import products into Drupal Commerce (from csv). My product type has a number of term reference fields that also need to be assigned a value by import. Most of these work fine (e.g.: field_product_unit, field_product_discount_category), except one: field_product_group. I'm searching the taxonomy term by term name.

Importing the product group used to work at some point, but for some reason or other, it stopped working. Not a single value gets imported. I can't pinpoint when it quit on me. I don't see an obvious difference between the fields that do work, and the one that doesn't. The only slight difference is that product groups are hierarchical, and the other taxonomy lists don't use hierarchy.

I don't get any error messages or "I can't find this term" notices.

I've tried the following:

checked and double-checked the names of the terms matching the csv values: they do.
importing my taxonomy term name into a text field (to make sure it could find the input field): works fine.
my taxonomy lists all use multilingual names and descriptions. To avoid a mix-up there, I reset it to a single language: no difference

How do I proceed now? How can I figure out what's going wrong?

As a first step, you could check whether the field has been parsed properly:

In sites/all/modules/feeds/plugins/FeedsProcessor.inc:

Add debug($item) after line 180:

  public function process(FeedsSource $source, FeedsParserResult $parser_result) {
    $state = $source->state(FEEDS_PROCESS);

    while ($item = $parser_result->shiftItem()) {
       debug($item); // debug entry

      // Check if this item already exists.
      $entity_id = $this->existingEntityId($source, $parser_result);
     ...

debug() is a core function that lets you print out debugging information:

https://api.drupal.org/api/drupal/includes!common.inc/function/debug/7 and/or

http://blog.boombatower.com/drupal-7-debug-and-simpletest-verbose?utm_source=buffer&utm_campaign=Buffer&utm_content=buffer5ee6f&utm_medium=twitter

The result will be processed using drupal_set_message(), and will appear in http://example.com/admin/reports/dblog (probably, depending on your configuration).

You'll get one notice for each imported line, like:

User notice:

array (
  'title' => 'This is a test title',
  'body' => 'And a test body',
  'tax' => 'And a taxonomy term',
  '' => '',
)

Alternative: download (from http://drupal.org/project/devel, or drush dl devel) and enable the Development module (Devel in admin/modules), or drush en devel and use drupal_debug() or another tool from the devel module.


Add a remove button to a custom unlimited value field? I'm working on a custom compound field that includes a text value and an entity reference id. The field will contain multiple values, so the widget needs to provide "add new value" functionality, and a way to remove values already added (i.e. a "remove" button).

Following the (older) thread here: https://drupal.org/node/1143880, it seems that "add new value" is provided automatically, but not "remove" existing values? Is that still the case?

The thread above also links to a sandbox project here: https://drupal.org/sandbox/daggerhart/1363702. I tried this code, and it does seem to work, although the formatting is a little different.

What's the current best practice for adding a "remove" button to an unlimited value field widget?

Edit: here is a link to a feature request for this functionality in D8: https://drupal.org/node/1038316

there are two modules already

Multiple Fields Remove Button
Field Remove Item


SMTP module - "Unable to send e-mail..." and "A test e-mail has been sent..." I am using the SMTP module (7.x-1.0) on Drupal 7. The site is hosted on a cloud server on which I've installed LAMP. My SMTP config settings are:

SMTP server:  smtp.gmail.com
SMTP port:  465
Use encrypted protocol:  SSL
Username: example@gmail.com
Password: [password]
E-mail from address: example@gmail.com

When I try to send a test email, I get two messages and an error in the "Reports > Recent log messages":

A test e-mail has been sent to example@gmail.com. You may want to check the logs for any error messages.
Unable to send e-mail. Contact the site administrator if the problem persists.
Error sending e-mail (from example@gmail.com to example@gmail.com).

The email is NOT sent. However, the email appears in "Reports > Maillog" (Maillog module).

There is an error in /var/log/apache2/error.log:

  sh: 1: /usr/sbin/sendmail: not found

Update/Edit:

I was under the impression that the SMTP module avoids the need for
Sendmail.I thought, the whole point was that it uses an external SMTP
server. I found the following issue by the way:
drupal.org/node/1078106.

It looks like the sendmail service is not installed.

Try the command sudo apt-get install sendmail via ssh to install it.


How to convert static HTML template to drupal theme Is there any tools available to convert html template to drupal theme and is there any modules that make drupal 7 theming much easier ?

There is no such tool that converts HTML to Drupal theme. But there are services where we can create some kind of Drupal theme with basic regions & templates.

Some modules you can try

Themer 6.x only
Theme developer
Skinr

Theming Drupal 6 and 7

Modules for theming

A nice screencast for a beginner
Introduction to Theming Basics for Drupal 7


how to save new value of autocomplete field with hook_form_submit? creating a custom submit function for the form of mymodule

/**
 * Implements hook_form_submit()
 */
function mymodule_form_submit($form, &$form_state){

    $new_user = drupal_anonymous_user();
    // removed basic user fields here to make it more clear

    // save taxonomy checkbox field
    foreach ($form_state['values']['third']['field_functioncat'] as $key => $value) {
        if($value > 0){
            $new_user->field_functioncat[LANGUAGE_NONE][$key]['tid'] = $value;
        }
    }

    // save text field
    $new_user->field_firstname[LANGUAGE_NONE][0]['value'] = $form_state['values']['first']['field_firstname'];

    user_save($new_user);
}

Above code works but I'm having trouble saving the autocomplete field.

What I'm trying:

// get value of the form
$tid = taxonomy_get_term_by_name($form_state['values']['first']['field_city'], 'field_city');
// get the first array value and then the tid of the left over object:
$tid = reset($tid)->tid;
// save field to user profile
$new_user->field_city[LANGUAGE_NONE][$tid]['tid'] = $tid;

This works for existing terms, but when I put in a new term it can't get the id of the term because that term name is not created?

How do I create the term name and get the tid to submit it to the user creation?

note:
I've created the field_city as taxonomy term and linked it to the user profile so it's visible and editable in on the user edit profile page.

As you said if you're unable to find the tid then its a new term. You can save the new term using taxonomy_term_save()

For example,

$term = new stdClass();
$term->vid = <field city vid>;
$term->name = $form_state['values']['first']['field_city'];
taxonomy_term_save($term);

After saving the new term you can access the tid like this,

$term->tid

If you want to fetch the vid referenced with particular field then look at the following thread - How to get the field settings in drupal 7


How to programmatically set user state to "active" Is it possible to programmatically set all users to active?

This problem arises because I am trying to display my users using Views, but because my migrated users are "blocked", I cannot expose them to Views.

Could someone provide a snippet of code or a tutorial on how to set user status to active?

This is the code that I need to execute at the beginning.

define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost";
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Set the active DB
db_set_active('sage');

You can use a combination of user_load_multiple() and user_save() to update the status property of the users:

$uids = db_query('SELECT uid FROM {users}')->fetchCol();
foreach (user_load_multiple($uids) as $account) {
  $account->status = 1;
  user_save($account);
}

It's worth bearing in mind that any mail notifications you have set to inform users of their account status will be invoked using this method.

If you don't want that to happen I think you'll have to go directly into the {users} table and set the status manually (not recommended):

db_update('users')
  ->fields(array('status' => 1))
  ->execute();


All Blocks in One Theme Automatically Disabled On a Drupal 7 site that I help maintain, the blocks in one of the themes were all disabled automatically.  I manually added all of the blocks back of course, but can't promise this won't happen again.  To try to find out what happened, I queried the block table and discovered that the tracking columns are not provided (e.g. created, changed, uid).  So then I went on to see if MySQL could tell me the last time that these rows were modified, but there is no such native function.

Has anyone seen this problem?

I haven't run into this specific problem, but I would advise getting as much of this as you can into Features - that way you can easily revert it all back, should this problem recur, and you wouldn't have to do it manually.


Commerce Kickstart: facets are disabled when using back button Commerce Kickstart facets get temporarily disabled (showing reduced opacity) after selecting one of them until the new search downloads. This is a cool feature. However, if the user clicks the browser's back button after that, then the previous page is displayed without reloading and the facets are still disabled, therefore making a new search impossible unless the user manually reloads the page.

In order to reproduce this problem, just visit KickStart Demo (http://demo.commerceguys.com/products), select a facet term, wait until the search is loaded and then go back.

What's the easiest way to solve this? I've been thinking of forcing a page reload in search pages or to use jQuery to make sure that all facets are enabled. Neither of them sound very natural.

Thanks for you answers!
David

This is an issue with how FireFox serves cached pages when you use the Back button.

There appears to be two ways of solving this:

1) Per the first answer here, set autocomplete="off" for all form elements that can be disabled. As that form likely isn't one you have direct control over (without hacking a module), you'll have to do this with a hook_form_alter().

2) The second answer in the question linked above provides some JavaScript that you can use to stop this from happening:

window.addEventListener('pageshow', PageShowHandler, false);
window.addEventListener('unload', UnloadHandler, false);

function PageShowHandler() {
    window.addEventListener('unload', UnloadHandler, false);
}

function UnloadHandler() {
    //enable button here
    window.removeEventListener('unload', UnloadHandler, false);
}


When creating a content type programmatically, is there a way to disable promoting to the front page by default? In Drupal 7, I'm creating a large number (15+) of content types programmatically. There is one in particular that should never be promoted to the front page. It would be really nice if, by default, the box to do this was unchecked. I'm aware that this can be done through the front-end, but my goal is to make the web application as portable as possible. That is, other than content, I want it to be able to be moved completely and properly by only installing the correct modules.

I'm removing authoring information, for instance, by setting the variable node_submitted_{content type name} to FALSE. It would seem like there should be something like this available for promoting by default.

Thanks.

Whether nodes of a particular content type are promoted to the front page by default is stored in the Drupal array variable node_options_{content type name}:

$node_options = variable_get('node_options_{content type name}', array());
$promote_key = array_search('promote', $node_options);
if ($promote_key !== false) {
  unset($node_options[$promote_key]);
  variable_set('node_options_{content type name}', $node_options);
}


Link a Drupal 7 site with a Facebook account I would like to know if there is a Facebook App that can automatically post content from the feed generated by a Drupal 7 site to one's Facebook Wall.
I would like something that does what My Blog Posts Facebook App promises to do but more efficiently (since that works only by manually refreshing the state).

Thanks a lot !

You might want to check out Drupal for Facebook.

A quote from the project page: If you already have content in Drupal, you can expose it on Facebook.

Documentation can be found on http://drupal.org/node/195035


Issues with update hook in drupal 6 I have this purchase module defined. And I have implemented the update hook something like this

<?php
  function purchase_update($node) {
    echo 'Updating';
    exit(0);
  }

  function purchase_help($path, $arg) {
    $output = '';
    switch ($path) {
      case "admin/help#purchase":
        $output = '<p>'.  t("Update help") .'</p>';
        break;
    }
    return $output;
  }

However, whenever I edit a node of type purchase, it doesn't call my update function. Any suggestions what could go wrong?

Did the purchase-module create and implement the entire purchase node type or did you create that in the admin system?

If you created it in the admin-system you can't use those functions. They are for node type modules (a rarer and rarer kind of module use these days).

You probably want hook_nodeapi. It's a common misconception.
http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6

function hook_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'update':
      if($node->type == 'purchase') {
        echo 'Updating';
        exit(0);
      }
    break;
  }
}


Comments - Allow deletion of comments on your content without Administer Comments permission? Is there a way to allow users to delete comments that are on their own content without giving access to Administer Comments?

Example:

Authenticated user makes a blog post (or some node content)
Another Authenticated user comments on it

Author does not like comment- wishes to delete.

The only option I have is edit/reply.

Should be doable with the User Comment module in Drupal 6, or the Comment Access module in Drupal 7. They both add permissions so that authors can approve, delete or administer comments on their own content.


Drush archive-dump override sql dump name Is there a way to use drush archive-dump but to pass it somehow the name of sql file it dumps into archive? Current name is too long (full path with dots instead / and # to separate path and site name) and not as useful so I would love to override its name (like I can do with tar.gz name with --destination parameter)

Unfortunately, there is no way to stipulate what the sql dump file should be named.  See the archive-dump source code for reference.

Wouldn't be too hard to adjust; PRs would be welcome.


output same form buttone on same page - drupal_render($form I try to duplicate form button on the same page. The button is printed like this

drupal_render($form['continue_shopping']);

The problem is that once I render the button, the second one is not rendered again later in DOM. How to overcome this? Thank you

From the top of my head, I would just duplicate the button in hook_form_alter() and render it as two separate buttons.

Some code examples here:
https://www.drupal.org/node/1415334

And here:
How to add extra save buttons


Taxonomy vs. CCK List for categorizing Events Could someone let me know what the best practice is for choosing between implementing something as a Taxonomy vs. a List field in the Content Type?  Assuming that there is a preset list of values and there is no need for content creators to create their own.

For example, a Content Type of an "event" could be categorized based on audience or type.  Audiences can be [Kids, Youth, Adults, Seniors, etc.].  Similarly, type would have a preset list as well.

Should audience or type be created as Taxonomy or a List field in the Content Type?

If you use taxonomy, then using the calendar module they can be colour-coded in the legend based on their category.


Imce file browser not showing select button The IMCE file browser seems to be missing it's select button. On this File field, I'd like content creators to choose an image that is already located on the server (not uploading a new image).

What setting might I have missed?

The field on this content type is configured as follows:

The profile is configured as followed:

File Permissions
The /tmp folder is owned by the apache user and is chmod'ed to 2775. The /sites/default/files/images folder is owned by apache and chmod'ed to 755.

Oh for heavens sake. I turned off Aggregate-JavaScript and cleared cache. The select button shows up. As to why this happened I can't say. I'm leaving this answer here in case any one comes up against this.

Temporarily turn off magnification and clear cache.


How can I import the contents of an uploaded csv file into a drupal managed table using rules custom php? I am using drupal 7 and have the data module managing/adopting a table I have manually added to my drupal db. What I was hoping was that when a csv file is uploaded via a specific content type I could use rules to execute some custom php and import the csv into the table (as feedsdataprocessor no longer exists from what I can see). I see there is a drupal_write_record function but the problem is first how do I get the array out of the file and secondly my file can be different to the table in structure - for example, sometimes the csv will have columns 1,2,3,4 and sometimes 3,4,5,6,7. How can I check the headers and import into the managed table?

So conceptual steps:

Extract CSV file path from the node.
Open CSV file, read fields from header.
Read each row, convert the keys, save row using drupal_write_record().
Close the CSV.

I'm not sure how the rules integration will work I'm assuming you can pass the node into it some how.

So for step one assuming it's stored into $node and your field is named field_csv_file we can hand the URL to fopen():

$csv_uri = $node->field_csv_file['und'][0]['uri'];

So now we can open fopen() to get a file handle:

$handle = fopen($csv_uri, 'r');

If there's no value we don't want to procede.

Read the header row:

$row = fgetcsv($handle);
$columns = array();
foreach ($row as $i => $header) {
  $columns[$i] = trim($header);
}

Then load each row and convert the format:

while ($row = fgetcsv($handle)) {
  $record = array();
  foreach ($row as $i => $field) {
    // This is pretty brittle... if someone screws up the field
    // names the data won't be written.
    $record[$columns[$i]] = $field;
  }
  drupal_write_record('your_table', $record);
}

Close the file:

fclose($handle);

So issues with this:

All this code it totally un-test.
What happens if someone re-uploads the file? You'll probably get duplicates.
What happens if someone messes with the headers?


multiple keyword match with db_like I am using db_select for database query, following code works fine when $keyword is any string

 $result = db_select('my_table', 'mt')
        ->fields('mt')
        ->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE')
        ->execute()
        ->fetchAllKeyed();

How can I make the same query working when $keyword is suppose to be an array of strings like ("del","mum") ,if my_column is location column so query will return me places like Delhi, Mumbai.

You can build your query while looping through each keyword and adding this as an OR condition.

$db_or = db_or();
$query = db_select('my_table', 'mt');
$query->fields('mt');

foreach ($keywords as $keyword) {
    $db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE');
}

$query->condition($db_or);
$results = $query->execute()->fetchAllKeyed();


Integer thousands separator in add node form I need to place thousands separator on integer field type in add node form when the user is typing a number in the field. Is there any module or quick solution for this problem?

you can quickly and easily build a custom module around this:

<form>
    <input type='text' id="input">
</form>

<script>
    jQuery('#input').keyup(function (event)
    {
        var value = jQuery('#input').val();

        if(event.which >= 37 && event.which <= 40)
        {
            event.preventDefault();
        }

        var newvalue = value.replace(/,/g, '');
        var valuewithcomma = Number(newvalue).toLocaleString('en');
        jQuery('#input').val(valuewithcomma);
    });
</script>

adapted from here

EDIT

This code has been modified and works in Bartik theme, using an Article content type with an integer field 'number' - it simply resets the value of the input and strips the commas before the form is submitted to the server:

<script>
    jQuery('.page-node-add-article .field-name-field-number input').keyup(function (event)
    {
        var value = jQuery('.page-node-add-article .field-name-field-number input').val();

        if(event.which >= 37 && event.which <= 40)
        {
            event.preventDefault();
        }

        var newvalue = value.replace(/,/g, '');
        var valuewithcomma = Number(newvalue).toLocaleString('en');
        jQuery('.page-node-add-article .field-name-field-number input').val(valuewithcomma);
    });

    jQuery('.node-article-form').submit(function()
    {
        var text = jQuery('.page-node-add-article .field-name-field-number input').val();
        var newtext = "";
        for (var i = 0; i < text.length; i++)
        {
            var c = text.charAt(i);
            if (c != ',')
            {
                newtext += c;
            }
        }
        jQuery('.page-node-add-article .field-name-field-number input').val(newtext);
    });
</script>