Add javascript to multiple specific urls I'm trying to add some javascript to my template.php file on a Drupal 7 site. I'd like the javascript to load on a specific set of pages, based on the url. For example, I'd like the script to load on:

mysite.com/blog/page1

mysite.com/blog/page2

but not on:

mysite.com

or
mysite.com/blog

or
mysite.com/about

I'm using

function mytheme_preprocess_html(&$variables) {
  $theme_path = path_to_theme();
  $path = drupal_get_path_alias();
  if($path == 'blog/page1') {
      drupal_add_js($theme_path . '/js/example.js');
    }
}

to load the script on that specific page, but is there any way to use a url argument or wildcard or something so that all internal blog pages (i.e. blog/page1, blog/page2, blog/page3) will load the script?

Thanks!

The drupal_match_path() function should do the trick:

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

if (drupal_match_path($path, $pattern)) {
  drupal_add_js($theme_path . '/js/example.js');
}


Simplenews automatically send out email notifications when new content is published I'm trying to figure out a way to allow anonymous users to subscribe to my blog and receive email updates whenever I publish new content.

I've tried a couple of solutions, but none of them seem to work the way I would like them to. This page (http://drupal.org/node/983184) says that I should be able to use Simplenews to do it, but I can't figure out how.

That module seems to be based around creating a Newsletter content node and which gets sent to the subscribers. However, what I want to do is post a new Article and have the system automatically send an email to all my subscribers containing something like a Teaser.

At the least, I'd like to send a simple email with the Content Title and a link to the node.

How do I configure Simplenews to work like this?

Recommend to try the Newsletter module. This may also help you.
This may also be another solution for you.


How to have new fields show with default content on new items? For example:

I created a content type with 2 fields, the default values are:

Field 1 = A
Field 2 = B

When creating BRAND new content items, the fields show up on display with populated default data:

A
B

But when editing content that was created BEFORE creating the fields it doesn't work.

Is it normal that the default fields will only work on NEW content items?

I want to be able to add fields to items

Is it normal that the default fields will only work on NEW content items?

Yes, that is normal.

The way I work around that to update the OLD fields:

Go to the database and export the field table.

For format: select CSV (do not select "CSV for MS Excel")

Open the .csv file in Excel and make changes to the values.

To replicate a cel fast in excel, highlight 1 cel and move mouse to the right bottom corner of the cel (cursor will change to a +), then hold down left click and scroll down.

Import back to the DB and check-mark "replace table data with file".
In Drupal, clear/flush the caches to see changes.


Handling access denied result In Drupal 8, what is the correct way of returning access denied to a user (outside of access requirement on a controller)?

I'd say it is to throw an AccessDeniedHttpException most of the time, but I have seen modules set an event response to 403, or do a redirect response to system.403.

Generally, the correct way is to throw new AccessDeniedHttpException() over setting a 403 or a redirect response, which bypasses the exception handling, so that it's no longer possible to configure a different handling of 403's in contrib or custom code. Unless you want to bypass this intentionally, for example if you want to produce a faster 403.

However, in most cases it is preferable to control the access as route requirement. The main effect is the same, the routing system throws an exception as well. But it does other things, like controlling the visibility of menu links, which you don't get when you throw the exception in custom code.


Print User Registration Block Through template.php file I just want to print the user registration block through my template.php file without using the Form Block or Enabling php on my site to use this code:

<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

I have tried the following:

function my_template_form_alter {

      $form = drupal_get_form('user_register_form');
      print drupal_render($form);
}

I want this block to appear on my blocks administration page just like the user login block, so I can place it anywhere I like. Any help as per how to achieve this? Thanks

You won't need any alters. Just go to the template in which you want to place the registration form and add,

$form = drupal_get_form('user_register_form');
print drupal_render($form);

This will print the user registration form. It's always good to have a check for anonymous users as a wrapper of this output.

Edit #1 (After question update and comments)
I suppose you want to create a block that will appear in your "admin/structure/block" page and you can assign the block in any desired region? - Right? I don't think your question says the same but this can be done in the following way,

Create a hook_block_info() & hook_block_view()
In the hook_block_view() assign the "content" the following,

$form = drupal_get_form('user_register_form');
$block['content'] = drupal_render($form);

I hope this can solve your problem. I haven't tested this yet!


Views/Block: Only display if node field has a value I've created a Block in Views. I only want this Block to display if a boolean field on the node is ticked. The View itself should only display content that relates to the node. How can I do this?

When displaying content in Views that relates to a node, you can normally use "Context Filters ID: Node". This would allow a View to take over a node. But it only seems to work in the Page display of the View and not the Block display.

I now I can use modules such as Rules, Panels or Node Fields Block to achieve this. But those are quite big modules and I only want to use it for a small thing on my site, so I was hoping their might be some solutions that can be done without any extra modules.

The context module lets you conditionally display blocks on pages. context_entity_field then would let you set a condition based on the boolean field in your node.


Migrating Contacts from Joomla to Drupal The Joomla module in Drupal does a good job on migrating content and users, but it doesn't have functionality to pull the contacts from Joomla.

Has anyone successfully migrated contacts from Joomla to Drupal? What methods are there of accomplishing this?

I started to manually move the contacts... but there are about 100 of them =/. I started by creating a new content type with the fields for the contact, and am using the Views module to create a table for the contacts.

Used phpmyadmin to dump the data from the table containing the content I needed, and put it into a CSV file. Then I used Drupal's Feeds module to import the CSV into the content type that I created.

Worked beautifully.


Listing child terms based on relationship with parent The premise:
I have a taxonomy listing “countries” on the first level and “country subdivisions” on the second level.
E.g.:

Canada

Ontario
Quebec
etc..

United States

Alabama
Alaska
etc..

A user is attributed to a country in the user Account Settings. E.g: John Doe is from Canada.
I would like to create an Entity Reference View that would list all Provinces related to the user attributed country.
E.g.:
List of provinces offered to John Doe while creating a node:

Ontario
Quebec
etc..

First you have to create the Taxonomy hierarchy within Views, so later only the children terms will be in Views rows results (so they can be chosen from a ER field on the node creation form). You can't do that starting from User Views because only Parent Relationships are available, no way to drill down, only up is possible.

Create Taxonomy term Views of your particular Vocabulary. They will list both Parents and Children. It will already have the Taxonomy Name field, keep it.

To create the hierarchy add the Relationship Parent first (It's called "Taxonomy term", search for "parent" to find it quickly in the Relationships list. Require it because we only want to display terms that have a parent, we only want children terms to show on our list

Then add another Relationship, introducing the User, it will be named something like User using field_country, make it use the Parent Relationship (so we get users who are tagged with top-level terms). Require the Relationship because we only need terms that do have users tagged with them.

Now add the Contextual filter User ID. It will automatically use the Country Relationship, and configure it:
When the filter value is NOT available
Provide default value
User ID from logged in user
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Hide view or what ever makes sense in your case
To easily test whether the correct sub-terms appear enter some user ID into the Views Preview field. It will provide the context directly to Views so you can see which sub-terms are shown and whether they match that user Country.

Add the Entity Reference Display to your Views and adjust its Settings, (Search fields: Name). Save the Views so you can use it in the next step.

Create/Edit Taxonomy Reference Field on your CT, select the Views as the Reference Type and then select the Views you've created in the first step.

Adjust the "Manage form display" for the new field so it appears as you like it on the node create page.

Now when you go to create a new node of that type the field will list all the sub-terms of the Country the author is tagged with.
You still have to test by logging in as some user to test that the context is passing through correctly (Switch user block can speed it up).


How to auto reference? I have created 2 content types one is called Album and the other is Image. I gave Image a reference field so it's linking to Album. Now when a user goes to upload a image how can I make it auto reference to the album? cause the user will have no knowledge in using drupal

Check out the nodereference url module. It's designed exactly for this use case.


nid for custom form module I have created a custom module(a simple form) in drupal 7 using  https://www.drupal.org/node/717722 , i have successfully installed newly created module and able to save the form data. But i need an nid for this module which is being use by other module to perform series of tasks, i have been searching a lot about how can i found the nid of custom module ,but none of solution worked , also i have searched in the database table , other contents like webform , basic page and articles are there in database with there nid's but the newly created module's nid is not there ,can any one please help how can i find the nid of custom module and if there is no such nid then how can i set and nid for newly created module.

thanks in advance

Forms don't have nid. Only nodes are having nid (node_id) in drupal. If you are displaying the form on any node page, suppose on http://example.com/node/123. Here 123 would be the node id and you can fetch it in form by

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
}

And if you want this $nid to be passed through different form states, add this as form field

$form['nid'] = array('#type' => 'value', '#value' => $nid);


How can I have all drupal links work on ajax based? Is it possible to have all drupal internal links work on ajax based without any page refresh?

If there is any ready module, please share the link. Your help is really appreciated.

Maybe this module will help you: http://drupal.org/project/ajax_links_api

  Ajax links API module help you to load any content to a specified DIV
  using JQuery Ajax. This module will also load JS and CSS for
  Ajax-loaded content by using Drupal.attachBehaviors(). Links will work
  as normal if Javacript is disabled.

  In HTML5 browsers, title bar and url will change using
  window.history.replaceState() (This feature is disabled by default.
  Check ajax_links_api.js to enable).


Menu link that is author nodeid specific When a user creates an account i have a rule that creates a node and set them as author for it.

I need a user specific link in the menu that varries from user to user.

User 1 may need the link: "Edit your node" -> Links to node/1/edit
User 2 may need the link: "Edit your node" -> Links to node/5/edit

So its something like:

If content type = FOO, and node author = logged in user, show link "Edit your node" that links to -> node/%/edit.

You should use tokens in your menu-item for it to change dynamically. Install Menu Token module. From the module page-

  Menu Token allows to use both global tokens and entity ones: node, user, term, etc.

Then allow your menu path to use tokens and set something along node/[node-id]/edit as your path.


How to render views inside page-front.tpl.php? I have a view named 'Updates' which displays latest article. How to render this view directly in my tpl.php ?

<?php
print views_embed_view('my_view', 'block_1', $arg1);
?>

replace view_name with your view name
replace block_1 with your machine name
replace $arg1 with an argument (if want to manually pass a value to your contextual filter) This is optional, if you're not going to use it, you can delete it.


Drupal confusion when including multiple instances of same webform on a page I have nearly the same problem than this : Multiple forms on single page?

But the answer  is for an inclusion on a page template and I want to do the same on a node template where I can't use any incremental ID loop. I'm using Drupal 7.

In either Display Suite or a node template just call the forms using drupal_get_form each form will given a unique build_id and there should be no problem displaying any number of forms on the page.

hook_forms in this answer https://drupal.stackexchange.com/a/6230/3279 has nothing to do with your question. You don't need to worry about incremental form IDs or anything.

Here is an example of how to use a preprocess function for a Node (type):
http://purencool.com/drupal-7-preprocess-tutorial-adding-variable-to-template this uses this Drupal API function https://api.drupal.org/api/drupal/modules!node!node.module/function/template_preprocess_node/7

Your code would look something like (this is example code not guarenteed to work):

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'MY_NODE_TYPE') {
    // link to webform paths.
    $vars['custom_form_links'] = implode(' ', array(l('Please Fillout Form 1', 'some/path/to/webform'), l('Please Fillout Form 2', 'some/path/to/webform2')));
    // Or just embed the forms.
    $form1 = drupal_render(drupal_get_form('myform1'));
    $form2 = drupal_render(drupal_get_form('myform2'));
    $vars['custom_forms_embed'] = $form1 . $form2; // You may want additional HTML wrappers, figure it out.
  }
}

Then in your themes template files for like node--YOURCONTENTTYPE.tpl.php you echo these new variables.

Display Suite makes all this a ton easier with Code Fields, or custom fields, and dynamic view_modes so you don't need to touch template files either ...

None of this code is guarenteed to run -- it's just a rough example.


advance search to show post by date i trying to make the search on drupal show result by date. for example if i type 25/05/2010 it should return posts for that date and also search by key work which is default on the search. how can i acheive that.

function mytheme_preprocess_search_result(&$variables) {
    $result_node = $variables['result']['node'];
    $image_realpath="";
    if(!empty($result_node->field_op_main_image)){
        $image_field = $result_node->field_op_main_image;
        $image_realpath = file_create_url($image_field['und']['0']['uri']);
    }
    $variables['image_uri'] = $image_realpath;
    $author_name="";
    $info = "";
    if(!empty($result_node->field_op_author)){
        $author = $result_node->field_op_author;
        $lang = $result_node->language;
        $author_id = $author[$lang]['0']['nid'];
        $author_detail = node_load($author_id);
        $author_name = $author_detail->title;
        $info .= $author_name . ' - ';
    }
    if(!empty($result_node->field_date)){
        $date_obj = $result_node->field_date;
        $date_val = $date_obj['und']['0']['value'];
        $info .= date('d/m/Y', strtotime($date_val));
    }
    $variables['info'] = $info;
    // dpm($variables);

above is the code for displaying my result for now.

please help thanks

=======================================================================

EDITED

so this is what i got so far: let me try to explain:

i was trying to modify the search-form and the search-block-form i was able to add a jquery date picker so that the user might search for a specific date or a key word.

the date picker is working

now the issue is:

when i search for key words and press submit it return the article with key word. but if i enter date only it give error to enter keyword and if i enter keyword and date it search by keyword only and ignore the date

code is below

// function to modify search form
function fiveplus_form_alter(&$form, &$form_state, $form_id) {

// $variables['form']['actions']['submit']['#value'] = 'search';
if((array_key_exists('#id', $form) && $form['#id'] == 'search-block-form')){
    $form['actions']['submit']['#value'] = '';
}
if((array_key_exists('#id', $form) && $form['#id'] == 'search-form')){

    $form['basic']['submit']['#value'] = 'submit';
    $form['basic']['keys']['date_field']['#title'] = 'search';
    $form['basic']['date_field'] = array('#type' => 'date_popup','#date_format' => 'Y-m-d');
    dpm($form_state);
    //$form['advanced'] ;
}

so anyone can help me figure out how to make a user be able to search only by 1. date 2. date and keyword 3. keyword

thank you

You can use views to search all of your content.

Rather than me write out every step for you, Please try the tutorial at http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7


How can I enable HTML output for checkbox options? I am adding theme styling settings and I would like to have associated color to the checkbox in themes setting form. So far, i haven't been able to do so, because the output strips inline styling and then external styling is being reset for the admin view. How do you enable html output of the text next to the checkbox?

Here is my code so far:

function THEMENAME_form_system_theme_settings_alter(&$form, &$form_state){
       $form['theme_style'] = array(
        '#title' => 'Theme Style',
        '#type' => 'fieldset',
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
    );
    $form['theme_style']['color'] = array(
        '#title' => t('Color Skin'),
        '#type' => 'checkboxes',
        '#options' => color_schemas(),
//        '#process' => array(),
        '#pre_render' => array(),
        '#post_render' => array(),
        '#format' => array('text_format' => 'full_html'),
    );
}

function color_schemas(){
   $colors = array(
        'blue' => htmlentities('Blue'),
        'black' => 'Black',
        'maroon' => t('Maroon'),
        'grey' => t('Grey'),
        'white' => t('White'),
    );
    return $colors;
}

Here i try different things. To set the text format in '#format' attribute. I also attach 'id' element so could style in external style sheet but those are reset by admin imported CSS. I also try convert all html entities and output which works but it doesn't render the html correctly

For starters, if you're using an admin theme like Seven for your administration pages, nothing on those pages will ever be affected by another theme's code. If you need to write code that applies across any theme, then you should be putting that in a module.

Inline styles are an attack vector for XSS, which is why they're generally not allowed in any kind of markup that is the result of user input. That includes the label text for a form element, such as a checkbox: the label is constructed by theme_form_element_label(), which sanitizes the text with filter_xss_admin(). That's absolutely the correct thing to do.

The proper way to do this is to put your styles in an external spreadsheet, as you've mentioned. Consider whether you could implement your code as a module instead.


Ctools Multi step form throws error when form_validate is from another file Ctools Multi step form throws error when form_validate is from another file even I had included the file using module_load_include.

As per this example I used a function not from the current file but by using module_load_include this is working fine. But when it comes to form_validate it is throwing an error.

Any suggestions?

Figured it out, we need to include using the below function

form_load_include($form_state, 'inc', 'module_name', 'module_name.file');


Report complains about Unsupported Release but no modules listed On my report page, I get a warning about Unsupported Release of modules or themes.

but when I click the "available updates" link, the next page tells me that all my projects are up to date.

I've tried clearing my cache and running cron but I get the same result.

EDIT:

Apparently this is a known bug that I missed in my searches. Unfortunately, the link to the bug below doesn't include any info on how to find out WHICH modules are unsupported. :( So, I have no way to figure out which things I need to upgrade or remove.

Where can I find a list of the unsupported modules in my installation?

If using Drush, try:

drush pm-updatestatus

Note: It gives you a list of the individual modules with their status, so you can determine which one is unsupported!


Ajax button in admin So I figured I'd create a configuration for my module. I created a normal form with some fields to let the users configure the module with variables. I also added a button which would do an ajax-call to a service. Problem is, this button is within the form, meaning it submits the form aswell.

$form['products']['update'] = array(
            '#type' => 'button',
            '#ajax' => array(
                'path' => '/products/update',
                'event' => 'click'
                ),
            '#value' => t('Update Products')
);

I just want the button to actually call this service (/products/update) and not act like a submit button. This worked in beta3 but is not an annoying feature in beta4, preventing the actual service call. How do I fix this?

ajax path is not supported anymore I think. It would need to be a route.

Why do you need a path? The common way to do this is to have a #submit callback on that form element, then just that will be called.


Custom block for anonymous users is shown to every user I have a simple problem that has me stumped. I created a block with custom "login" and "create an account" links, which I only want to display to anonymous users, naturally. I deployed the block using a Glazed Builder drag&drop feature, but it's showing up for all users. I also set the block so that it should not show up on /user/ or /user/* but it is showing up on http://example.com/user and http://example.com/user/login, etc.

I used drush cc all and am using an incognito window in Chrome, but cleared the browser cache anyway.

I'm on Drupal 7.54. I am using Glazed Theme from SooperThemes, which allows us to place blocks using a drag & drop editor. The block is still in the "disabled" list in the block list for some reason.

First of all, you have to remove the first slash in the show block on specific pages text area :

user/
user/*

will hide your blocks in user pages as expected, while /user/ /user/* won't.

This will solve half your issue. Then check if maybe your theme was complaining because of this misconfiguration detail, and may show now your block for anonymous users only.


Templating. Check if entity is comment or node? I'm modifying a template file for an Advanced Forum sub theme. AF uses a single template to theme both nodes AND comments with the same markup. I need to add a php check inside the node template to see if the current entity is a node or a comment, then print some flags based on the result.

I don't think there is a straight forward $entity_type variable to check, so how would I go about writing this?

Assuming this is for Drupal 7, there isn't an official way to do this, unfortunately. See core issue: https://www.drupal.org/node/1042822

One possible workaround is to check if the entity has some known fields that you are aware of. This obviously wouldn't be a generalized solution - but might work for you.


Upload images between texts in CKeditor I have a user manual in my site using Drupal 6, Which was created using book module. I use CKEditor as the editor and I want to upload images between the paragraphs. CKeditor asks for url to upload images.

Insert is must for easy insertion of image links in the text of node. You case insert using Colorbox or lightbox2. It can also insert using image styles you may have defined.

Make sure you do the screencast mentioned in the Insert module page.


How to handle non-fatal errors during a batch operation? Most tutorials about Drupal batch processing suggests that you provide something like the following as a callback for when the batch has finished.

function mymodule_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Success'));
  } else {
    $error_operation = reset($operations);
    drupal_set_message(t('At least one error occurred'));
  }
}

This is also how my finished-callback looks like (I know you can report more fancy statistics about the operations, but that is not relevant here. I want to keep this question simple).

I want to loop through a bunch of files in a batch and report at the end if any of them are not readable by the web server.  I do not want to abort the batch when a non readable file is found.

My test site is a clean Drupal 7.37 + Devel and a custom module called "mymodule".

This is how operations function for processing a single file looks like:

function mymodule_process_one($file, &$context) {
  $context['results'][] = check_plain($file);
  if (!is_readable ($file)) {
    // I need some code here that indicates that this is an error.
  }
}

I've indicated with a comment were I think there should be some code that indicates that there is some non-fatal error.  My question is: What should this code be?

I've made sure that one of files processed are not readable.  Using Devel to print out the three variables passed into mymodule_finished, this is what I get:

$success is TRUE.
$results is an array with all the file names.
$operations is an empty array.

Since there is no actual code in the operations-function to mark an unreadable file as an error , my finished-callback always print "Success", even if there are one or more unreadable files in the batch.  How can I make it report any errors at the end?

PS: I've searched the site and found examples on how to terminate the batch process if a fatal error occurs in an operation - e.g.: How to terminate a batch when an error occurs and
Can a batch process be stopped.  I am not interested in that.  I want an answer that explains how to process all items and produce an error message in finished callback if one or more operations failed.

Edit: I know that I can accomplish this by using a global db variable as an error flag. However, I am not interested in workarounds.  I want to learn how do this correctly using the batch API.

Preamble:
The answer given by burnsjermey did help me find the solution. He deserves kudos for pointing me to the correct documentation and this project on github. Both helped a lot, so I've accepted his answer.

However, his answer contains a lot of stuff that has nothing to do with the question. Also, his code examples have bugs that stops them from working. Therefore, I also want to add a self-answer containing only code snippets that are relevant to the question asked.

Self-answer:
First, as pointed out in the API documentation, non-fatal error management should be handled using 'results'. Hence, when we encounter a non-fatal error, we add an error message to the results array:

function mymodule_process_one($file, &$context) {
  if (!is_readable ($file)) {
    $context['results']['error'][] = t('@file is not readable.', array('@file' => $file));
  }
  else {
    $context['results'][] = t('@file processed.', array('@file' => $file));
  }
}

Then, in the finished-callback, we put code that looks for these errors, and prints them out if there are any.

function mymodule_finished($success, $results, $operations) {
  if ($success) {
    if (isset($results['error'])) {
      drupal_set_message(t('There were !count non-fatal error(s):', array(
       '!count' => count($results['error']),
      )), 'error');
      foreach ($results['error'] as $error) {
         drupal_set_message($error, 'error');
      }
    }
    else {
      drupal_set_message(t('No errors.'));
    }
  } else {
    $error_operation = reset($operations);
    drupal_set_message(t('A fatal error occurred'));
  }
}

That's all folks!

PS:
If you want to learn how to handle fatal errors during batch processing, the best answer is the accepted answer to: Can a batch process be stopped.


How to create an 'Upload a file' field? I have a content entity type, and I would like to have an 'Upload file' field. I have declared the field in my Entity class

$fields['file'] = BaseFieldDefinition::create('file')
    ->setLabel(t('Upload a file'))
    ->setDescription(t('Choose file from your computer'));

And in EntityForm I am trying to set some settings, because I need to make this dependable later with the '#states'

$form['file'] = [
    '#title' => $this->t('File'),
    '#description' => $this->t('Upload a file from your computer'),
    '#type' => 'file',
    '#default_value' => $entity->file->value,
];

But at the moment the field is displayed, but I have problems on saving the form. The file is attached, but not getting uploaded and the error says:

  Fatal error: Call to a member function getValue() on a non-object in
  C:\A
  plus\drupalsite\core\modules\file\src\Plugin\Validation\Constraint\FileValidationConstraintValidator.php
  on line 18

$form['File'] = array(
        '#type' => 'managed_file',
        '#title' => t('Choose  File'),
        '#upload_location' => 'public://MyFilesFolder/',
        '#default_value' => $entity->get('File')->value,
        '#description' => t('upload file'),
        '#states' => array(
          'visible' => array(
            ':input[name="File_type"]' => array('value' => t('Upload Your File')),
          ),
        ),
      );


Remove taxonomy page navigation pages I've a taxonomy page of a company which should show all nodes pages with this term.

I want that this page list at least 20 or so nodes, then we will need to click 1 or 2 or 3 to go to next levels.

Currently you can see every page is listing only single node. How to change this behavior?

I think your view is setup to show 1 node per page.

  Go into views admin/build/views
  Choose the view that is used for those pages most probably taxonomy_term view
  On basic settings: use pager click on the cogwheel and change the items from 1 to 20 items per page
  After saving this setting the basic setting should look like the following image


How to force homepage to non-default language I'm working on a bilingual website (French and English). The homepage currently shows up as per language detection settings, but I need it to show in French first, with the English version available via language switcher.

Info: Both languages use prefixes, and the language detection settings are ordered as URL>User>Browser>Default (English). The homepage is built with Panels and Views.

I've tried playing with redirects (has no effect) and i18n Variables (results in the page content not being found).

At admin/config/system/site-information add your system path (node/1, node/2 or whatever) to Default front page field. (Don't ask why the "prompt" sometimes displays the language prefix, sometimes doesn't, I don't know.)

Language detection settings have no effect here, I think. At least when you have URL first.


Creating line items in Ubercart 3 I have to build a module to add custom charges along with the order, e.g., gift wrapping charges.

I am using Drupal 7.

I've done exactly this before; I'll dump the code I used. Hopefully, it'll give you an idea.

/**
 * Implements hook_menu().
 */
function uc_giftwrap_menu() {
  $items['admin/store/settings/giftwrap'] = array(
    'title' => 'Gift Wrapping',
    'access arguments' => array('administer gift wrap'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_giftwrap_admin_form')
  );

  return $items;
}

/**
 * Implements hook_permission().
 */
function uc_giftwrap_permission() {
  return array(
    'administer gift wrap' => array(
      'title' => 'Administer Gift Wrap Settings'
    )
  );
}

/**
 * Form builder for the gift wrap settings.
 */
function uc_giftwrap_admin_form($form, &$form_state) {
  $form['uc_giftwrap_cost'] = array(
    '#type' => 'textfield',
    '#title' => t('Gift Wrap Cost'),
    '#description' => t('Total cost of gift wrapping for an order.'),
    '#default_value' => round(variable_get('uc_giftwrap_cost', '0.00'), 2),
    '#field_prefix' => '&pound;',
    '#size' => 10
  );

  return system_settings_form($form);
}

/**
 * Implements hook_uc_checkout_pane().
 */
function uc_giftwrap_uc_checkout_pane() {
  $panes['gift_wrap'] = array(
    'callback' => 'uc_giftwrap_uc_checkout_pane_callback',
    'title' => 'Gift Wrapping',
    'desc' => 'Provide gift wrapping options for the checkout.',
    'weight' => 5
  );

  return $panes;
}

/**
 * Callback for the checkout pane.
 */
function uc_giftwrap_uc_checkout_pane_callback($op, $order, $form = NULL, &$form_state = NULL) {
  if ($op == 'view') {
    $description = t('Please check this box if you wish your order to be gift wrapped.');

    $contents['gift_wrap'] = array(
      '#type' => 'checkbox',
      '#title' => t('Add Gift Wrapping') . ' (' . uc_currency_format(variable_get('uc_giftwrap_cost', 0)) . ')',
      '#default_value' => isset($_SESSION['uc_giftwrap_checkout']) ? 1 : 0,
      '#ajax' => array(
        'callback' => 'uc_giftwrap_update_line_items',
        'effect' => 'slide'
      )
    );

    return array('description' => $description, 'contents' => $contents);
  }
  else if ($op == 'process') {
    if ($form_state['values']['panes']['gift_wrap']['gift_wrap'] == 1) {
      if (!isset($_SESSION['uc_giftwrap_checkout'])) {
        uc_order_line_item_add($order->order_id, 'gift_wrap', 'Gift Wrapping', variable_get('uc_giftwrap_cost', 0));
        $id = db_query('SELECT MAX(line_item_id) FROM {uc_order_line_items}')->fetchField();
        $_SESSION['uc_giftwrap_checkout'] = $id;
      }
    }
    else {
      if (isset($_SESSION['uc_giftwrap_checkout'])) {
        uc_order_delete_line_item($_SESSION['uc_giftwrap_checkout']);
        unset($_SESSION['uc_giftwrap_checkout']);
      }
    }
  }
}

/**
 * AJAX callback for the checkout form (allows instant updating of total when gift wrap option is chosen).
 */
function uc_giftwrap_update_line_items($form, $form_state) {
  $commands = array();
  if (isset($form['panes']['payment']['line_items'])) {
    $commands[] = ajax_command_replace('#line-items-div', drupal_render($form['panes']['payment']['line_items']));
    $commands[] = ajax_command_prepend('#line-items-div', theme('status_messages'));
  }

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

/**
 * Implements hook_uc_line_item().
 */
function uc_giftwrap_uc_line_item() {
  $items[] = array(
    'id' => 'gift_wrap',
    'title' => t('Gift Wrapping'),
    'weight' => 2,
    'default' => FALSE,
    'stored' => TRUE,
    'add_list' => TRUE,
    'calculated' => TRUE,
    'callback' => 'uc_giftwrap_uc_line_item_gift_wrap',
    'display_only' => FALSE
  );

  return $items;
}

/**
 * Callback for line item type.
 */
function uc_giftwrap_uc_line_item_gift_wrap($op, $arg1) {
  // Required callback for hook_uc_line_item()
}

/**
 * Implements hook_uc_checkout_complete().
 */
function uc_giftwrap_uc_checkout_complete($order, $account) {
  if (isset($_SESSION['uc_giftwrap_checkout'])) {
    unset($_SESSION['uc_giftwrap_checkout']);
  }
}


Is there a better way to make a user profile tab using a view? I have created a question node type using CCK and would like to show all of the questions which users create on a tab on their profile page.

The way I have done this feels a little indirect. I have:

Created a view which lists all of a user's questions and made a block to display it.
Configured the block so that it only displays on the right path ("user/*/questions").
Created an entry in hook_menu for this path. Used a page callback which calls a function which creates an empty page (see below).

Is there a more direct way to do this by, e.g., attaching the view directly to the profile page?

The code in hook_menu() is:

$items['user/%/questions'] = array(
  'title'            => 'Your Questions',
  'description'      => 'User Questions',
  'page callback' => 'answers_blank_page',
  'access arguments'  => array('create question content'),
  'type'     => MENU_LOCAL_TASK,
  'weight' => 9,
);

The page callback is simply:

function answers_blank_page () {
  return '';
}

There isn't any need to use a custom module for this: The Views module already allows you to associate a URL to a view and make the view appears as a menu tab.

The following screenshots are for Views 7.x-3.x-dev, but the settings are present also in previous versions of the module.
Under "Page settings," there are two options: "Path" and "Menu." The screenshots shows the settings used for a view implemented by a third-party module (the Flag module), whose view is shown as menu tab.


How to create a related page or content type with in an existing custom content type? I have created a custom content type that is a product page. It takes various pieces of information relevant to creating a software product page. For example the products Name, System Requirements, and features and builds a custom page for each piece of software that I may make.

The issue is that I have a product page, and several ways to obtain the software:

Potential Trial version download from my site directly.
Link to Purchase from the Mac App Store,
And a link to Purchase it from a FastSpring store.

I am Trying to find a nice way to conceal that all behind one button on my product page, so that I do not have to clutter my Product page with 3 links to various ways to obtain the product. I just want to have a button "Get Product" that can load a separate page or equivalent.

What are some ways to do this in a semi automated way so that it can happen when I create a new product page and then have Drupal also make another page or something that I can fill in with links that I know to acquire the product?

Because I really don't want to manually make two separate content types one for the product and one for the product downloads links and then have to manage a releationship between them for all products.  Trying to make it so that the ways to obtain the product are included in  the product page content type in an elegant way.

If your concern is merely visual, you can use Fields to separate the different buying options then use Field Groups to separate them using, for instance, an accordion. You could then use javascript to control/open/close the items on the tabs.


Templates aren't called in custom module? I am trying to add templates for the paragraph in the custom module. It invokes only the paragraph.html.twig.

In theme suggestion, paragraph--example-ch-hero-panel.html.twig is given. I am using the same templates. By default, The template will be taken for the paragraph here. But here its not working. I am not using hook_theme in .module for this. because I am not passing any values to the templates.

even try this also

function example_ch_hero_panel_theme() {
  return [
    'paragraph__example_ch_hero_panel' => [
      'render element' => 'element',
      'template' => 'paragraph--example-ch-hero-panel',
      'base hook' => 'paragraph',
    ],
  ];
}

added theme registry too

function example_ch_hero_panel_theme_registry_alter(&$theme_registry) {
  $theme_registry['page']['path'] = drupal_get_path('module', 'example_ch_hero_panel') . '/templates';
}

  Please try again later.Twig\Error\LoaderError: Template
  "modules/custom/example_ch_hero_panel/templates/page.html.twig"
  is not defined. in Twig\Loader\ChainLoader->getCacheKey()

can anyone sort out this issue.

Your problem is coming from this code:

$theme_registry['page']['path'] = drupal_get_path('module', 'example_ch_hero_panel') . '/templates';

The first array key, page, means you are working the page template. You've told the system to look for page.html.twig in your module's /templates directory. It's not finding it, so you get that error.

Remove that hook altogether, it's not the right way to do what you are trying to do.


Limit multiple fields node add form How can I (either with a module or programmatically) limit the number of values for multiple fields? For example, the user can add only a single value for field A OR field B OR field C.
The total maximum number of values behind all fields can't exceed 1.

Using a contrib module:
You can use the conditional_fields module.

Doing it programatically:
You can use the #states property in a custom form or form_alter hook.

You must add this to field A, B and C:

'#states' => [
  'invisible' => [
    [':input[name="field-name"]' => ['filled' => TRUE]],
    'or',
    [':input[name="field-name-2"]' => ['filled => TRUE]],
  ],
],

Of course you have to replace "field-name" and "field-name-2" with the two field names that are not the one adding the states to, hope it makes sense.

If you can’t find the name of the field you can look in the browser inspector to get the name of the input field.


How can I recreate a previously deleted Content Type? I have deleted a Content Type called news some months ago using Drupal’s Field UI. Now I would like to recreate a new Content Type with the exact same machine name news. However no Content Type shows up. When I take a look at the database a new entry has been created in the node_type table.

Somehow Drupal doesn’t remove the Content Type in the database. What’s the recommended way to cleanup orphaned Content Types? Why does Drupal keep these leftovers? I don’t want to mess around in database.

You should delete the actual content first before deleting the content type. And nodes are going to be orphaned too and provably they will not display same as the content type news. can you try to search the existing news node in admin/content and check if you can still see the existing node type news that you created before. and try to delete them all before deleting the news content type and try to re-create the news content type.


Calling a PHP script from Drupal retrieves different result than calling it outside Drupal I'm trying to create a module that creates a Shortlink using Google Apps Shortlink Api (undocumented since its still in labs).

Here's the script (also at http://drupalbin.com/18667):

function drapps_shortlinks_createlink($url, $verbose = FALSE, $bypass_validattion = FALSE) {
  //loads ShortLink Class
  include_once('ShortLink.php');

  // URL validation with 2 clauses:
  // 1 - FILTER_VALIDATE_URL -> tests if the url is well constructed
  // 2 - @fopen -> tests if the URL actually exist
  if (!filter_var($url, FILTER_VALIDATE_URL) OR !@fopen($url,"r")) {
    // URL not valid or inexistant, so bail
    if ($verbose) {
      $msg = 'Invalid URL';
      return $msg;
    }
    else {
      return;
    }
  }

  // Get configuration values
  $domain = 'mydomain.com';
  $key = 'someHMACKEY';
  $user = 'username@mydomain.com';

  // Check if user admin has configured DRAPPS and DRAPPS ShortLinks
  if (!$domain OR !$key OR !$user) {
    //Something is missing so bail
    if ($verbose) {
      $msg = 'DRAPPS Shortlinks is not configured. Please go to admin/settings/drapps';
      return $msg;
    }
    else {
      return;
    }
  }

  //PHP Google Apps ShortLinks Implementation
  $slink = new ShortLink($domain, $key, $user);
  $r = clone $slink->pub($url);
  $status = $r->status;

  if ($status == 'ok') {
    return $r;
  }
  elseif ($verbose) {
    return $status;
  }
  else {
    return;
  }
}

This script uses a custom created class called SHortLink.php.

EDIT: This function is called in Drupal's node-news.tpl.php like this:

...

<?php print drapps_shortlinks_createlink($url, TRUE, FALSE); ?>

...

test.php

<?php

$path = "path/to/drupal"; //changed for security reasons

include_once($path . 'sites/all/modules/drapps_shortlinks/drapps_shortlinks.inc');

$url = 'http://www.google.com/';

print drapps_shortlinks_createlink($url, TRUE, FALSE);

?>

When I go to http://www.mydomain.com/test/test.php, the script works fine and I get an 'ok' response from google; a short link is created and it works fine. When I navigate to a news node, the script runs OK, but Google responds with a 403 (forbidden) error.

EDIT_1: THIS SCRIPT WORKS. So i think I can safely assume that the reson behind this has something to do with drupal rather than the script itself.

EDIT_2: I think the real question behind this is: What reasons could make a script behave differently when called from drupal? Any input will be appreciated: brainstorming, ideas, tips, troubleshooting methods, anything you think that might help, I will really appreciate it.

You really shouldn't use include_once, Instead you should use module_load_include.

After you've done this start putting in Debug code in your include file to make sure it's being loaded.

Also makes your your include file contains namespaces functions and no variable being used outside a function scope. To avoid any naming collisions that could happend.

Besides that, there really is not much help anyone can provide. A script will work the same way in Drupal as it would when being include in a regular php file.


How do I include a term's additional fields on node display? With Drupal 6 there was Taxonomy Image to do this, but with the field goodness of Drupal 7 we can just add an imagefield to a certain vocabulary. This works quite well to output stuff with views, but I can't seem to find a way to show up the additional field on the node display.

In my case I simply have a vocabulary called countries that has an additional imagefield to hold the country's flag. When viewing a node that has assigned a country term I need the flag of the country to show up instead of its name.

Regards,
Daniel

I've not played with semantic fields before, but I can tell you that configuring a term's display is the same as configuring a nodes display. The administration for a vocabularies display can be found at Structure --> Taxonomy --> VOCAB_NAME --> Manage Display or the path

admin/structure/taxonomy/VOCAB_NAME/display

Again, same as nodes you can configure the labeling & formatting options from this area. However, the location to configure a node's display is Structure --> Content Types --> YOUR_TYPE --> Manage Display

These settings are used for Drupal's native output. Using views can bypass these settings depending on the view (fields) or can work together (full, default, teaser).


What is the Context column for in String Overrides module? With Drupal 7 I have the String Overrides module and there's a coulmn called "Context." I was wondering what this is for?

I was thinking maybe I could type in something like 'user/' and the string replacement would occur only on 'user/' pages?

Currently, not much!

It appears to mostly be for D8.

http://drupal.org/node/1477568


Right URL rewrite after 404 redirect Is it possible to rewrite the url in a 404 redirect according to the page which is actually being displayed ?

For example, if the non-existent url "/fzenk" is requested, and you have configured the default 404 error page to be the front-page, the url in the address bar after the redirect should be front-page's.

I tried Global Redirect module but it didn't work. Is it possible to do the 404 redirect = URL-rewrite with another module or should we request a new feature ?

Update:

While it is possible to do it, it seems to be a bad idea to rewrite 404 pages url.

Thanks to Krister Andersson answer, I seem to have got it right.

function THEME_preprocess_page(&$variables, $hook) {
   $status = drupal_get_http_header("status");
   if($status == "404 Not Found") {
      // get the configured 404 error page url :
      $not_found_url = variable_get('site_404');
      unset($_GET['destination']);
      drupal_goto($not_found_url);
   }
}

It will rewrite the url according to the configured default 404 error page, it works with multilingual variable too.


Access list of view modes available for nodes In my code, I need to get a list of all the view modes defined for nodes.

In Drupal 7, it was available via entity_get_info(). What is the equivalent method for producing a list of available view modes in Drupal 8?

View modes are config entities, so an entity query would do the trick:

$view_modes = Drupal::entityQuery('entity_view_mode')
  ->condition('targetEntityType', 'node')
  ->execute();


Discount based on a field in product display node in Drupal Commerce? I want to create a pricing rule based on discount entered in a field in the product display node? Is it possible? I have been trying to do it but i can't see the discount field in the dataselector. I tried entity has field but there only line-item entity appears and no node entity?

You can do this, I have done so myself. It's been a lot easier to do this than when I needed to do this.

The thing is that in rules, in order to get the fields of an entity, to use it in Rules, you need to either add a condition that the field exists or add a condition that the entity is of type X.

I've attached the base setup that does this for the commerce kickstart install profile. You might be using a different product type, but it should be easy to change.

{ "rules_example_discount" : {
    "LABEL" : "Example discount",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_product_reference" ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "product" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:type" ],
          "value" : "product"
        }
      }
    ],
    "DO" : []
  }
}

Update:

Since you are saving the discount on the product display, you are making it more difficult for you. What you need to do, is from the line_item/product context to be able to figure out which product display the product comes from. The easiest way to do that would be to add a node reference field on the line item and then populate that with the product display node when adding the product to the cart. This should be doable with a custom submit handler added to the add to cart form with hook_form_alter. Then you need to tweak the rule accordingly and use the field from the node referenced on the line item instead of the product reference on the line item.


maxlength depending on nodetype (contenttype) i use one field in different content-types. for example in article, this field should be limited to 130 characters, but in gallery, the same field should be limited to 50 characters. The field is also used to generate the breadcrumb menu, so i can not simply add another field. so is it possible, to set different maxlength-values depending on the nodetype?

You could use hook_node_presave to set the maximum length of a fields value before the node is saved or inserted in the database.

For example, to force a field field_dummy for a node of type article to a maximum of 50 characters you could do like this:

function HOOK_node_presave($node){
  if($node->type == 'article'):
    // force the field to max 50 characters
    $node->field_dummy[$node->language][0]['value'] =
       substr($node->field_dummy[$node->language][0]['value'], 0, 50);
  endif;
}


Multilingual comments in Drupal 8 I set up an English/Arabic Drupal 8 website.
However, comments are misbehaving.
When a user enters a comment in the English version of the article, it appears in the Arabic version, and vice versa.
I went through all the different options I can think of, but I ended up with all comments being treated and displayed as Arabic.
I don't know what I'm missing, or what how I am supposed to configure it.

Shouldn't it respect languages out of the box?

Please, any help or documentation would be greatly useful. Thanx

At this moment in my team, we have identified 3 bugs around this, and to make this works you need to apply this 3 patches:

https://www.drupal.org/project/drupal/issues/2751269#comment-12559117

https://www.drupal.org/comment/12521645#comment-12521645

https://www.drupal.org/comment/12561153#comment-12561153


Programmatically save file into profile2 entity I'm trying to save a file into my Profile2 entity, I've taken the user through a multi-step form, I've saved all the data and at the point I want to input my data into my profile object, I have a variable which 'holds' the file object which has already been uploaded before this point.

However, I can't find out what code I need to run to tell my profile2 entity (in pseudo terms)

field_cover_letter = $file

I've tried opening up a profile object of an existing account to see what it saves it as, which it seems to just be an array of the file object as well, but I tried typecasting my object to an array and using those values, but it throws a PDO. There must be a simple command to add a file to the profile2 object?

Cheers

If you are working with an unmanaged file, the following three-step process should do the trick:

Move the file (if necessary) to its final home defined by the file field on the entity.
Create a file object (see file_save_data() for some hints on how to do this) and then save it using file_save().  This will turn the file from unmanaged to managed.
Add the file reference to the file field.  You may also want to add an entry in the file usage table by calling file_usage_add().  Here is a code snippet for adding a file object to a file field on a node.

$node->file_field_name[LANGUAGE_NONE][0] = array(
  'fid' => $saved_file_object->fid,
  'display' => 1,
  'description' => '',
);

This assumes the file field accepts only one entry (index 0).


Trying to create a table with an uid field that auto-increments and is the primary key, but keep getting an error I'm working on an .install file for my module in Drupal 7.  I want to create two tables, one called tls_connect_floormap_images and one called tls_connect_floormap_coords.  I'm not having any trouble with the _images table.  But when I try to make the uid field of the _coords table a unique key that auto-increments, I get an error that says:

  Fatal error: Unsupported operand types in C:\Program Files
  (x86)\Zend\Apache2\htdocs\TLSConnect3App\includes\database\mysql\schema.inc
  on line 85

I get this error on install, When I Save Configuration I get the WSOD with the error message.  When I put in the url for /admin/modules there is an error that says Notice: Undefined variable: schema in floormap_install() (line 37 of C:\Program Files (x86)\Zend\Apache2\htdocs\TLSConnect3App\sites\all\modules\custom\TLSConnectPackage\floormap\floormap.install).  I see that the module is installed though, and when I check for my tables in phpMyAdmin they are there, uid auto_increments but is not a unique or primary key.

Here is my code:

function floormap_schema(){
    $schema['floormap_images'] = array (
            'description'   => 'Floor map images.',
            'fields'        => array (
                'image'     => array('type'     => 'blob',      'not null'  => TRUE,),
                'name'      => array( 'type'        => 'varchar',       'length'        => 30,      'not null'  => TRUE,),
                'active'    => array('type'     => 'int',           'unsigned'  => TRUE,    'not null'  => TRUE,),
            ),
            'unique keys'   => array('name' => array('name'),
            ),
        );
    $schema['floormap_coords'] = array (
        'description'   => 'Floor map images.',
        'fields'        => array (
            'uid'       => array( 'type'    => 'serial',    'unsigned'  => TRUE,    'not null'  => TRUE,),
            'floormap'  => array( 'type'    => 'text',  'not null'  => TRUE,),
            'item_type' => array( 'type'    => 'text',  'not null'  => TRUE,),
            'pos_a_x'   => array( 'type'    => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_a_y'   => array( 'type'    => 'int',       'unsiged'   => TRUE,    'not null'  => TRUE,),
            'pos_b_x'   => array( 'type'    => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_b_y'   => array( 'type'    => 'int',       'unsiged'   => TRUE,    'not null'  => TRUE,),
            'pos_c_x'   => array( 'type'    => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_c_y'   => array( 'type'    => 'int',       'unsiged'   => TRUE,'   not null'   => TRUE,),
            'pos_d_x'   => array('type' => 'int',       'unsigned'  => TRUE,    'not null'  => TRUE,),
            'pos_d_y'   => array('type' => 'int',       'unsiged'   => TRUE,    'not null'  => TRUE,),
        ),
        'unique keys'   => array('uid' => array('uid'),),
    );
    return $schema;
}
function floormap_install() {

    //Create table to store floor map images if it doesn't already exist
    if(!db_table_exists('tls_connect_floormap_images')){
        db_create_table('tls_connect_floormap_images',$schema['floormap_images']);
    }
    //Create table to store floor map coordinates if it doesn't already exist
    if(!db_table_exists('tls_connect_floormap_coords')){
        db_create_table('tls_connect_floormap_coords',$schema['floormap_coords']);
    }
}

I only get the error when I have

'unique keys' => array('uid' => array('uid'),),

in the $schema['floormap_coords'] array.  It works in the ['floormap_images'] array though, not sure why its not working for coords.  The only difference is that the 'uid' field is serial datatype and name is varchar.

First of all please provide which version of drupal you are using ?

If you are using d7 than you don't need to check in hook_install is table exists ?

Just provide hook_schema in your module file and it will create your tables.
For floormap_coords make uid as primary ( primary key itself unique)
'primary key' => array('uid'),


Content type permission to specific users How do I set content permission so that specific content types become visible/usable to the admin user only, while other content types may be visible by other user roles?

After I added new content types, I checked the rebuild permissions.

Content access is working fine but the problem seems to be the fact that the enw content types aren't made visible / accessible to the other roles...

The core's built-in support for node access control is rather course, and to control a specific role's access to view a page, it is not enough to go to admin/people/permissions to set permissions, since there is only a global setting for "View published content" that apply to all published content.

However. to give the permission to Create new content (node/add), there is no need for an extra module, since all other permissions, i.e. Create, Edit, Delete, is managed by the Drupal core and there are per-role settings in the built-in permissions interface.
First, just to make sure content is visible, navigate to admin/people/permissions and make sure you have the permission View published content checked for the authenticated user role.

Then, just below it, locate the check boxes to "Create new content" for the content types you want users beyond the administrators to be able to create, and check those for the roles you want to have this permission granted (ditto with the Edit and Delete permissions).

Also make sure new content is Published. If content is not Published, the only user that has access to it us the super admin user.

To set the default to Published for a new content type, navigate to Administration → Structure → Content types. Then click on the edit link for the type you want to configure- Locate the "Publishing option" tab. and make sure that there is a tick mark for "Published" under "Default options".

If you need fine grained access control beyond this, you need to install a node access control module.

The module I recommend for this is Content Access.  It let you control access per content type and user role.

To set the per content access settings, navigate to Administration → Structure → Content types. Then click on the edit link for the type you want to manage, and then on the Access control tab. This takes you to the control panel for role based access control settings. The screen dump below  shown how do set this for the built-in content type "Basic page":

After setting the permissions the way you want, click "Submit".

There is a nice tutorial about installing and configuring the Content Access module on YouTube. (Thanks to @shrish for bringing this to my attention.)


Whats the correct way to programmatically include unpublished content in entity reference fields? (without views) I have a node reference field whose options get reduced to those nodes in which the current user is referenced:

function mymodule_process_form_field_project_ref(&$field) {
  $field['#required'] = true;
  $field['widget']['#required'] = true;
  $options = $field['widget']['#options'];

  $project_nids = mymodule_user_get_referenced_projects();

  foreach ($options as $key => $label) {
    if (is_numeric($key)) {
      if (!in_array($key, $project_nids)) {
        unset($options[$key]);
      }
    }
  }

  $field['widget']['#options'] = $options;

}

The problem is, in $field['widget']['#options'] unpublished nodes are being removed in the first place. How to keep those? Do I have to define an own ServiceProviderBase class using the alter function?

You will need to create a custom EntityReferenceSelection plugin.
Which should probably extend the NodeSelection plugin in core.


How to get the Bootstrap 3 Datepicker to redirect to an URL when a date is picked? I use the Drupal bridge module Bootstrap Date & Time picker with its associated JavaScript libraries.  I am trying to create a Drupal form where the user clicks on a particular month, and then the user is redirected to a page showing all the events happening that month.

This is how I build the form:

function rbg_date_picker($form, &$form_state) {
  $form['date'] = array(
    '#type' => 'date_text',
    '#bdtpicker' => TRUE,
    '#date_format' => 'Y-m',
    '#datepicker_chain' => array(
      'my_interval_end[date]' => 'next',
     ),
     '#datepicker_options' => array(
       'viewMode' => 'months',
     ),
  );
  return $form;
}

The form show up and when the user clicks on a month in the widget's grid, the date field gets filled in with the year and month.  So far, so good.

However, at this point, I want the JavaScript to redirect to an URL so that I can create an ordinary page with the relevant information.  For example, if the user picked August 2017, the Javacript should redirect to "http://example.org/2017-08".

Maybe there is already support for this functionality in the Drupal bridge module (and I haven't spotted it), or maybe I need to add a small JavaScript snipped to make this work (confession: I suck at JavaScript).  Any help will be appreciated.

(PS: I know that if I add a submit button to the form, I can pick up the year and month in the submit handler.  However, I think the UX would be better if the user can just click on the month, without having to explictly hit "Submit" afterwards.)

You can redirect using ajax forms and ctools, first of all you will need to add #ajax property to your form field so the code will be :

function rbg_date_picker($form, &$form_state) {
  $form['date'] = array(
    '#type' => 'date_text',
    '#bdtpicker' => TRUE,
    '#date_format' => 'Y-m',
    '#datepicker_chain' => array(
      'my_interval_end[date]' => 'next',
    ),
    '#datepicker_options' => array(
      'viewMode' => 'months',
    ),
    '#ajax' => array(
      'callback' => 'SOME_FUNCTION_NAME',
    ),
  );
  return $form;
}

The rest is easy, in callback function you will need to have some code like below :

function SOME_FUNCTION_NAME($form,$form_state) {
  $time = $form_state['values']['date']; // maybe need ['und'][0]['value']
  //Some code to fetch desired values from date like month or year
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  //Some code to fetch desired values from form and compute 'some-valid-url'.
  $commands[] = ctools_ajax_command_redirect('some-valid-url');
  print ajax_render($commands);
  exit;
}


Restrict admin/content view by organic group membership I'm using D7 with organic groups. Have 7 groups each with their own content.  Anonymous users can view all content from any group.  Group admins can only edit the content from their own group.

When a group admin goes to admin/content they see all content items, though they can only edit their own.  Is there a way to restrict the output on admin/content so the group admin can only see their content on this page?  This would make it easier for them to review and manage their content as they would not need to page through all of the site content.

Thank you

You can add a module that implements hook_query_alter like:

function gestionsesion_query_alter(QueryAlterableInterface $query) {
global $user;
if (current_path() === 'admin/content'){
    if ($query->hasTag('tablesort')) {
        $query->condition('n.language', $user->language );
    }
    }
}

Here we filter by user language but you could do it by role...


How do I add a region to the Color module? I have a menu I would like to be able to style with the Color module.  I have found many examples for the Drupal 7 Color module and they have led me to believe that if I just add a line to the 'fields' array in the color.inc file in my theme I will be able to add more regions.

Below is my 'fields' array.  I copied an existing file as a guide and simply added my primary menu

'fields' => array(
  'top' => t('Header background top'),
  'bottom' => t('Header background bottom'),
  'primarymenu' => t('Primary navigation menu'),
  'bg' => t('Main background'),
  'sidebar' => t('Sidebar background'),
  'sidebarborders' => t('Sidebar borders'),
  'footer' => t('Footer background'),
  'titleslogan' => t('Title and slogan'),
  'text' => t('Text color'),
  'link' => t('Link color'),
),

I just added the 'primarymenu' field to the standard bartik array

I realize there is more to do to connect this field to something so it will actually change colors but everything I can find is for D7 and requires altering php templates.

Why is my field not showing up in the appearance settings menu and how do I connect it to change the color of my menu?

Edited To add the schemes array

'schemes' => array(
'default' => array(
  'title' => t('Blue Lagoon (default)'),
  'colors' => array(
    'top' => '#055a8e',
    'bottom' => '#1d84c3',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#f6f6f2',
    'sidebarborders' => '#f9f9f9',
    'footer' => '#292929',
    'titleslogan' => '#fffeff',
    'text' => '#3b3b3b',
    'link' => '#0071B3',
  ),
),
'firehouse' => array(
  'title' => t('Firehouse'),
  'colors' => array(
    'top' => '#cd2d2d',
    'bottom' => '#d64e4e',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#f1f4f0',
    'sidebarborders' => '#ededed',
    'footer' => '#1f1d1c',
    'titleslogan' => '#fffeff',
    'text' => '#888888',
    'link' => '#d6121f',
  ),
),
'ice' => array(
  'title' => t('Ice'),
  'colors' => array(
    'top' => '#d0d0d0',
    'bottom' => '#c2c4c5',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#ffffff',
    'sidebarborders' => '#cccccc',
    'footer' => '#016b83',
    'titleslogan' => '#000000',
    'text' => '#4a4a4a',
    'link' => '#019dbf',
  ),
),
'plum' => array(
  'title' => t('Plum'),
  'colors' => array(
    'top' => '#4c1c58',
    'bottom' => '#593662',
            'primarymenu' => '#ffffff',
    'bg' => '#fffdf7',
    'sidebar' => '#edede7',
    'sidebarborders' => '#e7e7e7',
    'footer' => '#2c2c28',
    'titleslogan' => '#ffffff',
    'text' => '#301313',
    'link' => '#9d408d',
  ),
),
'slate' => array(
  'title' => t('Slate'),
  'colors' => array(
    'top' => '#4a4a4a',
    'bottom' => '#4e4e4e',
            'primarymenu' => '#ffffff',
    'bg' => '#ffffff',
    'sidebar' => '#ffffff',
    'sidebarborders' => '#d0d0d0',
    'footer' => '#161617',
    'titleslogan' => '#ffffff',
    'text' => '#3b3b3b',
    'link' => '#0073b6',
  ),
),

),

You need to also provide a color for the field you added. In fact, the function that adds the form elements for the color settings contains the following code. (See color_scheme_form().)

 foreach ($palette as $name => $value) {
    if (isset($names[$name])) {
      $form['palette'][$name] = array(
        '#type' => 'textfield',
        '#title' => $names[$name],
        '#value_callback' => 'color_palette_color_value',
        '#default_value' => $value,
        '#size' => 8,
        '#attributes' => array('dir' => LanguageInterface::DIRECTION_LTR),
      );
    }
  }

Without a color value for your field, $form['palette'][$name] will not be added, and it will not be possible to change the color for it.

In fact, the Bartik theme uses the following values, for its default palette.

$info['schemes']['default'] = array(
  'title' => t('Blue Lagoon (default)'),
  'colors' => array(
    'top' => '#055a8e',
    'bottom' => '#1d84c3',
    'bg' => '#ffffff',
    'sidebar' => '#f6f6f2',
    'sidebarborders' => '#f9f9f9',
    'footer' => '#292929',
    'titleslogan' => '#fffeff',
    'text' => '#3b3b3b',
    'link' => '#0071B3',
  ),
);

The keys you find in (for example) $info['schemes']['default']['colors'] are the same keys you find in $info['fields'].


Workbench Moderation and Custom Field Issue I have another "interesting" problem using Workbench Moderation. I'm using Workbench for workflow, along with Workbench Access, Workbench Moderation (7.x-1.3) and Workbench Moderation Notes on a new Drupal 7 site.

I have created a custom Approvers field on my content type that editors will use to select which approver should receive the notification email. This is a list field where the approver name is displayed for selection (the label) and the associated value (key) is the email address of the approver. The latter is to be used in a rule to send the email to the correct address. I have written some PHP to extract the value from the selected item in this Approvers list field:

<?php

$node_id = arg(1);
$node = node_load($node_id);
$fieldname='field_approvers';
 $items = field_get_items('node', $node, $fieldname);
if($items)
{
$key = $items[0]['value'];
echo "key = ". $key;
}
else
{
echo $node_id;
}
?>

Note that this is inserted in a block for testing purposes and I am not very experienced in PHP (or Drupal for that matter!).

While testing, I have discovered that before publishing the node, all works well and I can extract the correct email address. However, similar to my issue yesterday (Workbench Moderation - Issues with New Drafts of Published Nodes), once a node is published and set back to draft, things stop working properly. The published value of the list field is always returned, even when the list field itself shows the correct new approver. So, if I set back to draft and change the approver in the list field, the PHP code will always return the value from the published version of the node. I have debugged the node and checked the database and the web and I can't figure out how to get the Approvers list field value from the current revision.

Due to the underwhelming response, I had to figure it out for myself :-). To save any other newbie hours of angst, here is the solution:

As predicted, the answer was simple, but finding it was the problem! I eventually found how to load the latest revision by looking at the workbench moderation module source code. If you add the line under the $node variable assignation below, it will return the value on the current revision:

<?php

$node_id = arg(1);
$node = node_load($node_id);
$node = workbench_moderation_node_current_load($node); //NEW LINE!
$fieldname='field_approvers';
$items = field_get_items('node', $node, $fieldname);
if($items)
{
 $key = $items[0]['value'];
 echo "key = ". $key;
}
else
{
 echo $node_id;
}
?>

Hope this helps someone.


Redirect a user after the node has been saved I'm looking for a hook to use after a node of a specific content type is created or saved, to perform a redirection to a specific page.

Form redirect after node save.  This blog discusses the usually way of redirecting a form, the problem with node forms, and how to solve them for Drupal 6.   I believe it should also work for Drupal 7


function defined in module not global? I created a module in order to define a few functions that I would like to use from a workflow rule. The workflow rule is triggered by an event and runs a php code snippet. The php snippet that it runs is simply a function call to the function that I defined in my module.

However each time my rule executes the code, I see an error in the httpd error_log - call to undefined function. I ran the module through php lint, and I enabled it, flushed caches, and even restarted httpd for good measure. Still I get the error "PHP Fatal error:  Call to undefined function" in the log.

I'm new to modules and Drupal programming so I must be missing something, but I thought functions defined in drupal modules (modulename.module) are global?

BTW I followed the instructions here.

Edit1: I defined my functions in module.module (not .inc...)

I usually define my modules functions in a separate .inc file, and when i need them somewhere (usually sub-modules) i first include them with module_load_include( file-extension, module-name, file-path)

You can add the module_load_include() call at top of your snippet, or, if you need those function in many other places in your module hook_init() and make it avaible to every page.


How to allow user content on the front page? I am just struggling with my first site and a handful of friends helping to beta test.

Whenever admin posts there is an option to post to front page, but not for others.

I am not sure if I want the users to even see that option  -it might confuse the non-techy - but they do want to see their recent stuff on the front page.

How can I do that?

For the content type you want to be promoted you need to set the options on that content type to automatically be promoted to front page.

In Drupal7 find this under admin/structure/types pick one of the content types and choose "edit".  Under "Publishing Options" choose "Promoted to front page".


how to redirect to another site but still have same url Is it possible to have an entire path from a drupal 7 site , eg. /externalpaths  which will go to an outside application, yet still have the same domain name in the url, so that it looks like you have not left the drupal site ?

You should be able to do that relatively easily with full HTML mode using an <iframe src='desiredurl'></iframe>. You will most likely want to do some custom styling/template editing to make it look good.

Whether that is a good soluton for you depends a bit on how you want it to look etc. Do note taht security restrictions can break it - and make custom scripting/styling problematic as well inside the iframe. I'd suggest reading the Mozilla Dev Network's iframe page.


How-to display a product variation field twice (or more)? I want simply display a field of a product variation type (commerce) two times with different render settings.

I have tried with a dynamic field (display_suite) but it not working... I would prefer to know a programmatically solution to accomplish this task and I want use the (Drupal core) Display Manager for designate my layout (not a template file) :)

Note: This product field do automatically refresh (ajax) like other when a different product variation is selected.

See this related "issue": https://www.drupal.org/node/1494192#comment-7031370

You should be able to use template_preprocess_node() to duplicate a field.

I've not run this code and just written it from memory but something like this should suffice:

function template_preprocess_node(&$variables) {

  // Check this is the node type for commerce products
  if($variables['node']['#type'] == 'product') {

    // Copy the existing field to a new item
    $variables['content']['YOUR_FIELD_2'] = $variables['content']['YOUR_FIELD'];

    // Now make any changes to how you want to render the duplicate field
  }

}


Auto fill billing information in cc avenue payment I am using Commerce Cc Avenue as a payment gateway for my eCommerce site. During checkout step user enter his billing information. In the next step it verifies his/her order and redirects to Cc avenue payment gateway, there it asks user billing address again. I want to auto fill the user billing address which he/she enters in previous step. Is that possible to do?

Finally found the answer with help of this issue queue https://www.drupal.org/node/2310505

In commerce_ccavenue.module added few lines inside commerce_ccavenue_redirect_form($form, &$form_state, $order, $payment_method)

$billing_address = $wrapper->commerce_customer_billing->commerce_customer_address->value();
  $order_data = array(
    'merchant_id' => $payment_method['settings']['merchant_id'],
    'amount' => $wrapper->commerce_order_total->amount->value() / 100,
    'order_id' => $order->order_id,
    'cancel_url' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'redirect_url' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'working_key' => $payment_method['settings']['working_key'],
    'access_code' => $payment_method['settings']['access_code'],
    'language' => 'EN',
    'currency' => $currency_code,
    'billing_name' => $billing_address['name_line'],
    'billing_address' => $billing_address['thoroughfare']. ' ' . $billing_address['premise'] . ' ' . $billing_address['sub_premise'],
    'billing_zip' => $billing_address['postal_code'],
    'billing_city' => $billing_address['locality'],
    'billing_state' => $billing_address['administrative_area'],
    'billing_country' => 'India',
  );

These lines are missing inside commerce_ccavenue_redirect_form($form, &$form_state, $order, $payment_method). Works fine after adding those lines.


Is there a module that creates an input filter to convert text to the ASCII character-set? I have a textarea on a content type that needs to be converted ASCII character-set. Is there an available module that adds a input filter for this? This field needs to be fed to another platform with this formatting.

If you have the Transliteration module installed, you can create your own filter.

Go to /admin/config/content/formats and click on Add text format at the top. One of the options is Convert all characters to US-ASCII. Set the roles you want to allow use of the format and save.


Want to filter result by using two filters "event start day" and "event start time" in one view for showing upcomming events? I want to show a view of upcoming events. I have added event start day filter to my view, it's showing today's events as well as upcoming events.

This functionality is working fine but problem is that  it's showing all  events of today not on the basis of time but it's showing morning's event whose time is passed away. It must only filter the values on the basis of current time and coming time(current day and upcoming days).

I want to add one more filter event start time filter. How to add two filters(event start date and event start time) in one view?

You can try this Views between dates filter module. Or you can create filter by selecting event date and time from the content.
Views Between Dates Filter:

This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
Creating this functionality with standard Date filters requires two filters: start date less than or equal (<=) to the supplied date and end date greater than or equal (>=) to the supplied date. The problem is two filters means users must enter a date range, when technically selecting "September" is a range: September 1st to the 30th.
It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.


Example of hook_file_download How do I restrict the access to certain files based on their content type? I have the download section for registered users, and I want to prevent them to post links somewhere outside my site.

Is implementing hook_file_download() sufficient?

I tried this code and it's enough for my purpose, but the documentation of hook_file_download() doesn't help much.

function customize_file_download($uri) {
  global $user;
  if (!array_intersect(array('administrator','editor','expert','verified'), array_values($user->roles))) {
    return −1;
   }
}

There is a couple of hooks in drupal 7 to restrict access to files.

One thing you have to realized is that these access hooks are only going to work if your download method is private, and the files are in your private path.

As you mention in your question there is a hook_file_download that should work in your case (assuming the file is private). This is not going to work if the file, someone is linking to, is somewhere public such as sites/default/files/abc123.txt.

If you happened to be uploading these private files in a field, then hook_file_download_access would seem more appropriate. This will give you the field that the file belongs to and also the related entity that this field is being used on so you should be able to do more complicated logic such as calling the the appropriate access function to check if the user has access to the field instead of having a hard-coded list in the code.


How to add custom CSS to each page All,

I complete Drupal 7 newbie here.

I am tackling the themeing of our website (using Adaptive/ Sky theme). Now previously I would have loaded up all the CSS files in the sky.info file but then read that all the stylesheets in theme info file get loaded on every page.

What I want is to load each unique page's CSS on that page only. Example being the 'Home Page' would have its own unique CSS, same for 'About Us', 'Contact Us' pages etc.

As per my research, I am meant to use 'drupal_add_css' function in the template.php file, however, I dont know PHP & have no idea how to add the if condition that each page's alias should dictate which css file is preprocessed & loaded.

Any guidance would be great.

An easier way to address multiple CSS loads, is to cache and compress the CSS. You can do so by going to /admin/config/development/performance and selecting "Aggregate and compress CSS files"

But if you must have them load on separate pages I'd recommend doing it the Drupal way; separating them by content types or blocks, forms, not by URI. The simplest way to do it, is to use Theme Hooks.

For instance, to include a yourthemedirecotry/css/MYTYPE.css for content type MYTYPE;

Copy /modules/node/node.tpl.php into your theme directory and rename it to node--mytype.tpl.php.
Insert <?php drupal_add_css(path_to_theme() . '/css/mytype.css', array ('group' => CSS_THEME)); ?>
Don't forget to flush cache.

From now on, nodes with content type MYTYPE will include a yourtheme/css/mytype.css.

Likewise, you can insert CSS into specific blocks, fields, page. For more options, see Theme Hooks and drupal_add_css.


How to intetrupt a form submission in drupal I have made a custom module where I create one page. In that page I load the existing form for creating a new content and also add a password field. In my loaded form I have an email field. I want before submitting the form to check if there exists a user with the username the value found in the email field and the password offered by the password field. Here I have 3 scenarios:

if the user does not exist I take the email and password and create an account then create the content
if the user exists and the password is correct , I create the content
if the user exists but the password is incorrect I stop the form submission

My problem is I don't know how to stop the form submission ( I am refering to scenario number 3). Any suggestions are most aprerciated

Here are the callback for the page function:

function add_new_article_simple_page() {
  module_load_include('inc', 'node', 'node.pages');
  $node_form = new stdClass;
  $node_form->type = 'announcement';
  $node_form->language = LANGUAGE_NONE;
  $form = drupal_get_form('announcement_node_form', $node_form);
  return $form;
}

the alter function to insert the password field :

function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form')
  {
    $form['#after_build'][] = 'add_new_article_after_build';
    $form['account_password'] = array(
        '#title' => 'Parola',
        '#type' => 'password',
        '#required' => TRUE,
    );
    $form['#submit'][] = 'add_new_article_form_submit';

    return $form;
  }
}

and the form submit function

function add_new_article_form_submit($form, &$form_state){
  $email=$form_state['values']['field_email']['und'][0]['value'];
  $password=$form_state['values']['account_password'];
  //check if the email even exists
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE name = '".$email."';")->fetchField())
  //create the new account
  {
    $edit = array(
        'name' => $email,
        'pass' => $password,
        'mail' => $email,
        'init' => $email,
        'roles' => array('4' => 'standard user'),
        'status' => 0,
        'access' => REQUEST_TIME,
    );
    $loc_var=user_save(drupal_anonymous_user(), $edit);
    $GLOBALS['new_user']=$loc_var->uid;
  }
  else
  {
    //check if username + password are valid combination
    if($uid = user_authenticate($email,$password))
        //log in user after account creation
    else
        //this is where I want to interrupt the submission of the form
        form_set_error('account_password', 'Parola nu este buna pentru acest email.');
  }
}

When i test the 3rd scenario: The content is created , the page jumps to that content page and that is where the error message appears

I have followed a suggestion to try hook_form_alter, so I wrote a simple validation function which should always give an error. The problem is that the content is still submited and saved. It doesn't seem to even call hook_form_validate .. Here is the function :

function add_new_article_form_validate($form, &$form_state)
{
    $email=$form_state['values']['field_email']['und'][0]['value'];
    $password=$form_state['values']['account_password'];
    form_set_error('account_password',t('The form is being validated.'.$email.' and '.$password));
}

Thank you,
Cristi

Try adding the validate function as you have added the submit function:

function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form')
  {
    $form['#after_build'][] = 'add_new_article_after_build';
    $form['account_password'] = array(
        '#title' => 'Parola',
        '#type' => 'password',
        '#required' => TRUE,
    );

    $form["#validate"][] = 'add_new_article_form_validate';
    $form['#submit'][] = 'add_new_article_form_submit';

    return $form;
  }
}


How to create links which pass arguments to a page? I am making a website which displays table from a database. For every row of the table I want to provide a link(or button) which will be placed in the last column and will redirect to a page displaying records from another table associated with that row. Is there a way to create such link which would pass an argument (row id) to another page so it could display apropriate records?
Thanks

You can use l() function, Like
Suppose You are showing some data in table format as you mention in your question and using some query you get some data from databse in $result variable,

$header = array(t('Approved By'), t('Role'), t('Points'), t('View
More'));
foreach ($result as $row) {
    $rows[] = array($row['user_name'], $row['user_role'], $row['date'], l(t('View'), 'node/' . $row['row_id']));
}
return theme('table', array('header' => $header, 'rows' => $rows));

Now above code create a page showing table

Approved By    Role                    Points    View More
Eve            content writer          94        View    -> url: my-page/1

John           content manager         80        View    -> url: my-page/2

Adam           manager                 67        View    -> url: my-page/3

Jill           admin                   50        View    -> url: my-page/4

function my_module_menu() {
    $item['my-page/%'] = array(
        'title' => 'my page',
        'page_callback' => array()
        'page callback' => 'my_page_callback',
        'page arguments' => array(1),
        'access arguments' => array('access content overview')
    );
return $item; }
function my_page_callback($row_id) {
    // Get some data from database using $row_id
    // show in table
}


Call to undefined function drupal_execute() In a drupal8 module install file I have used drupal_execute() function like as follows

drupal_execute("content_copy_import_form", $form_state)

But this resulted in an error

  Call to undefined function drupal_execute().

Any solution?

drupal_execute hasn't existed since Drupal 6.

In Drupal 8 you can submit a form programatically like this augmented example from ProgrammaticTest::submitForm:

$values = ['foo' => 'bar'];

// Programmatically submit the given values.
$form_state = (new FormState())->setValues($values);
\Drupal::formBuilder()->submitForm('\Drupal\form_test\Form\FormTestProgrammaticForm', $form_state);


How can I add to the class name of a form element? I'm trying to add an additional class to a form element using the following code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function grant_opportunity_form_grant_opportunity_node_form_alter(&$form, &$form_state, $form_id) {

    $form['grant_opportunity_end_date']['#attributes']['class'][] = 'datepicker';

}

But the additional class is not being added. Am I doing this incorrectly? This is a very simple thing I'm trying to do, so I'd prefer not to go through the trouble of overriding the theme, or anything more involved like that.

EDIT: To be clear, a class is being added to the parent div of this element, but not the element itself.

I think it needs to be an array.

Try this:

$form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));

You can also call it directly from hook_form_alter().
For example in your themes template.php you could add:

function YOURTHEME_form_alter(&$form, $form_state, $form_id)   {
  if($form_id == 'YOUR_FORM_ID') {
    $form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));
  }
  // this displays some general info so you can check
  drupal_set_message("Form ID is : " . $form_id);
  drupal_set_message(dprint_r($form, TRUE));
}


Testing the value of Fields stored on Taxonomy Terms I have a field (called Division) attached to a node. I want to print out a link (called Switch) on page.tpl.php that varies according to the value of this (node-based) field.

I can successfully do this with the following code:

In template.php

function elite_field_division_helper(&$variables) {
  if ($node = $variables['node']) {
    $field_division = field_get_items('node', $node, 'field_division');
    if ($field_division[0]['tid'] == 1) {
      $variables['switch_site'] = 'Visit Our Business Website';
    }
    else if ($field_division[0]['tid'] == 2) {
         $variables['switch_site'] = 'Visit Our At Home Website';
    }
  }

}

In page.tpl.php

<?php if (!empty($switch_site)):?>
  <?php print $switch_site; ?>
<?php endif; ?>

My question is: How can I get this code to work with fields that are attached to TAXONOMY PAGES? (As Drupal 7 allows taxonomy pages to have fields).

Panels is very good for overriding Taxonomy pages. You can have different page and layout variants per vocabulary, user, theme, site etc. You can then include your code in a custom panel pane for taxonomy pages, together with whatever layout or views necessary, or write your own CTools content type for Panels.


Drush SSH Port 22 Error I've been trying for quite some time now to get my drush to play nicely with my Drupal configuration and I'm having some problems. I'm attempting to perform cc all and uli on my Drupal directory and I keep getting the following error:

ssh: connect to host site.dev port 22: Operation timed out

The command I'm running is "drush @site.dev cc all" and "drush @site.dev uli"

Whenever I run uli I get a slightly longer version of the same error:

The external command could not be executed due to an application     [error]
error.
Illegal string offset 'site' backend.inc:1030                        [warning]
The command could not be executed successfully (returned: ssh:       [error]
connect to host site.dev port 22: Operation timed out
, code: 255)
current() expects parameter 1 to be array, null given                [warning]
user.drush.inc:415
parse_url() expects parameter 1 to be string, array given            [warning]
exec.inc:427
 does not appear to be a resolvable hostname or IP, not starting     [warning]
browser. You may need to use the --uri option in your command or site
alias to indicate the correct URL of this site.

I'm not really sure where to start with getting this to work. I've poked around in my Vagrant configuration and I'm able to SSH on port 22, so I don't really know where else to look to correct this error.

This is what my alias configuration looks like:

Vagrant.configure("2") do |config|
  mc_settings = {
    :domain => 'site.dev',
    :docroot => '/home/vagrant/docroot',
    :host_docroot => '../docroot',
    :database_name => 'site_dev',
    :vbox_name => 'site_dev'
  }

It's really hard to answer specifically, since it really depends on how you have set your vagrant up.

Long story short

You need to setup your drush alias so that it's using SSH settings to access your vagrant box. The issue is probably that your vagrant box doesn't expect connections on port 22 or that you haven't setup the correct IP/domain for SSH connection in your alias.

If you want to use Vagrant for Drupal development I can recommend parrot. It has all you want for Drupal developetment, uses puppet, which makes it pretty easy to change PHP versions etc, and has Varnish, Solr etc.

If you are using parrot you should be able to access the Vagrant box by doing.

ssh vagrant@site.dev

Assuming that your site is located on the site.dev url.


How do I mimic Pathauto transliterated output for an alias in my custom PHP code? When writing my custom function I need to manually append node name to a taxonomy term link. To get the taxonomy term part done I use:

  $link_uri = taxonomy_term_uri($term);
  $path_alias = drupal_get_path_alias($link_uri['path']);

This works ok, now - I want to append node name ("/" . $node_name), but instead of raw string, I want the Pathauto transliterated output, as set in the URL alias configuration, for that node context.

What function should I use to mimic that output? I looked at hook_pathauto_alias_alter(&$alias, array $context) but I'm not sure that's what I need.

If you want to filter your string the way pathauto does it, you can use pathauto_cleanstring():

module_load_include('inc', 'pathauto', 'pathauto');
$node_title .= pathauto_cleanstring($node->title);