Jquery popup stops the ajax in the form fields I have created a .js script that creates a popup box next when a button is clicked. This pop shows a lost of the different content types you can add from that popup. When you click on one of those links it will load the form elements through AJAX. That is all working great but there is a major problem.

The AJAX fields within the form that is loaded onto the the popup does not work itself, I can enter in some text but no AJAX is performed. The field type of the that field is an entity reference field.

Can anyone help me on this one please? Thank you in advance!

Maybe not the answer you're looking for, but things would probably work if you load the form page within a iframe. I've used this approach successfully with forms that have AJAX fields. In D7 the admin overlay is also built using iframes.


Remove password reset fields on user profile Since we're only permitting logging in via the Drupal Admin and LDAP.

How might I turn off or hide these fields in the User's Edit Account (user/xx/edit) tab?

To hide the password fields on the user edit form, put this code in your custom module, which implements hook_form_FORM_ID_alter():

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  hide($form['account']['pass']);
}

You may also want to prevent users from going to user/password page and change their passwords on that page:

function YOURMODULE_menu_alter(&$items) {
  $items['user/password']['access callback'] = 'user_access';
  $items['user/password']['access arguments'] = array('administer users');
}

One more hint, if you want to remove the links on the user login block:

function YOURMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['links'] = '';
}


How to add a button "Add More" with ajax for adding multiple fields? I want to add a button "Add More" with ajax for adding multiple fields
I have writed this code, I don't understand why when I click to "add more" nothing work, there is an solution?

this is my code:

function produits_add($form, &$form_submit){

        if(!isset($form_state['num_names'])){
            $form_state['num_names']=1;
        }

        // Create wrapper for ajax
        $form['#prefix'] = '
';
        $form['#suffix'] = '
';

        for ($i = 0; $i < $form_state['num_names']; $i++) {

            $form['name_' . $i] = array(
                '#type' => 'textfield',
                '#title' => t('Name')

            );
        }

        $form['add_button']= array(
            '#type' => 'button',
            '#value'=> 'Add more',
            '#ajax' => array(
                'callback' => 'ajax_add_col',
                'method' => 'replace',
                'effect' => 'fade',
                'wrapper' => 'form-wrapper',
            ),
        );

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

        return $form;
    }

    function ajax_add_col($form, &$form_state){

        $form_state['num_names']++;

        // rebuild whole form with new values
        $form_state['rebuild'] = true;
    }

function produits_add_submit($form, &$form_state){

// Some code
}

In your form function, group the textfields under a key, you can define your own key. I use group here.

// Create wrapper for ajax
$form['group']['#prefix'] = '
';
$form['group']['#suffix'] = '
';

for ($i = 0; $i < $form_state['num_names']; $i++) {

  $form['group']['name_' . $i] = array(
    '#type' => 'textfield',
    '#title' => t('Name')
  );
}

In your ajax callback, return part of the form.

function ajax_add_col($form, &$form_state){

  $form_state['num_names']++;

  // rebuild whole form with new values
  $form_state['rebuild'] = true;

  return $form['group'];
}


How to show thumbnail preview in node display for uploaded video in file field I am using a file field and media module in a custom content type to upload video files. The videos play fine.  The preview image for each video is a gray box.
How can I display a preview image or thumbnail for each video in place of the gray box in the node display?

Update: the preview image does not have to be auto-generated from the video; I would be OK with adding an field for an image to upload along with the video.

Go to your content type >> MANAGE DISPLAY settings and set FORMAT as Rendered file and view mode: perview


Thoughts on YSlow Feedback I have read many articles on improving the page load for Drupal and used as many steps as possible to enhance the speed of the site.

I installed the FireFox pluggin YSlow to get feedback on my site.  I scored a 91 with an A rating thanks to the changes recommended in the forum.

YSlow is giving me an Grade F on Configure entity tags (ETags) and Grade F on Use cookie-free domains.

Are ETags and Cookie-Free domains, something I should concern myself with?

Even though I have a good rating, I still feel the home page loads slowly.  Even going from a page with images to a text only page there is a delay.

Thank you.

If your using multiple web servers then ETags need to be configured correctly. Add this to your .htaccess file (at the bottom) if this is the case. If you only have 1 server then you can safely ignore this recommendation.

FileETag MTime Size

Cookie-free domains offer a slight performance improvement because less data will be traveling over the wire. You need a CDN to get a cookie-free domain setup correctly.


Printing printer friendly version of nodes in bulk My scenario is this, a user selects a bunch of nodes and selects to print all the nodes.  What I'd like to happen is, once the user clicks the print button, the print dialog opens up and all the nodes are printed at once.  I'm using the Print module and I'm having a hard time figuring out how to print programmatically and all at once.

While the print module doesn't have much of an API, you can look at print_controller_html() to see how it renders printed pages:

$query = $_GET;
unset($query['q']);

$html = theme('print', array('node' => $node, 'query' => $query, 'format' => $link['format']));
drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
drupal_send_headers();
print $html;

For your purposes, you can changes a few arguments to the theme function and wrap it around a loop of nodes you wish to print. Something like

$html = '';
foreach($nodes as $node) {
  $html .= theme('print', array('node' => $node, 'query' => $_GET, 'format' => 'html'));
}

The theme function makes use of a template that you can override in case you want alter the HTML printed in a significant way.


How to define a timestamp field using drupal6 schema In this way I can create a table with a timestamp field in MySQL:

CREATE TABLE foo (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  created_at TIMESTAMP,
  name varchar(255)
);

Which would automatically insert a timestamp value each time a new row is inserted.

For example:

INSERT INTO foo (name) VALUES ('bar');
SELECT * FROM foo;

Output:

+----+---------------------+------+
| id | created_at          | name |
+----+---------------------+------+
|  1 | 2012-03-12 10:47:02 | bar  |
+----+---------------------+------+

How can I create a timestamp field like this using the drupal6 schema API?

In short, you cannot do this because the schema API does not support the TIMESTAMP type.

  The MySQL implementation of the Schema API implements the datetime field using MySQL's DATETIME type. That type does not support automatic initializiation/update to the current time.

  MySQL's type TIMESTAMP supports automatic initializiation/update to the current time. Switching from DATETIME to TIMESTAMP is not an option, though:

  TIMESTAMP behaves differently in MySQL versions 4.1, 4.1.2, 4.1.3, 4.1.6
  The first TIMESTAMP column in a table behaves different than other TIMESTAMP columns in that table.


css file defined in .info file is not loading in Drupal 7 This is the my .info file details

name = Tripsinn
description = A flexible, recolorable theme with many regions.
package = Core
version = VERSION
core = 7.x
stylesheets[all][] = css/responsiveslides.css
stylesheets[all][] = css/style.css
scripts[] = js/responsiveslides.min.js

but these css are not loading

URL: http://dev.easysites.in/tripsinn/

this is a custom drupal theme under development.

As far as I can see in the URL you posted, both css/style.css and js/responsiveslides.min.js are being loaded fine, but there is no trace of the css/responsiveslides.css file. Maybe you are not placing that file in the appropriate directory?

Hope that helps,


Given a taxonomy term id, how do we get the value of other fields; specifically the machine_id? A good example of getting the children is posted How to get fields...

I need the machine_id of the parent (or target)

Code below fetches the name;

$product_name_id = $product_name_reference->getValue()[0]['target_id'];
$product_name = \Drupal\taxonomy\Entity\Term::load($product_name_id)->label();

The machine_name is visible under 'values'. How do I get it!

The machine name is the vid:
if you search for machine_id inside taxonomy module there is no machine_id field declared.

But if you look at core/modules/taxonomy/config/schema/taxonomy.schema.yml you can see that:

vid:
  type: string
  label: 'Machine name'

So to get the vid (Machine name) you should use getVocabularyId
something like:

$product_name_id = $product_name_reference->getValue()[0]['target_id'];;
$product_name = \Drupal\taxonomy\Entity\Term::load($product_name_id);
// Vid or machine name.
$vid = $product_name->getVocabularyId();


hook_form_FORM_ID_alter being called twice (even before submit) I want to make some changes to the "Content" page.
The ID of the form is views_form_content_page_1, so I made a quick test (after drush cr of course):

function my_module_form_views_form_content_page_1_alter(&$form, FormStateInterface $form_state) {
  kint($form);
}

When I go to the page, the $form is being printed twice by the devel. I checked, all of the array items are the same. If I do kint('cat');, then it will print cat two times.

Why is this happening? Of course I could make it work, that my action will run only once (eventho drupal tries to run it twice) but I would like to rather solve this one, and understand if it's a bug, and why it is happening.

It has to do with the fact that Drupal redirects after the form submit. So after a form submit you will make 2 requests: the form submit and the redirect. Hence the 2 messages in your hook_form_alter().

You can disable this redirect by calling $form_state->disableRedirect() in your form submit handler. By disabling the redirect the form values will be preserved in the form. The redirect is in place to 'clean' the form inputs after submission.


Subscribe flag to auto-subscribe authors I have set up a flag so that users can flag certain types of nodes and receive an email notification if there is any activity on it, such as comments. It's paired with the answers module. What I can't figure out how to do is make is so that authors are automatically subscribed to those types of nodes that they author. Other associated modules are message_subscribe, flag_actions, message_subscribe_email,

Using flags version 7.x-3.9. Let me know if I left out any pertinent information.

For the Answers module (you know the dril: I'm a co-maintainer ...) to function, you must have the Rules module enabled also.

Therefor, have a look at this rule (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_subscribe_question_author_automatically" : {
    "LABEL" : "Subscribe question author automatically",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "ON" : { "node_insert--answers_question" : { "bundle" : "answers_question" } },
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_answers_notifications",
          "node" : [ "node" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "You\u0027ve been subscribed to your own post automatically (use the unsubscribe link if that\u0027s not what you want)." } }
    ]
  }
}

For those who are not an expert in Rules-ese, this is what the above rule will do:

Rules Event: after saving a new node of type "Question".
Rules Actions:

flag that node by the user who created it, by the flag with machine name subscribe_answers_notifications (which by accident is exactly also what happens if a user manually clicks the "subscribe" link (below the question).
Show an informational message like "You've been subscribed to your own post automatically (use the unsubscribe link if that's not what you want)."

I think this Answers (oeps: answers) the question ... which was "... authors are automatically subscribed to those types of nodes that they author ..."

Notes:

in case some author does not want to be subscribed to a question author by that author, it is still possible to use the unsubscribe link  (typically bottom right below the question) after they created their question (node).
the above rule only applies to nodes of type "Question", though with a minor improvement you could as well make it work for type "Answer".


how do i programmatically set the ANONYMOUS USER permissions on a site install profile? I am having trouble figuring out how to set permissions for users I personally did not programmatically create in my site installation profile. Can someone please help?

I would like to set 'View published content' as true for the ANONYMOUS USER user role in the .install file.

I am using the code below to grant permissions; but I do not know how to access permissions for the ANONYMOUS USER role.

       // Create the roles.
$roles['Content editor'] = array(
    'name' => 'Content editor',
    'weight' => $weight++,
    'permissions' => $base_permissions,
);
foreach ($roles as $role) {
    $role_object = new stdClass();
    $role_object->name = $role['name'];
    $role_object->weight = $role['weight'];

    // Save the role.
    user_role_save($role_object);

    // Grant permissions.
    if (!empty($role['permissions'])) {
        user_role_grant_permissions($role_object->rid, $role['permissions']);
    }

There is a constant for the anonymous RID named DRUPAL_ANONYMOUS_RID.

So, you would be able to use something like:

user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('your permission 1'));


Views to display different text than field I have added a field in Article content type,

field_url : contains external URL

I made a view to display the items in table format, Now my problem is to display as small text as possible in table.

I want to display Yes or No for field_url. If somebody have filled the field while adding content then instead of displaying whole URL I want to display only Yes with a link, if the field was empty I want to display No.

"To display Yes or No for field_url" - I done something similar to this but with Drupal 6 and Views Custom Field.

So for Drupal 7, I think you need to use Views PHP and add Custom Field:PHP field in your view and make conditions.

<?php

$static = $this->view->display_handler->get_handlers('field');

$x=$static['tid_1']->last_render;
$y=$static['tid_2']->last_render;

if($x !== null)
{
echo ""."Yes"."";
}
else
{
echo "NO";
}

?>

note: tid_1, tid_2 are field tokens, instead change it with your fields token.


Finding menu item ID How to find a menu item pointing to the specific node?

On node creation I want to create a main_menu link for the node.
With menu_rules it is relatively easy. The problem arises when the parent element can differ.

main_menu
Groups
-[GROUPS]
--[GROUP_CONTENT]

main_menu
...
Groups
-A
--a1
--a2
-B
--b1
-C
...

In the above case adding a new group D is easy - I simply add a menu item to 'Groups', but what if I would like to add a3?
I know the name of A and I know what it is linking to (a node representing a group) but I don't know its randomly generated menu ID (for example [menu-1082]).

How do I find that Id?

I'm almost new user of Drupal, but I encountered the same problem because I write myself my modules.
My need is to create a node and to insert it as submenu of a main menu Item. I solved my problem in this way:

I wrote this function

function mymodule_get_plid($menu_name , $name) {
    $menu = menu_tree_all_data($menu_name);
    foreach ($menu as $item => $menuitem) {
        if ($name == $menuitem['link']['link_title']) {
            return $menuitem['link']['mlid'];
            break;
        }
    }
    return false;
}

where $menuname is a string like 'main-menu', $name is the menu item for which I'm searching for it's Id. Function return Id if it find $name, false otherwise.

Now to complete node creation i wrote this.

$node = new stdClass();
$node->title = "YOUR TITLE";
$node->type = "page";  // Creating a node of Basic page type
node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
$node->uid = $account->uid;
$node->status = 1; //(1 or 0): published or not
$node->promote = 0; //(1 or 0): promoted to front page
$node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write

$node->menu['enabled'] = TRUE;
$node->menu['menu_name'] = 'main-menu';
$node->menu['plid'] = mymodule_get_plid('main-menu' , 'Inquiries');
$node->menu['link_title'] = 'MY SUBMENU NAME';
$node->menu['description'] = ''; // Needed even if empty to avoid notices.  /*

$node = node_submit($node); // Prepare node for saving
node_save($node);

Now all behaves well, "MY SUBMENU NAME" is created as a new node and appended as sub menuitem of the 'Inquiries' menu Item of the main menu.


My view's 'more' link needs to go to a page with exposed filters already selected I have a view that is a list of a certain content. The more link for the view needs to link to a page I have set up that has exposed filters for sorting the content.

So let's say the view I have is of baseball-related content. The more link will go to another page that contains all sports, but in this case it will link there but already have the baseball filter selected. Confused?

What I had been trying was to use the Custom URL field in the view, but no tokens can be used. Maybe this isn't even the right way to go about it. I'd love to know what is.

Any ideas?

I believe you want to use Contextual Filters (or, the functionality formerly known as Arguments").

Expand the "advanced" fieldset on the right side of your View's admin panel.

If, for example, I select "Content:Type" as a contextual filter, and my main page output of the view has a path of "/testview" then I can go to "/testview/Page" and see all content of type "Page". Same with my other content types, which happen to be "Story", "Product", and "Slide". You can do this with features besides content type. It sounds like using taxonomy terms would meet your needs.


Write drupal config in a profile installation Here's my problem: I use profiler builder to generate a profile from an installation. But the fact is : the profile only list my modules.

What I want my profile to do is also to keep my Drupal configuration. For exemple, if I generate the profile of a drupal installation with a WYSIWYG installed and configured, I want the profile to keep this configuration and reload it to new instance (created with the profile).

Is it possible ? Thanks.

Many configuration elements can be exported and imported using Features module.

  Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

Problem is that it only accepts modules that exports their configurations with Chaos tools style, so you can't export blocks, but can export boxes, and so on. Wysiwyg has currently ctools commented out from it's requirements, so you will need to see if it can be exported or not, at it's current stage of development.

If configuration is kept in system variables, you could consider using Strongarm:

  Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.

As Clive pointed out, there is also Configuration Management module:

  For the most part this module provides the same functionality as a subset of the features module.

The main difference is - it packs only configuration, is smaller and easier to handle, and was written explicitly to deal with "the shortcomings of using features module for configuration management". Still, you are moving whole page, so features with their broader goal might be the way. Your choice.

In all other cases you need to figure out how module stores it's configuration and data, and interact directly with database from your installation profile.


Using ajax to filter drupal autocomplete form I'm trying to build a custom search form, and I want to limit the scope of the search with a dropdown select menu, ie. choose "jewelry" in the dropdown menu and the autocomplete form will only return matches of that category.

Here's what I have so far:

function mymodule_search_menu() {
$items['mymodule_search-autocomplete-test'] = array(
'title' => 'Test autocomplete',
'page callback' => 'drupal_get_form',
'page arguments' => array('category'),
'access arguments' => array('view published content'),
'type' => MENU_NORMAL_ITEM,
);

$items['mymodule_search-autocomplete-engine'] = array(
 'page callback' => 'mymodule_search_autocomplete',
 'access arguments' => array('view published content'),
 'type' => MENU_CALLBACK,
);
 return $items;
 }

function mymodule_search_form($form, &$form_state) {
$form = array();

$form['category'] = array(
    '#type' => 'select',
    '#title' => 'First Dropdown',
    '#options' => array('All','Product'),
    '#ajax' => array(
    'callback' => 'mymodule_search_ajax_callback',
    'wrapper' => ???,
    'method' => ???,
    ),
);

$form['search_autocomplete'] = array(
'#title' => t('Search'),
'#type' => 'textfield',
'#maxlength' => 60,
'#autocomplete_path' => 'mymodule_search-autocomplete-engine',
'#prefix' => '
',
'#suffix' => '
',
 );

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Søg alt',
 );

 return $form;
 }

function mymodule_search_autocomplete($text) {
$results = array();
//query products
$query_products = db_select('commerce_product', 'p');
$query_products
->condition('p.title', '%' . db_like($text) . '%', 'LIKE')
->fields('p', array('title'))
->orderBy('title', 'ASC');
$res = $query_products->execute();
while ($res1 = $res->fetchAssoc()) {
  $matches[1][$res1['title']] .= check_plain($res1['title']);
}

array_unshift($matches[1], "PRODUCTS");

//query content
$query_content = db_select('node', 'n');
$query_content
->condition('n.title', '%' . db_like($text) . '%', 'LIKE')
->fields('n', array('title'))
->orderBy('title', 'ASC');
$res = $query_content->execute();
while ($res2 = $res->fetchAssoc()) {
  $matches[2][$res2['title']] = check_plain($res2['title']);
}

array_unshift($matches[2], "CONTENT");

$matches = mymodule_search_flatten($matches);
$newmatches = array();
foreach ($matches as $match){
$newmatches[$match] = $match;
}

drupal_json_output($newmatches);
}

function mymodule_search_ajax_callback($form, $form_state) {
  ???
}

As you might see, I have 2 different querys in my autocomplete function, and (I think) I would like to limit the result to only the selecteded querys with help of an ajax call from the dropdown category.

Oh, and don't mind all the "unshifting" and looping that goes on in the autocomplete function - I have to have category headers in my result, and this was the only way I could think of to do that.

If there's a better way to do this, or if you know how to accomplish this, please let me know.

Thanks!!

I know it's too late but for others who might find this questions, the answers are here:

form auto complete how to restrict results by previous drop down

and

Dynamic select list in the form (dependent dropdown)


Which Views template file to override to display fields in formatted table? I have some hierarchical content and I am trying to customize the output. I am trying to output a table something along lines of

Lesson Title    Description

 Exercises in Lesson    Exercise1
                        Exercise1 Description
                        Exercise2
                        Exercise2 Description

I looked at the existing display output template, expecting it to generate the view output. But that is not the case. I need to find the right file to edit, to add the PHP code to build my customized table.

Any ideas?

Thanks

There are quite a few ways to find this information, most of them are pretty easy to accomplish. I'm going to list a few different ways that I usually include in my process. (See update below for the choice to use template suggestion or template.php override function)

Theme Debug

Read here:
https://www.drupal.org/node/223440#theme-debug

When turning on theme debug you can inspect the HTML of the page and you will see the templates that are actually used and template suggestions for the markup of the page. The Drupal gods blessed us with this one as of D7.33, so it won't work on anything before that.

Views Theme Information

There are quite a lot of little tricks built into views to help developers. One of them is the ability to see what template file is being used for a particular view.

This is where the magic is for the template files being used.

This is what that modal shows.

Read here for more in depth documentation of each particular template file and what it does exactly.

Notes:

From your question and your layout of what your view is doing or trying to do (only speculation, so take this with a grain of salt, the more information given the easier it is to answer these types of issues) you are using views grouping of some sort to achieve that layout or hierarchical display of information. Views grouping is a little bit different than the regular template files as it uses a registered theme function for that, which is better for performance but you can still override with a template file as well. You can find that template file here if you think that may help in your current situation. I know that there are a lot of ways to skin a cat and a Drupal page so I could be off on that assumption. If I can add anything more to help just let me know.

I haven't watched the video mentioned in the comments yet but if I see exactly what that is referring to I will add some more information about that. You can also search for custom view handlers and other cool custom view options to achieve basically anything a BA can imagine.

Update:

I watched the video from the comments. I'm guessing that is fairly important to you since you mentioned it specifically in the comments on your question. Just to be clear for future readers incase the video is ever lost or deleted, OP is asking if he should use the template override (as in getting the template suggestion and copying the file to your theme/sub-theme and changing it from there) or overriding the template file in a function in your themes template.php. I have seen either way used before but there is a rule of thumb to use for this, if you are doing a major logic change of some sort use the override function in template.php. If you are only making basic markup changes and small data display changes you are safe to just use the actual template file. I will go ahead and say that on larger projects the amount of template files can get pretty large and unruly so unloading some of that in your template.php (even better broken out into inc files, see Bootstrap/Zurb themes for examples of breaking pieces out) helps out in some cases, but besides the rule of thumb mentioned that is up to you as the developer. (I haven't ever been told any different or read anything in Drupal standards as to say which way to go on this one besides the basic rule of thumb I mentioned and I consider myself pretty high up there with wanting/needing to follow Drupal standards, if anyone has any more information on that please chime in)


Slideshow background images in Background I'm building a site in Drupal 7. Using the JCarousel module I'm trying to create something similar to this:

http://dale.no/

It's simple enough to create a full width slideshow and adding text over images is not too bothersome with a few adjustments to CSS.

But is it possible to make the images into backgrond CSS images, the same as on the dale.no site? The reason is, when you resize the browser, or use a different size monitor, I would like the centre of the image to remain in the centre of the browser. At the moment, on a square monitor, the centre of the images are cropped by the right hand side of the view port.

Is this possible with this module? Are there are other modules that can achieve this?

There are few jquery library which are not using images directly. They are using images as css background.

I found one link for you - http://demo.marcofolio.net/bgimg_slideshow/

The following tutorial might be useful for you-
http://www.techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/

This tutorial explains how to use css background images for slideshow.


How do I add a block of JavaScript to the home page only? I have a block of JavaScript I need to add to my homepage (and only my homepage) to enable the logging of clicks via a heat mapping service I signed up for.

They specified the code needed to be placed just before the </body> tag, but I imagine it's safe to put it anywhere within the <body> tag.

I'd like the snippet not to appear on any other pages. How can I accomplish this?

I am running Drupal 6.

If by home page you mean the front page, then you can implement hook_preprocess_page() in a custom module.

function mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
    $variables['scripts'] = drupal_get_js();
  }
}

The same code works on Drupal 7, as $variables['is_front'] is set in _template_preprocess_default_variables() (called from template_preprocess()), using the following code.

  // drupal_is_front_page() might throw an exception.
  try {
    $variables['is_front'] = drupal_is_front_page();
  }
  catch (Exception $e) {
    // If the database is not yet available, set default values for these
    // variables.
    $variables['is_front'] = FALSE;
    $variables['db_is_active'] = FALSE;
  }

The reason of calling drupal_add_js() first, and then drupal_get_js() is that, in the case another module that is executed after would run the following code, the JavaScript file would still be added.

function quite_a_different_module_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('module', 'quite_a_different_mymodule') . '/quite_a_different_module.js');
  $vars['scripts'] = drupal_get_js();
}

Using drupal_add_js(), the file will be added to the output returned from drupal_get_js().


drush sqlc import causing Mysql 1045 (28000) Error Acces. How to resolve it? I'm trying to move a live Drupal 7.39 site to my local Acquia dev set up which installs Drupal 7.41.

I follow what I think is standard procedure, which is to get a clean install, copy my site's sites folder, and then upload the database and run the update script.

I'm using the drush command drush sql-drop -y && drush sqlc < dump.sql. The first part of the command runs, the database tables are dropped, but then I get a 1045 error (28000) for my database user.

What perplexes me, is that the first part of the call works, but it fails in the second part. The sql file is too large to import through phpmyadmin, and I'm really dumbfounded here.

Should I update the live site to 7.41 before migrating it? I don't want to do this because I don't want to do updates on the live site.

What is causing this issue? I think it's a conflict with the SQL settings in the settings.php file, but they match the database user and authentication but I don't know enough about the guts of drush to figure out how to fix this.

To reduce the possibility that the size of your database is what is causing your problem, I would try to use the Backup and Migrate module.

In doing so, you can exclude all sorts of tables (which might reduce the size tremendously), similar to what I described in my answer to the question about "How to get an import of a very large Drupal database working?".

PS: my answer to your 2nd question (= Should I update the live site to 7.41 before migrating it?) is No, because you should not have to update a live site to create a development environment. If you have a need for them to be at the same level (to start from), then rather do the opposite: have your local site start from 7.39, then sync your database, and if needed (only) then upgrade your local site to 7.41. You'd get the same result, without touching your live site, right?


Define zone-wrapper in Omega 4 and 960px I'm using omega 4 and i got problems. How can i define 960px in omega 4 ? should i define it in _grid.scss like this :

$grid: 12px ;
$gutters: 1/3;

$tab:44em;
$desk:77em;
$mobile:15em 35em;

If it's true , how can i have something like omega 3 zone-wrapper with 100 % width ?!!!

If you are using Susy, something like that will do the job:

$total-columns: 12
$column-width: 6em;
$gutter-width: $column-width / 3;
$grid-padding: $gutter-width / 2;
$container-style: fluid;

html {
  font-size: 62.5%;
}

.l-page {
  @include container();
}


Force a session to become HTTPS? I'm working with a very complex legacy D7 site, and very complex requirements (bleaugh).

Anyway: I'm working on a deeplinking system that allows a jump to the site, which then logs-in a user (this is based on an encrypted ID), does some other stuff like setting up cookies, and then jumps to the required page.

This is fine, except some of them are HTTP pages, which work, and some are HTTPS, which don't.

What happens is that when it arrives on the required page there is no logged-in user (so "Access Denied"). But if I then go to an HTTP page (like the front page), the user is logged in.

So clearly I need to set up the HTTPS session data before jumping to the required page. I've been through the Drupal session code but I can't figure it out.

I need to set the SSESSPHPID cookie and possibly some other stuff - but what and what's right? Any help would be appreciated.

Long story short: It wasn't Drupal. We have the Brocade Traffic management stuff running above the site (and on local sites too so the dev environment is as close to live as possible).

The HTTP/HTTPS switching in that was causing the problem. After working with it for so long I should have checked it. Such is the life of a professional developer.


HTML In a hook_menu title callback I'm trying to insert a span class around some text in title callback. It passes through a t() function so all the html is escaped.

Is there a way round this?

My code is:

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

  $items['discussion'] = array(
    'title' => 'Discussion',
    'title callback' => 'custom_module_title',
    'page callback' => 'custom_module_tester1',
    'access callback' => TRUE,
    'menu_name' => 'document-menu',
    'type' => MENU_NORMAL_ITEM,
    'options' => array('attributes' => array('class' => 'discussion')),
    'weight' => 10,
  );

  return $items;
}
function custom_module_title() {
  $discussionnid = custom_module_postexist(3);
  if ($discussionnid) {
    return 'Discussion 85';
  }
  else {
    return 'Discussion';
  }

}

The HTML in the title is escaped because template_preprocess_page() gets the title using the following code:

// Construct page title
  if (drupal_get_title()) {
    $head_title = array(strip_tags(drupal_get_title()), variable_get('site_name', 'Drupal'));
  }

drupal_get_title() then contains the following code:

function drupal_get_title() {
  $title = drupal_set_title();

  // during a bootstrap, menu.inc is not included and thus we cannot provide a title
  if (!isset($title) && function_exists('menu_get_active_title')) {
    $title = check_plain(menu_get_active_title());
  }

  return $title;
}

The title is escaped from that function.

As far as I know, the content of <title> should not contain HTML tags; that is the reason it is escaped.

In the W3C specifications for HTML 4 is reported the following text:

  Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments). Here is a sample document title:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A study of population dynamics</TITLE>
<!-- other head elements -->
</HEAD>
<BODY>
<!-- document body -->
</BODY>
</HTML>

In Changed Elements it's not reported any changes between HTML 5 and HTML 4 about the <title> tag.

In Drupal 7, you could set the title with drupal_set_title($title, PASS_THROUGH), but the documentation says:

  Only set to PASS_THROUGH if you have already removed any possibly dangerous code from $title using a function like check_plain() or filter_xss(). With this flag the string will be passed through unchanged.

PASS_THROUGH is used to avoid the title is filtered twice, not to filter the title at all.

Then, using drupal_set_title() is not possible from the title callback; you should set it in a different place. I would not suggest doing so, though.


twig debug what does % mean - name of page.twig I wonder about the "%". What does that mean?

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
  * page--node--31.html.twig
  * page--node--%.html.twig
  * page--node.html.twig
  x page.html.twig
-->

And what names are possible? I need a page for a specific and custom block for viewing the whole content.
I need something like this, but do not know how to do it right.

page--node--[my-custom-block]

page--node--%.html.twig

This would be a universal template for page level views of any content type.  So if you wanted to have the same template for different content types you could use this convention.  If you need different templates for each content type you could apply:

page--node--[content type machine name].html.twig


Users complain they can't "click on anything" on my Pressflow site The users of my site complain they cannot click on anything on my site, which runs Pressflow.

If that makes any difference, I am using some Nginx Caching, and the server config from the Barracuda Aegir project.
I can't seem to figure this out, or reproduce it in another site.

I fixed the issue (which was general): I was using a Microsoft CSS filter to scale the background image. It somehow made the whole page render incorrectly. I removed filter, and the problem was solved. I can live without a nice background on IE, for now.


Enabling clean URLs cause a 404 error I am trying to enable clean URL in a Drupal 7 website. The clean URL is supported by server, as I can see the checkbox to enable it, but after enabling it, I am able to access only the front page of the website. For other pages, I get a 404 error. I can see the page just by putting /?q= after the website address.

How can I resolve this issue?

Add .htaccess file in your drupal folder and the issue with the clean url would be solved.

.htaccess file would look something like

#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value upload_max_filesize 40M
  php_value post_max_size 42M
  php_value default_socket_timeout 600s
  php_value max_execution_time 300s
  php_value max_input_time 600s
  php_value memory_limit 512M
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

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

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

Hope that the answer helps you to clean the URL and you wont have to add the query parameter.


Configuring PayPal Express Checkout to accept BRL currency When configuring PayPal Express Checkout on Payment Methods, the Default Currency selector don't show BRL as an option.

In the FAQ page https://www.drupal.org/node/1902660#comment-9118725, where we read

  PayPal only supports a small set of currencies, and these vary by
  service. This module uses the most up to date documentation to
  populate currency option lists.

on documentation link there are more currencies that Express Checkout accepts. So isn't it necessary to update the set of currencies in Default currency selector?

When I go to paypal site  through checkout button I can't complete transaction because the currency send from Drupal is in USD instead of BRL.

There is a patch in Issues for Commerce Paypal module. I have applied that patch and now BRL is showed. Going to PayPal page from my site's checkout section now works fine.


Change From on Admin Order Emails In the Drupal Commerce module is there a way to change the ADMIN ORDER EMAIL sender to the customers email instead of it being from the administrators email?

Thanks!

You can just edit the Rule that controls that admin email and there is a From field for you to enter in the token or data selector for the customers billing email.


Inheritance filters in view I've got content-type with two fields with real values. Their interior name are field_price1 and field_price2. I created page view includes contents. I've got search. I want to allow user to give some value(s) in search (min and max) to seek contents. I want to display only these contents whose field_price1 OR field_price2 is between min and max filled in by user.

Has someone any ideas?

I tried and I decided to create two filters. First filter (for field_price1) exposed, second (for field_price2) not. So that, in my search I've got two inputs (I chose between operator). I wanted the second filter inherits values from first filter. I coded:

function customSearch_views_pre_execute(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

I place that function in my custom module named customSearch. My view is named search. Unfornately it doesn't work. Second filter doesn't inherit values from first one. I don't know why. Could someone help me, please?

You will need to implement hook_views_query_alter to get this going.

Start with the filters in Views.

Make your filters look exactly like this. With that I mean that there should be two groups of filters with AND between the groups. And you need to set Or in the second group. This is important otherwise the code below will not work.

Then replace hook_views_pre_execute with the code below for hook_views_query_alter. I also recommend you rename your module to customsearch instead of customSearch, small letters is standard in function names for Drupal.

/**
* Implements hook_views_query_alter().
*/
function customsearch_views_query_alter(&$view, &$query) {
  if ($view->name == 'search') {
    if (isset($query->where[2]['conditions'][0]['field']) && $query->where[2]['conditions'][0]['field'] == 'field_data_field_price1.field_price1_value') {
      $query->where[2]['conditions'][1]['value'][0] = $query->where[2]['conditions'][0]['value'][0];
      $query->where[2]['conditions'][1]['value'][1] = $query->where[2]['conditions'][0]['value'][1];
    }
    else {
      unset($query->where[2]);
    }
  }
}

In the code I first check to see if something has been entered in the exposed filter. If it is present we populate the second filter's values.

If you enable the module devel and do dsm($query) just before the last } you can debug and look in  the array yourself. For exammple number 2 in $query->where[2] means the second group of filters, which you will see easily if you debug.

Update: I've added an else statement so that the price fields are not in effect at all if nothings been entered in the in betweens.


Is there a way to consume external web services and show results in Views? I have an external web service, which can be accessed using a HTTP call (with parameters passed as query string), and that returns the result in XML format.

I would like to use Drupal to access that web service (with the desired parameters), and display the result using Views.

These are a sample query and the result obtained from the web service I am using.

Query: http://localhost/query.php?cy=in&q=abcd&cat=22
Result:

<?xml version="1.0"?>
<results>
<Jobs>
    <Job ID="111">
        <Title>Test one</Title>
        Test one summary
        <DateUpdated Date="2011-04-04 18:03:00">4/4/2011</DateUpdated>
        <Location>
            <Country>India</Country>
            <City>Delhi</City>
        </Location>
        <CompanyName>Test Company</CompanyName>
    </Job>
    <Job ID="222">
        <Title>Test two</Title>
        Test two summary
        <DateUpdated Date="2011-04-04 18:03:00">4/4/2011</DateUpdated>
        <Location>
            <Country>India</Country>
            <City>Chennai</City>
        </Location>
        <CompanyName>Test company</CompanyName>
    </Job>
</Jobs>
</results>

The advised solutions are based on getting the data into the database first, then showing it in Views.

An alternative is querying the service directly from Views, by using a custom query backend.
Checkout http://drupal.org/node/958270 for links to custom backends which you can use as an example for writing your own (it's not a lot of work)


How to let users allow other users to view specific node content? I'm using Drupal 9
I would like users to be able to allow other users to view their node content. Ideally a user will request access to view the content and the content owner will grant them view access.
How would I go about that?
I've looked at Nodeaccess, but it doesn't seem ready for Drupal 9 yet.
Node access user reference has nothing close for Drupal 9

You can do it using a small custom module.

Make a allowed users/node list (database table oe entity)
Implement hook_entity_access()
return AccessResult::allowed() or AccessResult::forbidden() according to your user/node table


Update command won't work for multisites I have a Drupal 7 site with a half-dozen multisites/subsites and I am trying to setup Drush so that I can run my modules updates from the command line for the subsites. Running Drush for the main site works fine. Running Drush for ONE of the sub sites works fine. However for about 5 of the subsites I can run commands like

drush @subsite status

or

drush @subsite updb

but if I try to run

drush @subsite update

or

drush @subsite ups

I get an error:

Command pm-updatestatus needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

So I don't understand what makes all the other sites different from the one, or why some commands would work and others not. I am running these commands from my main Drupal install path:

/var/www/html

What am I doing wrong, and how can I get update to work for my subsites?

It's worth noting that the majority of these subsites were setup at a time when I didn't necessarily know what I was doing, so I can only describe their configuration as "wacky". One of the affected sites is setup in a fairly standard way and the working subsite is of the "wacky" variety, however, so I don't expect that's the problem.

EDIT:
Because it is working for one site and not others, I'm wondering if it's a file permission issue. What user does Drush run as, and what level of access does it needs to which files? In my case, I am working on Ubuntu.

As a test, change your working directory to the directory that contains the settings.php file for the site you want to operate on, and then run drush pm-updatestatus.  See if that bootstraps correctly.  If so, the issue is with your alias files.  These should work, so long as 'root' and 'uri' are set.

Note, however, that if all of your contrib modules are in sites/all, then one run of pm-updatecode will update the code for all sites. You will need to run drush updatedb for every site that shares any code updated by the last run of pm-updatecode.  Drush does not manage this for you, even with pm-update (which runs updatedb on just one site).

This is the added cost of multisite configurations -- you have to be a lot more careful with your update processes, and must update all of the sites at the same time.


Print image field with multiple entries from field in twig template I have a twig template for a custom content type. And it is able to render most fields just fine, but I am unable to print an image field with multiple images.

node--mycontenttype.html.twig contains

{{ content.field_mytitle }}
{{ content.field_myheaderimage }}

    {% for galleryimage in content.field_gallery_images %}

 {{ galleryimage }}

    {% endfor %}

content.field_mytitle and content._field_myheaderimage outputs the title and image just fine. But when I use the for loop

    {% for galleryimage in content.field_gallery_images %}

 {{ galleryimage }}

    {% endfor %}

I receive an error

Exception: Object of type Drupal\node\Entity\Node cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 443 of core/lib/Drupal/Core/Template/TwigExtension.php).

When I just use

{{ content.field_gallery_images }}

It's able to output each image, but this does not allow me to wrap each item in divs and add content to each one.

Print the image field in the node template like any other field:

{{ content.field_gallery_images }}

And then use a field twig to loop through multiple field items:

field--field-gallery-images.html.twig

  {% for item in items %}

{{ item.content }}

  {% endfor %}


"Language neutral" is not available for content On a standard multilingual Drupal installation (Drupal 8.6.10), when editing existing content or creating new content the option language neutral isn't available; only the enabled languages and some other options are shown.

How do I select Language neutral?

In Drupal 8 LANGUAGE_NONE (neutral) has changed to LANGUAGE_NOT_SPECIFIED, LANGUAGE_NOT_APPLICABLE and LANGUAGE_MULTIPLE.

I usually use LANGUAGE_NOT_SPECIFIED where I used to use LANGUAGE_NONE in Drupal 7.

Berdir mentions that all those new options makes no difference to how content is displayed, but they let you treat differently to content on your site if you'd wanted to in views, custom code, ...


Drop down menu question I found a tutorial for a nice menu for my site.

Everything went well till step 7; when I enter this in Views3 on Drupal 7, I get this error message:

  Display "Block" uses fields but there are none defined for it or all are excluded.

How can I solve this?

Have a look at your "content post date", it seems to be excluded (click at it, uncheck the option "exclude from display") therefore no field is displayed hence the error.


Filter three views blocks by the same filter Is there a possibility to filter three separate views blocks by one filter form.

Basically the Idea is:

Filter:

Text field

Date field

Search button

And below we show

First views block
Upcoming

Second views block
Current

Third views block
Past

Whatever we select in the filter is affecting these three blocks. And there are corresponding orderings for each block.

Another complication:

Each block can have a grouping by type:

Example:

Upcoming:

type 1:

data 1

data 2

data 3

Type 2:

data 2

data 23

data 24

And the same is for Current and Past

Views Attachment Displays are the way to go, because they are like Blocks but have special options for accepting contextual or exposed filters from the View they are attached to.

Create a Views Page Display with your Text and Date exposed filters, and show Upcoming information there (through the usual Filters).

In the same Views create a new Display of type Attachment. In the Attachment settings set:
    Attach to the Page from the previos step,
    Attachment position to After
    Inherit exposed filters to Yes
    Override the Filters to display Current info, and override fields if they are different from the default

Repeat the procedure for adding another Attachment, only this time for the Past information.

You can override the Fields, Filters and Sorting individually for each of those individual displays, while Exposed filters will be applied to all at the same time.

Format can also be overriden for each display. Just make sure you first set it to "This attachment (override)" and Save, even if you have to save the same Format (Table for example). Then under Format settings select your Grouping fields. Although IIUC the Grouping field will be the same in all displays.

The Page you created will show all 3 views results, one below the other, and all will react to the Exposed filter, assuming your 3 different structures share those same fields you have exposed.


Trying to embed a video in a Views Header I am trying to embed a video in the header of Drupal 7 View. I have the header text format set to full HTML. The full HTML text format is set to: (X = checked)

_ Limit allowed HTML tags
_ Display any HTML as plain text
X Convert line breaks into HTML (i.e.
 and
)
X Convert URLs into links

The code below is what we used to embed the video in our Drupal 6 site but it was in an article not a views header. No video is showing up in the header and view source shows that the code is getting stripped out.

<embed id="mainFlash" width="550" height="440" quality="high" name="mainFlash" src="http://www.oursite.com/main-video-en.swf" type="application/x-shockwave-flash">

Is it possible to embed the video? Do I need to use the <object> tag instead?

The 'Full HTML' format in Drupal 7 by default still strips out some of your tags, check your format settings under Administer » Configuration » Content authoring » Text format, or /admin/config/content/formats/ and you'll see that for the Full HTML format, you're limited to the following tags:

<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>

You can either add an object, embed tag here to make these work for this input format or you can add a separate input format that has no restrictions. The choice will really depend on what kind of site you are running and who else might have access to this format. If I were letting users use the 'Full HTML' format for adding comments, content, I would definitely want to restrict the tags they use and allow only admins access to an unfiltered format.


Compare Two Select Lists, and Require User to Select Different Values Use case:  I'm presenting the User with two Select Lists populated with the same People names.

The first select list is Primary Person, the second select list is Backup Person.

The User must select a different value from each list. The same Person can't be a primary and backup. If the User attempts to save the page using the same value, Drupal will throw an error.

What's the best approach?

For the Drupal form API, this would be handled with your validation handler. Have it check your 2 form values for equality, and throw an error if so.

function MYFORMBUILDER_validate($form, $form_state) {
  if($form_state['values']['person_primary'] == $form_state['values']['person_backup']) {
    form_set_error('person_primary', t('The primary and backup person must be different'));
    form_set_error('person_backup', t('The primary and backup person must be different'));
    array_pop($_SESSION['messages']['error']); //Remove duplicate message
  }
}


Why does the Node reference module search only for node titles? I have two content types: Type A and Type B. Type A has 3 fields: title, location, and zip code.

I want to get references to Type A in a field for Type B. I have tried using the Node reference and the Entity reference modules, but they allow only to get options in autocomplete when I write the title of a Type A node. I want to get a list of all the Type A nodes with the zip code entered in the field.

You should  use tokens and autonodetitle modules.

After enabling tokens and automatic node title , go to Stucture->content types -> edit (type A) content type. If you scroll below you will see an option Automatic title generation . Click on 'automatic title generation' you will see an Pattern for the title and list of options containing token list
like curent user, current date, current page, node , random etc.
Click on node and find the token related to node Type A.Like for the field location and field zip there will be token similar to this [node:field-zip],[node:field-location]
add this into pattern for title field. Now you can check the Type B autocomplete entity reference field for type A . you will find that as title is changed the entity reference field has location and zip in the title.


Drupal 8 JavaScript and Best Practice I am building a theme for Drupal 8 that I want to make available in the drupal.org theme section. As such, I want it to conform to best practice code wise. When adding JavaScript, I notice there has been some changes. Here is how I do it:

function THEMENAME_preprocess_page (&$vars, $hook) {
  $path = drupal_get_path ('theme', 'THEMENAME');
  // Render the main scripts file.
  $local_js = array (
    '#attached' => array (
      'js' => array (
        $path . '/js/THEMENAME.js' => array ('group' => JS_THEME, 'weight' => 9999),
        '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' => array ('group' => JS_THEME, 'weight' => 9000),
      ),
    ),
  );
  drupal_render ($local_js);
}

Is this it? the best-practice way?

Edit:

In accordance to Aneek's answer I am now including JavaScript this way:

First, I created a THEMENAME.libraries.yml:

THEMENAME-base:
  version: 1.0
  js:
    //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js: {}
    js/THEMENAME.js: {}

Then, in THEMENAME.info.yml I added the libraries:

--snip--
core: 8.x
stylesheets:
  all:
    - css/grid.css
    - css/style.css
regions:
  header: 'Header image'
  home_intro: 'Home intro'
  breadcrumbs: Breadcrumbs
  content: Content
  sidebar-main: 'Sidebar main'
libraries:
  - THEMENAME/THEMENAME-base

This method includes the JavaScript files to all pages on the site. If one needs to include on specific pages only, the preprocess_page would probably be the way to do it.

As of newer versions of Drupal 8, the "js"-key (or "css") is not allowed anymore in the #attached-array. Use "libraries" instead.


Why is the 'values' array not set on an unsaved entity? Is there a way to make it get populated? When I load an entity, its protected 'values' property contains all of its field values.

But when I create a new entity with MyEntityClass::create($array_of_values), its 'values' property is not set until I have saved it.

Is there a way to get that set, for the purposes of debug output?

The code comments in ContentEntityBase say that $values always hold the original, unchanged values of the entity:

/**
 * The plain data values of the contained fields.
 *
 * This always holds the original, unchanged values of the entity. The values
 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
 * is used for values in default language.
 *
 * @todo: Add methods for getting original fields and for determining
 * changes.
 * @todo: Provide a better way for defining default values.
 *
 * @var array
 */
protected $values = [];

Quick glance through the code suggests that the public method updateOriginalValues() would do the trick:

/**
 * Updates the original values with the interim changes.
 */
public function updateOriginalValues() {
  if (!$this->fields) {
    return;
  }
  foreach ($this->getFieldDefinitions() as $name => $definition) {
    if (!$definition->isComputed() && !empty($this->fields[$name])) {
      foreach ($this->fields[$name] as $langcode => $item) {
        $item->filterEmptyItems();
        $this->values[$name][$langcode] = $item->getValue();
      }
    }
  }
}


Using hook_js_alter to change localsettings variable in the autologout module drupal I want to know how to use hook_js_alter to change the localSettings variable in autologout.js.

In autologout.module in line number ( 377 - 389)

$settings = array(
    'timeout' => $refresh_only ? ($timeout * 500) : ($timeout * 1000),
    'timeout_padding' => $timeout_padding * 1000,
    'message' => t('@msg', array('@msg' => $msg)),
    'redirect_url' => url($redirect_url, array('query' => $redirect_query)),
    'title' => t('@name Alert', array('@name' => variable_get('site_name', 'Drupal'))),
    'refresh_only' => $refresh_only,
    'no_dialog' => $no_dialog,
  );
drupal_add_js(array('autologout' => $settings), 'setting');
drupal_add_js(drupal_get_path('module', 'autologout') . "/autologout.js");

In this it passes the settings variable to the javascript file.

I want to change
" 'title' => t('@name Alert', array('@name' => variable_get('site_name', 'Drupal')))," attribute using "hook_js_alter" in my custom module so that javscript takes the new value.

The structure of the $javascript array passed to hook_js_alter() is similar to the following one. (I reported only the relevant part of the array.)

array(
  'settings' => array(
    'data' => array(
      0 => array('basePath' => '/'),
      1 => array ('pathPrefix' => ''),
      2 => array('ajaxPageState' => array ('theme' => 'bartik', 'theme_token' => 'oFpiDA70-NnnvSdIL6bFt1oLccvTT5SZeOp3G34cOfs')),
      3 => array ('overlay' => array('paths' => array('admin' => 'node/*/edit node/*/delete node/*/revisions node/*/revisions/*/revert node/*/revisions/*/delete node/add node/add/* overlay/dismiss-message user/*/shortcuts admin admin/* batch taxonomy/term/*/edit user/*/cancel user/*/edit user/*/edit/*', 'non_admin' => 'admin/structure/block/demo/* admin/reports/status/php'))),
      4 => array('overlay' => array('pathPrefixes' => array())),
      5 => array('overlay' => array('ajaxCallback' => 'overlay-ajax'))
    ),
    'type' => 'setting',
    'scope' => 'header',
    'group' => -100,
    'every_page' => true,
    'weight' => 0
  )
  // ...
);

I would use the following code for hook_js_alter().

if (isset($javascript['settings']['data']) && is_array($javascript['settings']['data'])) {
  foreach ($javascript['settings']['data'] as $index => $settings) {
    if (isset($settings['autologout']['title']) && is_array($settings['autologout'])) {
      $javascript['settings']['data'][$index]['autologout']['title'] = 'Your value';
      break;
    }
  }
}


Moving a DB table into a different module Here is cleanetica_advanced.install file (of a "custom" module containing particulars of the site we work on):

<?php
function cleanetica_advanced_schema() {
  $schema['video'] = array (
    'description' => 'Videos with HTML titles',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of videos',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'urlinfo' => array(
        'description' => 'The string referring to the video',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'The title for a video, used in admin part only',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
      'richtitle' => array(
        'description' => 'The HTML-formatted title for a video',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

function cleanetica_advanced_update_1(){
  drupal_install_schema('cleanetica_advanced');
}

I now think that it is better to create a separate module to manage 'video' database table and related things.

The trouble is that I have already created 'video' DB table. How to move/transfer a table into an other module?

The simplest way is to uninstall your existing module completely (not just disable), cut the schema definition from the old to the new, then enable both modules. The uninstall will remove the table, and the install will add it back in from the other module.

You'll also want to get rid of the cleanetica_advanced_update_1() function from your current module as that could cause some interesting inconsistencies if left unchecked.


What is content pane and embed? When you click the Add tab in a view, you have many choices including Content pane and embed.  What are those?

Many modules provide add-on functionality for Views. Chaos tools suite (ctools) provides the Content Pane display, which is a way to embed views in other areas of your site using advanced context passing. The views are not treated as pages and you can therefore embed them multiple times, just as you can with blocks, but with blocks your context handling is very limited.

For one good example of where and how to use it you may look at Panels module.

Some tutorial here:

Drupal Tutorial - Panels #6 : Related Content With Views Content Panes | WDTutorials.com


How do you make entity fields appear in Rules when converting a Webform submission to node? Steps to reproduce this use case:

[Rule event] Submit data on a specific Webform (new submission)
[Rule action] Create content node by type
[Rule condition] Use 'content is of type' condition
[Rule action] Access Webform submission data to set node content fields

How can 3 & 4 above be executed in this order and allow for access to both the created entity and webform submission? i.e. - by passing arguments or otherwise.

Related articles which get some of the way there but did not answer my question entirely:

Using webform rules to create node after webform submission
How to create a node from a Webform using rules?
How to create a node with submissions of a webform?

Assuming you are using Webform Rules, you should move 3 and 4 to a Rules Component, but unfortunately Webform Rules does not allow to expose webform data (transfer submission between rules and components) without the patch from here https://www.drupal.org/node/2020149 Without it the data is only available using tokens, and you can not even set the webform data to the variable.

There is another solution, you can extract the Webform SID ([data:sid]) and send it to your Component together with newly created entity and webform itself, then inside your component you can convert received [data:sid] to integer and fetch the submission (Rule Action: Fetch Webform Submissions) and access it using PHP. You will also be able to use Entity:has field inside your component to access all the fields from your newly created entity.

Something like that (component):

The component parameters has:


File/function that is executed when I open node from view I have created view for displaying the nodes. I want to know which function/file is executed when I click on the node listed in the view table. I want to add some code to the file when the node information is loading. Can anyone suggest me the function/file where i'm supposed to do the changes?

You've two ways to afford the problem:
Site building way
If you're using a wiew of rendered nodes (usualy teasers) you can redefine the layout, tags, fields, etc. on admin/structure/types/manage/YOURCONTENTYPE/display/teaser

If you need more options try display suite and fences modules:
https://www.drupal.org/project/ds
https://www.drupal.org/project/fences

Developer way
Editing your view, on the "advanced" colum, "other section" you've the "templates" there the "Theme: Information" item.
There you've the name of the templates the view is using.
You can redefine then on your custom them.

EXTRA BALL: Common sense way
Probably a mix of two others are que best option


How to create a custom 'fluid' layout in Display Suite I created a Display suite custom layout following this tutorial: https://drupal.org/node/1098068

It works fine, but I need this custom layout to be Fluid.

  In Display Suite, the "fluid" refers to the templates ability to
  expand the column width if one (or more) columns are empty.

How can I do this? I guess I need to add some php code which will add some extras css classes. But I don't know how and where to add this code.

Just select the custom layout in the Manage Display page:

And add the required CSS in your theme. See the examples included in Display Suite:


Customize search block in frontpage I am using Zen3 theme , i created a subtheme ,i want have a big search box in front page , for doing this , i created  a front page template page--front.tpl.php.
also i added a custom css to my search-box by this code in template.php

function myrtheme_form_search_block_form_alter(&$form, &$form_state) {
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-icon.png');
    $form['actions']['submit']['#attributes']['class'][] = 'search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'search-box';
    }

my problem is how can add css class only to the frontpage in page--front.tpl.php.

I suggest you use drupal_is_front_page() to check it is on front page or not. You can achieve it using code similar to the following.

function myrtheme_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-icon.png');
  if (drupal_is_front_page()) {
    $form['actions']['submit']['#attributes']['class'][] = 'fpage-search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'fpage-search-box';
  }
  else {
    $form['actions']['submit']['#attributes']['class'][] = 'other-page-search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'other-page-search-box';
  }
}


Prevent Anonymous users info to be displayed in my views I am making a list of users for views categorised in my table, however, there are users that are "Anonymous" and i dont want them to show up in the table. Is there any way of fixing it?

I think that if a user is showing up in your users table (and thus users view), they must have an account on your system, so they would, at a minimum, be an 'Authenticated' user.  But they probably have no other roles other than 'authenticated'.

So try the following to filter them out of your users view:

Add a filter to your users view

Select the 'User: Roles' filter and configure it as the screenshot below:

Let us know if this worked.

p.s. I'm assuming you have Drupal 7 here, since that's what the screenshots are showing -- Views under Drupal 7, but it really helps to tag your question with the version of Drupal you're running.


Img tag getting removed in views drupal 8 I am trying to rewrite the results of a field to include an img tag.
The first part of the tag then gets stripped, the second part stays:

<img src="http://example.com alt="Image" /> results in alt="Image" />.

What is causing it and what will be work around for it.

I was using wrong image formatter . Instead of rendering the image the image tag was being rendered.


Pulling components out of a Features module into a Drupal site I have a site that has some functionality provided by a Features module. They include a view, some nodes, and some content types. Now, we don't want them in the Feature anymore; we want them as native Drupal things.

How do we migrate components provided by a Feature module back into Drupal?

Use the Feature Tools module. The main goal of the module is to give the ability to remove elements from a feature and put them back to the DB.
It adds a "Safe Create Feature" button to the recreate feature form, that detects the element that has been removed from the feature and saves them in an unlink file.
In order to save the elements to the DB you need to go to the admin/build/features/unlink page, check the element you need to import and submit.


Custom submit handler is also called when deleting a node So these are my functions:

function mycustom_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'b2share_form_submit';
  return $form;
}

I can also attach the custom submit handler in other ways to the form, but only this way I can still access the nid and the bundle of the node.

function b2share_form_submit($form, &$form_state, $entity_id, $entity_type) {
   $values = array(
   'url' => $form_state['values']['b2share_fieldset']['url'],
   'pid' => $form_state['values']['b2share_fieldset']['pid']
  );

  if ( (empty($values['url'] == false) || (empty($values['pid']) == false)) ) {

    $insert = db_insert('field_data_field_b2share')
      -> fields(array(
       'field_b2share_url' => $values['url'],
       'field_b2share_pid' => $values['pid'],
       'entity_id' => $form_state['node']->nid,
       'entity_type' => 'node',
       'bundle' => $form_state['node']->type,
       'delta' => 0,
       'language' => 'und',
    ))
   ->execute();
 }
}

I can add nodes and edit them perfectly, but whenever I try to delete one, the custom handler function is called and prevent drupal from doing anything. No error messages, nothing in the logs.

Can someone help?

You made the mistake of giving the form submit function a name that matches the patter form-name_submit. So it does not only trigger by your submit button. It is triggered by every submit button in the form.

Rename your function and you should be good.


Show cached pages with boost for logged in users I have a website that is only available to logged in users, I want to increase performance with boost by caching pages for authenticated users would i just edit the code above?

http://drupal.org/node/509694

here it says this code is what prevents boost from caching for logged in users

<?php
  // For authenticated users, set a special cookie to prevent them
  // inadvertently getting served pages from the static page cache.
  if (!empty($user->uid)) {
    boost_set_cookie($user);
  }

No, because it will break your site for logged in users. Try Authcache module instead.


Is there an easy way to prepopulate webform field default values from profile2 field values? We are working on major project where client wants webform fields to be prepopulated from profile2 fields. Webform version 3.17

Is there any way to create tokens or similar from profile2 fields to be used on webform default values?

hook_form_alter(){
//and set default values form profile2_load_by_user();
}


One exposed filter for multiple views One exposed filter for multiple views

I have an exposed filter which is a date field containing a month and year using the “date module”.

I want to use different views to read the URL and filter with a “Contextual Filter”. This is how the URL looks and I can see it has separated out the Month and Year;

?field_month_value%5Bvalue%5D%5Bmonth%5D=6&field_month_value%5Bvalue%5D%5Byear%5D=2016&=Apply.

I know the contextual filter in views is looking for 062016 so I’m struggling to read the URL in the contextual filter.
Is it possible to use PHP GET in the contextual filter to get the month and year and convert it to 062016?

if(isset($_GET[' field_month_value']))
    return $_GET[' field_month_value'];
else
    return;

I’m using D7. Thanks loads

From your question, I believe you want one exposed filter to reload the page when chosen and then all the other views on the page follow that filter?

A workaround if no one else answers is to expose the filter on all views and hide the ones you don't want with css. In each view, go to the filter's settings under Admin at the bottom and you can rename them all to field_month_value if they're different.


How to delete all translations when deleting a node using default language? I'm trying to delete all translations when deleting a node using default language?

For that purpose, I am using the hook_node_delete, but I am not able to invoke node_delete() from it. It cause a fatal error and the process can't terminate. Even the first node I am deleting isn't deleted preoperly.

 function hook_node_delete($node){
        $translation_list = translation_node_get_translations($node->tnid);
        $default_language = language_default()->language;

        if($translation_list!=""){
           foreach($translation_list as $translation_list_item){
              if ($translation_list_item->language!=$default_language){
                  node_delete($translation_list_item->nid);
              }
           };
        };
    }

So I am forced to simply unpublish the translations by doing something like that:

 function hook_node_delete($node){
                $translation_list = translation_node_get_translations($node->tnid);
                $default_language = language_default()->language;

                if($translation_list!=""){
                   foreach($translation_list as $translation_list_item){
                      if ($translation_list_item->language!=$default_language){
                          $node_translated = node_load($translation_list_item->nid);
                          $node_translated->status = 0;
                          node_save($node_translated);
                      }
                   };
                };
            }

Why can I not invoke node_delete() from hook_node_delete()??

you first have to remove the nodes from the translation set before you can delete them. So do something like this:

function hook_node_delete($node){
    $all = translation_node_get_translations($node->tnid);

    foreach($all as $del){
        if($node->nid != $del->nid){
            translation_remove_from_set(node_load($del->nid));
            node_delete($del->nid);
        }
    }
}


Filter to display articles from the last edition date only I have a magazine type project but articles are grouped into editions(issues). So I have 2 content-types interconnected using node reference.

What I need is to create a view to display only the articles of the last edition on frontpage. I can use a criteria of edition date or edition number (need the last one). Unfortunately I cannot find how to do do it. What value of the operator to enter.

What if you filter by Edition Date, order it by descending, and display only first value?

It should give you the last available edition, if I'm not mistaken.


How do I get the current language in custom user edit Twig file? I have a custom user profile edit twig file.How can i check current language code in user twig file in drupal8?

You can check language in twig as below:

{% if (language.getId() == 'en') %}
    Do something
{% endif %}


Exclude configuration from import/export I thought this was a simple use case of the new Configuration management system, but I haven't had any luck finding out how to solve this:

Problem

I want to store configuration in git and use drush to export configuration during development and then on deployment import the configuration. Pretty similar to doing a features revert in Drupal 7. My problem is that I don't want to store access codes in git for various integrations. This results in these configurations being deleted on
$ drush cim -y

Where I looked

I was hoping there would be a simple list/configuration for configs that should be excluded on import/export. It seems there was at some point but it must have been removed again, since it's available at present Drupal 8 release.

I looked into how config changes are being made comparing the active and sync storange to see if there as a place where I could remove changes, this didn't seem to be the case.
I looked at how drush does the configuration import as it has some configuration excludes of it's own, but it didn't look like this was extensible.
I looked at ConfigEvents, but these all seem to happen after an import, so doesn't look like this can be used.

Am I missing something, or is it not possible to simply exclude configs from import/export?

You can use the "Config Ignore" module: https://www.drupal.org/project/config_ignore

Ever experienced that your site's configuration was overridden by the configuration on the filesystem, when doing a drush cim?
Not anymore!
This module is a tool to let you keep the configuration you want, in place.


Automating module activation during installation of Drupal I want to add some modules in an installation profile, so that they are automatically installed during installation. Some modules need to be configured before using them.

Is it possible to do it?

You can create a custom installation profile

  Installation profiles combine core Drupal, contributed modules, themes, and pre-defined configuration into one download. Installation profiles provide specific site features and functions for a specific purpose or type of site. They make it possible to quickly set up a complex, use-specific site in fewer steps than if installing and configuring elements individually.

See How to write a Drupal 7 installation profile and the Install profile API for more info.


Drupal form #states using OR I am trying to make a part of my form display depending on the state of a select box. The select box code is:

$form['product_type'] = array(
    '#type' => 'select',
    '#title' => t('Product Type'),
    '#options' => array(
      'a' => t('a'),
      'b' => t('b'),
      'c' => t('c'),
    ),
    '#required' => TRUE,
  );

I then have a field when I only wan to show it when the value is b or c.

$form['problem'] = array(
    '#type' => 'textarea',
    '#title' => t('Problem'),
    '#states' => array(
      'visible' => array(
        array(
           ':input[name="product_type"]'=> array('value' => 'b'),
           ':input[name="product_type"]'=> array('value' => 'c'),
        ),
      ),
    ),
  );

What is happening is that what ever the last value in the page is being used.
I have found the following pages https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_states/7 & https://drupal.org/node/1464758 but am still lost.

it is no right at all, this is the right way to make an OR:

$form['problem'] = array(
  '#type' => 'textarea',
  '#title' => t('Problem'),
  '#states' => array(
    'visible' => array(
      array(
        ':input[name="product_type"]'=> array(
          array('value' => 'b'),
          array('value' => 'c'),
        ),
      ),
    ),
  ),
);

Regards


I get 404 when uploading private *image* files in D7 I have this Drupal 7.15 site (it needs an upgrade, I know).

I have some public and private files in there (all according to my settings). I have a public file field and a private file field.

So, using my private field, I can upload some files that are set to private (I've set the allowed extensions as: .zip, .pdf, .jpg, .png, .gif, and some more). I'm the only user allowed to use the private field.

When I upload an image file (png, jpg or gif), it does get uploaded ok, but when trying to click on the link I get a "404 error". When there's any other file type uploaded, everything works just fine.

The private files field is inside a content type that is set as a "group content type".

All files get uploaded ok and they do appear at the list of uploaded files in the normal way.

Some configuration information

My Apache file handler is mode_php (aka DSO).
Permissions and file owner of all files (images or not) are the very same: rw-rw-r-- (664)
Group and owner are the same too (images or not): nobody and nobody
All files are being uploaded to the same folder: ../files/private/filename.ext
All files get the same symlink: ../system/files/filename.ext

But only the pdf file is accessible to users (with perms to view the node). Even as an admin I get the 404 error when trying to access the image files.

What's wrong?

First, have you already checked the status report (/admin/reports/status)?

If that's all green then do you can dig around the content type field settings and also the content type view fields settings to see if you're using any image styles on the images. If you are you need to make sure the folder sites/default/files/styles has proper access perms.


How to use the Tabs module? I've installed the Tabs module, but I don't know how to use it.

Can anyone help me, please?

I guess you're talking about tabs

As it is written on the page :

  The tabs module integrates the jQuery UI tabs plugin, providing client-side interactive tabs. This is a helper module. It doesn't do anything on its own. Rather, it is used by other modules that provide tabs.

If you are not a coder, don't use this module.
If there is not any module that ask you to install this module, don't use this module.

If you want some tabs to break long pages into smaller ones, have a look on paging module.

If you just want to add some tabs like "Views," "Edit," etc on nodes, this is handled by core code; have a look to the API, especially hook_menu().


Validation programmatically in Drupal I am creating a user programatically.

I have following files

$fields = array(

    'name' => $name,
    'mail' => $mail,
    'pass' => $password,
    'status' => 1,
    'init' => $mail,
    'field_first_name' =>array('und'=>array(0=>array('value'=>$first_name))),
    'field_last_name' => array('und'=>array(0=>array('value'=>$last_name))),
    'field_company_name'=>array('und'=>array(0=>array('value'=>$company_name))),
    'field_company_number'=>array('und'=>array(0=>array('value'=>$company_number))),
    'field_mobile_number'=>array('und'=>array(0=>array('value'=>$mobile_number))),
    'field_secondary_number'=>array('und'=>array(0=>array('value'=>$secondary_number))),
    'field_mobile_or_landline'=>array('und'=>array(0=>array('value'=>$landlinemobile))),
    'field_promo_emails_notifications'=>array('und'=>array(0=>array('value'=>$email_notification))),

);

Now i am using user_save(NULL,$fields);

Which is working fine. Now field_first_name, and some other fields are required which i have set under account mangefields. How to check validations of these fields. Does anybody tell me

Thanks

Validation is pretty much depends on what kind of fields are they! Still I can show validation for the common fields as on user registration process.

You must be hooking into the user registration form somewhere, unless form is custom form.Assuming you are implementing hook_form_alter() to hook into user registration form.

> Step 1: Add validation handler to the user registration form.

    // Implementing hook_form_alter() to add validation handler to user registration form.
    function mymodulename_form_alter($form,$form_state,$form_id) {

    // Not sure you have to check form id of the user registration form.
      if($form_id == "user_registration") {
        $form['#validate'] = array(
          '#validate' => array('_mymodulename_registration_validate'),
        );
      }
    }

    // Write validation callback.
    function _mymodulename_registration_validate(&$form,&$form_state) {
       // Validate last name.
      if (trim($form_state['values']['last_name']) == '') {
        form_set_error('last_name', 'Last Name field is required field');
      }

      // Validate company name.
      if (trim($form_state['values']['company_name']) == '') {
        form_set_error('company_name', 'Company Name field is required field');
      }

      // Validate the e-mail address.
      if (!valid_email_address(trim($form_state['values']['email']))) {
        form_set_error('email', 'Please enter valid email address');
      }
      if (_mymodulename_registration_user_validate_mail(trim($form_state['values']['email'])) == 1) {
        form_set_error('email', 'Email address already registered');
      }
        // Validate password.
      if (trim($form_state['values']['password']) == '') {
        form_set_error('password', 'Password field is required');
      }
      if (trim($form_state['values']['password_confirm']) == '') {
        form_set_error('password_confirm', 'Repeat password field is required');
      }
      if (trim($form_state['values']['password_confirm']) != trim($form_state['values']['password'])) {
        form_set_error('password_confirm', 'Passwords do not match');
      }
    }

/**
 * Helper function to validate email adress already exists or not.
 *
 */
function _mymodulename_registration_user_validate_mail($email) {

  // used db_query_range() to check if email exists or not.
  if ((bool) db_query_range("SELECT mail FROM {users} WHERE mail = :name", 0, 1, array(':name' => $email))->fetchField()) {
    return 1;
  } return 2;
}


Hide blocks in node page using context i am new to context module and based on some tutorial i have used context. Now my problem is,

Currently, I have created one context which will show default header logo in all the pages. Now got new requirement to show different logo on the node pages with selected taxonomy terms.

For this i created one more context and used taxonomy conditions with selected taxonomy terms for the different header logo. when i visit the page, i got two logos in the header section, so i edited the first context and added the taxonomy condition and selected those taxonomy terms and set the "No" to "Set on node form" option.

You know whats happens, the default logo gets disappear from all the pages but still showing two logos in the node pages with the selected Taxonomy terms pages.

I am not sure what condition to set to show in all the pages except in those selected taxonomy terms pages. Could you please someone guide me on this.

This should work... Context allows contexts to be fired based on the presence of other contexts. So in your "global" context, you can add the condition 'Context(all)' and then add ~[taxonomy_context_id]. Where taxonomy_context_id is the id of the taxonomy context. Make sure that "Require all conditions" is checked. And save.

Now the "global" context should only show when the the other isn't available.

Recommendation: If you are looking to switch logos based on taxonomy term, you can use template_preprocess_page() to switch out the path of the logo based on the current menu_object that is loading. This allows for you to have a global context that persists and doesn't duplicate the work/blocks and provides an override to the page.tpl.php variables instead of multiple possibly conflicting context.


Choose node item from list and add to form I have content type 'Machinery' and I need to create the form for users where they can enter their name, email, phone number and to select some node from a list and attach it to form.

The user can select unlimited items and when click on 'Add' to add to form.

In this way, the user has the option to attach some machines to the form and send a request for renting those machines. Email that will be sent from this form needs to contain all fields along with the list of added machines.

Since I need this content type because I'm using it for another page to show the list of available machines, I need to create the form in this way so when I add new machine (node) it's automatically available on this list in the form.

Any idea how I can do this? Is there some way to create form through Views so I can add this list field?

I'm working on Drupal 8.

I'm not sure what kind of form your question is about. You say, you want to e-mail the result, so this is probably a Contact form.

Here you can add a reference field for content and then configure this field for the content type "Machinery". You can set this to unlimited values, so that you can add multiple machines. The default is an autocomplete field. You can change this to a select list in "Manage form display".


Problem with change position of Sidebar I am using the Droupon theme of Drupal. I am facing problem while changing the sidebar from right to left. Using CSS I can change it. But I want to know if I can change the position of the sidebar from admin panel without any modification in the CSS.

Thanks
Subha.

If it is available in theme options at http://example.com/admin/appearance/settings/drupon then you can.
If Drupon provides both "left sidebar" and "right sidebar" regions, you can move blocks from one region to the other at http://example.com/admin/structure/block
If it's compatible with Panels or other fast theming system, see it's documentation
If none above, you need to subtheme to alter CSS or structure.


How do I use a display mode for anonymous users, and another one for logged-in users? I would like to change the display mode only for entity.node.canonical, so that a logged-in user would see something completely different than anonymous users.

For example, an entity displayed by an entity reference field should be displayed in teaser mode for anonymous users, and in full mode for logged-in users.

How can I achieve this?

This is similar to How do I change the node view mode before rendering?, only that you want to add conditions for the route name and the current user:

/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article') {
    if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
      if (\Drupal::currentUser()->isAnonymous()) {
        $view_mode = 'teaser';
      }
    }
  }
}