1 Views Filter (exposed) for 2 fields I am interested in having one view filter for two separate fields.

Example:
In a staff directory I am working on, users have both a "First Name" and "Nickname" field.

The output results show both, but in order to keep it user-friendly, I would like to have a "First Name" filter that sorts by both "First Name" and "Nickname" based on the input.

I found this question on here and it seems like it gives the proper direction of what I am looking for but I am not quite sure how to execute this solution.

3 separate fields,one views exposed filter

The suggestion based on the question above would be to expose both the "First Name" and "Nickname" filters but to hide the "Nickname" filter with CSS.

Following that, if a user typed a name such as "John" into the "First Name" filter and then clicked "Submit", before the query is executed, the input value "John" would also be automatically input into the CSS-hidden "Nickname" filter.

The concept makes sense to me but I am confused as to how to execute it.

Are there any detailed guides that could explain how I could make that happen?
With the PHP code given in the question linked above, would I have to modify a core file? Would it be in a template file? Would it have to be in a module file?

Or is there an even simpler solution to this that I am not thinking about?

Any help is appreciated.
Thank you!

Have you tried with an exposed Global Combine fields filter ? I'm not sure which Views version implemented that filter.

Alternatively, you may use the Views filters populate module :

Add the fields you want to search in a OR combination of filters, not exposed.
Add the Global : Populate filters provided by the module (exposed),  checking the filters you added in the Or group.


Opening a ctools modal on form submit I have a custom profile form (part of a multi-step registration process) that requires a modal to be displayed once submitted. I am not clear on what the process is for this to happen, and the documentation i've seen isn't clear.

What I have tried (as seen below) is adding the submit action via a $form['#action'] which only returns the JS Object for the modal. Clearly, this isn't working. What should I do to render this modal when the form submits, while assuring the validation and submit calls fire?

The actual Ctools Modal logic is in its own modal, of which it generates on a hook_menu() call to the correct route.

function example_profile_update_form($form, $form_state) {
  $form = array();

  $form['item'] = array(
    "#type" => 'textfield',
  );

  $form['#validate'][] = "example_profile_update_validate";
  $form['#action'] = url("modal/updated/nojs"); //Implemented as a hook_menu() call in its own module
  $form['#submit'][] = "example_profile_update_submit";

  return $form;
}

Form API and Ajax frameworks work quite well together.

In your submit button, that you want to trigger the popup, it should work as an Ajax element first.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit (and open popup)',
);

If you use submit and validate handlers as you have shown in your question, those submit and validate handlers will be executed at this point. If you want different submit/validate handlers, then you have to add them to the submit button itself.

Now, add #ajax property to the element.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit (and open popup)',
  '#ajax' => array(
    'wrapper' => 'id_of_some_unique_element',
    'callback' => 'my_module_give_this_function_a_nice_name',
  ),
);
ctools_include('modal');
ctools_modal_add_js();

We play a trick here. Typically, #ajax property is used to replace some parts of the form. That's why we use the wrapper to indicate the replacing element. This will not be used at all if you trigger the modal, but make sure you refer to a unique DIV. Better leave it empty.

The callback is what we need. This callback should be a PHP function name, that returns some or full $form first parameter, or, it can print some Ajax commands. Do not set $form_state['rebuild'] = TRUE in your #submit handler.

ctools_add_modal_js() adds the modal.js file because it's necessary to trigger the popup.

function my_module_give_this_function_a_nice_name($form, &$form_state) {
  // this function gets the $form_state after submitting the form. All values, including the submitted values preserved.
}

Now, we need to print the modal contents.

function my_module_give_this_function_a_nice_name($form, &$form_state) {
  // this function gets the $form_state after submitting the form. All values, including the submitted values preserved.
  ctools_include('modal');
  ctools_modal_add_js();
  $commands = array();
  $commands[] = ctools_modal_command_display('title', 'modal content goes here');
  // You can add extra modal using drupal_add_js/css. You can also have them `#attached` to a rendarable array that you are going to print.
  print ajax_render($commands);
  exit;
}


Forum Post urls with Pathauto I'm using Drupal (v7.21) with Pathauto and Advanced Forum and would like the paths to be formatted like:

domain.com/forum
domain.com/forum/the_topic_name
domain.com/forum/the_topic_name/the_post_name

Under Forum Paths 'Pattern for forums and forum containers' is set as:

[term:vocabulary]/[term:name]

And under Content Paths I've set 'Pattern for all Forum topic paths' as:

[node:taxonomy_forums]/[node:title]

This is working except for the Posts which are missing the /forum/ part:

domain.com/the_topic_name/the_post_name

I could manually get this to work by setting the 'Pattern for all Forum topic paths' as:

forum/[node:taxonomy_forums]/[node:title]

But I'd rather have it set using a pattern if possible.

Any ideas?

you can add pattern like [node:content-type] or [node:content-type:name]. So the actual pattern will be [node:content-type]/[node:taxonomy_forums]/[node:title]


Multiple instances of same form in views do not work properly I have a funny problem with Drupal 7 and Views.

I created programatically a simple form with two submit buttons (yes / no). This form is displayed on a full view of a node and when the 'yes' is pressed, it goes to a 'review' form which autofills the title with the one from the node. It works very well!

function mymodule_form($form, &$form_state,$nodeid) {
  global $user;
  $form['nodeid'] = array(
    '#type' => 'value',
    '#value' => $nodeid,
    '#access' => false,
  );

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

  $form['no_button'] = array(
    '#type' => 'submit',
    '#value' => t('No'),
    '#submit' => array('no_button_submit'),
  );
  return $form;
}

//Submit handlers
function yes_button_submit($form, &$form_state) {
    $nodeid = $form_state['values']['nodeid'];
    drupal_goto('node/add/review', array('query'=>array('id'=>$nodeid)));
}

I decided to add the buttons on the teasers that I display in a Views block. I call the form through a function which is called via a Global Php field. Here is the code inside the Global Php field, having added 'content: nid' as a hidden field in the view:

<?php
  $bling=mymodule_answers($row->nid);
  echo $bling;
?>

With the bit of code from mymodule_answers:

function mymodule_answers($nodeid) {
  $theform3 = drupal_get_form('mymodule_form',$nodeid);
  $output .= '
'.drupal_render($theform3).'
';

  return $output;
}

My problem is that if the view is something like this:

Node 1
Node 2
Node 3
Node 4

If I press 'yes' on any of the node teasers 2 to 4, then the review form is filled with the title of Node 1... meaning, the one at the top of the list!

I have thought about creating uniquely named forms, but I wouldn't know how to automatically generate the differently named submit handlers. Any ideas?

After looking for a while on the Internet, I found a solution.

Firstly, you can add a '#name' to your submit buttons to distinguish them, and then do a switch case in the submit handler... I was trying this for a while before realising that it was not my problem.

My problem consists in the fact that I am calling the same form multiple times on the same page. I found a previous post which highlighted the fact that each form should get a unique form_id in order for it to work. Using hook_forms was the best method for this. I followed the instructions from here. It worked despite it being for Drupal 6.

Amended code...
I added this hook:

function mymodule_forms($form_id,$args){
  //Check if the form_id passed to drupal_get_form() contains the string 'mymodule_form'
  if (strpos($form_id, 'mymodule_form') !== FALSE) {
     //Lets attach mymodule_form to $forms[$form_id].  This effectively allows you to use the same form builder function to build a form with any form_id of your choice.
     $forms[$form_id] = array(
       'callback' => 'mymodule_form',
     );
     return $forms;
  }
 }

And then, the code that calls the form was amended to this:

function mymodule_answers($nodeid) {
   $theform3 = drupal_get_form('mymodule_form_'.$nodeid,$nodeid);;
   $output .= '
'.drupal_render($theform3).'
';

   return $output;
}

Voila!


Multiple Book Versions I imagine this has been asked before, I'm just struggling to find the right answer.

Using Books to create documentation for an open source project. We're covering 3 domains, Users, Developers, and Admins. Easy enough.

Where I am struggling is how to create versions of these books for each software release. Do I just create a new book for every version? 1.0, 1.1, 1.2, etc? Should I be using a taxonomy vocab for the releases? What is a manageable way to handle this?

Documentation can be done in many different ways using different modules. If you decided to go with Books, then it is really up to you to create new books or taxonomies for new releases. Look at how Drupal's documentations is organized on https://www.drupal.org/documentation.


Omega Layout Configuration I'm new to Drupal and Omega theme. I made a subtheme of Omega 3.x HTML 5 using Omega tools.

I need to configure zones and regions in theme settings, Thus i went Home » Administration » Appearance » Settings (on my subtheme) > Zone and region configuration.

But those zones are not configurable. and I cannot click on those. Where did i do the mistake ?

I'd go in with firebug and check first that those collapsible blocks contain the HTML form content you expect to be there and that it is simply hidden by CSS rule(s). Then if that is true then edit the CSS for those collapsible blocks to make them able to dismay content.
If there is no form content there then possibly could be a permissions issue at a guess.


Is there any API to get corresponding field in a custom content type? I have drupal 7 and created a custom "content type" with several fields. just imagine i have:

title field
subtitle field

I need to search the data. I want to search titles and when i found my certain title I want to get corresponding subtitle (in the same row of that title)! I know I can do it by going to directly to my database and do it by db_query(and i have to know the structure of my database as well). but is there any API in this regard?
i need to get them inside my custom module

In this instance using db_query is appropriate...

$nids = db_query("SELECT nid FROM node WHERE title LIKE :title", array(':title' => '%'.$title.'%'))->fetchCol();

$nodes = node_load_multiple($nids);

foreach($nodes as $node) {
    $subtitle = $node->field_subtitle[LANGUAGE_NONE][0]['value'];
    // do things with the subtitle....
}

What has happened here is we are using db_query to search the node table for nodes with matching titles. Once we have the nids we call node_load_multiple and that loads the whole node(s). Drupal uses caching here so we don't have to necessarily connect to the DB at all to do this.

The resulting $node object has all of the fields already attached to it so knowing where they are actually stored in the DB at this point is irrelevant.

As Clive has pointed out we shouldn't really access field items directly as using field_get_times or EntityMetadataWrapper will ensure that we always load the field items in the correct language (the language of the current user).

To use field_get_items you could:

foreach($nodes as $node) {

    // using field_get_items here automatically loads the field in the correct language
    $field_items = field_get_items('node', $node, 'field_subtitle');
    $subtitle = $field_items[0]['safe_value'];

    // do things with the subtitle....
}


How to programmatically trigger a click on an AJAX enabled form submit button? I'm trying to programmatically (with jQuery) trigger a click on button with AJAX behavior in a Drupal form, but so far jQuery('#edit-submit').click() doesn't do anything.

A real mouse click on that button works as intended. Any ideas how to make it work?

jQuery('#edit-submit').mousedown() - apparently there's a big difference.


Properly adding an action to a ContentEntityForm I've created an add/edit form for a custom entity type, which extends Drupal\Core\Entity\ContentEntityForm. By default this form always comes with a "Save" button, and a "Delete" button if editing. I've been asked to add a "Cancel" button as well, but can't figure out how this is supposed to be done in Drupal.

I've seen plenty of answers about using hook_form_alter(), but nothing that is really working. My current solution is to add

$form['cancel'] = array(
    '#type' => 'submit',
    '#weight' => 10001,
    '#submit' => array('cancel_submit'),
    '#value' => t('Cancel'),
);

to the form's form() function, where cancel_submit() is a custom function, but that renders like  which looks awful.

How can I get the two buttons to be in line with each other? Is there a way to properly add a button to the form actions?

This is relatively simple when you define the form class yourself and one of the reasons Drupal 8 has gone all out on OOP. What you need to do is to extend the form class and implement the ::actions method. This would look like this:

class CustomEntityForm extends ContentEntityForm {
  ...

  protected function actions(array $form, FormStateInterface $form_state) {
    $actions =  parent::actions($form, $form_state);
    $actions['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelSubmit'],
    ];
    return $actions;
  }

  public function cancelSubmit($form, FormStateInterface $form_state) {
    // Du custom submit validation
  }

}

You could also achieve this with normal form alter, but would need to place the submit button inside the actions element, which is usually called actions, fx

$form['actions']['cancel'] = array(
  '#type' => 'submit',
  '#weight' => 10001,
  '#submit' => array('cancel_submit'),
  '#value' => t('Cancel'),
);


adding meta info to contents and filter them the target is to be add a meta field for drupal custom content type. that meta tag should be selectable by user when adding a new article .

the meta field is meant for language . (e.g. English / Urdu). the content types should show which  belong to the specific meta tag. e.g. if user selects English then the articles marked with english meta tag show up only.

any help appreciated

Have you looked at the Internationalization module?

  This is a collection of modules to extend Drupal core multilingual
  capabilities and be able to build real life multilingual sites. Some
  features:

  Taxonomy translation (both, per language terms and translatable terms)
  Multilingual variables Multilingual blocks (control visibility per
  language and translate title and content)
  Language selection (when you switch the site language you'll see only the content for that
  language)
  Requires Variable module 2.x (Drupal 7)
  Read a complete
  feature overview in the Internationalization handbook: Building
  multilingual sites .

If you dont want a full i18n site you can always just use a custom field or Taxonomy term and Views to build page lists of content tagged with that language.


Passing the actual path in File Save Data I have the following line in my script, but it fails to save the file in site/default/files folder. Is it possible I can replace public://feedproducts.xml with an actual absolute path to the files directory?

$file = file_save_data($sxe->asXML(),"public://feedproducts.xml",FILE_EXISTS_REPLACE);

This script runs from the command line, and is inside a sub-directory inside the root. It also loads Drupal Bootstrap.

The issue was that the script was running from a subdirectory. Calling chdir(DRUPAL_ROOT) before file_save_data() fixed it.


How can I remove a property from an entity in Drupal 7 I have a custom entity that was create a long time ago.  Now we want to update the schema to remove a property (not a field) that was defined in the original schema.

I've reviewed the Drupal API for managing schema for custom entities and I don't see anything that allows me to remove the column during a hook_update_N function.

Am I missing something obvious here?

You're looking for db_drop_field(). Although it's called a "field" here, it's essentially the remove-a-column-from-the-DB-table function.

Example from filter_update_7005():

// Drop the roles field from the {filter_format} table.
db_drop_field('filter_format', 'roles');


How to use single search box (autocomplete) for users and content? How can I use single search box with autocomplete for all the users on site and all the content of particular content type like blogs.

Thank you.

No need to create two views this can be achieved by modifying the query if you are using views. You can easily alter the query, if you are using the custom form then you can use Form API with autocomplete and in autocomplete callback you can do whatever you want. I have solved this using the autocomplete and its callback using FAPI


How do I override the username in forum views? I have created a module that overrides the real user name with the string "Anonymous" when a node is displayed.  I use hook_node_view() to do this.  This works fine.

However, to keep the user truly anonymous, I need to override the display of the user name in other contexts as well, for instance in the views of last post in a forum, or in the forum topic list produced by the core forum module (Drupal 7).

The screenshot below illustrates the problem.  It shows a forum post by a user "bob" that is supposed to be Anonymous.  As shown, "bob" is not Anonymous in the first two views, only in the last view of the node itself.

What I am looking for is a hook (or something else if there is no explicit hook for this) that let me override the display of the user name in these views produced by the core forum module.

Took me more than two months to figure this one out, but the answer is obvious once you know it.

Yes, there is an explicit hook for this. It is named: hook_username_alter.

D'oh!


Conditional checkbox fields if checked show a related textfield So I want to create an Order form for my products list in Drupal 7, I'm using Entity form module, I have a prepopulated checkbox list widget to show all my product's node title as checkbox. What I want is if anyone checks a checkbox a textfield shows up to add the amount he wants to offer. I tried Conditional fields module too but it kind of doesn't work for my case because there will be more products added to the list and I cant add textfield to it manually and it will be a massive waste of time to do that.

I appreciate any suggestions and approaches or any other modules you might recommend.

If you need to show a field when something gets checkked, you could just use JS to display a hidden field.

My approach would be to make custom table form that has the required input field as hidden. Then add javascript event listener to checkboxes that show the input at that row.

Then just do the normal validation and submit callbacks to update entities based on rows which are checked.


How do I disable memcache? I've inherited a site that connected with memcache even though its not necessary and its not installed on the server. Although I've disabled the memcache module,
the settings file has these lines which I cannot delete or the site stops working:

$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['cache_default_class'] = 'MemCacheDrupal';

I am getting this log message every two or three minutes:

  Failed to connect to memcache server: 127.0.0.1:11211

Clearing the Drupal cache and restarting Apache do not seem to fix the problem.  How can I fix this?

Hi You have to follow below steps in order:

disable and uninstall module.
remove from settings.php and delete folder of module.
clear cache (make sure all tables are empty)

For users using drush:

drush dis memcache

The following extensions will be disabled: memcache
Do you really want to continue? (y/n): y

Thanks


HybridAuth hide additional information form for twitter I'm trying to integrate hybridauth module for social login. Its working fine for Facebook.

But for twitter, after successful sign in, its asking E-mail, first name, last name & gender details.

If I uncheck required information, I won't get email to create user in back-end.

How can we do set up in twitter side to get these details?

Or

Is there any way to get these required informations with out showing the form?

My intention to successfully login into Drupal site after sign in using twitter, with out asking any addition informations.

After sign in I'm getting below form (Want to hide this form):

Drupal back end setting (If i hide, above form wont come but can't get email ID and other details):

The reason it prompts for that information is the Twitter API doesn't provide it; you can't retrieve user emails through the API; it only provides a single field for a user's real name (thus the prompt for the last name); and it doesn't collect information on a user's gender.


Webform Confirmation AjaxResponse I'm trying to update the URL on a successful webform submission, with an inline ajax confirmation. The form works and submits fine and I already have a custom Drupal ajax command to history.push setup, but cannot figure out how to hook into the confirmation flow.

I have tried:

Adding a custom callback to $form['actions']['submit']['#submit'] and returning an ajax response from that callback
Adding a custom handler, but can't see where I could add the functionality necessary

Thanks.

I ended up doing this by creating an event subscriber and listening for the webform ajax response as described on this issue page: https://www.drupal.org/project/webform/issues/2911409

The keylines (amended for brevity):

// The event to listen for
KernelEvents::RESPONSE

// Check to see if it is a webform ajax request
if(
    $event->getResponse() instanceof WebformSubmissionAjaxResponse and
    $event->getResponse()->getWebformSubmission()->isCompleted()
)

// Add my custom Ajax command
$event->getResponse()->addCommand(new UrlHistoryCommand)


Core forum hook_menu_local_tasks_alter() override i'm trying to implement lightweight topic tracker for core forums (tracking new topics and comments on main forum view).

I'd like to override forum_forum_load() method, but core forums calls forum_forum_load() method inside of a forum_menu_local_tasks_alter() and besides my overridden mymodule_forum_load() and mymodule_local_tasks_alter() it'll still call core forums own forum_forum_load() method making 2x more queries (2 x Amount of forums, in this case 28x2).

I replaced forum load function call inside of forum_menu_local_tasks_alter() with my own function and seems like it's working just fine, but I don't want to mess with the core, so I'd know if there is other way to prevent that behaviour.

I tried some other forum extending modules and they all have exactly same problem.

You're right in not wanting to mess with core; it makes things tricky when you're trying to update to a new version of Drupal. You have to maintain patch files which may break with new core code and it just gets messy.

Fortunately Drupal does provide a method to handle exactly what you're after.

In Drupal 7 hook implementations are alterable, so you can use hook_module_implements_alter() to stop forum_menu_local_tasks_alter() from ever running:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_local_tasks_alter') {
    unset($implementations['forum']);
  }
}

You'll need to copy the code from forum_menu_local_tasks_alter() and put it in your own mymodule_local_tasks_alter() function, and just replace the call to forum_forum_load() with the call to your mymodule_forum_load() function.


how to use parent field in child view in views field View I am using Views Field View module.
I need to filter the child view using the parent field. Can anyone experienced in it please share.

You will have to send a contextual filter from your parent view and catch it in your embedded view. There are plenty of tutorials on contextual filters, but this one should get you started:
http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

UPDATE
you can set a contextual filter from your parentview by editing the embedded view in 'fields' and define it in the view-settings drop-down.


How to include any view into the same panel To reduce duplicated panel pages for every view I want to display, I'd like to re-use the same panel (the same layout) for several views. The problem is that I can't find how to include ANY view in panel where view is passed by argument or URL. There are only particular Views Content panes available but this results in creating as much panel pages with URLs as there are views. And any changes in "common" panel content elements must be made for every panel page which is overkill.

There is analogue solution for nodes - predefined panel "node_view" ("/node/%node") which can display ANY node's content passed in URL. There's an element "Node content" which does that.
Is there similar solution for views? Thanks in advance!

If you can use a PHP snippet in your panel you could use views_embed_view($name, $display_id = 'default') to render the view from url.

Let's suppose your panel's url is /mypanel. You can use /mypanel/myviewsname/displayname to access that panel with a particular view and display using the following code in a PHP snippet:

<?php
$display = arg(2)?arg(2):"default";
print views_embed_view(arg(1), $display);
?>

arg() gets a list of arguments passed through url. views_embed_view() embed a view in a PHP snippet and it will return nothing if no adequate view name is passed. This should work whenever myveiwsname is an actual view name and displayname is an actual display of that view or is not provided.

You may be able to include PHP in a panel only if you have PHP filter module installed.

You should use PHP filter module with caution.


Export node display with Features not taking in account format of fields I'm trying to export a node display with features and I already created the feature with the display and imported it to another site.

The problem is that the display has some differences, mainly in the format of the fields (see the graph in yellow). It seems that the format of fields are not exported. I checked the generated code and found nothing about these formats.

Moreover, I'm changing the formats of the fields and features do not change at all, it status is not "Overriden", and I generated it anyway and there is no change at all, despite the different formats.

I don't know if it is a common issue with Display Suite or if I should active another module to do a better export.

How to fix this problem? Do you have exported node displays with features? What else can I do.

The format and other settings of the field in a DS display are exported as part of the field instance element containing an array of settings per DS display.
So, except from the DS display you have to track all the Field instances (from the related Feature section) in your feature.

An example of an exported field instance of a text field field_location with format Plain text in the Full DS view mode in feature file my_module.field_instance.inc is:

// Exported field_instance: 'node-image-field_location'.
  $field_instances['node-image-field_location'] = array(
    'bundle' => 'image',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'inline',
        'module' => 'text',
        'settings' => array(),
        'type' => 'text_plain',
        'weight' => 42,
      ),
      'full' => array(
        'label' => 'above',
        'module' => 'text',
        'settings' => array(),
        'type' => 'text_plain', // This is the exported format
        'weight' => 0,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 0,
      ),
      'token' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 0,
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_location',
    'label' => 'Location',
    'required' => 0,
    'settings' => array(
      'entity_translation_sync' => FALSE,
      'text_processing' => 0,
      'user_register_form' => FALSE,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'text',
      'settings' => array(
        'size' => 60,
      ),
      'type' => 'text_textfield',
      'weight' => 21,
    ),
  );


places where register_globals can be set Story for background problem: I have a hostgator account. Uploaded the content of a drupal install folder to the actual root of the server. To fix this, I deleted all the files that I recognised from the drupal installation folder. The hostgator person on the chat reassured me that by default the .htaccess file is empty so going to back to an empty would bring me back to the original state.
Everything seemed fine

Until I wanted to update 1 drupal 7 installation from 7.17 to 7.18. when starting to run mysite.com/update.php it said

  PHP register globals  Enabled ('1')
register_globals is enabled. Drupal requires this configuration directive to be disabled. Your site may not be secure when register_globals is enabled. The PHP manual has instructions for how to change configuration settings.

Checked the cpanel's php quickconfig settings. This said register_globals was set to off. So that means this setting is overwritten somewhere on a deeper level (it's a shared server so the root of my server is at a deeper level than the php installation which I obviously can't touch).
There IS a php.ini file in my root folder of my server but that one also says

register_globals = Off

I looked up this problem and a lot of people seem to solve this by settings the register_globals to off in the places I mentioned. I also put a php.ini file in my drupal installation folder at the same level as my index.php file. This solved the register_global problem, but then I started getting errors about the PDO not being compatible with my current php version (5.2.13 while PDO would be needing 5.2.4 and up). And I don't think asking my provider to update php would be the way to go....

I have hostgator account too.
In hostgator and certain other host providers the php.ini that overrides the default values should live in /home/USER/ (i.e. check if /home/USER/php.ini exists, where USER is the username of your hosting account). Make sure that this file has register_globals = Off.

If /home/USER/php.ini is not there then either copy the default (if you have shell access check php.ini location with the command php -i | grep php.ini and then copy this file to /home/USER/php.ini) or ask tech support to help.

More details can be found here on HostGator support site.

Finally, if you are using drush on your host account you might encounter "Register globals detection" issue in which case I would suggest the solution in comment #6, i.e.

cd drush/
ln /home/USER/php.ini php.ini

the resason for this is that drush script (drush/drush) checks for drush/php.ini and if it does not find it there it detects the default php.ini not the /home/USER/php.ini one.


Colors to my header and footer not applying by using color scheme options in my theme I am trying to incorporate color scheme which is available in  bartik, into my theme. I am able to generate the files which will be located at

  sites/default/files/color/theme-4855b5/colors.css

after making options in color scheme of my theme.

But in the head tag of styles files, it still points to my theme directory colors.css instead of above mentioned directory, Which results in no change of colors for my theme.

My theme is actually a sub theme. What am i doing wrong ??

I have included color folder and inside that have color.inc files.
Also included color.css folder inside css folder.
hook_process_page(&$variables)  and     hook_process_html(&$variables)  these functions included in template.php
included css file in info file too.  stylesheets[all][] = 'css/colors.css'

What am I missing in not getting that css being replaced by dynamically generate one? Thanks in advance.

I am able to apply css for my header and other things, I found an alternative way to include the css.Even though I can't find a way through drupal_add_css(), the following helped me in adding css.

This is the way I included dynamically generated css file which is located at sites/default/files/color/theme-768/color.css

In the theme folder in the html.tpl.php after <?php print $styles;?> include this

<?php
       print '<style>';
       print '@import url("' . $filepath . '")';
       print '</style>';
?>

This includes the css file and provided colors for header, footer etc.


Multi-domain user login access control E.g. My site has two subdomains : domain_a and domain_b.

And My site has three roles: role_a, role_b, role_c.

I hope:

User with role_a can login domain_a, can't login domain_b.
(When user visit domain_b user status is not logined and not lost domain_a logined status)

User with role_b can login domain_b, can't login domain_a.

User with role_c can login domain_a and domain_b.

Does anyone have any solution?

You have two options:

Domain Access has it figured out

Domain Access module excerpt:

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

Then, you need Domain Roles:

  Allows you to save user roles per domain. Allows a certain user to be just authenticated on one domain and admin on another etc.

You can't totally prevent cross-logins, but you can make user logged in with no permissions at all, except to log out.

If you prefer Multisite approach

You can change the settings for the access to the database that are contained in the settings.php file used by your Drupal site to something similar to the following one (replace the values between brackets with the correct values for your site):

$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);

Taken from this answer.

Then, in hook_user_login(&$edit, $account) test if user has a role he needs to access given page, and if not, logout him with proper message.


secondary navigation per page I created a secondary navigation that I display with $secondary_menu in page.tpl.php. It seems to work fine, however, it displays on every page now and I of course don't want that, it should only show on a specific page (where I have a secondary navigation). Now in order to achieve this, am I creating a special page template for the page where I want to show the links or can I somehow set on which pages my secondary navigation should show up?

Thanks!

Your secondary menu will be available as a block.

Go to /admin/structure/block, place the block in the page region you wish to use, and set it to display only on the pages you wish to have it on.

This is much easier than trying to set up specialized templates.


Some of node links of content types are corrupted There are about 5000 nodes in my website of different content types. After a while (updating the Drupal to 7.34 and configuring the Server by server administrator) some of node links are corrupted and they are redirected to the front page. They are not too many but I don't know why some links that were working, are not working now. As an example the link /node/286 is redirected to the front page.

Is there any problem with the update that causes such thing?

The host server was victim of an attack and a few guest websites on it were hacked. So I guess (not sure!) the administrator may blocked some PHP functions, could this be the reason for such misbehavior of the links ? If it is right then why only a few of them are broken?

I've hit redirecting-to-front-page nodes in the past when I've stripped out use of the PHP filter input format. Turns out there was conditional logic that sometimes printed javascript redirect code.

Does the pages in question use the PHP filter format? If the admin blocked eval() perhaps it could stop execution of PHP and just render redirect code?

You can check disable_functions value in /admin/reports/status/php to confirm your suspicion about disabled functions.


How to access the links variable from a template? I have created a views template for a block and I would like to insert the list of links that normally appears at the bottom of teasers and/or pages (the $links variable) into the template like it is done in page.tpl.php.

However I can't find how to get this information given a node's id.

How do I accomplish this? Is there a Drupal 7 command that accomplishes this?

I have found the solution to this problem. You need to do the following in your template:

<?php $node = node_load($fields['nid']->raw);
global $language;
node_build_content($node, 'full', $language->language);
if (!empty($node->content['links'])): ?>
    <div class="links">
      <?php print render($node->content['links']); ?>
    </div> <!-- /links -->
<?php endif; ?>


Load a panels display in code To load a Panel display from the database we can use panels_load_display($did)

However, the $did value is an autoincrement value from the database. It is not present in exported Panel page displays (e.g features export).

I thought perhaps we could use ctools_export_object_load to load the exported panels display.

However, I found that it only returns a result if the display is in the panels_display table in the database, and returns empty empty for exported code storage displays.

e.g:

// Attempt to load Panels display
ctools_include('export');
$uuid = '49c15c71-d5d1-d574-b539-0149f912f925';
$display  = ctools_export_load_object('panels_display', 'conditions', array('uuid' => $uuid ));
var_export($display); // empty array if not in DB.

How can we load a Panel display in code when that display is exported in features and using code-based storage?

The relationship between tables and their exported datasets is declared via the export key in a table's schema definition. We can see that key both for page_manager_pages and panels_display.

ctools also allows the definition of a default hook. If non was provided it will fall back to default_{table}.

When loading a ctools exportable via ctools_export_load_object() ctools will first query the table for objects, then invoke the default hook to retrieve any objects stored in code.

When page manager pages are exported, panels_display objects are not declared separately under their own hook, but are wrapped in hook_default_page_manager_pages().
In order to retrieve them by their UUID they would have to be declared within hook_default_panels_display().


How to use hook_menu to create wildcard aliases to a normal node page I have a node template where I check the url for the existance of some parts and play with that, eg, if the node is called your/recipies, I catch urls like

/your/recepies/bananas
/your/recepies/apples
/your/recepies/oranges

and check the url for bananes,apples,oranges in the template.

I used aliases to point those urls to the original node, but they keep on dissapearing. It's probably be a breeze to set up a module router, like

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

        $items['your/recipies/%'] = array(
            'title'  => t('Recipies'),
            'page callback' => 'drupal_magic',
            'page arguments' => array('your/recipies')

        );
 }

to make drupal just render the node (and not redirect somewhere).
however, i cant find out what to write instead of drupal_magic.

(recipies, if you must know, is a webform; not something i can easily generate myself)

fwiw, I now did this different. I won't accept this as an answer, because it isnt. But this works as well in my case

function kitchen_url_inbound_alter(&$path, $original_path, $path_language) {
    if (preg_match('|^your/recepies(/\w+)?|', $path, $matches)) {
        $path = 'your/recepies';
    }
}


Is it helpful to improve performance by mysql table indexing? Yes I am talking about manually indexing drupal cache table.
Is it helpful to improve site performance by indexing cache table?
For ex::
SELECT cid, data, created, expire, serialized, tags, checksum FROM cache_default WHERE cid IN ( 'locale:en::anonymous' ) ORDER BY cid;

The cache_default table already has an index by CID (as well as indexes by creation and expiry date that allow old entries to be discarded).
Since almost all queries to the table are by CID there's not really any need for other indexes and it's not clear what benefit you would hope to see.
Adding extra indexes to tables does not result in cost-free performance enhancement. Every additional index makes write operations to the table more expensive, so you should not add any new index to a table until you have clear evidence of slow queries resulting from its absence.


Drush PHP syntax error when running I am following the instructions to install Drush that are listed on this page: https://github.com/drush-ops/drush/blob/master/docs/install.md

I seem to be getting a syntax error within the code:

[user@localhost ~]$ wget https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar
--2015-11-16 16:23:02--  https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar
Resolving github.com (github.com)... 192.30.252.131
Connecting to github.com (github.com)|192.30.252.131|:443... connected.
HTTP request sent, awaiting response... 302 Found
2015-11-16 16:23:05 (1.47 MB/s) - drush.phar saved [3496991/3496991]

[user@localhost ~]$ php drush.phar core-status

Parse error: syntax error, unexpected '[' in phar:///home/user/drush.phar/includes/output.inc on line 188

I am not seeing this error on Google. Any idea how to fix it?

You're using Drush 8, which requires a minimum PHP version of 5.4.5 (http://docs.drush.org/en/master/install/).

Your current version (5.3) doesn't understand short array syntax, hence the error you're seeing.

To fix, either upgrade PHP, or switch to an older branch of Drush.


How can I use Views to create a page with 3 Content Types, grouped by type, limited to x number of each type? Sorry for the long title.  Essentially what I'm looking for is the best way to create the standard News style list page, in which I might display something like the 3 most recent News Articles, Company Events and Press Releases.

The content would be grouped by content type so would essentially look like this:

News Header
News Item 10
News Item 9
News Item 8

Events Header
Event 10
Event 9
Event 8

Press Releases Header
Press Release 10
Press Release 9
Press Release 8

Seems like a common use case so I'm thinking (hoping) someone has done it before.

I've got it working up to the point of showing only x number of each content type, but can't seem to figure how to limit content without limiting just the overall number of items, not per Content Type.

Thanks a lot.

Here's a solution using only the Views UI.

Create a view with the following master settings: display 3 items, sort post date descending with the node tile included in your fields. Probably as you have it already.
Add a page or block display with type == News articles. This will be your parent view display. Again, you might have this already, but your type filter may need to be adjusted. We just want 3 news articles here.
Add an attachment display with title as Events and update type == events. Attach this to your parent view display above.
Add another attachment display with title as Press Releases and update type == press releases. Attach this to the parent view in the second bullet point above.

You can find the attachment to setting in the second center column on the views ui, assuming this Drupal 7.

Jason.


JS Resize function for div containing a a slideview slideshow and set as a page background This is for a drpal 7 install.

Is there a way to apply the same function they discuss in this thread

https://stackoverflow.com/questions/10373349/height-and-width-of-background-picture-adapt-to-each-screen-size

to a whole div instead of a single image? For example, I have a drupal 7 install. I'm using skeleton theme. I have been requested by the client to have a full screen images slider as a the background in the homepage. I have given the images a 1680px Image style and calling the block from a custom template file for the front-page with $ block = module_invoke. That's aright but, it obviously doesn't adjust to screen res. If I give the div one of the skeleton's css classes, the whole layout gets messed up.

I'm trying to find an alternative via custom js.

Is that possible to achieve the same behaviour as in the demo in the link, for the slideview block?

Demo- http://so.devilmaycode.it/height-and-width-of-background-picture-adapt-to-each-screen-size/

If so, please indicate how to add the js to the code, where and how. Thank you!

Found two options: cycle2 for which the project is still in development stage:
http://drupal.org/sandbox/BenYoung/1832338
(and did not work when following the installation guidelines, since I never got the Cycle2 option in the dropdown and needs jquery 1.7 which apparently causes a lot of trouble)

And one that is actually fully functional
Flexi Slider here http://drupal.org/project/flexslider , for which I found also this great tutorial here http://coldfrontlabs.ca/blog/creating-responsive-image-slider-galleries-adaptive-images-drupal-7.
Strange that they're so well hidden when adaptive design and full width sliders are so requested now...

Now it works as I wished for it to be, except for one thing I will ask a different question for.


How does Drupal select default domain for relative links? In one of our Drupal sites (core 7.14) links in two blocks displayed on the front page recently started using one of the alternate domains defined in the Apache config for the site instead of the primary domain. Neither block was changed recently. There are other blocks on the front page, and throughout the site, that were not affected.

The links in the block were of the style href="node/123" (without a leading slash). After investigating any modules or settings that seemed related to blocks or links, we added a leading slash to the links (i.e. href="/node/123") just to see if that had any effect. It did. The links using a leading slash selected the primary domain while the ones without a leading slash choose one of the alternate domains.

Any links in the block without a leading slash used the same alternate domain, so Drupal wasn't randomly selecting domains for each link.

The site launched using 7.10 and this odd behavior didn't start until we upgraded to 7.14. This only appeared in one site (so far); our other Drupal sites don't do this.

So my question is, how does Drupal choose the domain to use when rendering links and did that change somehow in 7.14? Does Drupal read the Apache config file?

Thanks for taking the time to read and consider my question.

You can specify the domain in settings.php - it's the variable called $base_url (around line 271). It is not always necessary, but I've found it can prevent some unexpected errors if the domain is set explicitly. I'm not sure how Drupal decides the domain if the $base_url is not set. By default, the $base_url is commented out. To set it, remove the # in front and change www.example.com to your primary domain.

Are the links in the block built using a Drupal menu? I think when you set the leading slash, you actually circumvented Drupal's menu handling which is probably why it worked. If you set the $base_url, I think you could remove the leading slashes from the links.


Common Javascript File for all Themes I have a multi-site installation using domain access module and each sub-domain has its own theme. I have a javascript file which is common to all the themes. Right now I've placed the js file inside all the themes folder. Is there a way to place the js file in a common location so that all themes can share it ? Can I use Libraries API module for this purpose ?

Yes, you can use the Libraries API for this.  The docs explain all of this fairly well.   This is best for things that change infrequently.

For my custom Javascript libraries (which I work on continuously), I make module with an instance of hook_library

function mymodule_util_library ()
{
    $path = drupal_get_path("module", "mymodule_util");

    $libraries = array();

    $libraries["mymodule_util"] = array(
        "title" => "MyModule Javascript Utilities",
        "version" => "0.0",
        "js" => array(
            $path . '/UTIL.js' => array(),
            $path . '/UTIL.HTML5.js' => array(),
            $path . '/UTIL.COLOR.js' => array(),
            $path . '/UTIL.MATH.js' => array(),
        ),

        'weight' => -10,
    );

    return $libraries;
}

Put the module in "site/all/modules" so all of your sites can see it, then enable it on the sites you need.

Then, wherever you need these JS libraries, you use drupal_add_library

drupal_add_library("mymodule_util", "mymodule_util", $every_page);

Typically, this is in a hook_block_view or a preprocess function.


How to add extra class in main menu? I'm creating custom theme. I am struggling to create main menu with drop down. I created a menu with custom code:

 <?php
            $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
            print drupal_render($main_menu_tree);
          ?>

But it doesn't working as I want. I need to add class in that particular <UL> tags. How can I achieve that?

I tried to Hook custom function in templates file. But no luck. How to call custom function into view page?

Below are some more screenshots.

Main menu with correct:

Menu with Wrong:

How to call custom menu design in custom theme?

You can use Menu Attributes Module to add classes.

  This simple module allows you to specify some additional attributes
  for menu items such as id, name, class, style, and rel.

To custom code it, you can add class to menu links using hook_menu_link_alter . Try something like this:

$item['options']['attributes']['class'] = array('class-one' , 'class-two');


How to add multiple taxonomy terms to node? I'm new to PHP and Drupal module development.
I'm having a site on which the users can create their own posts(nodes).

Can someone help me with how to save multiple taxonomy terms to a node. The users are filing their post in a form and the data is sent back through ajax. For example the taxonomy terms are sent to the server in this format: apple, banana, orange.
I don't know how to save all these terms to a node.

First of all, be sure that the taxonomy reference field exist in manage field page of your content type, then you can attach that field to your node via the function field_attach_update, before attaching that field to node let's get it from your data passed through Ajax :

 $terms = $form_state['values']['your_tax_field'];

 // attach to node :
 $node = new stdClass();
 $node->nid = $nid // Make sure that the nid exist;
 $node->type = 'your_content_type';
 $node->your_tax_field = $terms;
 field_attach_update('node', $node);
 entity_get_controller('node')->resetCache(array($node->nid));

Not tested but should work like that! You can use devel module to debug your data passed in the form.


moving D8 from one sub-folder to another If you move your Drupal 8 website from one sub-folder (example.com/oldsite) of your domain to another sub-folder (example.com/newsite), you will find that internal links to pages and references to images are not updated. Instead, these links and references will point to your old domain name. How to fix this issue?

For example, this is one of the pages after the move the site from one subfolder to another. If I click on any of this links it's taking me back to the old website.

Thanks

I had to update the content links manually. I learned that for to create any link for the internal content i need to use relative links instead of an absolute link.

Thank You


Restrict "add more" button to add new fieldset after adding 5 fieldsets I have taken a field of type field collection in my user-profile-form and its cardinality is set to unlimited as I wanted to have "add more" button for the users. I want to restrict the addition of fieldset to five numbers.

If I change the number of fields to be displayed to 5 from edit, it renders all the five fieldsets altogether which I do not want.

I tried overriding field_multiple_value_form() in my template.php file but did not succeeded. Please suggest some ideas to achieve this.
Thanks In advance.

This can be achieved using css. First of all write hook_form_alter() on your custom module. and your code should be like this..

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    if (isset($form['your_field']['und']['#max_delta']) && $form['your_field']['und']['#max_delta'] == 4) {
      $form['your_field']['und']['add_more']['#prefix'] = '';
      $form['your_field']['und']['add_more']['#suffix'] = '';
    }
  }
}

Where $form['your_field'] is your field collection field machine name. You can write your custom css on #prefix and #suffix and set it to display none.


Views Data Export not showing data export display option in view I installed Views Data Export module on a Drupal 7.50 site and it works beautifully. I am trying to incorporate it now into a new website (which happens to be 7.54). I have cleared all the Drupal caches as well as the browser cache and have checked that the module is enabled. I also have Views Excel Export extension installed and enabled on both sites.

I'm completely stumped that this works perfectly on one site and not working on another.. .

Update: I thought I checked the versions, as I installed them on the same day, but somehow, the one on the site that works is an older version (3.1 vs. 3.2).

I tried uninstalling it and installing the older version but it didn't resolve the issue. I also checked permissions but there aren't permissions for this module.

Here is the conversation on Drupal.org with no resolution.

I had installed the Views Excel Export module first. I had to uninstall both modules and then reinstall them in the correct order: Views data export first and then Views Excel Export. This solved the issue for me!


How will speed be affected by entity_metadata_wrapper()? I'm building a big website and I'm using entity_metadata_wrapper() in lots of places around the website.

I'm wondering how this will affect the website's speed and server resources.

Thanks

Entity API does a lot of things, but most of them are cached.

For example, entity_metadata_wrapper() calls entity_get_info(), which uses the cache to retrieve the data. If the cache is empty, other functions are called:

drupal_schema_fields_sql()
cache_set()
...

Other modules may be involved through hooks:

module_invoke_all('entity_info');
drupal_alter('entity_info', $entity_info);

But note that no data is fetched from the database, this is because when you call entity_metadata_wrapper() you already have the entity loaded -it's a parameter to the function, indeed.

So if you are running critical or long processes such as importing data or running thousands of iterations inside a loop, you should better use entities directly. But even then, the cache should help a lot.

Look how Drupal looks without Entity API:

$field = '';
if (isset($entity->field_name[LANGUAGE_NONE])
    and isset($entity->field_name[LANGUAGE_NONE][0])) {
  $field = $entity->field_name[LANGUAGE_NONE][0]['value'];
}

It's ugly. This is why I use Entity API almost everywhere, and I haven't had any performance issues so far. For the benefits, I think it's worth using it.


Remove/hide title/subject from published comments How can the title/subject not be displayed in a published comment.

I have already disabled the subject/title field for entering comments, meaning that users only have a comment body box for which to enter text. (I used the following question and answer to achieve that: Remove subject field from comments )

However, even with this disabled, the initial few words of the comment body get displayed automatically as the subject/title.

Background: I'm developing a stackexchange question/answer style system for my site and am looking for a similar kind of layout.

P.S. I'd be happy with a code-based solution (in a module, or theme) to override a hook (I'm examining the mark-up for clues myself) Or a module would be fine.

In your theme folder, if you do not have a comment.tpl.php file, create one. And customize yours to not have the title. Just take out the title from the file

Another option is to try removing it in your template.php file in the yourtheme_preprocess_comment() function


Some nodes totally inaccessible A great many of my nodes are not showing up at all on their node page (e.g. mysite.com/node/1234) but they are showing up in views, and they do exist in the database. What could cause a node to be unable to be viewed or edited on its node page, but still show up in Views and the database?

To clarify, "Not showing up at all" means I get a 404. I have cleared all caches.

I tracked it down.

Node_load() was dying whenever the query it was trying to run, failed. The query failed because it was joined on the UID of the author, and some users had been deleted. Lists of content that didn't use node_load() yielded the node's info without incident.


Node date in a different language? I use the following code to display the date in my node template:

<?php echo date("j F Y", $created); ?>

But I need to display the months in a different language, how can I do that?

I think you should use format_date() function that allows you add you own format and Drupal will translate it into the currently website site language.


Global PHP "sort through" vs other fields In drupal views, you can create a field called "global php" and insert your own php code. Also as well, it has a sort feature which is handy when your view style is a table.

However, the other fields does not have a "sort" feature on them. Is there a way to add it to them? Or does it just have to come with it, like global php does?

It has to be supported by the module supplying the field. In hook_views_data(), each defined field has a 'sort' element that defines the sort handler function for the field.


variables table in D8? What database table in Drupal 8 replaces variables table in Drupal 7?

Where are the values of Configuration stored?

example : $config->set('message', 'Hi')->save();
Where can I find value of message variable in database?


REST Export View Path is empty I have created a REST export view of contents.

I have all default configuration. I set my path to "/api".

Now when I try to add another rest export view on it, and create a contextual filter and I want to provide the path into "api/%", I am getting "Path is empty" when I click apply.

This is outdated. Should be fix by having proper configuration.


export drupal2drupal migrate settings I am using the drupal2drupal UI for a D7 to D7 migration. Is there anyway I can export the setting for the migration including the connection string and the field mappings so that we can repeat the exact migration on another server without having to repeat the UI setup?

There is a feature request for the Migrate module: Export migration configuration as code. Beware that this is highly experimental! Here is the summary of the issue:

Apply this patch to the Migrate module and be sure to clear cache. This patch makes your configuration exportable as a Feature.
You can now create a new Feature on the source site and select your configuration inside the Migrate fieldgroup. Check all options that apply and download/export your Feature.
Copy the Feature to your target site, enable it and then revert it to copy all your settings.


Event does not trigger each time I load a page I'm using event dispatcher in a custom module to auto login users in a Drupal 8 website. I'm using the KernelEvents::REQUEST, with a onRequest fonction. I put an echo for testing that the function was call :

When the user is already log in, the event work and my function was call on every request
When the user IS NOT log in (anonymous), the function was call on the only first request of a page. Never call again if you reload the page. Only way to get my echo again is to empty drupal cache (I make a drush cr).

Don't know exactly how Drupal cache work... Is there any way to trigger my event on every request, anonymous or not ? Or another better way to do my auto login ? Thanks.

my module structure :

/mymodule
|-- /src
|---- /Controller
|------ MyModuleController.php
|---- /EventSubscriber
|------ MyModuleEventSubscriber.php
mymodule.info.yml
mymodule.routing.yml
mymodule.services.yml

MyModuleEventSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\externalauth\ExternalAuthInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;

class MyModuleEventSubscriber implements EventSubscriberInterface {

  protected $currentRouteMatch;
  protected $externalauth;
  protected $currentUser;

  /**
   * Constructs a MyModuleEventSubscriber object.
   */
  public function __construct(ResettableStackedRouteMatchInterface $currentRouteMatch, ExternalAuthInterface $externalauth, AccountProxyInterface $currentUser) {
    $this->currentRouteMatch = $currentRouteMatch;
    $this->externalauth = $externalauth;
    $this->currentUser = $currentUser;
  }

  /**
   * Implements EventSubscriberInterface::getSubscribedEvents().
   *
   * @return array
   *   An array of event listener definitions.
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('onRequest');
    return $events;
  }

  public function onRequest(GetResponseEvent $event) {
      // echo 'test' => do my echo here
      if ($this->currentUser->id() == '0') {
         auto_login(); // I simplified the code here, but you get the idea
      }
  }
}

mymodule.services.yml

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MyModuleEventSubscriber
    arguments: ['@current_route_match', '@externalauth.externalauth', '@current_user']
    tags:
      - { name: event_subscriber }

This look like it is the module "Internal Page Cache", which caches pages for anonymous users. This cache runs before any event as middleware.

In your case there is no need for this module and you can uninstall it.

If there is other code that does interfere you should be able to control this with a priority you set on the event subscriber.


How to creating custom links that can be echo'ed individually Let's assume I have a footer with this div for which I have created a custom block named as custom_footer:

{% if page.custom_footer %}

{% endif %}

Now, I would like to put links inside the footer that are created using Home  > Administration > Structure > Menus > Add menu in other words I don't want to insert hard-coded menus like services  inside the footer div.

So, is there anyway to echo all the custom links for page created inside my footer?

This can be implemented using blocks.

First create the required menus from  Home  > Administration >
Structure > Menus > Add menu
Place the new  menu as a block under footer section in Home  > Administration > Structure > Block layout
Save blocks

Find the reference images:

Add user account menu to footer block (You can also include your custom menus),

Image listng user account menu on footer


Programmatically change the Base URL? Is there any way to programmatically change the Base URL, Just as the "locale" module does..
My Website is multi-lingual which has to recognize 3rd argument, after the language identifier. Some custom code will be triggered when base on the third argument.

Have tried to Find a solution for this but the most of the Solutions suggest settings.php approach.

I am looking for a hook that will allow me to alter the third parameter in the URL for custom functionality.

Sample URL: www.example.com/hi/arg3
Above "hi" is the language identifier and "arg3" will be used for custom functionality. Hence a node to be rendered will have url as  www.example.com/hi/arg3/node/1

You can do that with:

hook_url_outbound_alter

Keep in mind all URLs run through that function so your hook implementation should be as fast as possible.

Example from locale module:

  Rewrite outbound URLs with language based prefixes:locale_url_outbound_alter

See also: Language Negotiation API


how to show ubercart fields in manage fields section of content type I'm needing to access the price, sku, etc fields in the manage fields section in structure/contenttypes. None of these fields show up in the manage fields section? I can manage their display under manage display tab, but I need to be able to manage the field itself in order for conditional fields to affect them.

How can I show these fields in the manage fields section?

Thanks in advance.

Billy

It sounds like you might need to create a relationship between the content node and the product node. In the content node, you will only see a reference field pointing to the product node, which usually holds all the constructs you are looking for.


Trouble incorporating "Related Articles" block into panel I have a "Related Articles" view block that is in use on the site, and it functions fine. The site's original dev team configured everything through templates, but the code is placed in the "Article" template properly, and it all is well. This is a standard Related Articles block that uses the contextual filter "Content: Has taxonomy term ID" to find other nodes of Article type with the same taxonomy terms.

I have a problem, though, creating a similar block for a recently created content type ("News"). This node type's display is configured through Panels, though I'm not sure if that's what's causing the issue. I cloned the original block and altered the (non-contextual) filter to select content based on whether the content type is either Article or News (the original does only Article). Everything else is the same, including the contextual filters. When I place this block in the News panel, I get no results in the block (I've double-checked to make sure I'm using terms that exist on other articles).

I'm sure there are a number of things that could be causing the issue, but I don't know where to look. Can you offer me any guidance?

Thank you.

EDIT:

Here is their php code. I'm not proficient in php, but this looks pretty barebones to me.

<?php print '

Related Stories

' . views_embed_view('related_stories', 'block') . '

'; ?>

EDIT 2:

I have tried placing the following php into the panel:

<?php
$node = menu_get_object();
if (is_object($node)) {
  $tid = $node->field_article_tags['und'][0]['value'];
  $output = views_embed_view('related_articles_for_news_', 'block', $tid);
}
echo $output;
?>

Still no luck. Everything looks correct to me. The URL on the view as I edit it is:

admin/structure/views/view/related_articles_for_news_/edit

and this is the only display in the View. The advanced settings say that the machine name is "block", and I confirmed that field_article_tags is correct.

Additionally, I accidentally left off the trailing underscore in the view title originally, and, of course, that did not work either.

Any thoughts as to where I might be going wrong?

Thanks again.

The problem is that, your view accepts a Term ID which it uses to get other nodes tagged with the same term. But when you are placing the views block (accepting TID asparameter) in Panels, how are you passing the context to it?

This is probably why your dev went in for the code based approach. I think you can create a custom PHP panels content, grab the node from the present path, then grab the tid from term reference field, and the pass in the tid as context while calling the view through views_embed_view() function.

If you want you can paste the code your dev used and I can help you how you can re use the code in panels to get the same result.

Code Should be something like this:

$node = menu_get_object();
if (is_object($node)) {
  $tid = $node->field_yourfieldname['und'][0]['value'];
  $output = views_embed_view('your view name', 'display name', $tid);
}
echo $output;

Put the above code in the panel, using a custom content with PHP.


WSOD while trying to install Drupal Commerce Kickstarter I'm trying to install Drupal Commerce Kickstarter with core, but I cannot go past random WSOD, or hangs, to complete installation. WSOD happens randomly, but mostly after "Configure site" step. Very rarely I can reach "Installing additional functionality", but then it just stops at some point and won't move.

(At this point:  )

I'm trying to install it on local apache2, and have 128M of memory_limit, 1000 of max_input_vars, and 60 of max_input_time. If you need any more information, just ask and I will provide it. What can I do to complete installation?

According to Commerce's docs http://www.drupalcommerce.org/commerce-kickstart-2/troubleshooting-kickstart-2-installation

RAM: minimum 128M, more is recommended because your server can fail with this memory if it is at all strained

Since the Commerce Kickstart 2 distribution can install an entire setup and configured working demo, the installation process requires a bit more sustained power. In our early beta tests, installations can sometimes silently fail when it uses close to your memory limit.

So, the answer is, "Scotty, we need more power!"


Technical advantages of either Configuration or Features over the other? In short, Configuration vs Features, in Drupal 7, fight!

As always, technical advantages, or other hard facts, as we don't do discussions here. Drupal 7 specific to limit to scope, as CMI vs Features is a completely different discussion.

Watch Configuration for the future, because it more closely follows the model of Drupal 8. But I wouldn't suggest using it for now, because it is in alpha state, which means you need to be prepared to hack on it to keep it working, and you need to constantly update it, because it will not get formal Security Advisories if security issues are discovered.

Features is at 1.0, so it's a more stable choice for projects going to production soon, as you can trust that minor version updates will not break your existing features.


How to show text fields from a User object to anonymous users without "View User Profile" permission? I have a few basic fields on the user object to display "Author Bio" cards at the bottom of articles. It seems that anonymous users cannot see any of this information.

All I want to do is show first name, last name, phone number and email address. Is this hidden away because it requires "View User Profile" permission? How can I get around enabling that? I don't want to enable that if I don't have to. Conversely, how I can prevent anyone from getting to user/* pages?

Is there something I can change in the render array to change the access check?

Conversely, how I can prevent anyone from getting to user/* pages?

Getting technical here, you wouldn't want to block all /user/*; otherwise, you wouldn't be able to /user/login or /user/logout and also you would still want admins to access those /user/{uid} pages.

If  you inspect core/modules/user/user.routing.yml you can see most of the user routes. But what you expect, the /user/{uid} is not defined here.

It's actually defined in UserRouteProvider.php as /user/{user}

You can easily find the route name by enabling WebProfiler module that comes with Devel and  going to /user/1

Now all you gotta do is override the route's access by giving it a role of administrator.

mymodule/src/Routing/RouteSubscriber.php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Allow only admins to access '/user/{user}'.
    if ($route = $collection->get('entity.user.canonical')) {
        $route->setRequirement('_role', 'administrator');
    }
  }

}

Alternatively, in your custom module, you could create a new permission and use that for the Route's setRequirement instead and then assign the new permission to the roles that you want to have access.

mymodule/example.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

For more in depth information about altering routes, see: Altering existing routes and adding new routes based on dynamic ones.


Acquia Dev Desktop Export to archive I'm a newbie, so please forgive me if this is a dumb question.

Exactly what files does the "Export to Drupal archive" feature of Dev Desktop actually back up? I have searched the web and didn't find anything that would answer this question.

My understanding, at this point, is that I need to export/backup the database and my Sites folder. PhpMyAdmin will do an export/backup of the database, but I have to manually copy & paste the Sites folder and fool with all the settings in phpMyAdmin. It would really be nice if the Export to Drupal archive does this with only one click .

Thanks!

It does what you almost exactly described. Export to Drupal archive... creates a tar.gz file (tarball) with a backed up docroot folder (your drupal site code) & a .sql file (DB dump). This is everything you need to export your site to any host that runs MySQL/MariaDB & Apache/PHP


Executing JS calls during user login validation (Drupal 7) I need to execute three different JS calls during the login process (for tracking reasons) depending on how the validation goes. I have no idea where to include them:

1. Event: Login failed (wrong password and/or user name)
-> wrong_pass();

2. Event: Incorrect E-Mail format (I am using E-Mail addresses as user names)
-> wrong_email();

3. Event: Login successful
-> login_ok();

How can I catch these events and react to them by executing the respective JS calls?

Thanks in advance!

You could add a validation hook to the user login form & block to add the javascript if the fields fail to validate.

So to alter the form:

function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  // Add the validate function
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // Add your javascript that contains Drupal.behaviors
    drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/MODULE_NAME.js');
    $form['#validate'][] = '_MODULE_NAME_user_login_validate'; // this is the function name
  }
}

Then in your validation function:

function _MODULE_NAME_user_login_validate($form, $form_state) {
  // Do your field validation here, I'll only showcase one of them (username)
  if(!valid_email_address($form_state['values']['name'])) {
    // Add a setting to the Drupal.settings variable available in javascript
    drupal_add_js(array('MODULE_NAME' => array('name' => FALSE)), 'setting');
  }
}

Finally in your MODULE_NAME.js file you can check to see if the setting was set:

if(Drupal.settings.MODULE_NAME.name == FALSE) {
  wrong_email();
}


Disable front-end access I want to disable the front-end access of my headless Drupal site, that is just a REST API for a Vue site.

Except for the login page, there is no need to access any node, taxonomy or view directly as everything is delivered via REST.

How can I achieve this?

Based on your responses in the comments, it sounds like you want anonymous users to be sent to the login page on any access and for authenticated users to be able to access the site as normal.  You can achieve this with a custom module that checks for logged-in status and redirect to the login page, or via the Require Login Module which does essentially the same thing.


Drush cannot rr or en a module I have a Drupal 7 dev-site hosted on pantheon. Using git bash and composer I installed drush on my windows 10 machine and I thought I did so globally. When I run composer --version and drush status I get what appear to be good responses. However, when I try to enable a module using drush or rebuild the registry I get ...

samha@LAPTOP-99SBTCQM /c/localworking/thecottagepress (master *=) $ drush
@pantheon.thecottagepress.dev rr
/bin/bash: -c: line 0: unexpected EOF while looking for matching `''
/bin/bash: -c: line 1: syntax error: unexpected end of file

Here is what I get when I run drush status...

samha@LAPTOP-99SBTCQM /c/localworking/thecottagepress (master *=) $ drush
status Drupal version         :  7.56
Site URI               :  http://default
PHP configuration      :  C:\PHP\php.ini
PHP OS                 :  WINNT
Drush script           :
C:/LocalWorking/thecottagepress/vendor/drush/drush/drush.php
Drush version          :  8.1.15
Drush temp directory   :  C:\Users\samha\AppData\Local\Temp
Drush configuration    :
Drush alias files      :  C:/Users/samha/.drush/pantheon.aliases.drushrc.php
Drupal root            :  C:\LocalWorking\thecottagepress
Drupal Settings File   :  sites/default/settings.php
Site path              :  sites/default

What do I need to do to make drush fully functional? I have researched for most of today whith no luck. Thank you. Sam

If you are running drush on you're local site, you do not need to include @pantheon.thecottagepress.dev to run the command. Just run drush from your site root as so: drush rr. Drush won't be able to run the command on a remote machine if it can't resolve the domain name.


How to include order details in eMail notifications created with the Message module? I am working with placing an order with the Commerce module in Drupal. When the order is confirmed, a notification will be send to the user with order details. Here I am using a rule like when an order is confirmed, customer will receive an email.

The email content will be from the Message module based on the Rules module. Also there is a content from the Commerce module regarding order details.

My doubt is that how to get this order details content from the Commerce module to this Message module content.

Below is the mail content that I saw in the backend when the rule is applied. But the content doesn't have any order details. But when the mail is received order details are present. I want to find out how to get these order details along with this content.

  Dear [message:message-commerce-order:commerce-customer-billing:commerce-customer-address:first_name], Thank you for purchasing through [site:name]. You can view your order history by logging into our website at:[message:message-commerce-order:view-url] Sincerely, Order Number: [message:message-commerce-order:order-number]

You just goto
http://localhost/project/admin/commerce/config/checkout/rules/manage/commerce_checkout_order_email/edit/3

then as screenshot into the message value you can set your custom message and also use "Replacement patterns" for order detail to the message.

thank you..


Ignore Users Content with Flags> I am developing a network of websites for our nonprofit organization.

As with any membership site, we have some members who simply do not get along and often, their back and forth "drama" will detract from the other member's positive, supportive experiences.

Rather than simply banning members who can't get along with each other, we'd like to set up a way for members to flag a member and "mute" them, so that instead of seeing their content, they will see a message like "You have muted this member and cannot view their post. To unmute the member, visit your profile page." or something to that effect.

There was a module for 6 that is  ported to 7 called Ignore User, but it doesn't seem to be in a stable release for 7.

It seems to me that there has to be some way to do this with flags, rules, and views -- but I admit it is a bit above my knowledge level.

Has anyone ever done something like this on a Drupal 7 site? Can you help me make this work? I really do feel it will make a big difference for our chapters and minimize some of the "drama" we have to deal with on a regular basis.

Thanks
Heather

There is Ignore User, but for D7 there is only a dev version that hasn't seen any progress in over 2 years. Might be worth a look though, maybe you can start with that and even contribute back any improvements.

Everything else would require a considerable amount of configuration concerning the flags themselves, any views listings and node displays. Probably you will even need to do some custom coding.


Insert an ad into Views Grid? I'm using the Views Grid layout and I'm looking for a way to place Google Adsense ads randomly within the grid. Here is the code in views-view-grid.tpl.php:

<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>
<table class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>

<?php print $caption; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_number => $columns): ?>
      <tr <?php if ($row_classes[$row_number]) { print 'class="' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>

Is editing the template file the correct way to do this? I'm not a programmer so a lot of this is beyond me but I am willing to learn.

Nice attempt, but no the template file is not the best place for that.

I would work on including the ads in your View result rather than trying to hack the template file.

Does your view show rendered content?  Easy, make a new content type that contains your ads and include that content type in your filter.

Does your view show fields?  Same thing, just make sure the ad content type has the same fields as the content you're showing in the grid.


Is there a way i can import users having profile2 with feeds I have done user migration using feeds. but i am not able to migrate the profile2 fields with it. Is there a way? am I missing something. I am trying to use migrate module but its tricky. Any help is welcomed.

There's a module called Feeds Profile2 which extends the built-in User processor so that Profile2 profiles can be created and updated as part of a user importer.


Language detection method "Browser" doesn't work if I check "Cache pages for anonymous users" I have two method detection activated in this order:

1- URL

2- Browser

Problem is that the method "Browser" doesn't work at all if "Cache pages for anonymous users" at 'admin/config/development/performance' is checked. The default language is loaded all the time regardless the Browser language.

It works fine if I uncheck "Cache pages for anonymous users".

See the captures.

have you seen and tried:

https://stackoverflow.com/questions/22792062/drupal-7-always-redirecting-to-default-language

  You might be affected by a bug in Drupal core. I had the same problem
  for a while and finally found the cause and a workaround for it.

  It goes like this:

  Add this code to a custom module (change "mymodule" to your modules' name):

/**
 * Implements hook_language_negotiation_info_alter().
 *
 * Remove the 'cache' setting from LOCALE_LANGUAGE_NEGOTIATION_BROWSER since
 * the code that utilizes this setting will in fact prevent browser negotiation.
 */
function mymodule_language_negotiation_info_alter(&$negotiation_info) {
    unset($negotiation_info[LOCALE_LANGUAGE_NEGOTIATION_BROWSER]['cache']);
}

  Clear all caches (e.g. "drush cc all")
  Go to admin/config/regional/language/configure and press "Save settings" once (this will rebuild the variable
  'language_negotiation_language').

  Now browser language detection should work properly.

  I'm also looking for a real solution but this requires changes in core
  and probably some discussion beforehand because of the nature of the
  bug. I've opened an issue here: Browser language detection for
  anonymous requests is broken

there is now a patch from Berdir


Field Collection Major Error! Help Needed! After trying to add new field collection item, I get this message in Chrome when going back to the previous page in browser:

  Notice: Undefined offset: 92 in field_collection_field_widget_embed_validate() (line 1675 of /sites/all/modules/field_collection/field_collection.module).

and when I tried to save I got this:

  EntityMalformedException: Missing bundle property on entity of type field_collection_item. in entity_extract_ids() (line 7734 of /includes/common.inc).

I should add that I'm having 92 items in my field collection. When I work in Firefox the browser just freeze. Can't find any other solution to my site at the moment then to use field collections this way. Any thoughts? I wonder if a field collection inside a field collection would decrease the heavy JavaScript load?

Check your maximum_input_vars setting in php.ini

I recently had a similar issues with a repeating field collection once we added a certain amount.  We bumped from 1000 to 10000, but I feel that was excessive.


How to make 2 different code run acording to different cron schedule? I have 2 different code running under hook cron like below:

function custom_module_cron(){

  // First here code run for posting nodes to Facebook pages
    (this should run for cron tab Ist )

  // Second code runs for sending new posted links in form of digest
     to users according to their selected hours. (This should run for cron tab 2nd )

}

For above process I have different cron tabs running on my server such as:

http://oexample.com/cron.php?cron_key=something7rsds

For Facebook at : 23:30,  23, 21,  and many more  hours

For Digest at : 7 , 8 , 10 and many more

How can we differentiate that each code run according to required hours.
Can we make different urls to run for different code  to prevent running of code at unwanted hours? I am using rough technique by using in_array for current time and hours in cron tab but thats very handy and I think its not solution.

Please suggest what I can do to make my codes run according to separate schedules ?

Thanks!

Adding a GET parameter should work. In your crontab edit the url and add something like &type=facebook.

In the hook_cron implementation you should be able to catch the type via $_GET['type']


API error: "The 'administer nodes' permission is required." When sending a POST  to Drupal 8's JSON:API (to create an entity) that references another content piece (linked by a UUID), I get the error:
"The current user is not allowed to POST the selected field (uid). The 'administer nodes' permission is required."
or in more detail:
"errors": [
        {
            "title": "Forbidden",
            "status": "403",
            "detail": "The current user is not allowed to POST the selected field (uid). The 'administer nodes' permission is required.",
...

the original JSON in the POST request is:
{
  "data": {
    "type": "node--itinerary",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "value": "a05c9063-d594-4e5e-8b1f-f0b6b9f0d77e"
        }
    }
  }
}

I've tried researching this issue but it's not clear what the permission is that needs to be set (there is no: "administer nodes" in permissions) and it's not clear if this level of access is too much. Does anyone have any further information/ideas?

First, administer nodes is the machine name of the permission.  On the Permissions page, the name of that permission is Administer content.  There's probably some historical reason why Drupal has some permissions where the machine name is different than the name shown in the UI, but it's horrible usability.
In any case, this is definitely too much access if you just want the user to be able to set the entity reference.  Normally, you probably want to give the user some combination of Content type (Itinerary): Create Content type (Itinerary): Edit, and Content type (Itinerary): Delete permissions, which will be under Node at /admin/people/permissions.
Actually, though, your code has another problem.  The error is about posting uid, which is not your entity reference, but the author of the node.
The format for setting the user id, as noted in the docs:
{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "data": {
          "type": "user--user",
          "id": "{{UUID of user 1}}"
        }
      }
    }
  }
}

You are missing the part about data and type.
And, even if you use this code above, it won't set an entity reference field.  To set the entity reference field, in addition to the author, you need to set the entity reference field like this (example of setting a node entity reference field on a taxonomy term flag; this is maybe not the best example for your case but its code I wrote recently that shows how to set an entity reference field; in this case, the entity reference field is flagged_entity):
  data: {
    type: 'flagging--my_flag_type',
    attributes: {
      entity_type: 'taxonomy_term',
      entity_id: drupalId,
      field_text: textFieldValue,
    },
    relationships: {
      uid: {
        data: {
          type: 'user--user',
          id: MyUser.id,
        },
      },
      flagged_entity: {
        data: {
          type: 'taxonomy_term--group',
          id: MyGroup.id,
        },
      },
    },
  },


How to add a time picker in datetime form elements I have made a module that display a form. One of the form elements is a datetime field.

$form['FirstDate'] = array(
      '#type' => 'datetime',
      '#title' => t('First date-time'),
      '#id' => 'inputFechaMd',
      '#required' => TRUE,
      '#default_value' => '',
      '#prefix' => '

',
      '#suffix' => '
',
      '#attributes' => array('style' => array('margin-bottom: 1em;'))
    );

When the form is displayed It has two fields, one for date and one for time. The date field has a date picker, but the time field hasn't a time picker. I would like to add a time picker for this fields, but I don't know how to do it. Also, I would like to hide seconds and request only hour and minutes.

Your code renders a time type input for the second field, which will invoke the standard time widget for browsers that support it (most modern ones do).

For all browsers that I know of, that's a simple input mask and placeholders, not a dropdown picker like the date field. If you need such a picker, you'll have to find and integrate a JS library to get it.

You could do it yourself, but there's a contributed module, Datetime picker, which integrates 3 different time picker libraries so you can choose your favourite. If that doesn't give you exactly what you want, the code should at least give you a good starting point to implement your preferred solution.

In case you still need it, you can remove the seconds from the time input by setting #date_increment on the element to 60, which sets the step attribute on the element. That causes Chrome at least to only include placeholders for hours and minutes.


What is the difference between using Drupal as a CMS and using it as a Portal? I have a lot of already existing web applications that are not in Drupal.  They are independent systems.  I am looking to create an Intranet solution to tie them all together, meaning, have links to them, not an integration with Drupal.

Is this using Drupal as a CMS or a Portal?  Does this go against the philosophy of what Drupal is for?  I want to use Drupal 8 if it matters.

Is this using Drupal as a CMS or a Portal?

I would say "CMS", and probably even "CMF" (Content Management Framework). E.g. using things such as Webservices.

  Does this go against the philosophy of what Drupal is for?

No, it's just 1 out of dozens of usages of Drupal.

  I want to use Drupal 8 if it matters.

Depends how much in a hurry you are, but I'd strongly recommend to not yet use D8 in production. Some more details on that:

Use Drupal 7 if you want to build production ready sites today, or in the near future.
Use Drupal 8 to get ready for "the future". To answer the (next) predictable question (= by when would I have to be ready for that), be aware of the famous quote from "Mr. Dries", which is something like: Drupal 8 will be ready when it's ready ....

Some more words/thoughts about D8

I do not think the D8 development architecture will change anymore (therefor it's too late).
So to start developing with D8 with a production date far away from today might make sense. And if you adapt to the new (OOP) stuff with Symphony, etc, then you probably don't need many more changes by the time D8 gets released.
Be careful however with an assumption like "... D8 is just about ready". Even if there are only a seven critical issues left before RC1.
D8's first beta was released at DrupalCon A'dam (2014). And I wouldn't be surprised if somewhere between Sept 17, 2015 and Sept 24, 2015 the first RC1 would be released (at DrupalCon Barcelona). But from then on an official release will not be just a matter of weeks (I "hope" for somewhere in 2016 ... and would "love" it to be in "2015" still).
The key challenge after D8 is released will be the contrib modules you'd need: if you can get the job done with hardly any contrib modules (now that Views is in core), then you're fine. But what if you'd depend on modules that only support D7? Or modules that don't have a stable D8 release yet, such as the Rules module?

Future-Proof your Drupal 7 site

To make transitioning to Drupal 8 easier, there are quite some decisions can you make now on your current or new Drupal 7 sites.

For more details on that, refer to the (amazing I think) presentation of David Reid about all those amazing contributed modules in Drupal 7, which are like backports of new Drupal 8 features.


Custom teasers and show summary checkbox The function generating teasers in D6 does not make nice teasers.  At the same time I do not want to bother my users to set teasers themselves, I would rather get rid of the whole system.

Anyway, I tried writing a little helper module which went through the published nodes and tried to correct teasers that were too short or too long.

My problem:

Between the node_load() and a node_save(), what parts should I care about, just place a <!--break--> in $node->body or adjust $node->teaser?
I had the problem after adjusting $node->teaser and deleting the break; the "Show summary in full view" checkbox was unchecked when manually editing this node.  Which variable is controlling this checkbox and how do I set it?
If I wanted to implement some teaser-corrections via hook_nodeapi(), which event should I hook to, when I do not want to patch the node core module and interfere with its node_teaser() function?

I know there are a couple of modules around, that store teaser data in separate CCK fields.  I would like to avoid this if possible.  (and yes, I want to have a proper value for the teaser variable and not just manipulate the output via views etc.)

Set $node->teaser to the value you want to use as teaser. That is what node_submit(), the function indirectly called from node_form_submit(), does.
node_body_field(), the function that add the form fields for the node body, contains the following code:

// Check if we need to restore the teaser at the beginning of the body.
  $include = !isset($node->teaser) || ($node->teaser == substr($node->body, 0, strlen($node->teaser)));

// …

$form['teaser_include'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show summary in full view'),
  '#default_value' => $include,
  '#prefix' => '
',
  '#suffix' => '
',
);

The checkbox is not selected if

the teaser is set, or
the teaser is not the initial part of the body

I would use hook_nodeapi('presave'), which is invoked before the node is saved, but before hook_nodeapi('insert') or hook_nodeapi('update').

To notice that, if the problem is the length of the teaser, node_teaser(), uses the value of the "teaser_length" Drupal variable as length if the teaser. I am not using Drupal 6, but if I remember well, there should be a setting page that allow to change the value of that variable. If the value of the variable is not modified from a setting page, then you can set it in settings.php, or from a custom module.