How to translate field collection which has unlimited values? My configuration:
latest dev entity translation and field collection module + patch.
I tried:
1. Entity translation is on just for taxonomy term and node, but not for field collection (it triggers notice: not translatable because of valid base path...)
I have taxonomy term with field collection (unlimited value). In FC field there are just two fields that needs to be translated. FC and fields inside FC have set "enable field translation by users".
With these settings I can create a term, set values to FC fields on default language and save. Then I can translate and set values to FC fields for second language and save. All good when checking if it did saved 2 different values - each for own language. Then I create view which is used on panels and is using termID as context filter. View has relationship on FC field and I added FC fields to show.
What happens: on view when I preview with term ID (context filter) I get correct result for the language in URL (en/admin/structure/views..). Also when I change URL to another language prefix I get translated fields in that language. But translated fields don't show on actual term pages.
2. Beside what I described in 1, I also enable entity translation for field collection. Notice about valid base path is still there, but I applied patch and i don't get errors when adding or translating FC.
With this configuration I create fresh FC with new fields and enable field translation for all of them. On term I set some values for FC fields and save it. I repeat this step when translating. But when I save translations and open them they are empty. On the next fill they remain. But the view for this configuration is still not showing right values for selected languages.
Does anyone have any hint what I am doing wrong? I really need to fix this issue on my site and I am short on time.
What I need is to translate FC field (and it's fields) which can have unlimited values.

I think that I found a workaround for this problem. Check my post at drupal.org.


How to switch existing file field from public to private? I have a Drupal 7 website with an existing file field set to store files in the public folder (i.e. sites/default/files).

I need to switch this one field so that it stores files in the private folder. Because the field has already been set to public and there are a number of existing files in place - the option to change the settings to private is not available in the user interface. I was wondering if anyone has a way to make this change manually in the database.

I know this was asked a while ago, but posting this in case anyone else needs it:

https://gist.github.com/thsutton/6878688

This gist takes the steps from this comment on d.o. and makes it into a simple script: https://drupal.org/node/1806220#comment-6960906

Here's the steps from the linked comment:

backup your site and db
copy the table for your field (and the revisions table for the field) to make a backup (in my case i copied: field_data_field_attachments to field_data_field_attachments_bk)
empty table field_data_field_attachments
go to drupal and the option to change the file system should be available, so change it
copy all data from field_data_field_attachments_bk back to field_data_field_attachments
go to drupal, select your content type, select your file field, in file path settings select retroactive update
click save and it will move all your files to the right place in file system and update your db to the new path

I ran through the script and field updates on several fields myself recently and it just works.


How can I change the style of a specific CCK field? I need to change the position to fields of content types. How can I modify the style of a specific field?

When I check the code for knowing the class, I see this:

<input id="edit-field-first-name-0-value" class="form-text text" type="text" value="" size="60" name="field_first_name[0][value]">

you can review the style in the source code, detecting the 'id' of the specific field.

for example add this rule (according the specific id):

#edit-field-color-value {
color:#00FF00;
}


How to show all autocomplete results ? I have a node reference field and the auto-complete widget. Right now, It only returns/suggests 10 nodes maximum.

How can i increase the number of nodes suggested by the auto-complete? (Or) better yet make it return all the suggestions?

You need to create a custom module and also you need a .info file change 20 to the number you want

function custom_tweaks_menu_alter(&$menu) {
  if (isset($menu['nodereference/autocomplete'])) {
    $menu['nodereference/autocomplete']['page callback'] = 'custom_tweaks_nodereference_autocomplete';
  }
}

function custom_tweaks_nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();

  $references = _nodereference_potential_references($field, $string, $match, array(), 20);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';
  }
  drupal_json($matches);
}

Taken from this source


Drupal 7: Variables in external file access Im having a tough time accessing variables from my own external file.

I gave this file:

?php include_once('/exercise_names.php'); ?

Which contains the following:

 ?php

//Exercise Names

$memory01 = '1';
$memory02 = '2';
$memory03 = '3';
$memory04 = '4';

?

I cannot get the page to render the names.  I keep getting the following errors:

Notice: Undefined variable: memory01 in eval() (line 4 of /home/webapps/drupal/releases/modules/php/php.module(80) : eval()'d code).

Basically its telling me it cant find the required variables, but they are in the file.  For some reason it cannot read the included file.

Any ideas?

thanks, Mac

If I have a module called foo, I put all of my includes in a subdirectory called 'inc/' and then use this

<?php

require_once(dirname(__FILE__) . "/inc/constants.inc");
require_once(dirname(__FILE__) . "/inc/class.FOO.inc");
require_once(dirname(__FILE__) . "/inc/class.BAR.inc");

in foo.module.  If doing Drupal 7, you may also want to take a look at the files directive for .info files:

  Drupal now supports a dynamic-loading code registry. To support it,
  all modules must now declare any code files containing class or
  interface declarations in the .info file, like so:

files[] = example.test

  When a module is enabled, Drupal will rescan all declared files and
  index all the classes and interfaces that it finds. Classes will be
  loaded automatically by PHP when they are first accessed.

EDIT TO ADDRESS COMMENT

Even if you aren't doing this in a module, you should really abstract out the constants into a module that provides getter functions and/or a static class and/or a singleton with getter functions.

Another option is to bail on includes, and use variable_set / variable_get, preferably in conjunction with a module settings form.


using EntityFieldQuery to find a custom taxonomy field I have the following query which works:

$query = "SELECT field_code_description_value FROM {field_data_field_code_description} WHERE bundle = :vocabulary AND entity_id in (SELECT entity_id FROM {taxonomy_term_data} WHERE name = :name)";
  $results = db_query($query, array(':name' => $fund_code, ':vocabulary'=>'fund_code'));
  $terms = $results->fetchObject();

I'm trying to convert this into using EntityFieldQuery, as it seems to be the best way to go (and I need some practice), but I couldn't get it right. This is what I tried:

$query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type','taxonomy_term')
      ->entityCondition('bundle','fund_code')
      ->fieldCondition('taxonomy_term_data','field_code_description', $fund_code, '=')
      //->propertyCondition('vid', $fundCodeTaxonomy->vid);

    $results = $query->execute();
    foreach($results['taxonomy_term'] as $tid) {
      $term = taxonomy_term_load($tid);
      dpm($term);
    }

How do I properly use EntityFieldQuery here?

The code_description field does not appear in the WHERE condition of the original query. Therefore there is no need to add a fieldCondition on the EntityFieldQuery neither.

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->entityCondition('bundle', 'fund_code')
  ->propertyCondition('name', $fund_code) ;

$results = $query->execute();
foreach($results['taxonomy_term'] as $tid) {
  $term = taxonomy_term_load($tid);
  dpm($term);
  $items = field_get_items('taxonomy_term', $term, 'code_description');
  dpm($items);
}

However there is already the core function taxonomy_get_term_by_name doing exactly what you need here:

$terms = taxonomy_get_term_by_name($fund_code, 'fund_code');
foreach ($terms as $term) {
  dpm($term);
  $items = field_get_items('taxonomy_term', $term, 'code_description');
  dpm($items);
}


How can i customize the display of private message module? I am new to drupal, present i am using Private message module 7.x-1.4 version.

After installing this module it look like this (screenshots attached) current look and feel is not pretty. how can I customize this ? suggest me the changes.

If as you say you only want to change the look/theme then you should create a custom theme and override it using custom css rules.

Doing this requires knowledge of css/html and creating a drupal subtheme as modifying an existing theme/module/core is not advisable

Here is tutorial of how to create a custom subtheme
https://www.drupal.org/docs/7/theming/howto/create-a-new-custom-theme-with-css-alone

NOT RECOMMENDED
If you still want to HACK core/module/theme then in your Chrome/Firefox/Opera/Safari browser just right click on the element that you want to change and use inspect/inspect element or something similar.  There you can see which css rules and in which file influence the display of each element. You can even adjust the visual properties (css rules) of each element and when you are satisfied with the result you should go and change the appropriate files.

Here is a tutorial of how to use the chrome inspector https://developer.chrome.com/devtools but inspectors of other browser should be very similar


Is it possible to programmaticaly change the HTML rendered by Drupal 7? Imagine that we have a project completely finished, with lots of modules, themes, etc. Is it possible at all to have a module, which will be called at the last stage, and change the HTML output. For example, we want to make a ereg_replace of a img tag, and we don't want to deep into the modules. Is there a simple hook which can accomplish this extremely simple task ?

If you want to alter the rendered content of a page, you start by adding a post_render function to the node:

/**
 * Implements hook_node_view_alter().
 */
function MODULE_node_view_alter(&$build) {
  $build['#post_render'][] = 'MODULE_wrap_images';
}

And then in that post render function, you can do what you need to do. In the example below, I am replacing float:left and float:right with a wrapper div:

function MODULE_wrap_images($content) {
  // Find all links within the content and extract the complete  tag.
  if (preg_match_all('##i', $content, $matches)) {

    // Loop matches and process.
    foreach ($matches[0] as $index => $match) {

      // Align images left.
      if (stripos($match, 'float: left;')) {
        $new = '
' . str_ireplace('float: left;', '', $match) . '
';
        $content = str_ireplace($match, $new, $content);
      }

      // Align images right.
      if (stripos($match, 'float: right;')) {
        $new = '
' . str_ireplace('float: right;', '', $match) . '
';
        $content = str_ireplace($match, $new, $content);
      }
    }
  }

  return $content;
}


REST response gets cached for guest user requests I've implemented kind of a page hit counter as REST request. The article page renders a JS into the page that does a jQuery.getJSON to the REST resource later.

So far that works fine. The page is delivered from cache (X-Drupal-Cache:"HIT") and the browser does an extra request to the REST resource (/api/v1/check/l/1?_format=json).

Unfortunately the REST handler is not called for guest user views. Instead, Drupal delivers the cached response. It only works for authenticated users.

For guest I get

Cache-Control:"must-revalidate, no-cache, private"
X-Drupal-Dynamic-Cache:"UNCACHEABLE"

BUT:

X-Drupal-Cache:"HIT"

And the REST handler is not executed. My REST response is

return (new ResourceResponse($rc))->addCacheableDependency(null);

Thanks

This is probably the page cache for anonymous users, which works independently from the dynamic cache.

You can disable it with this command:

\Drupal::service('page_cache_kill_switch')->trigger();

You can trigger this anywhere in your code and it will be valid for any response  you send for the request. So this should also work for a REST response.


Autcache + Varnish modules installed but cache tables growing I have a site in Drupal 7, multilanguage and multidomain, and when I do a weekly manual database backup (apart from the automated ones), I see that the size of the mysqldump file is of about 200 Mb. When I run the cron (which is set automatically to once each 3 hours), clear the cache, and then, finally, TRUNCATE all tables with prefix "cache_", the size of the dumped file reduces 4 fold to 50 Mb. I have Authcache and Varnish modules activated, so I thought that the cache was functioning in another way. How is it possible that the cache tables are so full, even with cron updating each 3 hours? May I have something wrong in the configuration?

Varnish should not ideally affect your cache tables, not sure about auth_cache. You should try the reverse approach to figure out what is wrong, check which of your cache tables is growing abnormally and then do bit of digging around to find what module/s is responsible for stashing cache data in those tables.

There is a well-known issue with cache_form table in D7, it can grow abnormally for some live sites. Check this issue, Cache Form table size is enormous.

If you find your cache_form also huge you can use one these modules to help you to periodically clear it, https://www.drupal.org/project/optimizedb or https://www.drupal.org/project/safe_cache_form_clear.

Hope this helps.


Are there Drupal modules that help process e-mails dynamically I had the idea of implementing a workflow module for e-mail communications, something like this:

User role 1 can write e-mails (as nodes or custom entities)
User role 2 can review and approve e-mails
User role 3 can press send

I would then like the website to catch replies and enter them into the database with reference to the user entities that touched the e-mail entity, so that the workflow can also be applied to replies.
The part that I'm not sure I can do here, is doing advanced e-mail processing based on which users touched the e-mail.

Are there any modules that can handle encoding these entity references into the reply-to or message of the e-mail so that the Drupal site can process the replies dynamically?

Inmail is designed to be the low level framework to receive mails within Drupal. We proposed in D8 to also implement Mailhandler on top of Inmail and there's good chance this will happen to reduce complexity.

Inmail "works" and you can write plugins to handle the mails.

What you need is a system that supports dynamic mail addresses (through e.g. address expansion). They then need to be redirected / forwarded to the site. This is more a mail server (MTA) configuration than inmail on its own. Through this, every reply is sent to a unique mail address (defined when sending). You can then while handling the mail easily lookup the reference / know the origin.

We plan to add more support for common mail configuration to consider these dynamic situations through configuration only at some point.

Check the issue queue, open feature requests if you can't find a proper issue and start contributing to it! ;-)


Cloudflare country code for language negotiation Cloudflare.com provides CF_IPCountry http header.
This can be retrieved in php with

$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

as they say. It'll return XX if the country cannot be determined.

How can this header be used to negotiate language?
(I want to use it so that if users come for example from France, then to be redirected t www.site.com/fr/ homepage, and if they come for any other country in the world go to www.site.com/en/ homepage?)

My research:
There are 2 modules for Drupal 7, but I don't think they can do what I want.

One module is http://drupal.org/project/ip2locale, which is dev version and not updated for a year, and the other is http://drupal.org/project/smart_ip, which says it breaks caching because it adds session variable.
They both don't use cloudflare as source of ip.

Is there any php snippet that I can add somewhere, so that $_SERVER["HTTP_CF_IPCOUNTRY"] takes me to the locale I want?

If you ask me why I want to use cloudflare header, I suppose that maybe it's faster to determine country and more updated with ips, than other free solutions.

Thanks

Drupal provides a hook for those module that implements a new method for detecting the language to use: hook_language_negotiation_info(). This hook gets information about some callbacks, including the one that returns the language ID.
As example of hook, you can look at locale_language_negotiation_info(), and to the three callbacks used for the first provider: locale_language_from_url(), locale_language_switcher_url(), and locale_language_url_rewrite_url().

Any provider the modules implement are listed on admin/config/regional/language/configure, where the administration user can enable each of them.

The providers that are enabled are called to provide a language ID. For what I can understand code similar to the following one should work.

function mymodule_language_negotiation_info() {
  $providers = array();

  $providers['mymodule_cloudflare_provider'] = array(
    'callbacks' => array('language' => 'mymodule_language_from_cloudflare'),
    'weight' => -4,
    'name' => t('Cloudflare'),
    'description' => t("Use Cloudflare to detect the language used where the user is actually located."),
  );

  return $providers;
}

function mymodule_language_from_cloudflare($languages) {
  if (isset($_SERVER["HTTP_CF_IPCOUNTRY"])) {
    $langcode = mymodule_get_langcode($_SERVER["HTTP_CF_IPCOUNTRY"]);
    if (isset($languages[$langcode])) {
      return $langcode;
    }
  }

  return FALSE;
}

mymodule_get_langcode(), the function for which I didn't write the code, should return the language code from the country code returned from Cloudflare.com.


Using states in Drupal 7 form to provide 'select all' functionality I'm trying to use this to achieve the functionality of having a checkbox that, when selected, causes a range of checkboxes to all be selected. I made the selectall box a separate form field, and it looks like this, and works not a lick:

$form['report_group']['selectall'] = array(
  '#type' => 'checkbox',
  '#default_value' => 0,
);

$form['report_group']['boxes'] = array(
  '#type' => 'checkboxes',
  '#options' => $boxes,
  '#states' => array(
    'checked' => array(
      ':input[name="report_group[selectall]"]' => array('checked' => TRUE),
    ),
  ),

I don't think the "checked" property works with the "checkboxes" form control (or if I does I know how to use it!)

As a work around use the checkbox type instead:

$form['report_group']['selectall'] = array(
  '#title' => 'Check All',
  '#type' => 'checkbox',
  '#default_value' => 0,
);

$boxes = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five');

foreach($boxes as $key => $val) {

  $form['report_group']['box_'.$key] = array(
    '#type' => 'checkbox',
    '#title' => $val,
    '#return_value' => $key,
    '#states' => array(
      'checked' => array(
        ':input[name="selectall"]' => array('checked' => TRUE),
      ),
    ),
  );
}

Your selector was also wrong. This is a jQuery selector so I find it easiest to use firebug to figure out what it should be and test if it's working.


how to add a content creation in a view I've created a view where it displays all created articles by the current login user. named as "my Articles".

Now, I need to add a node/add/articles (which let me add a new article) together with the "my Articles"(view). where the "node/add/articles" is above of "my articles".

I don't have any idea how could I add an node/add/articles inside a view.

I need two solutions.

One is by not using a module and the other is using a module.

this could be done two ways that come to mind:

1) Create the view as a block, then under the block configuration set it to show at the top of the content region and only on node/add/article page

2) Create the view as a page, and then using Advanced Form Block create a block for the node/add/article form to show in the content region above the View, only on the page url for the view

  Welcome to Advanced Form Block Module. With this module you can do the
  following:

  1) Create any number of blocks with a particular node edit form.

  2) create any number of blocks with a particular node add form of a
  content type.

  3) Create as many blocks as you like of each kind.

  4) From the content type choose which fields to display on a per block
  basis.However required fields will be automatically displayed.

  5) All forms will be saved through ajax. So multiple node forms can be
  independently placed on a single page and worked with simultaneously.


How can i create a view of all drupal commerce products with the orders they appear in? I try to create an administrative view which lists all products in my drupal commerce installation, where some cols should contain data from the orders in which they appear:

PROD | PRICE | ORDERED
----------------------
one  | 12.-  | -
----------------------
two  | 10.-  | Pete P.
     |       | Anna D.
-----------------------
three ...

But as far as i can see, if i start a view of products, i have no relation to referencing line-items.

If i would start with line-items, i could not have products in my list, which appear in no orders...

Drupal Commerce does support some reverse reference relationships, but currently there is only a reverse relationship from products to nodes that reference them, not from products to line items that reference them. If I were you, I'd instead make the base table orders, because you can more easily establish relationships from orders to line items to products and get at the same fields that way. We use commerce_order as the base table for shopping cart Views, for example.


How to drush up multisite? I am not clear after reading another question on same topic how this is done.

At the moment I go to my root drupal install and drushup then updatedb so if I then go
to the folder of a multisite and try to drushup it says nothing to update.

If all the modules are in the root drupal install is that sufficient? Could you not make sure they are all placed in there so you would need to only drushup the root folder?

How then do you update individual databases?

There is Aegir, which is a system that helps you with doing that.

I personally have no experience with it, but I attended a talk on it a few weeks ago and it totally does the job.

In general, it gives you an admin interface of all your sites on that drupal installation while letting you update each one individually. It automatically rolls back if something fails.

Go have a look: http://www.aegirproject.org/

It probably is overkill with just two or three sites, but it seems to help a lot with bigger sites.


What's this type of content actually called? I think I've been getting the terminology wrong.

When I open a Panel and go to the Content region and click the gear icon, then Add Content a modal appears.

On the left of this modal are categories housing various site components - gallerys, forms, HTML, etc

What are these things collectively actually called?

I think those are called site content (but I don't know if you'll find a name for all of them written somewhere, as you said).


drupal_match_path() for multiple wildcard patterns? I want to add some CSS and JS to multiple matched wildcard URL patterns. According to Add javascript to multiple specific urls, I can use a wildcard using drupal_match_path() and that works well for one pattern. However, I am trying to use a few patterns to add the same JS and CSS. So far I've tried these:

  // By path matching wildcard patterns.
  $path = drupal_get_path_alias();
  $pattern = 'portfolio/* || photo-blog';

and

  $path = drupal_get_path_alias();
  $pattern = 'portfolio/*, photo-blog';

and

  $pattern = 'portfolio/*' 'photo-blog';
  $path = drupal_get_path_alias();

... but none of these work. I am guessing it may not be possible in the context of:

if (drupal_match_path($path, $pattern)) {
// add JS and CSS based on above
  }

The API page you've linked describes the format of the $patterns argument:

  $patterns: String containing a set of patterns separated by \n, \r or
  \r\n.

These are types of carriage returns, in different Operating Systems.

Sooo .... did you try:

 $pattern = "portfolio/*\nphoto-blog";
 // or
 $pattern = "portfolio/*\rphoto-blog";
 // or
 $pattern = "portfolio/*\r\nphoto-blog";

EDIT:

 // for platform portability heh
 $pattern = "portfolio/*" . PHP_EOL . "photo-blog";


Having trouble getting mega menu to work responsively I'm using Drupal 7 and bootrap theme, but I've tried other themes as well and I can't get it to work responsively.

What it does is drop down, but it doesn't scroll, having a hard time to troubleshoot with Chrome dev tool because of media queries.

Any idea what is causing this? Megamenu is supposed to be responsive out of the box?

URL is :

http://www.dev.wearelao.com

No, that module doesn’t claim to provide responsive menus.
Quite the opposite, in fact; its mission is to provide you with the tools you need to build your own styles, which can of course be responsive if you desire:

The module provides classes and ID's that allow for a full-range of styling customization, from more traditional (but multi-level) drop-downs to full width slide out menus.
A couple demo skins are supplied, but these are purely for instructional purpose to help get you started with theming your mega menu. Currently, you should have an understanding of how Drupal overrides module CSS files and how to add CSS to themes, in order to provide your own styles in your particular theme.

So the module just gives you a framework to start from, you need to provide your own CSS.


How do i change date format in View Exposed Date filter? How do I change date format in View Exposed Date filter?
By default it's in d/m/Y format, I want to make it Y.m.d format, without changing the query parameter date format (Y-m-d).

Any suggestion, how can I achieve this?

To make it easy let's disable Drupal datepicker and make it with javascript.

First disable jquery ui datepicker from exposed filter (like picture below)

Then create a module with libraries in file my_module.libraries.yml like below

d8_datepicker:
  version: 1.x
  js:
    https://code.jquery.com/ui/1.12.0/jquery-ui.min.js: { type: external, minified: true }
    js/datepicker.js: {}

And in our my_module.module let's alter the exposed form and add line below :

  function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
     if ($form_id == 'views_exposed_form') {
      $form['field_date_value']['#type'] = 'textfield';
      $form['field_date_value']['#attributes']['class'][] = 'datepicker-text';
      $form['field_date_value']['#attributes']['placeholder'] = 'yyyy-dd-mm';
      $form['#attached']['library'][] = 'd8/d8_datepicker';
      $form['#validate'][] = 'my_exposed_validate';
     }

In our validate form function we will change date from our custom format to format needed by drupal :

function my_exposed_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if(!empty($form['field_date_value']['#value'])) {
    $dt = date_create_from_format('Y-d-m', $form['field_date_value']['#value']);
    if($dt!==FALSE) {
      $value = $dt->format("Y-m-d");
      $form_state->setValue('field_date_value', $value);
    }
  }
}

And finaly in our file datepicker.js add this line :

(function($) {
    $('.datepicker-text').datepicker({ dateFormat: 'yy-dd-mm' });
})(jQuery);

Hope this helpful and if you wan't to go further, alter a form validation to check if the format sended is date or not ;)


How do I override the admin theme in my own theme? I created my own Drupal 8 theme:

mytheme.info.yml:

name: My Theme
description: 'Drupal 8 Theme'
type: theme
base theme: bartik
core: '8.x'

mytheme.libraries.yml

global-styling:
  version: 1.x
  css:
    theme:
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: { media: print }

I am using "Seven" as admin theme.

When I edit a page (/node/x/edit) Seven theme is used.

Now I have to add some CSS the the edit form.
How can I do this?
style.css is only loaded on front end pages. Edit pages use seven theme and my theme CSS is ignored.

How can I add some CSS to admin pages or edit forms in Drupal 8?

You can add admin CSS from a module hook.  Replace XXX with the module name.

1 Put your CSS in css/extra.admin.css

2 Declare a library by creating XXX.libraries.yml

extra.admin:
  css:
    theme:
      css/extra.admin.css: {}

3 Create a hook to load the library.

/**
 * Implements hook_page_attachments().
 */
function XXX_page_attachments(array &$attachments) {
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  if ($theme == 'seven') {
    $attachments['#attached']['library'][] = 'XXX/extra.admin';
  }
}


Alter menu link lists dynamically in regards to user's role? I have a navigation menu in a menu block. I want some of the links in the menu to be hidden if user doesn't have role xxx.

What is the best way to do so?

The best way to do it would be simply to restrict access to those pages to only the roles you wish to be able to see them. The menu system will automatically not print out links for pages the user cannot access.

How to do this depends on what you're linking to. If it's nodes, perhaps the core per-content-type permissions are enough. If not, there is a variety of node access modules you can use to implement more fine-grained node access, using taxonomy or other methods. If those pages are Views, you can set a View to only be available for certain roles.


how to track user profile page views? I want to track page views to a user's profile page similar to what the core "statistics" module does for node page views.

I don't want to use profile2 for my site, otherwise I could probably use the statistics module.

Eventually I want to use the Google Analytics module to track page views to cached pages as well.

I'm looking for a simple solution/workaround that I can use right now.

Have you checked the User Visits Advanced, and the User Visits modules?

The User Visits Advanced module is a module that depends from the User Visits module. It is extremely useful for social networking sites that wish to provide their users with statistics about the number of time a user's profile page is being viewed, and by which users.


create book navigation menu tree I have a book with few children article nodes. I would like to create a navigation block tree, that can be placed anywhere on page.

Problem: Normally if I place book navigation block using context (on book and article content type) - the menu shows all links with the link to main book.
However, if I try to print inside tpl.php like this

$block = module_invoke('book', 'block_view', 'navigation');
print render($block['content']);

The menu shows only child items. How to show the parent book as well?

This code worked for me:

$blockObject = block_load('book', 'navigation');
    $block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
    $output = drupal_render($block);
    print $output;


Override contrib module's theme I've been turning the internet upside down trying to find out how to simply override a contrib module's theme() file. Although I have find many ways that should work, no result pops up and I can't really troubleshoot why.

To be more specific, I want to override the output of the file (/sites/all/modules/contrib/commerce/modules/cart/theme/commerce-cart-block.tpl.php) through theme('commerce_cart_block').

Now, I've tried many things. I have tried something called suggestions trying trying to make a file named block--commerce--commerce_cart_block.tpl.php in my theme directory plus several other varies of names. I've also tried setting new path through custom_checkout_theme_registry_alter's passed array. But now changes are visible, with or without clearing the cache each attempt.

I'm clearly missing something since this should in my eyes be both easy to do and needed to be editable.

So the question in short; How can I with as good practice as possible override the theme file of a contrib module and use it's passed variables?

Copy commerce-cart-block.tpl.php file to your theme and edit that copy. Remember to clear your cache before you reload the page. That's all. Don't rename. Don't play with suggestions.


Multiple filed handlers in Views for a field How do I set multiple field handlers in Views on a single field.

I've applied the patch Relationship & sort for {history} to Views which brings in the user relationship on the history table. I then replaced the Views field handler for ['history']['timestamp'] in node.views.inc with this:

  $data['history']['timestamp'] = array(
    'title' => t('Node last access timestamp'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
      'help' => t('Show the timestamp a node was last accessed by user.'),
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
      'help' => t('Sort by the node last access time.'),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
      'help' => t('Filter by the node last access time.'),
    ),
  );

because I need the timestamp as a date field. Normally it is this:

$data['history']['timestamp'] = array(
    'title' => t('Has new content'),
    'field' => array(
      'handler' => 'views_handler_field_history_user_timestamp',
      'help' => t('Show a marker if the content is new or updated.'),
    ),
    'filter' => array(
      'help' => t('Show only content that is new or updated.'),
      'handler' => 'views_handler_filter_history_user_timestamp',
    ),
  );

But ideally I would like to have both field handlers available because I do not want to remove the default handler in Views. How do I do this?

You don't. That's not possible.

But you still have options:

Define your own field handler and add support for multiple display formats using configuration options, have a look at this snippet for an example: https://gist.github.com/juampy72/5816530. The key methods to implement this are option_definition, options_form, options_submit and render.
This is more of a work-around. Copy the definition of the first field handler under different database column key, e.g. $data['history']['timestamp_as_date'] = array( .... Then implement your own filter class as before, but also override the query method in order to ensure that the timestamp column is present. Then display that as you like.

There are a lot of code examples out there.


Overiding homepage template problem. "page__front.tpl.php" won't be loaded I am trying to overriding the homepage by creating a template file named "page__front.tpl.php"; I placed it under the theme folder where page.tpl.php lives.

After refreshing the site, the homepage still loads "page.tpl.php" instead of "page__front.tpl.php."
The cache and the theme registry are cleared.

The template filename should be "page--front.tpl.php"; you should use hyphens, not underscores.


4xx pages template override I am trying to implement the solution given in this question.

I want to have custom templates for 4xx pages.

I am using Drupal 8.3.1

I have tried the code as given in the above link to create the page suggestions in my theme's .theme file:

/**
 * Implements hook_theme_suggestions_page() to set 40x template suggestions
 */
function MY_THEME_NAME_theme_suggestions_page(array $variables) {
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  $http_error_suggestions = [
    'system.401' => 'page__401',
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {
    $suggestions[] = $http_error_suggestions[$route_name];
  }

  return $suggestions;
}

It does not appear to work.

page--404.html.twig or page--system--404.html.twig are not being used.

404 and 403 pages are not set inside the admin of the page.

What else am I suppose to do to get this working?

I have pretty much the same code as you have with the exception that I have a hook_theme_suggestions_page_alter(). With the _alter attached to it.

Try putting the HOOK in a custom module instead of the .theme file.


Difference between field widget price textfield and price with currency? What is the difference between the widget field price textfield and price with currency that you can use on the commerce price field?

The simple explanation is that:

Price textfield only allows the user to enter a price, where the currency code is selected in the field setting, where as Price with currency allows the user to select both price and currency and you can setup a default currency in the field setting.


Pre-cautions to take when manipulating table structures There are some use-cases for modifying the tables manually in the database. One such, when using MySQL, is "downgrading" all cache_* tables from InnoDB to MyISAM, to get better performance.

Another use case is text fields storing data that require 4 byte encoding, instead of the normal 3 bytes. Manually this would look like:

ALTER TABLE t1 DEFAULT CHARACTER SET utf8mb4, MODIFY col1 CHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;

And then when interacting with this field ones need to issue SET NAMES 'utf8mb4' to ensure the connection passed data properly.

Is there any functionality in DBTNG to handle such odd use-cases, in part or in whole? Or will one need to handle them entirely manually? Are there any other pre-cautions one should take, to reduce the risk of future problems in this type of case.

I'm not aware of any support for either of those changes in DBTNG, it's just something you need to do manually.

Luckily that means that once you've done it there's no chance of DBTNG knowing or caring about it - everything should continue to work as you expect.


Is this a possible attack on database? In the logs (Drupal 7), I have seen the next entry (I have edited some compromised info). It seems a failed (only I hope it actually failed) attempt to access the login account. I have tried to replicate the error, but cannot have the same error entry with failed login/password, so I am very worried that it originated in some possible breach of Drupal 7 security.

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
'Crap' AND status = 1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status = 1; Array ( [:name_0] => FcUk
 [:name_1] => Crap )
in user_login_authenticate_validate() (line xxxx of /[HOME_ROOT]/[PUBLIC_HTML_PATH]modules/user/user.module).

I asked a member of the Drupal security team about this and he referred me to https://www.drupal.org/drupalsa05FAQ#comment-9255523.

This points to a user attempting to exploit SA CORE 2014 005, but failing due to the site being patched. Cesar's attempt to reproduce triggers the PDOException, but does not (and cannot) result in actual SQL injection.


Where place spyc library dependencies I have a issue trying to activate REST SERVER from services. I need to add this library. I'm using drupal 7.19 on Ubuntu.

Reading this question, I add the spyc.php in 'servers/rest_server/lib/'

But where I must place the rest of files?

Reading the issue, #2 suggest that the best solution will be allow to place the library on 'sites/all/libraries', this doesn't work in my version.

The problem was I hadn't the dependency libraries . Just downloading this module, updating, and adding the spyc.php in 'servers/rest_server/lib/' Rest server will work.


Group module with advanced permissions based on taxonomy (preferrably) I have a hard time figuring out which Drupal module to use for groups. There are quite a lot of options for Drupal 8 that provide useful functionality.
So far I have looked (at various points in time) at the following modules:

Group
Organic Groups
Taxonomy combined with Permissions by term
Workbench+Workbench Access

The last two are the ones I tried latest. Workbench Access only allows editing access permissions to be regulated, not viewing. While the Permission by term module only allows viewing content, while not really regulating editing (except that when you don't have view access you can't edit either).
I can't remember the Organic groups module very precisely anymore, but from what I (subjectively) gather from other posts/docs, the Group module is meant to be a better replacement. And that pushes me too much in a format with their groups pages and stuff.

What I am really looking for is to have roles, where each role represents a department of my organization. On the other hand we have content that I want to be able to assign to a department, but also specify whether that content should be only accessible to department members only (separately for view and edit), or potentially for all authenticated users, or even anonymous users. The access permissions should be different for each individual node, not on a content type basis. And additionally users should only be able to create content for their own department.

I got there almost with permission by term and taxonomy, where the "access level" vocabulary specifies who can access the node (and taxonomy terms that a user doesn't have access to are automatically hidden), while the "department" vocabulary determines which department a node should be listed under. Views and display suite fill in the rest.

But as I said, this doesn't allow me to control edit permissions for nodes, only view permissions. I could potentially combine this with workbench access to organize the edit permissions, but somehow this feels to me like looking for trouble with combining different permission modules.

Does anyone have a recommendation for a setup that allows me to arrange editing and viewing of nodes per "department" and on a per-node basis?

You should really give the Group module a try, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

It creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 1            ! Class      ! 5             ! Alumni
 2            ! Customers  ! 6             ! Lead
 2            ! Customers  ! 7             ! Prospect
 2            ! Customers  ! 8             ! Licensed Customer
 2            ! Customers  ! 9             ! Sales
 2            ! Customers  ! 10            ! Support
 2            ! Customers  ! 11            ! Accounting
 2            ! Customers  ! 12            ! R&D
 3            ! Project    ! 13            ! Project Manager
 3            ! Project    ! 14            ! Developer
 3            ! Project    ! 15            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 3 roles that are configured:

Instructor.
Student.
Alumni.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These roles can be configured per Group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor, Student and Alumni (which are not available for the other group types).

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Addressing your specific questions

Here is a possible recipe to get you going:

You'd only need 1 group type, say labeled "Departments".
Define whatever Group Roles you'd need for this Group Type and configure the desired Group permissions for each of those roles.
Creating Groups like Department A, Department B, Etc.
Make each user a member of the appropriate group (could be 1 or more, depends on your needs).
Assign each node to the appropriate group.

Further refinements using some other modules

Additional permissions per node

Providing additional view permissions for specific nodes to "Outsiders" (not member of a group) can be provided by the Permission by terms module.

This can by achieved by creating a Taxonomy Term reference field on nodes which points to a vocabulary "Additional Permissions" with terms "public" and "intranet users". Those terms get permissions assigned to them for respectively the "Anonymous Users" and "Authenticated Users" roles. When you set the field on a node to either of those values, users of the respective roles get view permissions, irrespective of the group view permissions. Nodes that don't have a value for the term reference field just get the group permissions by default. Edit permissions are not affected by this and are just defined by the group roles/permissions.

Changing the Group page layout

If you don't like the default way the group pages look like, you can modify them by using the page manager, together with panelizer and bootstrap_kit for instance. Together with views (using the "Group content" and "Content from group content" relationships optionally) gives you tremendous flexibility over how the group page is displayed.

Comparison with the Organic groups module

Have a look at my answer to "What are the features of the Group module versus Organic Group module?" for details about:

How both modules (Group versus Organic groups) compare to each other.
Integration with various modules that you might want to take advantage of also.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site". This video tutorial describes a scenario that is extremely close to your question here ...


Setup on GoDaddy / Addon Domain "403 Forbidden Access Error" I currently have a working Drupal Commerce site up and running. This site is on a godaddy / cpanel server. This site is on an addon domain and sits in the following server directory:

home/.../public_html/siteX.com

I have the modules / configuration working well and want to use this base code to operate a second Commerce site, primarily to reduce my base code maintenance. (I am fairly new to Drupal and have built two sites for our family's small business. Pretty fun :)

I read a ton about setting up multi-sites that convinced me it would be fairly straightforward. Here's what I have done:

Created a new database on the server. Assigned my "user" to that database with all admin privledges
Created a new directory under the working Drupal Commerce site
home/.../public_html/xxxxx.com/sites/siteY.com
Pointed my "addon" domain to the Document Root above
Copied my default.settings.php into /public_html/xxxxx.com/sites/siteY.com
Renamed to settings.php with the database login information
Set my /siteY.com directory and settings.php to "777" permissions

When I navigate to "siteY.com", I keep getting a 403 error:

  Forbidden
  You don't have permission to access / on this server.
  Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

If I navigate to "siteY.com/install.php, I get a different permissions error msg:

  Internal Server Error

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

  Please contact the server administrator at webmaster@ to inform them of the time this error occurred, and the actions you performed just before this error.

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

  Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Is it an issue to create a multisite from an add-on domain?
What am I missing here?
Should I jump ship and use the "Domain Access" module?

Solved## Successful installation completed :)
When setting the Directory Root for the "multisite" SiteY.com addon domain, I got it wrong.
Incorrect: home/.../public_html/xxxxx.com/sites/siteY.com

Correct: home/.../public_html/xxxxx.com/

With the correct option, you point to the site that contains the code based you want to pull from, as well as the index.php file.
I don't fully get the mechanics at play here, but am thankful to be on the other side.


Migrate geolocation field I have gone through the /upgrade gui part on my website.  However the geo location fields have not copied across.

Am I correct in thinking that instead of manually entering the data again, I could:

Create the field (same name) and add it to the content types I was using.
Export the field_data_field_location
Import both these fields into the Drupal 8 database as field_revision_field_location respectively?

As far I can see the tables are pretty similar, although there are same number of fields 2 of them are different.

The D7 Table has a field entity_type
The D8 Table has field_location_data

I will attach the schema for both tables.

D7:

+------------------------+------------------+------+-----+---------+-------+
| Field                  | Type             | Null | Key | Default | Extra |
+------------------------+------------------+------+-----+---------+-------+
| entity_type            | varchar(128)     | NO   | PRI |         |       |
| bundle                 | varchar(128)     | NO   | MUL |         |       |
| deleted                | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id              | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id            | int(10) unsigned | YES  | MUL | NULL    |       |
| language               | varchar(32)      | NO   | PRI |         |       |
| delta                  | int(10) unsigned | NO   | PRI | NULL    |       |
| field_location_lat     | double           | NO   | MUL | 0       |       |
| field_location_lng     | double           | NO   | MUL | 0       |       |
| field_location_lat_sin | double           | NO   |     | 0       |       |
| field_location_lat_cos | double           | NO   |     | 0       |       |
| field_location_lng_rad | double           | NO   |     | 0       |       |
+------------------------+------------------+------+-----+---------+-------+

D8:+------------------------+------------------+------+-----+---------+-------+
| Field                  | Type             | Null | Key | Default | Extra |
+------------------------+------------------+------+-----+---------+-------+
| bundle                 | varchar(128)     | NO   | MUL |         |       |
| deleted                | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id              | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id            | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode               | varchar(32)      | NO   | PRI |         |       |
| delta                  | int(10) unsigned | NO   | PRI | NULL    |       |
| field_location_lat     | double           | YES  | MUL | NULL    |       |
| field_location_lng     | double           | YES  | MUL | NULL    |       |
| field_location_lat_sin | double           | YES  |     | NULL    |       |
| field_location_lat_cos | double           | YES  |     | NULL    |       |
| field_location_lng_rad | double           | YES  |     | NULL    |       |
| field_location_data    | longblob         | YES  |     | NULL    |       |
+------------------------+------------------+------+-----+---------+-------+

All help and advice appreicated!

Mark.

Turns out I was using the wrong version of geolocation.  If you use the 8.x-1.11 when you run the upgrade script it pull over the geolocation data into your system.  Although this isn't the default that composer installed for me, I had to re-install it.

Hope it helps someone out there,

Mark.


How do I add a script just above the closing body tag? How do I add a script on Drupal 8 site/app just above closing body tag?

Vendor provided some JS in the following form:

<script>
    ... code
</script>

Asked me to place immediately above </body>.

The script was only to run for Anonymous traffic.

Here's how I did it:

THEME = name of your theme

Removed <script> and </script> from code
Minified using https://javascript-minifier.com/
Created file name-of-my-script.min.js
Uploaded to THEME/js/custom/name-of-my-script.min.js
Added library to bottom of THEME.libraries.yml

name-of-my-library:
  version: 1.0
  js:
    js/custom/name-of-my-script.min.js: {preprocess: false} // {preprocess: false} is responsible for code showing up above </body>

Added the following code to THEME.theme to an already existing function: function THEME_preprocess_page(&$variables) {}

$logged_in = $variables['logged_in'];
    if (!$logged_in) {
    $variables['#attached']['library'][] = 'THEME/name-of-my-library';
}

Cleared cache.

Resourses that helped:

https://www.drupal.org/docs/8/api/javascript-api/add-javascript-to-your-theme-or-module
https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

You can achieve this simply by using jquery. If you want to access it from all theme pages you need to add the below line in your global common js file which has access to all the theme pages in the app.

$('body').append('<script src="/name-of-your-library"></script>');


Url mapping from custom CMS to Drupal We migrated a site from custom CMS to Drupal. The content has been migrated successfully, but there is a problem with URL mapping.

In old site the URLs were like domain.com/artists/Artist_ID/Artist_Name (e.g. domain.com/artists/5/picasso), where the URL would work without the last argument part (picasso).

With the Drupal site all URLs use domain.com/artists/Artist_ID as format (e.g. domain.com/artists/5).

They have shared the old site's links on social media where URLs are like domain.com/artists/5/fabien-m%25C3%25A9relle which used to work fine in the old site because last part didn't matter. The same URLs do not work on the Drupal site.

So can I make Drupal ignore the last part of the URL?

You can use Apache's mod_rewrite to map all the old URLs shared on social media sites into appropriate new ones, including ignoring the latter part.  However, Drupal 7 have a quirk.  You need to rewrite to unclean URLs for it to work.

So first, turn off clean URLs (which also means turning off PathAuto) on your site.  Then look up one of your artist's pages and figure out what the real URL is.  Let's say that for artist 5 (Fabien Mérelle), it is:

domain.com/?q=taxonomy/term/5

Now you should be able to insert the following rewriterule:

RewriteRule ^artists/([0-9]+)/.*$ ?q=taxonomy/term/$1

(You must of course change the target to whatever your test showed the true query string to be.)

The above rule will change artists/5/fabien-m%25C3%25A9relle into ?q=taxonomy/term/5.

Verify that that the rule "works" (i.e. that the URL is really rewritten).  Then you should be able to turn clean URLs and PathAuto back on, and it should still work.

The rule consists of two parts.  The first (^artists/([0-9]+)/.*$) is the pattern to look for, the second (?q=taxonomy/term/$1) is the target.  They're separated by a single space.

The ^ in the pattern indicate the start of the local path, so it looks for a pattern starting with artists/ followed by a number ([0-9+]) followed by a slash (/) followed by anything (.*).  The final $ in the pattern is just a marker for the end of the local path. The parentheses around the number stuffs the number into the variable $1.  The target simply consists of the static string ?q=taxonomy/term/, followed by the value of the $1 variable.

Note: You must place the line with the rewriterule inside the .htaccess file for the site, inside the block that starts with:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on


Including content types in a theme? If I'm making a theme that I want multiple people to be able to download and install (not just making it for one client), what's the best way to include the content types? For instance, say it's a portfolio type of website, and has a content type called "project". I don't want anyone who downloads my theme to have to go in and create the content types by hand.

What are best practices in distributing a theme with requirements like that? Is there a simple module I could expect someone to install first?

If your theme code depends on certain content types being there, then that tells me that you are actually building a module plus a theme, and not just a standalone theme.

One way to do this is to use the Features module to export your content types and other settings. Then you probably want to move some of your theme functions into the module code, so that other themers can more easily build on top of what you've created.


Gear menu unavailable Haven't been on Drupal for a while and now I seem to be lost at some points. Please help me get on the right track ;-)

I decided to build a theme based on the Stark theme and found out that the contextual menu gear widget does not appear. It's definitely a theme issue, because the widget comes up for the very same block when I switch the theme to, say, Garland.

What could be the reasone?

The contextual links are being exposed via contextual module. just by looking into the module, you would find the function contextual_preprocess.

 $variables['title_suffix']['contextual_links'] = array(
      '#type' => 'contextual_links',
      '#contextual_links' => $element['#contextual_links'],
      '#element' => $element,
    );

So my first guess would be, that you are missing in the block.tpl.php or page.tpl.php, etc... templates to output the $title_suffix variable?

<?php print render($title_suffix); ?>


how to put html in a .module php file I have a input box created with html need to put in the specific block. I saw posts writing there to add the html by function but i cant do it since it is php file
Is it right way to do this? what is the exactly way to do this?
    function firstmodule_block_view($delta = ''){

$block = array();

switch ($delta) {
    case 'signup':
    $block['subject'] = t('Newsletter signup');
    $block['content'] = myblock();
    break;
}
    return $block;
}

function myblock(){
//html code goes here????
}

So first you want to define a block that contains a form. You define the contents of a block in $block['content'].

/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $blocks['your_block_name'] = array(
    'info' => t('Name of your block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MYMODULE_block_view($delta='')
{
  switch($delta) {
    case 'your_block_name':
      $block['subject'] = null;
      $block['content'] = drupal_get_form('MYMODULE_form');
      break;
  }
  return $block;
}

An after that you need to define your form. In Drupal you use the Form API to build forms. In the example above we fetch the form called MYMODULE_form. And the form is defined by implementing hook_form().

/**
 * Implements hook_form().
 */
function MYMODULE_form($form, &$form_state) {
  $form['MYINPUTBOX'] = array(
    '#type' => 'textfield',
    '#title' => t('My label')
  );
  return $form;
}


How to add an image to nodes? I created a new content type (Image), which has an image upload field set. Now I can upload images and they are now nodes. But what do I need to do to add them to other existing content types?

My guess was to turn the image content type into a block. Is this correct?

My guess was to turn the image content type into a block, and if so, whats the best module to do that?

Bean

Bean is an acronym that stands for Block Entities Aren't Nodes.
This is a great introductory article about what the bean module.
What is Bean? Think of a Bean as a method to provide new types
(compared to node this would be a content type) which then provides an
add content interface to create as many blocks as you require (see
screenshot below). The bean content can then be placed around the site
just like any other block.
Beans were driven by the API first. This means that you can create
block types (bean types) all in a plugin class turning off the UI. The
entire configuration in code. No worry about feature reverts.

Here is a video tutorial
Basically it lets you add fields to blocks. This module comes with Drupal 8 core by default.


Running drush site-install on Windows I ran the following commands:

drush dl drupal-8 --drupal-project-rename=drupal_8
cd drupal_8
drush site-install standard --account-name=****** --account-pass=******** --db-url=mysql://*****:******@localhost/drupal_8 --site-name=Drupal_8

in windows 7 but I get following error:
Drush 6.7.0 does not support Drupal . See drush for more information.

Command site-install needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this

command.
The drush command 'site-install standard' could not be executed.

Am I doing something wrong or drupal 8 standard installation is not supported by drush yet?

Didn't realize that I need to upgrade my drush to 8.0.1 as drush 6.7 won't work with drupal 8.


Post/redirect form to url of node selected This is a continuation of this:

https://www.drupal.org/project/webform/issues/3023984

I was able to redirect to a node/term url using the token based on the answer provided, great!
However this is where it gets complicated. The first select list has three items, selecting one item will open a corresponding conditional second list - that is, there are 3 hidden list that will get displayed based on the selection of the first.

[webform_submission:values:ELEMENT_KEY:entity:url]

will work only for one list. How can I make ELEMENT_KEY be based on the selected list.

Thanks

You need to set the selected node's URL as the confirmation URLs token.

Here is an example webform that redirects to the select node when submitted.


Custom entity to load another custom reference entity fields I have two custom entities (Car and Car Type) and I am using one as a reference for the other.

When I load the "Car" entity I can only get the ID from "Car Type". I know I can then run entity_load to get the fields on "Car Type", but when I have multiple results of "Car" querying every record become inefficient.

Is there any way to load the "Car Type" entity fields when loading "Car" entity?

You might want to take a look at Entity metadata wrappers. They are not really efficient as they load even more data, but they simplify the working with entity properties and fields and also resolve nested entities (so you would be able to do something like $car->field_car_type->field_length->value()).

But under the hood (a car joke :D), it still performs an entity_load to get the values. It is less code for you though.

To answer your question:

Drupal makes the assumption a field is always attached to an entity, it would be very difficult to properly load some fields without actually loading the entity (I suppose that is what you are after). The function which loads field values and attaches those fields to entities (field_attach_load) already required loaded entities as input. (This function is often called during entity_load). You could attempt to replicate its behaviour without loading the entities, but you will probably run into a lot of issues.
The same applies for fetching a single field's value; field_get_items() and field_view_value() also expect a loaded entity. So my advise would be to just load the entity, possibly using entity metadata wrappers as they make your life easier.


Can I prevent Administrators from Updating Modules? So I had an issue yesterday where a module was updated on one of my sites that I wasn't ready for it to be updated on.  It caused some issues, but I was eventually able to get the previous version back from my test server and it is working normally again.

My guess is that someone with administrative rights (but not User-1) was able to update the module from the web interface.  Is there a way to prevent anyone from updating modules except User-1?

Uncheck the permissions "administer software updates" from roles, and they should no longer have access to this screen in the admin.

At the same time, it is advised to use drush or other methods of applying updates, as the admin screen is pretty not great for this.


Addind a meta noindex tag within template.php I would like to add a meta tag noindex from within the template.php file of my theme.

The purpose is to remove two nodes 404 error page from google's index, I would like to do it like so :

// in mytheme/template.php
function my_theme_preprocess_node(&$variables, $hook) {
   $node = $variables['node'] ;
   // '123' would be nid of the 404 presentation page
   if($node->nid == '123'){
   /* META NO INDEX CODE GOES HERE */

Is this possible to do in my theme, without using any module at all ?

You could use the following code.

function mytheme_preprocess_node(&$variables, $hook) {
  $node = $variables['node'] ;
  if ($node->nid == '123') {
    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
    drupal_add_html_head($element, 'mytheme_noindex');
  }
}

In Drupal 6, you just use drupal_set_html_head('<meta name="robots" content="noindex" />'), instead of drupal_add_html_head().

I would rather use the code in a module, as a theme should not know details such as the existence of a node with a specific ID. Plus, if the site has more than one theme enabled, or it is possible that a different theme is enabled in future, the code should be copied in each enabled themes, while a module will always be executed, independently from the theme being used.


Views php field table sorting error I have a taxonomy view with table list and I insert my code into a global php field and use enable click sort: sort numerically, but when I click the label to sort numerically I always get the error below.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /stocks/views/ajax
StatusText: OK
ResponseText:
Fatal error:  Function name must be a string in C:\xampp\htdocs\stocks\sites\all\modules\views_php\plugins\views\views_php_handler_field.inc on line 185

Whats causing this and is there a way to fix it? Im trying to have the field sort by highest number to lowest.

This is the code I am using in the php field.

<?php
$currentMonth = date('n');
    $currentMonth = $currentMonth - 1;
    $prevcurrentMonth = date('n');
    $prevcurrentMonth = $prevcurrentMonth - 2;
    $currentDay = date('j');
    $lastDay = $currentDay - 6;
    $currentYear = date('Y');

    $file = file_get_contents("http://ichart.finance.yahoo.com/table.csv?s=$row->name&a=$prevcurrentMonth&b=$lastDay&c=$currentYear&d=$currentMonth&e=$currentDay&f=$currentYear&g=d&ignore=.csv");

    $stockcontent = str_replace('Date,Open,High,Low,Close,Volume,Adj Close', '',  $file);
    $stockcontent = trim($stockcontent);

    $stockcontentex = str_getcsv($stockcontent, "\n");

    $stockex = explode(',',$stockcontentex[0]);

    print $stockex[2];
?>

Review this post

You will find there is a value box and a output box.

Your code above suggest you are doing the display from the value box and that won't work.

move most of your code to the value box and then end with:

value = $stockex[2];

then paste

<?php
    print $value
    ?>

in the output box.

Good Luck!


Not able to assign value to hidden form field using form_alter hook I have a form in which field my_consultant_id is "Hidden integer" type field and having widget type as "Hidden field".

I am assigning the value to this field by using hook_form_alter

function threebl_summary_report_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'eck__entity__form_add_summary_report_comparative_client_group') {
        global $user;
        $form['field_created_by']['und'][0]['#default_value'] = (int) $user->uid;
    }
}

But not able to set the value for that field.

If I inspect the form it shows html code for field like:

<div class="field-type-field-hidden-integer field-name-field-my-consultant-id field-widget-field-hidden form-wrapper" id="edit-field-my-consultant-id">

Thanks in advance.

I managed to do it by validate handler of the form. Using validate handler I assigned my value to the form variable before submit.

In form alter hook call validate handler like below

$form['#validate'][] = 'my_module_name_form_validate';

And following is the validate handler function code

function my_module_name_form_validate(&$form, &$form_state) {
$form['field_my_field']['#parents'] = array('field_my_field');
form_set_value($form['field_my_field'],array('und' => array(0 => array('value' => $new_value))),$form_state);

}

For reference please go through link


Form in template without  tags My forms dont seem to have  tags wrapping them in my templates.
What am I doing wrong here?

I have a template whith some calls to theme() inside it.
Two of these are forms with their own template.
This template is called from a block_view().

my modules block function:

$form = drupal_get_form('stappenoverzicht_appointment_form');
  $reset = drupal_get_form('stappenoverzicht_reset_form');

  $block['content'] = theme('overzicht', array('status' => $status, 'links' =>$links, 'form' => $form, 'reset' => $reset));

my modules theme function:

$return['overzicht'] = array(
'variables' => array('status' => array(), 'links' => array(), 'form' => null,
 'reset'      => null),
'template' => 'templates/dashboard--stappen-overzicht',
    'render element' => 'form',

);

$return['appointment'] = array(
        'arguments' => array('form' => NULL),
        'render element' => 'form',
        'template' => 'templates/form--appointment',
    );
$return['reset'] = array(
    'arguments' => array('form' => null),
    'render element' => 'form',
    'template' => 'templates/form--reset',
);
return $return;

base tpl:

   <?php print theme('appointment', array('form' => $form));?>

   <?php print theme('reset', array('form' => $reset));?>

form--reset:

       <?php print drupal_render($form['submit']);?>

  <?php print drupal_render($form['description']);?>
<?php
print drupal_render_children($form);
?>

I came across this Render form in template answere here, but I want to manipulate the wrapping html as shown in the reset template.

your module should be like this:

function yourmodule_menu()
{
    $items = array();
    $items['path/to/form'] = array(
        'title' => 'Page Title',
        'description' => 'Page Description',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('yourmodule_form_function'),
        'type' => MENU_NORMAL_ITEM,
    );
}

function yourmodule_form_function()
{
   //build form api here as array
   //return array
}

Hope this helps you!


How to set the tabs on node pages to always display in the site's default language? I don't want $tabs to be translated. How can I set the tabs on node pages to always display in default site language?

I've tried admin language module however the setting that works in that prevents menu items from been translated.

Is there a way to manually set the rendered language in the tpl?

You can use this function (inspired from this solution wich was for Drupal 6)

/**
 * Reverse translation: find source string for a given translated string.
 */
function rt($string) {
  global $language;
  $langcode = $language->language;
  $query = db_select('locales_source', 'ls');
  $query->leftJoin('locales_target', 'lt', 'ls.lid = lt.lid');
  $query->fields('ls', array('source'));
  $query->condition('lt.language', $langcode);
  $query->condition('lt.translation', $string);
  $result = $query->execute();
  $records = $result->fetchAssoc();

  return $records ? $records['source'] : $string;
}

Then via hook_menu_local_tasks_alter

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && isset($argument->type)) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        $data['tabs'][0]['output'][$key]['#link']['title'] = rt($value['#link']['title']);
      }
    }
  }
}


How to add "browse" button in image in CKE Editor? I wanted to put "browse" button in image button iframe(pop up).

But I am unable to put it.

How can I change the default behaviour and customize pop up screen in cke editor buttons ?

Thank you...

May be IMCE  module will solve your problem !

  IMCE is an image/file uploader and browser that supports personal
  directories and quota.


Simple conversation wall I want to create a simple wall, where user can post some text, and other users can reply on it. It can be done without ajax or with. I have made few modules before, but now  i am stack with this part, how to create a page(which i can link into menu) on which i can post message, and then watch the list of this conversations+comments, should i use Views module? any examples would be the way.

here is example of that wall,

Check this out http://drupal.org/project/facebook_status.
Also if ur on D7 then https://drupal.org/project/statuses


Why do I get "Undefined index: mail en comment_form_validate()"? Is there a way to fix the notice I get?

  Notice: Undefined index: mail en comment_form_validate()
  Notice: Undefined index: homepage en comment_form_validate()

This appears in my message area with the errors for comments, only if I enable the development snapshot of the module to display errors or warnings (the configuration say I should turn this off in production), but I'm not sure if this is normal.

Should I ignore this? The default comment module doesn't display this bug, with or without the  development snapshot settings working. Does anyone have a suggestion?

From your error messages it seems you are calling something like this

$form['field_name']['en'][0]['value']

Or something like that.  Which means the array key "en" is not available.  If you are not using languages, then I suggest using LANGUAGE_NONE as your key selector.

To prevent these types of messages you should perform an isset on the array element to make sure it exists before trying to retrieve a value from it.


Returning an entity from a custom Rules action I'm new to writing modules and back end dev. I'm trying to write a custom Rules action that takes a list and returns one item from that list to use as a relationship end point.

I've declared the rule here and got it working as far as I can extract one item from the list and put it as a message on screen:

function rules_additions_rules_action_info() {
$actions = array(
    'rules_additions_action_get_next_list_item' => array(
        'label' => t('Get next list item'),
        'group' => t('Data'),
        'parameter' => array(
            'list' => array(
                'type' => 'list',
                'label' => t('Select the current list'),
                ),
            ),
        ),
    );

return $actions;
}

And can do something like this, for example:

function rules_additions_action_get_next_list_item($list) {
    drupal_set_message(t('The item is ' . print_r($list[0], TRUE)), 'status');
}

What I want to be able to do is return that list item as an entity so at the next step in my rule set I can do "Add an item to a list" and select it in the rules UI.

I hope this makes sense.

Thanks in advance.

If you check the rules hook hook_rules_action_info docs, you'll see the provides element:

  provides: (optional) An array describing the variables the action provides to the evaluation state with the variable name as key. Each variable has to be described by a sub-array with possible attributes as described afterwards, whereas the name of a parameter needs to be a lowercase, valid PHP variable name.

Usage example from commerce_cart module:

  $actions['commerce_cart_product_add_by_sku'] = array(
    'label' => t('Add a product to the cart'),
    'parameter' => array(
      'user' => array(
        'type' => 'user',
        'label' => t('User'),
        'description' => t('Specify the user whose shopping cart order the product will be added to, typically site:current-user.'),
      ),
      'sku' => array(
        'type' => 'text',
        'label' => t('Product SKU'),
        'description' => t('The SKU of the product to add to the cart.'),
      ),
      'quantity' => array(
        'type' => 'integer',
        'label' => t('Quantity'),
        'default value' => 1,
      ),
      'combine' => array(
        'type' => 'boolean',
        'label' => t('Combine similar items in the cart'),
        'description' => t('If checked, the product will be combined added to an existing similar product line item in the cart by incrementing its quantity.'),
        'default value' => TRUE,
      ),
    ),
    'group' => t('Commerce Cart'),
    'callbacks' => array(
      'execute' => 'commerce_cart_rules_product_add_by_sku',
    ),
    'provides' => array(
      'product_add_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Added product line item'),
      ),
    ),
  );

Note that you need to return an array from your action with the parameters named, for this example, 'product_add_line_item':

// Only return an added line item.
if ($line_item = commerce_cart_product_add_by_id($product->product_id, $quantity, $combine, $uid)) {
  return array('product_add_line_item' => $line_item);
}

So potentially you could provide as many elements as you need in your actions for further actions or rules components.


Ubercart- Assign new role on expiry I am granting users specific a role on purchase of some product( using ubercart). In doing so I have added a rule to take away their initial role(so that they do not have 2 roles and confuse the content access permissions). When the role expires, I want to grant the use back his original role. I am trying to use rules to do this. However, I am unsure on what action to call this rule.
Any suggestions? Thanks!

It seems that "I am unsure on what action to call this rule" is your remaining issue, and that by using the rules module you are already close.

However, when talking about Rules and its Event-Condition-Action concept, your issue is about what Event to use. With that in mind, I would try to use the Rules Scheduler submodule of Rules, to schedule the rule to be executed at the moment of the purchase already.

Makes sense?


Can blocks created via the admin UI be cached? I am trying to understand if blocks created using the admin UI can be cached or not? I had a look at the block table in the database and it would appear that the cache value is set to -1 regardless of whether block caching is enabled or not.  So I am assuming that blocks created via the admin UI cannot be cached.  Is that correct?

https://www.drupal.org/project/blockcache_alter might be what you are looking for.


How can I grant permissions to anonymous users per session to download a file? Anon users can fill out and submit a form (webform). As soon as submitted, the user will be offered to download a pdf file with his entered form data. How can I manage this? With sessions?

Take a look at Webform protected downloads. It's a module I wrote a while ago to tackle this kind of situation.

Edit: Ah, sorry, just read your question again. The part with the modified pdf content depending on user input is not addressed by my module. Though, as the system uses the private file system you could maybe hook into there. This is not trivial though.

I see another easier option. You create a custom menu callback and use webform hooks or the redirect configuration of the webform to send the user to this url that contains the submission id of the webform (say, special-pdf-access/SUBMISSION_ID). With this information you can load the submission, thus accessing all the data entered by the user, then create a pdf file with this info and display a link to that file.

You have to pay attention to security though, so as not to allow arbitrary users to load pdf files they shouldn't have access to. For this you can use the global $_SESSION variable, to store the submission id after webform has processed the submission, and then check in the custom menu callback if the submission id in the session equals the requested submission as given in the url.


Boost. What does "Minimum Cache Lifetime" mean? In Boost module setting, there are

Maximum Cache Lifetime
and
Minimum Cache Lifetime

settings.

"Maximum Cache Lifetime" is like re-generate the page after that amount of time.

How about "Minimum Cache Lifetime", what does it do?

Updated:

Just a copy / paste from boost handbook for a reference.

Max: Default is 1 hour and can be increased for sites that do not change very much. The maximum cache lifetime is the maximum amount of time that will elapse before the cache is emptied. Cache lifetime gets checked on cron runs. Flushing the content before it is expired can happen, for example when a node is edited.

Min: [< none>] (select box) none is fine for small sites.
On high-traffic sites, it may be necessary to enforce a minimum cache lifetime. The minimum cache lifetime is the minimum amount of time that will elapse before the cache is emptied and recreated, and is applied to both page and block caches. A larger minimum cache lifetime offers better performance, but users will not see new content for a longer period of time.

Check out this handbook page describing all settings (for 6.x but still relevant to 7.x):

"On high-traffic sites, it may be necessary to enforce a minimum cache lifetime. The minimum cache lifetime is the minimum amount of time that will elapse before the cache is emptied and recreated, and is applied to both page and block caches. A larger minimum cache lifetime offers better performance, but users will not see new content for a longer period of time."


Content listing to show custom fields of associated terms instead of title I'm using Drupal 7 with views 3.

I have a Content Type of "Flag" associated with a vocabulary named "Colors", and its terms are Red, Blue, White, Yellow, etc. Each color has a custom field named field_color_image where I upload a small color thumbnail.

Currently I have a following 'Content' view set up, that lists flag names and it's colors(terms).

In my Views, the Fields is set to display 'Content: title' and 'Content: field_color'

The output looks like this:

- American Flag
Terms : Red, Blue, White

- Russia Flag
Terms : Red, Blue, White

- Sweden Flag
Terms : Blue, Yellow

How can I output the field_color_image of the term instead of the title?

Notes: I have checked under replacement patterns and they don't have custom taxonomy field support.

Thanks.

In Views under Contextual Filters select your vocabulary field. Now you can find your required image field under add button in fields. Add that field to your view.


Workflow for Entity relationship / relations I have a content type called Blog. I want the end users to be able to add new relations between the blogs, so that we can build a network of related blogs. But the challenges I am facing are

Users should be able to add the relations without having the access to edit blogs.
The relations(references) added by the users should be monitored. I need to have a workflow around it. Eg : If more than 2 users with the role moderator upvote this relations/reference then it should become public.

I have searched quite a bit for workflow and entity relationship but nothing worthwhile seems to come up. Currently the only option seems to be a combination of relations and workflow module. I haven't used in relations in any projects earlier and would try to avoid it if possible.

Any suggestions or inputs are greatly appreciated. TIA

How about a content type with two Entity Reference fields?  One for each of the two blogs.

Each node of that content type will then be a connector, and you can use the workflow module or perhaps Workbench Moderation to manage the connections.


Running cron without crontab I want code to be executed every n minutes. I know there is a way to run cron in Drupal with crontab but in my case it runs every 3 hours.

What would be the best way to achieve this without using crontab? Can I execute code every time a user opens the first page?

The simplest solution would be to set the cron to run more frequent: every 3 minutes is not unheard of.

However, many modules, including core, do not have a timecheck: they run their code regardless of how long it was since they last ran it. Other modules (also many core) have some "run only every X" implemented.

You will see an impact, but depending on your specific situation, that may, or may not be a problem.

Once that is done, you can implement hook_cron():

function yourmodule_cron() {
  $last_run = variable_get('mymodule_cron_last_run', REQUEST_TIME);

  if ($last_run <= (now() - 180)) {//180 seconds is three minutes.
    # DO SOMETHING EPIC!
    variable_set('mymodule_cron_last_run', REQUEST_TIME);
  }
}

If, however, you cannot run cron this often, you may want to write a cron bypass. In Drupal 6, the route would be, to create a menu-item, with a "secret" token in it (to avoid external folks from hitting that URL by accident/to overlad your server). In Drupal 7 there are (not well documented, AFAIK) methods to create thin requests: my code below will bootstrap an entire Drupal, while you may need only a very simple database-query to be ran without accessing any Drupal resources or APIs.

/**
 * Implementation of hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['yourmodule/cron/s0mes3cr3tkey'] = array(
    'title'            => 'not used',
    'description'      => 'not used',
    'page callback'    => 'yourmodule_do_epic_stuff',
    'type'             => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu Callback that does epic stuff.
 */
function _mymodule_do_epic_stuff() {
  # Do Epic Stuff.
}

You can then add an additional crontab to call only that url.

It is a very bad idea to run such code in the request of a user:

You don't know if users are visiting every 3 minutes. Even if you have 1000visitors per minute, there are potential situations where no user visits for, say 10 minutes.
You don't want your users to be bothered with maintainance code you run in their request.
You don't want your users to experience faults or errors in your cron-tasks. These tasks can, e.g. check whether some external API is up or down and throw errors on network trouble and such.


Title in address bar displaying twice I am having an issue that I don't know how to fix. The title of my website/pages are displayed twice and I can't figure out why. I configured my title at Configuration > basic site settings > name of website

Can anyone help me find what is causing this?
Any help is greatly appreciated.

This is how Drupal Title system works.

You PageTitle| Sitename

If you wants any modification then you can install Metatag and Token Module.


Renaming the label of the Title textfield Adding new fields allows you to specify the label of the field but the Title field does not. In fact, it just sits there on top acting all high and mighty. I just want to change the label of Title to something like Your name but retain the machine name. Does anyone have an idea how to do it?

Go to Content type, you will have a list of content types of your site. Under Operations click on edit  for the content type you want to change the title.  Under Submission form  settings you can change the "Title field label"


How can I hide specific user from dropdown list of users Could you please help me with one little question. I'm using Drupal module Support Ticketing System.

When the support ticket is created user can choose from dropdown form for whom this ticket is assigned. Usually it's a list of Drupal site users.

How can I hide a specific user from this list (admin for example)?

One possible solution is to add a new field show/hide Checkbox in account settings and then in drop down show only those whose show/hide field set to show.

This way if your client wants to hide another user go and edit the user and hide it


Drupal cron will unserialize array and add extra characters I am working in an application using Drupal. Thru the UI I upload a text file that is then parse and each line store in the DB as a serialized array. So far so good until there.

I have setup a module using queue and the hook_cron that will check each of the serialize arrays from the DB and make a node out of it.

I was getting some odd errors like the cron was not able to parse the serialized array and I noticed something odd the array keys were been serialize with extra characters (invisible characters).

While looking in the DB imports I notice that something like the word "comunique" that when serialize should be like:

s:9:"comunique"

instead it was showing like:

s:12:"comunique"

also a print_r show me the following:

[comunique ] => Array (...)

I even test changing the word and there are always 3 characters extra. I tested locally in my computer and it is all good.

What am I missing? is this a server config issue or a code issue?

Thank you for your input. I open the PHP file with Notepad++ and there was the hidden tilde character. I remove it an everything started to work again like a charm.

For people having a similar issue, I will recommend opening the file in a different text editor.


How to create dynamic select option field in webform module I have created a web form in drupal 7, i have one select option with two values and one input text box.
When i click on one value input text box should appear nothing so that anybody can write some text but when i click on 2'nd value, input text box should appear 6 drop-down values

How i can achieve this?

Go to Modules > Webform and see what version it is. If it is version 4+, as RoloDMonkey has mentioned, than conditionals are built in. If your Webform module isn't 4.x then I suggest updating it so that you can use this feature.

Go to Content and find your webform and open it.
Click "Webform" tab
Click "Conditionals" link
Click the (+) button
Implement the logic:

If "[select question that has the conditional answers]" is "[select name of answer that opens the textbox]" then "[name of textbox]" is shown
If "[select question that has the conditional answers]" is "[select name of answer that opens the selection menu]" then "[name of selection box]" is shown.

Make sure you have all possible options set up already in the webform before applying the conditionals.

Here is a demo someone built using Webform Conditionals:
http://www.sixmiletech.com/node/15


view to show content with future date I am creating a view which shows nodes of content type Movies. Movie content type has fields name, description,rating, and release date. Fields the view displays are name ,description and release date. What I want to display those nodes only that have release date set to some future value.
I googled a lot but did not find anything. How to do it?

Hopefully you actually used a date field for "release date".  If so, just create a view and you normally would then in your filters add your release date field. Set it to a relative date text. Make it "greater or equal to" and insert " now" into the relative date.


Migrate Site from aegir Drupal hosting platform to Acquia hosting I have three sites hosted in Aegir hosting environment. No I need to move them to Acquia hosting. Here are some doubts I have:

Should I need to move the code as a normal multisite setup to
Acquia?
Since the codebase is extracted from aegir environment, I don't have
any files on the drupal root like install.php, update.php?

Sorry I haven't worked so much with aegir. So this might sound dump. Please help me with this.

Disclaimer: I do not use Acquia and don't know their service.

  Should I need to move the code as a normal multisite setup to Acquia?

The documentation seems to say that multisite is supported: https://docs.acquia.com/cloud/multi-site

You would probably need to copy the platform from /var/aegir/platforms. If you look in that directory, each directory is a pretty normal Drupal multisite codebase.

  Since the codebase is extracted from aegir environment, I don't have any files on the drupal root like install.php, update.php?

The platform is just a normal Drupal codebase, it should have these files (even if it doesn't use them).

The hard part will be to move the databases, you will (presumably) need to create them in the Acquia frontend, and change the settings.php file of each site to use the new database info. Aegir creates a drushrc.php but in a non-Aegir environment you can just take the settings and move them into settings.php.

Hope this helps.


custom views handler to show dynamic all profile fields I'm using D6 and I like to have a view that shows all user profile fields. The situation now is, that you have to tic all  fields that you like to show. I'm using OG profiles and the user is able to add profile fields to it's group. In addition to that, I need a view that get all fields that are belonging to a group (automatic).

What is the starting point for me? Found that .. http://techblog.zabuchy.net/2010/non-database-field-in-custom-drupal-views-2/

But how to start?

pseudo code:

get all field belonging to a group (arg(1))
and disp

This is probably done better in a preprocess function in a theme instead. However if you want to do it you ned to create a handler, something like this:

class og_group_handler_field extends views_handler_field {
  function render() {
    $og = arg(1);
    $output
    // Load the group and add to $output what needs to be displayed
   return $output;
 }
 function query() {
   // Make sure we don't add anything to the queue.
  }
}

and the add the handler to a table like nodes

function module_views_data_alter(&$data) {
  $data['node']['og_all_group_fields_from_arg_1'] = array(
    'field' => array(
      'title' => 'title',
      'help' => 'Help Text',
      'handler' => 'og_group_handler_field',
    ),
  );
}

For Drupal 6 you also need to register the handler, the link you posted illustrates how this is done.


Form with Multiple fields in table format I have a requirement to design this type of form for a custom content type. This is one part in a large form.

At first what I did is made a Field Group called Income Information

Inside the Field Group I made new fields:

Age as textfield Integer
Sex as select list
Description as Long text
Family Income as Field Collection

Family Income field collection field would have a collection of fields like Family Member, Income, Savings and Loan.

My question is here how to present this part Family Member, Income, Savings, Loan in a table format as the picture below.

In Family Member: Father, Mother, Spouse are just listed by default. If users want to add some other then there is textbox for that, but the total family member will not increase from 5, that means no add more field button there.

You have multiple questions, so answering the title one: "Form with Multiple fields in table format"

You can do it with custom code by themeing the form and printing the fields in a table (I can elaborate on this if you want).
One thing to note though is that if you want the user to be able to add more rows to the table this solution gets trickier.

If you do want to add more rows or if you don't want to do custom themeing for your form you you can use the field collection module along with the field collection table module.

It works pretty well, however I currently recommend using the latest dev version of the field collection table module as there are some bug fixes in there you will want.

There are also a few patches in the issue queue that you might need depending on your specific needs, so if you run into bugs (I did when I used it) try searching the issue queue for patches.