Show nodes contaning same company term in Views I need to show a block on a node page which will show all nodes containing same company name taxonomy term.

What is the way to do it? I've tried adding a field_company term relationship but it's not working.

A product whose company term contains Samsung so when this product(node) is viewed I want to display other products from same company Samsung.

Create a new block view either selecting the single content type or all. Now, we will add two contextual filters. Content Id and the field which has taxonomy term id.

Configure Content Id filter as follows:

Provide default value: Content ID from URL
Under More tab - Check next to Exclude

Configure field which has taxonomy term id as follows:

Provide default value: Taxonomy term ID from URL
Uncheck: Load default filter from term page
Check next to Load default filter from node page, that's good for related taxonomy block
Multiple value handling: Filter items that share any value.
Under more tab check: Allow multiple values.

That's it. After saving your view go to bock page and enable it where ever you want.


How do I check if a link exists in a page? There is a form having a link clicking on which field set will be collapsed to show fields under it. HTML is shown as below.

    Hide
    Attach

How would I go about checking if this link exists (to click on it), and the fields under it are shown?

To answer my own question, I realized (even without clicking on the link) that fields can be asserted by DrupalWebTestCase::assertFieldByName().


Reset password in Drupal 6? My site is on localhost and I have access to database too. This is the structure of "users" table:

The password field is of type "varchar(32)" having collection "utf8_general_ci". I tried to decrypt the password online but it displays that password can't decrypted.

I manually updated the table and changed the password using md5 but whenever I try to login to the site as admin, it displays "Access Denied".

How to change the password for site?

Option 1 - Ask for a password reset link

If eMail is working in your site, ask for a password reset link. Use that link to then reset the password.

Option 2 - Use Drush

If you have Drush available, then you can use eiher of these Drush commands:

drush upwd --password="NewPsw" "username", to reset the password for username to NewPsw.
drush uli username, to generate a 1 time login link for username.

Option 3 - Copy an encrypted password that you know

Just copy the encrypted password from the same user table from any other user for which you know the password. Then paste that encrypted password in the record for your admin user. You should then be able to use that password for login with your admin user.

If you don't have another user yet (or don't know any of their passwords), then use standard Drupal facilities to create a new user first (and remember the new user's password).

If you don't have any user that is allowed to create new users (or you can't login with such new user), then (temporarily) create a new Drupal site and use the user/1 password of that new site.

Option 4 - Create a new admin user

Insert a new user in the "user" table (with an encrypted password for which you know the password). And make that new user an administrator also by inserting an appropriate row in the "user_roles" table (cloned from the row related to the user/1).

Then use the newly created user to perform a reset of the password for the admin user.


Send message to customer after the order has been created by administrator I use Drupal Commerce version 7.x-1.x. I want to Send message to customer automatically after the order has been created by administrator on page admin/commerce/orders/add. How can i done it with rules or hooks (for example mymodule_form_commerce_order_ui_order_form_alter) or other ways....

You could do that by adding a rule to fire on order update and checking to see if the order the order status was previously somestate and the current state now processing or completed.

Of course, you'd have to ensure that the states you wanted match your workflow.


Views Bulk Operations Modify entity values on one form I am trying to use VBO to update order status on entities.
When using "Modify entity values" it shows 'Modify entity values' on vbo dropdown and then it redirects to a page with dropdown with all the options.

How to make it all on one form so I could check rows and then select (eg.) an order status option?

Is there any module or do I have to go programmatically through this journey?

Thanks

Try creating a custom action in Rules that sets the entity value to the one you want rather than prompting for the value.  Then activate that action in your VBO view.

You can make new rules components at mysite/admin/config/workflow/rules/components/add


How to handle a lot of simple unique URLs (for click's statistics)? I need to create a lot of simple unique URLs (for click's statistics).
Each such URL consist of several parameters (project_name, unique_ID, etc).

Examples:
example.com/project1_id35 or
example.com/project1/id35 or
project1.example.com/id35 ...

I plan to use Rules to decipher these URLs and to save it to database.

But how Drupal site can catch all such URLs?
It's really hard to make aliases for every case.

May be mod_rewrite can help?
Or is there any useful module for such task?

PS. It seems mod_rewrite the best solution.
PPS. Another possible solution: override 404 page.

A great module to aliases auto-generation is PathAuto. It will allow you to define patterns to your url's using tokens, things like:

article/[title-raw]

will generate:

www.example.com/article/my-blog-post

Once you install the module, go to:

Administration > Configuration > Search and metadata > URL aliases, in the "Patterns tab" (admin/config/search/path/patterns).


The "Add another item" button doesn't work with field groups I am working on a site that uses a lot of horizontal field groups. I am having a problem where any fields that sit in a field group and have "unlimited" set for the number of entries is unable to use the "Add another item" button. The AJAX call is returning some JS settings but no HTML.

The fields themselves range from simple text fields to node references. If a field is not residing in a field group then it works fine.

I will point out that I am using Drupal 7 and field_group version 7.x-1.1.

It seems that the Drupal core is unable to properly identify which button was clicked and so has not idea how to respond.

another option is to use the field_collection as described here: http://openconcept.ca/blog/mducharme/creating-multiple-value-field-groups-drupal-7

i'd like to see this in field_group to though - as the detour of making collections under 'structure' isn't as intuitive as under 'manage fields'


Line breaks on seperated Tags When I comma seperate my tags to make individual tags, drupal tend to put a linebreak behind every individual tag.

What happens:

That means that I need to make 1 huge tag, which is not factual.

I am Pretty newbie when it comes to drupal but this is kinda annoying.

Thanks in advance.

This is just how out of the box drupal styles the tags fields.

You can fix it by overriding the themeing of your tags in your theme, but the easiest way I have seen to fix it is by using the Text list formatter module.

Install that then go to the display settings for your content type and there will be a new option "List", which then has further configuration options that can give you the output you desire.


Printing out path from views - /drupal/ appears twice I'm using this to print out a custom link format in views. I'm using it in the unformatted views tpl.php file.

<?php print l(' a',
              $view->style_plugin->row_tokens[$id]['[path]'],
              array ('html' => TRUE)); ?>

This line calls the relevant HTML path:

$view->style_plugin->row_tokens[$id]['[path]']

For example it might contain the value: localhost/drupal/node/31.

But when I put it in the l() function I get localhost/drupal//drupal/node/31.

Anyone know how I can stop the double print out? This is driving me mad.

<?php print l('',
'node/' . $view->result[$id]->_field_data['nid']['entity']->vid,
array ('html' => TRUE)); ?>

Here is the final solution.

It will add the NID on the end of node/ and create the internal path "node/x". If you're using Pathauto this will still work.


Store anonymous user selection temporarily until registration I want to let my first time visitors to first select a city, which will control what they see in my site, so it should be stored where I can see it everywhere (views, search and when posting content) until the user registers which then I store it in the user profile for later use.

Is that possible without development?
if development is mandatory, what are the right steps to do so?

I want to let my first time visitors to first select a city.

okk... so is this selection apart of say their Registration Process, if so you have 0 code to write? or some other random landing page on the site you are funneling new traffic too ... in which case you have to write some code ...

Anyways I would:

Add a field like user_location to their Account Profile fields under Admin -> Account Settings -> Manage Fields ... or use the Profile module to add such a field to a profile. There are "location" contributed modules for location type drupal Fields as well ... not sure what or how you want to store a "city" reference (string, geocode, zip, country + city, whatever).
Then that field will be available everywhere as apart of the $user object.

If, you want this field to be collected before a user has registered (or separate from the registration process -- any fields in a users account settings can be made apart of the registration process). I would:

create a simple module and define a FAPI form with a country list. The list_predefined_options module may help you make this list and manage it in code ...
store the value in the users Cookie session value. Upon login use hook_user_login to look for the cookie value on 1st login to update the account user_location field with the session value.

Good luck.


How to selectively import and export specific content without overriding existing destination database? I want my client to contribute content to the website, but the problem is, I'm simultaneously doing work on the site, modules, theming, adding stuff also etc...

I'm aware of the features module and can import and export selective tables with backup migrate or even phpmy admin, but it's tedious and error prone...

What data I want to import and export is:

- Content type
- Taxonomies
- Content itself including text and images(can ftp them manually no problem)

What would be an easy and simple solution for this without getting into code or shell access?

As you already mentioned, use features module to transfer configuration.

For actual content, you will need to use Views Data Export to export stuff. Make a CSV file.

VDE tutorial

Then use Feeds module to import the CSV file content into your other site.

Feeds Tutorial

Alternatively, for nodes you could just use Node Export, but you will still need feeds for the taxonomy importing.


Limit certain users from filling webform based on their location I have a contact us form, that I want only users from the US to see, fill and submit.
And the other users to see that form but a message says "web form is not available in your country" if the user is from outside the sates.
Is there a module to do so? or I just have to make my own? thanks.

You can use a module like Smart IP http://drupal.org/project/smart_ip, GeoIP http://drupal.org/project/geoip or just the Maxmind Geolite http://www.maxmind.com/app/geolitecountry table to look use the IP address of the user to determine the country.

Then use hook_nodeapi() or hook_node_view(), depending on if you are using Drupal 6 or 7, to redirect the person based on the country.

The pseudo code would look something like this (Drupal 6, using Geoip):

function MYMODULE_custom_nodeapi(&$node, $op) {
  switch ($op) {
    case 'view':
      if ($node->nid == 'NODEID OF WEBFORM') {
        $country = geoip_country_code();
        if (isset($country) && $country != 'us') {
          drupal_goto('node/' . NODEID OF REDIRECT PAGE');
        }
      }
     break;
  }
}

edit: When I saw 'webform' I assumed you meant using the webform module, hence the nodeapi, but if you are using the basic site contact form you can use hook_menu and create a new callback for the path of the form you are using and create the same kind of check as above.


Can I change the default tab at /admin without losing access to /admin/tasks? Below I have changed the default tab at /admin to /admin/index, but now /admin/tasks is 403.  Even if I change $items['admin/tasks']['access callback'] to TRUE I'm still denied access.

function hook_menu_alter(&$items) {
  $items['admin/tasks']['page callback'] = 'system_admin_menu_block_page';
  $items['admin/tasks']['access arguments'] = $items['admin']['access arguments'];
  $items['admin/tasks']['file'] = $items['admin']['file'];
  $items['admin/tasks']['type'] = MENU_LOCAL_TASK;

  $items['admin']['page callback'] = $items['admin/index']['page callback'];

  $items['admin/index']['type'] = MENU_DEFAULT_LOCAL_TASK;
  unset($items['admin/index']['page callback']);
  unset($items['admin/index']['access arguments']);
  unset($items['admin/index']['file']);
}

How can I both restore access to /admin/tasks and set the default tab to /admin/index?

Resolution: The admin module was the problem.  It's enabled by default in my installation profile.

please find this code to do this

function hook_menu_alter(&$items) {
$a_title = $items['admin']['title'];
$admin = $items['admin'];
$t_title = $items['admin/tasks']['title'];
$tasks = $items['admin/tasks'];
$i_title = $items['admin/index']['title'];
$index = $items['admin/index'];
$items['admin/tasks'] = $admin;
$items['admin/tasks']['title'] = $t_title;
$items['admin/tasks']['type'] = MENU_LOCAL_TASK;
$items['admin'] = $index;
$items['admin']['title'] = $a_title;
unset($items['admin']['type']);
unset($items['admin/index']);
$items['admin/index'] = $tasks;
$items['admin/index']['title'] = $i_title;
}


How do you use drupal's devel krumo ddebug_backtrace()? I've been trying to debug a weird bug on Drupal 7 for awhile. It happens randomly on my site as it's hard to reproduce. I'm able to finally get ddebug_backtrace() to run when the error happens. The error breaks all of my views on the site when it happens and throws the following error:

  Warning: include(/home/xxx/public_html/.tpl.php): failed to open stream: No such file or directory in theme_render_template() (line 1534 of /home/xxx/public_html/includes/theme.inc).

It's complaining that theme_render_template() can't find a template file as the variable given to the function is just .tpl.php.

I'm able to insert an if statement when this happens within that function as this:

  if($template_file == '.tpl.php') {
    ddebug_backtrace();
    print_r('
xxxx');
    print_r('TEMPLATE FILE: ');
      print_r($template_file);
    print_r('
');
  }

I'm able to get the debug output in krumo as shown below. I'm not exactly sure what I should be looking for. I just understand that each numbered line represents where that function was called within that order. But what I'm trying to look for is a blank variable of some sort which makes it output .tpl.php to give such an error.

Judging from the output, the culprit is the Views module, but I'm not sure where. What should I be looking for exactly?

This bug was quite annoying to solve. What I did was:

Isolate the variable that was causing the issue.
Setup a conditional to detect this variable when it happens.
Add drupal's ddebug_backtrace() to the conditional.
Trace back to where the function was being called up.
Find out how that problematic variable is being passed in.
Keep following the backtrace to the point where that variable is assigned and not just passed along to another function. In my case it was in theme() that assigned the blank variable $template_file.
From there I needed to know when theme() was being called. The original backtrace didn't leave any clues to which module was calling it aside from views, but views gets called all over the place. Now I needed to find the module that was calling views.
In theme() there were a bunch of hook variables that gave the hint of where it was coming from. I dpm() all the $hook and $hooks variables and it showed the error was happening when a "display suite" hook was being called.
In the end all I needed to do was uncheck this box. I still don't know why it caused the issue randomly... -_-

My debug code to get the output I needed:


How to get user all order_items from different orders by entityQuery I want to know if the user has purchased the specified product. I know the SQL. But I am learning to use entityQuery.
Example: user_id = 1, product_variant_id = 5
SELECT *
FROM commerce_order
    INNER JOIN commerce_order_item ON commerce_order.order_id = commerce_order_item.order_id
WHERE (commerce_order.state = 'completed')
    AND (commerce_order.uid = 1)
    AND (commerce_order_item.purchased_entity = 5)
ORDER BY commerce_order.completed DESC

Could anyone help me tansfer to entityQuery?

Unfortunately, what you want to do isn't possible with an entity query, because that API does not support the appropriate joins. While you can simulate a join between a base entity and field value tables with field conditions, you cannot query against field values of referenced entities. If all you needed were order items referencing the order ID and specific purchasable entity ID, you'd be fine to write a single entity query against the order item table, but once you need to filter by order status (or support multiple purchasable entity types), you need to use \Drupal::database()->select().
To build a select query for this, I'd use the following:
$uid = 1;
$entity_id = 1;
$state = 'completed';

$query = \Drupal::database()->select('commerce_order', 'co');
$query->leftjoin('commerce_order_item', 'coi', 'co.order_id = coi.order_id');
$query->fields('co', ['order_id']);
$query->condition('co.state', $state);
$query->condition('co.uid', $uid);
$query->condition('coi.purchased_entity', $entity_id);
$result = $query->distinct()->countQuery()->execute()->fetchField();

The main change between your query and this code is that I'm fetching a count of the distinct number of orders. If you're trying to get the order IDs, remove the countQuery() and replace the fetchField() call with fetchAllKeyed(0, 0). If you really just want to search for a non zero count, you can remove the distinct() for faster query performance.


External RSS Feed in View I am looking for a module or way to use an external RSS feed in a view. I know this was easily done in Drupal 6, but I can't seem to find much on Drupal 7.

I am trying to use Views RSS, but there is very limited documentation.

The simplest method is to use the Aggregator module included in core.

Enable the 'aggregator' module in core
Add your RSS feed in Configuration > Web services > Feed aggregator
On the same page, click 'update items' for your feed to retrieve the RSS feed and parse the items
Create a view that will show 'Aggregator items'
(Optional step for multiple feeds) Add a filter criteria for 'Aggregator feed: Title' to only show items from the specified feed

To do more advanced functionality you will need to use the Feeds module from contrib. That module will parse the fields from a feed into content nodes.


Combining Feeds (with teasers) on the homepage? I want to combine several feeds (several internal blogs from my site and several external feeds) and post them on the homepage.  I want to use teasers to only show part of each post.

How should I do this?

I have been trying to use the aggregator module and the feeds_block that it creates out of all the feeds, however it shows the entire posts. I want teasers.

I used the aggregator module and then added the Views block called "feed_block" on the homepage (and only the homepage).  So the blog posts appear just below my introduction to our organization page (that is published to front and stickied).

The aggregator module has all of my external feeds (from other sites). It combines them into a category (I'm not sure if this part is necessary).

The homepage then displays everything from aggregator and also any locally created blog posts (anything with a content-type of "blog").

I might replace this solution with the Feeds module - as the aggregator module does not remove items when the original item is deleted (unless you remove all items and them update them for that feed). Also the feed_block has a "more" link that is broken. It links to the www.domain.org page, when it should link to the node.


Adding conditional statements to custom text fields in views I have custom text fields set to display two items as follows:

  [field_title]: [field_subtitle]

Is there a way I can get rid of the colon if the subtitle field has no value? via php or javascript?

Sure.

Edit both fields -- [field_title] and [field_subtitle] -- so that both are "exluded from display"
Edit [field_subtitle], and select Rewrite the output of this field

In the box for the rewritten value, enter : [field_subtitle]
Make sure Hide rewriting if empty is checked at the bottom

Create a third field whose type is Global: custom text

Unlike the first two existing fields, do not check the Exclude from display box -- leave this one visible
In the Text box for that field (the value), enter [field_title][field_subtitle] (no spaces in between)

Hope that helps... :)


Views_view_result and Devel possible incompatibility I have experienced a very strange behaviour of Drupal 7. I had Devel module activated, and a View which made the sql logs to disappear from screen. The view was used by views_get_view_result(). When I have changed the exact code to use views_embed_view(), with the same and exact rendering, the SQL logs started to appear again.

Is there some Drupal 7 expert (ninja level suspected) out there that can understand what could happen? The bug was consistent, it always happened in the same View config (I replicated different Views with different names and the behaviour always appeared at the same point).

The configuration that caused the problem was:

Field collection
View with field collection
Contextual filter (here it started to ignore sql log output)
Call to the function views_view_result. Even the call itself, without using the value, caused the problem.

Solution: Call views_view_embed() instead. No problem anymore. Same contextual filters, and blocks used. Exact configuration and exact output than views_view_result().

Note: I need an explanation of why this is happening, and a possible solution. The output of the SQL logging is not sent to the HTML source output of the page.

Code used. The commented lines do not work, and are substituted by the non-commented lines above them. The function is supossed to return an integer.

 function sacar_numero_productos($id_categorias, $marca){
     $marca = str_replace("/", "", $marca);
     $a = views_embed_view("numero_productos", "block_1", $id_categorias, $marca);
    // LINE BELOW DOES WORK BUT DESTROYS THE OUPUT OF SQL QUERIES
    //$a = views_get_view_result("numero_productos", "block_1", $id_categorias, $marca);

return (int)(trim(strip_tags($a)));

   // IF I USE views_get_view_result, this is the return value instead.
   /*if(isset($a[0]->field_data_field_id_unico_oem_field_id_unico_oem_value) && (int)$a[0]->field_data_field_id_unico_oem_field_id_unico_oem_value > 0){
       return (int)$a[0]->field_data_field_id_unico_oem_field_id_unico_oem_value;
    } // if*/
    return 0;
} // function

The short answer: Devel is not incompatible with Views.

The longer answer:

The difference between views_embed_view and views_get_view_result is essentially that views_embed_view renders the view while views_get_view_result only executes it. The code for the two processes are almost identical, but the difference is that views_embed_view does more as part of the render process. You can see the details in view::render.

The gist of it is that when embedding the view, you get views to do a lot more things, like initializing the theme, invoking more hooks.

Best guess for where your problem lies would be some other module integrating with views and/or devel or some other details you haven't written in your question.

The devel query log works by using the core database log, starting it with hook_boot and getting the info with a shutdown function. There are some scenarios where devel will be silent, fx when doing redirects. There is a good chance, that the issue is related to how devel figures out when to be silent or not. It's near impossible to figure out the exact cause without being able to debug your exact site and configuration as any module / configuration can be the cause to what you are seeing. If you want to investigate you should look into

devel_silent()
devel_shutdown()
devel_shutdown_real()


Drupal 7 website layout/styling breaks all a sudden (random), how to debug? there are no logs One of my websites running Drupal 7 goes out of format, most often when user login.

This is how it should be

After running out of format this how it looks

This may be a CSS issue, it may be a caching issue, or it may be something else. As I know Drupal core code is almost perfect but contributed, custom modules and themes can spoil something by adding bad code.

After spending sometime doing research I come across many question and answer which were not that clear at all because there are many factors that can cause such a problem therefore it is really hard to say what is happening specially in some cases when there is no sign of error or warning.

For example in my case I am using Drupal7, Superfish menu  and following modules

addressfield, addressfield_staticmap, admin_views, ajax_register, auto_nodetitle, autoassignrole, backup_migrate, captcha, ckeditor, colorbox, content_access, css_injector, ctools, currency, custom_search, date, entity, entity_translation, faq, field_collection, field_permissions, field_slideshow, flexslider, flood_unblock, follow, galleria, gmap, google_analytics, i18n, i18nviews, image_captcha_refresh, jquery_update, l10n_update, lang_dropdown, languageicons, libraries, link, Location, login_destination, markup, menu_block, mlpanels, modal_forms, money, mortgage_calculator, page_manager_redirect, panels, pathauto, real_estate, realname, rules, select_translation, serial, simple_fb_connect, simple_gmp, simpleads, simplify, smart_ip, social_share, superfish, tablefield, tabtamer, taxonomy_acces, taxonomy_acces_fix, taxonomy_csv, token, translation_overview, unique_field, user_role_field, variable, viewfield, view, view_bulk_operation, views_content_cache, views_data_export, views_field, views_horizontal_slider, views_jqfx, views_jqfx_Cycle, views_php, view_Slideshow, views_slideshow_galleria, workspace, wysiwyg

The website is hosted in Cpanel

Itry may options to look for the error and identify the problem which where not helpful at all, I tried Mozilla browser and Firebug and there is no error or warning at all. I tried to add parameters into setting.php

error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

And still nothing changed. finally I decided to post the question here and ask all the great and genius developer to post their view and solution on:

What can cause a Drupal website to run out of format and broke the layout
What are the available tools or option that we can use to debug a Drupal

Can anyone please explain how to debug Drupal and deal with theme issue  in a step-by-step way to make it simpler for everybody?

Above all, I assume that you have Google Analytics Installed. Go to the Behaviours menu and from there look at Site Speed and Page Timings to see how much times it takes to load a page. Use the Speed Suggestion option to allow Google suggest you a number of fixes/tricks that can potentially improve the performance of your web page. This is very handy.

This is clearly a problem of CSS. Open your site in chrome, enable the development tool F12 and then keep refreshing and monitor Network and Console windows. I observed that every reload of the page causes a request to a CSS to break (hence the resource is never downloaded - each time a different CSS from a different module).

It would be a great idea if you could give this module a go https://www.drupal.org/project/advagg, I highly recommend that you aggregate all your site's CSS into few or single CSS file.

It is always better to download one slighty larger file than make over a hundred calls to a web server requesting for tiny tiny CSS files, because there is high chance that your request fail or die (to to waiting).

I will update my answer with more findings but, give that module and a go and let us know your findings.


How do I find the max length of a field (e.g. title field) I would like to retrieve the maximum length of a field programmatically, for instance the $node->title field .

I am writing a module that sets title and I don't really want to hard-code '255'. I am using Drupal 7.

The Drupal schema API has a function named drupal_get_schema (D7) or drupal_get_module_schema (D8) that lets you inspect a schema programatically and retrieve field constraints.

For instance, to get the maxlength of the title field in the {node} table, you can use the following in D7:

$schema = drupal_get_schema('node');
$maxlength = $schema['fields']['title']['length'];

You can also inspect the max length of any field used by Drupal simply by looking at the database schema that defines that field.  This will also tell you the names you need to use in the above PHP to get the right value in cases where you're unfamiliar with the schema.

For instance, if you are talking about the title field in the {node} table, you can see when looking at a scheme in a database inspection tool such phpMyAdmin that it is a varchar with a maximum length of 255 characters.


SQL Error on Calendar View with Relationships I have a calendar set up to show a date field from nodes that I get using relationships.

The relationship goes:

Application > Discipline > School > Date Field

In my view I get this error when attempting to use that date field as an argument in the Calendar:

user warning: Unknown column 'node_data_field_school_term_deadline.field_school_term_deadline_value' in 'where clause' query: SELECT DISTINCT node.nid AS nid, node.title AS node_title, node.created AS node_created, node_node_data_field_discipline_school_node_data_field_school_term_deadline.field_school_term_deadline_value AS node_node_data_field_discipline_school_node_data_field_school_term_deadline_field_school_term_deadline_value, node_node_data_field_discipline_school.nid AS node_node_data_field_discipline_school_nid, node_node_data_field_discipline_school.type AS node_node_data_field_discipline_school_type, node_node_data_field_discipline_school.vid AS node_node_data_field_discipline_school_vid, node.changed AS node_changed, node.type AS node_type FROM node node LEFT JOIN content_type_application node_data_field_application_discipline_id ON node.vid = node_data_field_application_discipline_id.vid INNER JOIN node node_node_data_field_application_discipline_id ON node_data_field_application_discipline_id.field_application_discipline_id_nid = node_node_data_field_application_discipline_id.nid LEFT JOIN content_type_discipline node_node_data_field_application_discipline_id_node_data_field_discipline_school ON node_node_data_field_application_discipline_id.vid = node_node_data_field_application_discipline_id_node_data_field_discipline_school.vid INNER JOIN node node_node_data_field_discipline_school ON node_node_data_field_application_discipline_id_node_data_field_discipline_school.field_discipline_school_nid = node_node_data_field_discipline_school.nid INNER JOIN users users ON node.uid = users.uid LEFT JOIN content_type_school node_node_data_field_discipline_school_node_data_field_school_term_deadline ON node_node_data_field_discipline_school.vid = node_node_data_field_discipline_school_node_data_field_school_term_deadline.vid WHERE ((node.status = 1) AND (node.type in ('application')) AND (users.uid = 1)) AND ((DATE_FORMAT(STR_TO_DATE(node_data_field_school_term_deadline.field_school_term_deadline_value, '%Y-%m-%dT%T'), '%Y-%m') <= '2011-12' AND DATE_FORMAT(STR_TO_DATE(node_data_field_school_term_deadline.field_school_term_deadline_value, '%Y-%m-%dT%T'), '%Y-%m') >= '2011-12')) ORDER BY node_changed ASC in /var/www/clients/client4/web39/web/sites/all/modules/views/includes/view.inc on line 799.

I'm not sure why it would be an unknown column. I don't know sql very well so I don't know where to begin when debugging this.

Any suggestions?

Have you recently deleted a field which name was field_school_term_deadline ? If so your view used it and is broken now, just remove it from the list of fields.


Allowed memory size of 134217728 bytes exhausted in system\image.gd.inc reported for styled images There is a content type in my website that has an image field. Some contents have images that are larger than 20MB.

I created an image_style called fp which scales and resizes the images in 800X400px it works well but when the browser displays this resized version it reports the following error

  Allowed memory size of 134217728 bytes exhausted (tried to allocate 73834563 bytes) in modules/system/image.gd.inc on line 237

I know by increasing the memory_limit the problem will be solved (even though it is not recommended).

From what I know Drupal creates a distinct file of the original image for every image style, so in sites/default/files/styles/fp there is a resized version of the original image. It means when browser displays the resized image, the PHP needs no process to resize the image, it only displays another image which is the resized version. But why it displays the above error while it only needs to display an image (styled version) which its size is about 200kb ?

128M is somewhat low for a Drupal install.  It may work well for front end pages, but I have found that it needs to be raised for admin pages.  I do not know where you get the recommendation that anything over 128M isn't recommendation.  That PHP variable is a holdover from custom PHP to prevent infinite loops from crashing a system.  And remember, it is a max value.  Page requests that use less will not get the full amount.

You are running into the problem because GD needs to load the image into memory to process it down to 800x400 before saving it to disk and serving it up for display.  The problem isn't as much the file size, as what it will decompress to and occupy in memory.  When you start doing the math on big images (multiple width x height x 4), you will see that, 128M is way too low.  When the style has already been made, PHP never gets involved.

I believe the ImageMagick library will end up using the CLI convert utility, which can save PHP memory, but I don't recall the last time I actually tested this to be sure.


How to set a multi line value from drush vset I was trying to add a value to the drupal antibot antibot_form_ids variable.

drush vget antibot_form_ids

returns a string separated by /r/n
Adding just a value to this string isn't just enough.
If you do a
drush vset antibot_form_ids 'webform_*\r\nuser_login\r\n
and so on you end up with exactly this value in the form field of the config area.

So how can it be done?

Well, I just put my drush code in a text editor like this:

drush vset antibot_form_ids "webform_*
user_login
any_other_form
even_more_values" -y

Then copy & paste the whole statement to your command line and voila the values are set correctly.


How should I setup Drush to work with Drupal 8.8.1 using Git Bash on Windows 10 I am using a Windows computer and using Git Bash, I just installed a new 8.8.1 site and also did 'composer require drush/drush'. I can't use Drush from anywhere so I am wondering if I should have installed Drush globally on the computer.

No, you don't install Drush globally anymore. You install the Drush Launcher instead. It will provide you a global drush command that automagically uses the local Drush from each project.

  Drush Launcher

  A small wrapper around Drush for your global $PATH.


How to force regeneration of Twig templates? Twig generates classes for its templates. These classes are effectively caches by being written to disc.

Generally speaking, one probably doesn't need to bother with the details of how the twig templates are handled, but there could be cases when the Twig templates must be manually re-generated. (Similar to the need for the Registry rebuild module in D7)

If it's relevant, I'm asking because I'm stuck with an error that looks like this:

  Fatal error: Class '__TwigTemplate_ddad913164239ac659c2bca09b3a49a5' not found in core/lib/Drupal/Core/Template/TwigEnvironment.php on line 107

Not sure why you get that specific error, but have a look at drupal_flush_all_caches(), which does

PhpStorageFactory::get('twig')->deleteAll();

That said, I'm not sure if this will solve your problem, as I've never seen that error, not sure how it could end up expecting a class that is not there.


Take all sites in a multisite environment offline at the same time Is there an easy way to take all sites in a multisite environment offline at the same time, in just one step?  I really don't want to log in to each one and do it one at a time when I do something that involves all of them.

If you have drush installed you could use this snippet:

#!/bin/bash
sites[0] = "http://www1.example.com";
sites[1] = "http://www2.example.com";
sites[2] = "http://www3.example.com";

for site in $sites; do
  drush vset --always-set --uri=$site site_offline 1
done

I'm not an expert in sh scripting but something like that should work.


Reset button in Exposed Form of Views I have a view named search-form. In my view there are some fields like age, profession, education, etc. In this view I am using 2 buttons i.e. Submit & Reset. These buttons show from Exposed Form setting of View.

Submit button is working fine but whenever I click on the Reset button. It works like submit button. I have check through firebug. Found this <input type="submit" id="edit-reset" name="op" value="Reset" class="form-submit">. I think in place of 'submit', 'reset' need to set. How can I solve this. Please help. Thanks.

Download and install the Better Exposed Filters module. This module provides a "Include Reset button" when you are creating a View.
Hope that helps.


How can I use session variables in a report created with the Forena module? I've installed Forena Reports. It's basically working, but I have some questions (see bottom of post to get right to it).

What I want to accomplish is the following

I want an anonymous user of the module page to be able to export their recommendations as a CSV file with a link like 'download now' or something.

Here's the staging environment for the tool I'm talking about, so you can see how it works: http://staging.grantstation-pathfinder.com/pathfinder.

So, as you can see, here's what I have so far

I have a custom module that's a multi-step form. The module prints out each page of the form. The user selects one option on each page (3 pages total) and on the final page submits the form. The module then redirects the user to a 'recommendations' page (page 4 - modulename/recommendations) where some custom SQL prints out to the page recommended resources for that user based on their selections in the form.

The values the users select are saved in session variables.

Here's how those variables get stored as sessions in the form itself. (This is the second page of the form, but they are all basically the same.)

function pathfindertool_first_form($form, $form_state) {
 // .. some code, some other fields, directions, etc.
        '#default_value' => isset($values['role']) ? $values['role'] : NULL,
        '#options' => array(
        t('Grant Writer'),
        t('Nonprofit Administrator'),
        t('Nonprofit Founder'),
        t('Consultant'))
    );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
      );
      return $form;
    }

    /**
     * Submit handler for the first form.
     *
     * @see pathfindertool_first_form() above
     */
     function pathfindertool_first_form_submit($form, &$form_state) {
      $values = $form_state['values'];

      // Save values to the form storage, add the next step function callback
      $form_state['rebuild'] = TRUE;
      $form_state['storage']['role'] = $values['role'];
      // submit code
    }

On the recommendations page I call SQL and use the session variables to determine which recommendations to display to users.

Here's how I set the session variables and redirect the users to the recommendation's page.

$form_state['storage']['topic'] = $values['topic'];
// set session variables to be used on recommendations page
$_SESSION['role'] = $form_state['storage']['role'];
$_SESSION['level'] = $form_state['storage']['level'];
$_SESSION['topic'] = $form_state['storage']['topic'];
// when user clicks 'submit' redirect them to recommendations page
$form_state['redirect'] = 'pathfinder/recommendations';

I successfully installed and configured the Forena module, and it displays my tabular data from the SQL file I created with the parameters I manually set. The CSV download works too. That's all fine.

How do I ensure the Forena modules uses the session variables set by the user in the multi-page form (and not my predefined parameters)?

I'm not (yet) sure about this one, because of the "session variables" that aren't clear enough to me (yet) ... Below are a few techniques (features) that you may want to consider to get it to work.

1. Using JavaScript and/or Skins

A possible solution "might" be to think of some technique you can implement via a JavaScript. And then make that JavaScript available via what in Forena is called "skins" (used for e.g. theming a report, like to enable the 'DataTables' plugin if you want, etc).

There are some "interesting" issues in the Forena issue queue with some great examples (ideas) of things you can do (add to Forena) via JavaScripts and/or Skins. HEre are a few of them:

Using the dataTables plugin to format reports, via an appropriate "skin".
Making table headers sticky, note the comments nr 8 (using Drupal Behaviours) and nr 10 (adding some JavaScript library).

2. Specifying Report Parameters as part of the URL

Report Parameters are similar to using arguments in Views. You can specify them as part of the URL, by first adding a ?-mark, followed by the name of the report parameter, a =-sign, and then the parameter value. So something like ?state=VA that you append to the report URL.

To see it at work in the demo site, try this example which uses ?state=VA (watch the URL of it also). Then change the end of the URL to something like ?state=IL,  ?state=CA, etc. To be complete, you can also specify multiple parameters (+their values) in an URL.

So if you have a way to massage those session variables in a such string added to the URL, then the answer to your question is something like "pass them as report parameters via the URL".

3. Other approaches

If what is above won't work, then please add more details about those "session variabes" (so that I can refine/rework my answer accordingly).

And if we don't find a real answer, then its time to experience the "support" that comes with Forena, via its issue queue on D.O. ... After all, keep in mind that I'm only a co-maintainer of this module. When I'm stuck (or out of Forena-inspiration), I escalate such questions/issues to David (the module owner and creator or Forena).


How can I render a birthday field to display only Day and month I am trying to render a birthday field to display only Day and month.

user's birthday is 07/21/1971

When I print:

<?php print render($user_profile['field_birthday']);

I get this: Wednesday, July 21, 1971

I added this to get only day and month:

<?php print date("F jS", mktime(0,0,0,$account->profile_birthday["month"],$account->profile_birthday["day"])); ?><br>

it gives me this:
November 30th

Any idea why?
Thanks for any help, RJ

Go to /admin/config/regional/date-time/formats and select Add format. You will be prompted to enter a format string. This is a php date() formatting string. If you enter "F j" (without the quotes" the date format will be the full month name and the date eg April 11. Refer to the manual for a full list of options.

Then go to /admin/config/regional/date-time and select Add date type. Call your new type 'Birthday' and select the date format you just created from the select list.

Under /admin/config/people/accounts/display select your field and configure the display to use the 'Birthday' format.


How to check if a Vocabulary is translatable? In Drupal Core, I found the following code:

$entity instanceof TranslatableDataInterface && $entity->isTranslatable()

But it looks like it is not working for the Taxonomy vocabularies

This information is stored in configuration and you can retrieve it by using this service:

\Drupal::service('content_translation.manager')->isEnabled('taxonomy_term', 'my_vocab')

More info Where do I fetch myself complete definition for a bundle?


How can I manually add a subscription to an account using Commerce Subscription Product module? I am using the Commerce Subscription Product module 1.x and I would like to add a few accounts manually that have a subscription. How do I achieve this?

I've honestly only quickly glanced at it right now, but as far as I can tell, a valid subscription is simply the field field_commerce_sp_time having a value, in number of weeks the subscription is valid from today.

Thus, you should be able to simply edit the user entity as you usually would, and set any number of week you want. Note that the module ships with relevant permissions for editing the field, so you need to have the field_commerce_sp_validity permissions.

Similarly, you could directly insert the relevant value into the database with

db_insert('field_commerce_sp_time', 'fcst')
  ->fields(array(
    'entity_id' => $uid,
    'entity_type' => 'user',
    'value' => $number_of_weeks,
  ))
  ->execute();


How to use Drupal for managing a public website together with an intranet and an MSSQL database? I'm new to Drupal and I've been digging through the documentation to find out most of the features and possibilities of this software.

I'm asking you an advice in evaluating if Drupal could be the case for a CMS for a client of ours.

The client is an Italian public administration; right now they've got two sites: internet and intranet. The two sites feature different layouts and different content (some content is mirrored in both sites, some is only on internet and some is only on intranet). Right now everything is managed manually with classic xHTML and some programming.

In an effort to switch to a CMS (don't consider content migration right now) we have to deal with different infrastructure problems, such as:

the intranet site is behind a private LAN not accessible from outside
the internet site is on a DMZ with no link with the private LAN (and they want to stay it that way)
the client database option is SQL server (they could provide access on a shared database from both sites, this is ok, but it is the only link they could give)

So I have some trouble to find a good software that could solve most of their problems.
How to:

Let them have only one administration panel (content is managed only once)
Let them choose if the content added has to appear on one of the two or on both sites
How to sync the files uploaded on both sites (if files are stored in the db it shouldn't be a problem)
Is there some module that can let editors to insert images directly in articles (let's suppose they have wysisyg editors for content) and save those attachment in the db (same problem as n. 3)
Manage different layouts on sites and also different content organization (menù, views, blocks etc.)

What do you think about it?

Drupal can most of this very well.

Someone with more experience can address how it can be set up for Intranet and Internet. It can handle multiple sites linked with data from same database (Not sure if this is what you want).

User permissions can be defined effectively down to the smallest content level so restricting access based upon any user categories you choose is not a problem.

Drupal works from a database (MySQL), apache, and php.  Transferring data will not be a problem for an experienced DB manager.

Images are stored as separate files on the site with references in the DB.  Images can be handled in a variety of ways on any page display including direct insertion.

Page layouts can be handled either through layout themes that handle HTML and CSS management and are fully customizable.

Drupal is exceptionally flexible and can do just about anything you can imagine.  There are hundreds of modules to choose from (all free and open source).

Having said all that, doing sophisticated site features is not for beginners and there is a steep learning curve for new site developers.  Getting a sophisticated site up and running requires an experienced Drupal developer.  Some of them are on this site and you can find others at Drupal.org.


Using Rules and Content access to restrict node access after date The Goal

I am working on a way to shut off access to all nodes of a given type by setting their Content Access permissions to off, after a certain date has passed (and presuming that their access levels are not presently set to not allow anyone to see them, as I don't want this to trigger every time the rules run in a date range). Rules + Content Access was suggested to me in the #drupal IRC channel, but I'm not totally sure it is going to work.

What I've done so far

I have added a rule to be triggered when Cron Maintenance tasks run.
I added a "Data Comparison" rule to check site:current-date and see if it is past a certain value.

The Issue

When I go in to add the action of "Revoke Access By Role", I do not have the option to set on which content types I want the access revoked by. In fact, the only option in the selector is site:.

I have also attempted to add a node condition, but there is also no way to select any node fields, presumably because it's wanting to act on whatever triggered the event (i.e. Content Updated in the case of nodes), and since I've selected a cron I only have access to the site: parameters.

My Question

Is there a way to tell rules to change the content permissions for all nodes of a content type via a cron maintenance run, or will I need to write a custom method to be triggered via the rules condition? (Or a completely separate module for that matter).

A proposition:

Enable "Rules Sheduler" at /admin/modules.
Go to /admin/config/workflow/rules/components and create a component

Add new component:

Component plugin => Action set
"Continue"

Component plugin:

Specify the component name (e.g. Revoke node access component)

choose in the table:

Data type => Content
Label => Node:Component or Node or what you want
Machine name => node_component or node or what you want
Usage => Parameter
"Continue"

Add actions:

Select actions to add => Revoke access by role
Data selector: is set as node-component by default; this is the selector name you have specified in the table in the step above
In "Role-based access control settings" check roles you want to revoke access for view/edit/delete content
"Save"

Go to admin/config/workflow/rules and add new rule (Add new rule):

Add new rule:

specify the rule name (e.g. Revoke node access rule)
React on event => After saving new content
Restrict by type => optionally, choose a node type you want to apply this rule to
"Save"

Events:

(optionally) you may also add here "After updating existing content" event if the rule has to triggered on existing nodes

Conditions:

(optionally) add your additional conditions here

Actions:

Add action
Select the action to add => Schedule component evaluation
Component: Select yor component you have already created (Revoke node access component)
Continue
Scheduled evaluation date:
click the "Switch to data selection and specify" button and specify:

Data selector: node:created (or other date-based condition)
Add offset: optionally specfify an offset for the chosen data selector (e.g. 1 seconds)

Identifier: Specify an identifer ("A string used for identifying this task") which is visible (Rules) "Scheduler" (/admin/config/workflow/rules/schedule) and in "Recent log messages" (/admin/reports/dblog). You may use tokens/replacement patterns.
Node:Component:
Data selector => node
Save

What's this?

This solution triggers a rule after a new and/or existing node has been saved. The rule "schedules" the component with an action set - in our case, the action is to revoke node access to the checked user roles. After content has been added as new and or edited, the component revokes node access on nodes for specified roles as scheduled on cron run, e.g. adding new article now +1 sec makes it unaccessible (view/edit/delete) on next cron on > (node:created +1 sec).

Hint:

It is also possible to add Schedule component evaluation as an action into a component. For example: you want this rule to be triggered using node:changed date, so every time you edit a node, the date for the action "Revoke node access" will be moved forward (e.g: node is changed now => the rule triggers in 1 day (offset in component settings); the node will be changed tomorrow, so the rule will be trigerred on tomorrow date +1 day and so on).

You can import and test the component:

{ "rules_revoke_node_access_component" : {
    "LABEL" : "Revoke node access component",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "content_access_rules" ],
    "USES VARIABLES" : { "node_component" : { "label" : "Node:Component", "type" : "node" } },
    "ACTION SET" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node-component" ],
          "permissions" : { "value" : [
              "view:2",
              "view:1",
              "view:3",
              "view_own:2",
              "view_own:1",
              "view_own:3",
              "update:2",
              "update:1",
              "update:3",
              "update_own:2",
              "update_own:1",
              "update_own:3",
              "delete:2",
              "delete:1",
              "delete:3",
              "delete_own:2",
              "delete_own:1",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }

    }

You can import and test the rule:

{ "rules_revoke_node_access_rule" : {
    "LABEL" : "Revoke node access rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "DO" : [
      { "schedule" : {
          "component" : "rules_revoke_node_access_component",
          "date" : { "select" : "node:created", "date_offset" : { "value" : 1 } },
          "identifier" : "Revoke node access",
          "param_node_component" : [ "node" ]
        }
      }
    ]
  }
}


How to add template suggestions for form elements of a certain form ID? I'm looking to edit some Twig templates for certain form elements, but I need template suggestions only for certain form IDs. How do I go about that?
I currently have the following functions in my .theme file:
function exmaple_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // Something here to alter suggestions of form elements only for the form with the ID 'user_register_form'
  }
}

function example_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#id'])) {
    $suggestions[] = $hook . '__' . str_replace('-','_', $variables['element']['#id']);
    // This works but returns global form element suggestions
    // For example 'form-element--edit-mail.html.twig' which affects all email edit form elements
    // I need suggestions like 'form-element--user-register-form--edit-mail.html.twig'
  }
}

This is kind of tricky as you'd have to write a lot of custom code to pass the form id to a form element as you stated above.  Fortunately, there is a contrib module called "Themable forms" which does exactly that, both for form elements and form element labels.
So for example, if I am on the user login page, for the form elements, I see these default theme hooks for all individual form fields.
<!-- THEME HOOK: 'form_element' -->
<!-- BEGIN OUTPUT from 'themes/custom/mytheme/templates/form/form-element.html.twig' -->

<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'themes/custom/mytheme/templates/form/form-element-label.html.twig' -->

Note, there is no granularity at all for the above.
Now, after I enable Themable forms, I start to see very granular theme hook suggestions being output in the form of
  form-element--[form-id]--[element-type].html.twig
  form-element--form-id--[form-id].html.twig
  form-element--type--[element-type].html.twig
  form-element.html.twig

So for example, with the username field, I now see
<!-- THEME HOOK: 'form_element' -->
<!-- FILE NAME SUGGESTIONS:
   * form-element--user-login-form--textfield.html.twig
   * form-element--form-id--user-login-form.html.twig
   * form-element--type--textfield.html.twig
   x form-element.html.twig
-->

<!-- THEME HOOK: 'form_element_label' -->
<!-- FILE NAME SUGGESTIONS:
   * form-element-label--user-login-form--textfield.html.twig
   * form-element-label--form-id--user-login-form.html.twig
   * form-element-label--type--textfield.html.twig
   x form-element-label.html.twig
-->

You'll now note a few things, the form id in the form element suggestion as well as the name of the form element itself.
This should get you where you want to be according to your question above.
You can install the module with:
composer require drupal/themable_forms


Profile2 Registration Path module integration with LoginToboggan Non-authenticated role I have a site where there are 2 independent user roles, USER_TYPE_1 and USER_TYPE_2. Profile2 RegPath module gives me the two unique registration pages for unique role assignments. With LoginToboggan, all new users get a 3rd type of role, NON_AUTHENTICATED, which is removed after verification.

I'm looking for users to get limited permissions (non-authenticated role) before verification, then more permissions (USER_TYPE_2 or USER_TYPE_2 depending on which registration form they used) after verification.

LoginToboggan invokes hook_user_update() when it validates an email. It sets the property $account->logintoboggan_email_validated to TRUE so you can test it upon your own hook invocation. Inside your hook_user_update invocation, you can use the profile2 function profile2_load_by_user($user) to load the validated user object profile to determine which additional roles need to be set.


Drush installed globally via composer as root user, but how to access Drush with ordinary user? By following the instructions on the Drush git page:

composer global require drush/drush:6.*

I have Drush up and running (it seems to live in /root/.composer/vendor/drush/drush). But I imagine I shouldn't be running it via root. So how do I run it as my ordinary shell users?

When I try running drush it says command not found. Although it lets me use Composer. I tried installing Drush again through Composer while logged in as ordinary user without any luck. The Drush folder is also inaccessible..

To install for all users on the server:

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
ln -s /usr/local/bin/composer /usr/bin/composer

git clone https://github.com/drush-ops/drush.git /usr/local/src/drush
cd /usr/local/src/drush
git checkout 7.0.0-alpha5  #or whatever version you want.
ln -s /usr/local/src/drush/drush /usr/bin/drush
composer install
drush --version

Personally I don't bother making the composer symlink from /usr/local/bin to /usr/bin and made the drush symlink to /usr/local/bin (rather than /usr/bin) as I have /usr/local/bin in my $PATH but YMMV...

Source: http://docs.drush.org/en/master/install/


how can I install Drupal 7 with PHP 5.2 on a Windows Server 2003 machine with IIS 6.0 and SQL server 2000 running on it? What I have:

Drupal 7.0
PHP 5.2
IIS 6.0
SQL server Enterprise Manager 2003
SQL server 2000 running on local system(my database is on the same system.)
Windows Server 2003.(makes any difference?)

I am using VPN to connect to the production system.(relevant?)

I have added the Microsoft SQL Drivers 2.0 to the php/ext folder.
I have added the sqlsrv module to the database\includes as well.

Got the option to install Drupal to sql server which was the only option by default in this case (got a message that my server does not support multiple databases hence sql server was selected by default).
I have the following fields available to me in the database setup:

The values I have entered are in []:

database type:radio button (selected by default--microsoft SQL server)
database name: [database_name]
database user name: [user_name]
database password: [password]

Advanced options:

hostname: [localhost]
port: blank
prefix: blank

I get an SQLState[20008]:SQL server native client [10.0] error: can't login.
what are the possible reason for not being able to connect?

I am not sure why you are using SQL2000 in 2014 because it is not supported anymore.
I have successfully connected to SQL 2008 version using SQLSRV module in Drupal.

I would do the following in this case:

Make sure TCP\IP protocol is enabled and it is listening on some port which is not getting blocked by firewall.
I would try connecting to the database server using IP address and port using enterprise manager first.
I would look in my SQL error logs because it records the authentication failures there.

Please share what you observe.

Thanks
C


Storing a date created with Form API Very simply, I'm creating a date of birth field pragmatically like so:

  $form['dob'] = array(
    '#type' => 'date',
    '#required' => TRUE,
    '#title' => t('Date of Birth'),
    '#default_value' => $sponsorship->dob,
  );

The API says the return value is in the form:

array('year' => 2007, 'month' => 2, 'day'=> 15)

My question is simply, how should I store this in a database table? I originally set the table column to varchar. But I would like to know what is normal practice and most efficient for handling a date using the Form API for Drupal, both saving to the database and then displaying on a page.

Drupal 7 Schema API Data types does not support the DATE datatype that you find in popular SQL dialects such as MySQL.  My preferred solution is the same as the one you suggest (set the column to varchar and store it as a an ISO 8601 format date string: 2013-05-07 for May 7, 2013).  It is human readable (useful when debugging) and it is the format used by the DATE format of most SQL dialects.

For date arithmetic, I use built-in PHP-functions such as gregoriantojd to convert to Julian dates to compute date differences, etc.

While it is possible to force Drupal to use the DATE type to your SQL dialect of choice - see this answer for details, a varcharis the simplest and most portable solution.

For displaying a date in Drupal, you may want to use the the Drupal format_date function (from common.inc), as this makes sure that dates are rendered consistent across the site, and adapt month names, etc. to the preferred language.  Note that this function takes a Unix timestamp as its first argument, so you need to convert from the ISO 8601-format to a Unix timestamp in order to use this (and this won't work for dates fore 1970-01-01).  Because of this limitation I instead use a small custom module with a slightly adapted copy of this core function that shares the format templates with the core function, but accepts an ISO 8601 date and datetime as valid input. I also supply my own custom format (you can set up this on the Home » Administration » Configuration » Regional and language  » Date and time  » Add Date type admin page) without any hours, minutes or seconds.

PS: Some people recommend using Unix timestamps (seconds from epoch starting 1970-01-01) for anything that has to to with time and date.  However, I do not like to use Unix timestamps  for dates where the resolution wanted is whole days.  In addition to not being human readable, and having a rather limited timespan (making it inappropriate to store the date of birth for someone born before 1970), Unix timestamp dates based upon the local time tend to produce weird bugs when dates cross seasons because DST is being taken into account when you do not expect it.  It may be considered strange that I depreciate the Unix timestamp when the format_date function wants this format - but I find that storing the dates in the database  in the ISO 8601 format is so attractive that I put up this extra conversion step when calling the format_date function.


Wrapping fields together in a Views Exposed Filter I'm trying to insert divs (or any tag) in my exposed filter form with the purpose of grouping related fields together. I want to have something like this:

  field one
  field two
  ...

So far, I have tried this in my hook_form_alter(), with no luck, since the prefix and sufix are added within field_one, instead of before field one and after field two:

$form['field_one']['#prefix'] = '
';
$form['field_two']['#suffix'] = '
';

How can I accomplish this (without external modules)?

I solved it by using a fieldset to group my fields.

  // Create a fieldset to group related fields.
  $form['my_group'] = array(
    '#type' => 'fieldset',
    '#attributes' => array(
      'class' => array('my-group')
    ),
  );

  // Move the desired fields in it.
  $form['my_group']['field_one'] = $form['field_one'];
  $form['my_group']['field_two'] = $form['field_two'];

  // Unset the original fields, so they don't show up in the form anymore.
  unset($form['field_one']);
  unset($form['field_two']);


Is there any alternative to the Quiz module? I like the Quiz module but its affiliated modules are not ported to D7.

Is there any alternative to the Quiz module?

Webform is an option. You can show different questions in different page (something that quiz doesnot do). You will require little bit of programming to show the answers for the questions and their scores once the webform is being submitted. This is if you want to capture the score.


Drupal 7 with Media: YouTube only embeds static image Using Media (7.x-1.3) and Media: Youtube (7.x-2.0-rc2) to embed a simple YouTube video on a page using the Media Browser in WYSIWYG.  I go to the "Web" tab in the browser, pasted the YouTube URL, and choose the "Default" option.

What gets put into the content is a static image.  What I'm expecting is an embedded video. Even a static image that uses the built-in lightbox capabilities would be fine.

Here's what I've already checked:

I was getting Lightbox2 errors in admin/config/media/file-types/manage/video/file-display.  Removed Lightbox2 module.
Went to admin/config/media/file-types/manage/video/file-display and confirmed that YouTube Video and YouTube Preview Image were selected for the "Default" option.
Went to admin/config/content/formats/full_html and ensured Convert Media tags to markup was enabled.  I also moved it to the top of the order.
Checked permissions for View media in admin/people/permissions

Suggestions are greatly appreciated.

Media 7.x-1.x only embeds images via WYSIWYG.
I would always recommend media 7.x-2.x for anyone unless you have a strict security policy of only using full releases. 2.x has many great new features.

With Media 7.x-2.x:

The media module currently only has support for embedding images via WYSIWYG.

What version of media are you using? If you use media 7.x-2.x you can get it to work by using this sandbox module - http://drupal.org/sandbox/DevinCarlson/1823634 (note that you also need separate http://drupal.org/project/issues/file_entity module with 2.x because it has now been split out of media - it was part of media in 7.x-1.x)

That sandbox module allows configuring which view modes are used for different file types when embedding via WYSIWYG.

There is a related issue for the media module here http://drupal.org/node/1792738 - It has been decided in that issue that the sandbox module will be integrated into the media module. So you can safely use the sandbox knowing that the functionality will eventually be in the media module, at which point you won't need to rely on a sandbox project.

When using that setup of modules I find that in a lot of cases it is also good to use http://drupal.org/project/entity_view_mode - which allows you to create new view modes (the file_entity 7.x-2.x module doesn't provide many view modes out of the box).


Statistics module doesn't update when getting a node I've created a custom module, which should regarding some other posts help updating the daycount. But it just doesn't get updated.

function services_statistics_improved_services_request_postprocess_alter($controller, $args, &$result) {
      // Increment hit count for node view api requests.
      if($controller['callback'] == '_node_resource_retrieve') {
        $nid = $result->nid; // May need to confirm this is the node id.
        dpm($controller);
        // See statistics_exit()
        if (variable_get('statistics_count_content_views', 0)) {
          // A node has been requested, so update the node's counters.
          db_merge('node_counter')->key(array('nid' => $nid))->fields(array(
            'daycount' => 1,
            'totalcount' => 1,
            'weekcount' => 1,
            'monthcount' => 1,
            'yearcount' => 1,
            'timestamp' => REQUEST_TIME,
          ))
          ->expression('daycount', 'daycount + 1')
          ->expression('totalcount', 'totalcount + 1')
          ->expression('weekcount', 'weekcount + 1')
          ->expression('monthcount', 'monthcount + 1')
          ->expression('yearcount', 'yearcount + 1')
          ->execute();
        }
      }
    }

Anyone able to help me out here?

The query to update the node_counter table may need tuning.

e.g:

if (variable_get('statistics_count_content_views', 0)) {
  // A node has been served, so update the node counters.
  db_merge('node_counter')
    ->key(array('nid' => $nid))
    ->fields(array(
      'daycount' => 1,
      'totalcount' => 1,
      'timestamp' => REQUEST_TIME,
    ))
    ->expression('daycount', 'daycount + 1')
    ->expression('totalcount', 'totalcount + 1')
    ->execute();
}

The other fields, such as 'yearcount' etc.. aren't in the node_counter, at least not by default which may be causing a PDOException there.


how do i install drupal with drush First off, I'm a drush newbie, just installed it and now I want to install drupal on my server, so I did a
 drush dl drupal --drupal-project-rename=Quaaoutand next I want to do a
drush si standard --db-url='mysql://quaaout:PASS@localhost' --site-name=Quaaout
but I keep getting
ERROR 1044 (42000) at line 1: Access denied for user 'quaaout'@'localhost' to database 'information_schema'
even tho I can login on the shell with mysql -u quaaout -p just fine when entering my password and also a show databases shows me the existing information_schema db. Why does it not let me proceed?
I'm on GoDaddy shared hosting with this.

You'll need to create a database first:

mysql -u quaaout -p
create database quaaout;

Then you can continue your drush install adding a db name after localhost:

drush si standard --db-url=mysql://quaaout:PASS@localhost/quaaout --site-name=Quaaout


How can I filter the taxonomy terms by language? I have searched a way to filter the taxonomy terms by language (as done for nodes), but I didn't find any way to do it.

Does the Views module support that filter in taxonomies too, or just in nodes?
How can I filter the taxonomy terms by language?

By enabling the module Internationalization Views, the option to filter the taxonomy term by the language is available. Note that the version is currently in dev but it works like a charm.


Renders my safe_value instead of the value When I'm displaying the contentfield of a node, Drupal only shows the safe_value. I want to use the full HTML from my WYSIWYG. I know this because, when I change $items[$id][$delta]['safe_value'] into $items[$id][$delta]['value'] (in modules/field/modules/text/text.module line 159 in the text_field_load hook implementation), it displays the correct HTML from my WYSIWYG.

How can I change this, so that Drupal shows the value with the HTML?

I needed to change the filter of the field. That fixed the problem.


Redirecting to "old" site I copied files and database of a Drupal 7 site to another domain.
When I put the site in maintenance mode, and I login, I am redirected and logged in to the old site. I cleared the cache, also in the database, but the result is the same. When the site is not in maintenance mode, this doesn't happen.

Additionally, I have to say that I created an SSL connection and checked _Use a symbolic link from private_html to public_html - allows for same data in http and https_. I don't know if this has something to do with that.

Where is the responsible file? What do I need to do?

Try setting the $base_url variable to the new site domain. This is in the /sites/default/settings.php file.


How can I merge a content type's fields and settings from dev to staging? I have an existing content type on staging. On dev we've added a ton of new fields and display and form setting changes, etc.
It's not practical to go through the config files and find all of the many dozens if not hundreds of interconnected config files related to the content types, its fields and its settings.
So I heard Features is the way to go (even though I thought config sync in D8 was supposed to make Features not needed anymore).
So I've created my Feature. Keeping it simple I just checked the single content type. Saved my feature module and moved it to staging.
When I try to enable to the module I get a screen full of "unable to install" because the configuration already exists errors. Ugg.
So I read that I should remove the configurations. But this removes content and/or associated configurations like vocabularies.
Surely there must be a practical way to merge a content type from dev to staging?

To fix the issue include config in optional directory instead of install directory in your features module. It will then only install the config which are not present in the new site. Which will solve your issue.

When I try to enable to the module I get a screen full of "unable to install" because the configuration already exists errors.

Ok, I misread your question. To update existing config as well you need to do partial cim.
Copy the feature configs into a different directory named feature-config-sync (can be anything other than standard folder names) in default site config directory. And execute the below command. It will import new config and update existing configs if needed. Limitation is it wont delete any configs.

drush cim --partial --source=../path/to/config/feature-config-sync

IIRC you can even map the module install/optional config directory as source during partial import.
Once your import is done you can delete the feature-config-sync directory.


Submitting a form causes 'secure connection failed' error that persists I've got a SSL certified server running drupal 7.37.
Everything was working fine until I started adding form submission to a module I'm working on.
As soon as I submit the form, I get 'Secure Connection Failed' in all browsers.
I can get to other pages ok, but not the homepage which then also throws the same error.
This persists until I restart my internet connection.

I did the following test to try and find the problem:

I submit the form on my desktop pc - secure connection failed.

I try to go to the domain root - secure connection failed.

I check on my laptop which is connected to the same router - secure connection failed.

I check on my phone using 4g - works fine.

So I seem to be causing a local network wide issue somehow, but I don't know how to fix it.

This is the form, it just uploads an xml file to the temp directory:

$form['file'] = array(
    '#type' => 'file',
    '#title' => t('XML file'),
    );
$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    );
return $form;

This is the validate function:

$file = file_save_upload('file', array(
    'file_validate_extensions' => array('xml'),
));

if ($file = file_move($file, 'public://'))
{
    $form_state['storage']['file'] = $file;
}
else
{
    form_set_error('file', t("No file was uploaded. Check extension is .xml"));
}

This is the submit function:

$file = $form_state['storage']['file'];
unset($form_state['storage']['file']);
dsm($file);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$filepath = file_create_url($file->uri);
dsm($filepath);

Any help would be appreciated, it's driving me mental.

UPDATE: This problem disappeared for a few hours, then returned for no apparent reason.
I'm thinking it might be a problem with my internet provider.

For those who end up in this situation, the reason for this to happen is an error somewhere in your PHP code that is not caught by the PHP interpreter or Drupal itself and the server disconnects to your browser immediately before sending any information (including for example the web server certificate). It is not a network-related error as suggested above here.

To solve the problem, install the xdebug PHP module, configure it and run your scripts again. You will now get far better insight in the cause of the error(s) and it is actually caught before a disconnect.

In my case, the disconnect was caused by a recursion limit hit in my code, which was not caught by the PHP interpreter. Took me a few hours, mostly looking in the wrong direction (network issues, certificate issues).


How to add colorbox in views gallery I follow these steps to achieve the gallery thumbnail in footer
  https://www.drupal.org/node/1497058
  and now my thumbnails shows like below

  but only thing left is when i
  click thumbnail image its open the next page and show the big image
  but i want when i click the thumbnail the big page open on colorbox
  when i click on thumbnail its shown like below

Install and enable colorbox module. And add place colorbox library in sites/all/library and rename folder to colorbox

Goto to admin/structure/views
Click edit on your views, here my view name is "Colorbox"

Click on your image field, eg., content:Image

select Formatter as colorbox and click "apply"

Save the view and clear the cache.

Hope it works


Why cannot I get the path of a video? I can't manage to get the video link of a media, I can achieve this with a picture but with videos it doesn't work.

This is the code I am using.

function slider_get_uri_by_media($media, $style = 'background'){
  // kint(isset($media->file_media_video_file));
  if (isset($media->field_media_image)){
    $file = $media->field_media_image->entity;
    if ($file && $fid = $file->id()) {
      $image = File::load($fid);
      if ($image_style = ImageStyle::load($style)) {
        return ['url' => file_url_transform_relative($image_style->buildUrl($image->getFileUri()))];
      }
    }
  }
  elseif (isset($media->file_media_video_file)) {
    $file = $media->file_media_video_file->entity;
    if ($file && $fid = $file->id()) {
      $video = File::load($fid);
    }
  }
}

Why cannot I get the path for the video stored in $media->field_media_video_file?

I think that you have a typo in the field name, you should replace
$media->file_media_video_file
with
$media->field_media_video_file (2 times)


Add node ID to template variables is there any way to add node ID (if it exists) to template variables using

my_theme_preprocess_page(&vars) function?

It looks like theme theme isn't using my_theme_preprocess_node(&$vars, $hook) so I assume that node object isnt available in vars for my_theme_preprocess_page(&vars).

It's not my website so I don't really know the structure.

If you want to access nid inside preprocess_page you should try something like this

arg(0) will return 'node' and arg(1) will return node nid.

Provided you must be inside a node.

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
   $node = node_load($nid);
   // creating the node variable
   $vars['node'] = node_load(arg(1), NULL, TRUE);
  }
}


How to use metatags_quick to add no-cache meta tags in D7? I'd like to add the following to the meta tags for a single page on my D7 site:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

Taken from here

However, when I try to use metatags_quick to accomplish this, it names all my metatags as

<meta name="Cache-Control" content="no-cache, no store, must revalidate">

with the "name=" attributes rather than "http-equiv".  How can add these tags?

I want to say that, in some cases, you can add by template way your meta tags to your specific page.

you can locate html.php.tpl in modules > system file. copy and paste it inside your template directory. then add your meta tags using some php code to show these tags only in that specific page:

  <?php
  if(isset($_GET['q'])){
      $path = $_GET['q'];
      if(preg_match('/test/', $path)){
      ?>
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="0">
      <?
      }
  };
  ?>

(you can add this snippet before, for example, the <title> tag line)

remember that if you need your meta in more pages, you can replace the pattern of preg_match() php function (in this example is /test/) for several pages (for example /(test|another_test_page|another)/ )

Update: if you do not see changes, is very important clear cache to see changes.

Update2 drupal_get_path_alias() could be an useful function to get the current alias: Given an internal Drupal path, return the alias.


How to check the stock count of an ubercart node I'm using a using a custom function to display child nodes of a taxonomy term while displaying the term page. Here is the function

function theme_name_child_terms($vid = 1) {
  if(arg(0) == 'taxonomy' && arg(1) == 'term') {
    $children = taxonomy_get_children(arg(2), $vid);
      if(!$children) {
        $custom_parent = taxonomy_get_parents(arg(2));
          $parent_tree = array();
          foreach ($custom_parent as $custom_child => $key) {
            $parent_tree = taxonomy_get_tree($vid, $key->tid);
          }
          $children = $parent_tree;
      }

    $output = '
';
    // Avoid unnecessary "Invalid foreach" errors showing up in the log:
    if (!empty($children)) {
        // If not empty, run the foreach loop:
        foreach ($children as $term) {
            // Then check to see if any nodes exist for that term id:
            $number_of_nodes = taxonomy_term_count_nodes($term->tid);
            // If there ARE nodes...
            if ($number_of_nodes > 0) {
              // ... then add them to the output:
              $output .= '
';
              $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
              $output .= '
';
              }
        }
    }
    $output .= '
';

    return $output;
  }
}

This is the output: screen shot. You can can see that it's showing terms and node counts in brackets for items that are not in the 'jewellery' catalogue anymore as they are sold.

The problem I have is that the nodes i'm dealing with are products in an ubercart catalogue - - all items are unique as it's an antique trading site. The function above still counts 'sold' items as nodes associated with the term - a sold item is of course still tagged with a taxonomy term  .  - so, some terms are leading to blank pages, because I filter out nodes that are sold, from the taxonomy view.

Can another step be added to the function that checks each node associated with a term if it is a has stock level of 1 or above?

I've found the following function in uc_stock.module:

/**
 * Get the stock level of a particular product SKU.
 *
 * @param $sku
 *   The Ubercart product SKU of the stock level to return.
 * @return:
 *   The SKU's stock level, or FALSE if not active.
 */
function uc_stock_level($sku) {
  $stock = db_fetch_object(db_query("SELECT active, stock FROM {uc_product_stock} WHERE sku = '%s'", $sku));

  if ($stock && $stock->active) {
    return $stock->stock;
  }

  return FALSE;
}

I just can't figure out where or how to call this function in the original function. It needs to be passed the product 'sku', but i'm not sure how to give it that parameter.
I guess it should be something like:

$stock = uc_stock_level($sku);
  if ($stock > 0) {
    ...
  }

Any help much appreciated.

Note: here's a good page to have bookmarked when you use Ubercart with D6: http://www.ubercart.org/docs/api (as opposed to http://api.ubercart.me for when you use D7).

Also note: this ended up being a lot more in-depth than I anticipated, but I was already knee-deep in it so I figured I'd finish it up. ;) That said...

You're definitely on the right track... Like you said, you could just supply the function uc_stock_level($sku) with the value of $sku, but that might be a lot of SKUs and therefore kind of resource intensive.

Another alternative that should work would be something like this:

Change this part of your code:

$output = '
';
// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
    // If not empty, run the foreach loop:
    foreach ($children as $term) {
        // Then check to see if any nodes exist for that term id:
        $number_of_nodes = taxonomy_term_count_nodes($term->tid);
        // If there ARE nodes...
        if ($number_of_nodes > 0) {
          // ... then add them to the output:
          $output .= '
';
          $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
          $output .= '
';
          }
    }
}
$output .= '
';

To something like this:

$output = '
';
// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
  // If not empty, run the foreach loop:
  foreach ($children as $term) {
    // Then check to see if any nodes exist for that term id:
    $number_of_nodes = taxonomy_term_count_nodes($term->tid);
    // And then check to see what the current stock level is:
    $stock_level = fetch_stock_level_from_termid($term->tid);
    // If there ARE nodes...
    if ($number_of_nodes > 0) {
      // And if the product is in stock...
      if ($stock_level > 0) {
        // ... then add them to the output:
        $output .= '
';
        $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
        $output .= '
';
      }
    }
  }
}
$output .= '
';

You'll then need to add the function fetch_stock_level_from_termid() to your code as well:

function fetch_stock_level_from_termid($term_id) {
  $sql = "SELECT SUM( {uc_product_stock}.stock ) AS stock
          FROM {uc_product_stock}
          INNER JOIN {node} ON {uc_product_stock}.nid = {node}.nid
          INNER JOIN {term_node} ON {node}.vid = {term_node}.vid
          WHERE {term_node}.tid = %d
          AND {node}.status = 1";
  $stock_available = db_result(db_query($sql, $term_id));
  return $stock_available;
}

Hope that helps... :)


Field collection item not visible to anonymous user I have a field collection, 'related content', that displays inside the 'page' content type tpl. It is a 'field' in the page content type.  It  works perfectly fine while logged in as admin, but cannot be seen by the anonymous users.

UPDATE: I've actually determined that this has something to do with Organic Groups.  The 'page' that the field collection belongs to is a member of a group...the anonymous user can see this page, can see the body, title and other fields...however, I still cannot get the field collection to show up on the page even though the variables are available and can be dumped to the page...rendering the content using render() results in nothing, but works fine if logged in as admin.

If I simply do var_dump($content['field_related_content']) I can see that all of the information is there...however print render($content['field_related_content']) displays  nothing for anonymous users.

The permissions for the individual groups also have to be set for each added field...it was kind of buried and hard to find.  The path would be like /group/node/13/admin/permissions


mymodule.install file not creating the table in drupal 7 I have a very simple table in my .install file and for some reason is not creating the table. What can it be? something i have to add in the .info file? please help.

Its a drupal 7.

this is what i have in my my_module.install file.

function my_module_schema() {
  $schema['my_module_config'] = array(
    'description' => 'Configuration settings for the my_module web service.',
    'fields' => array(
      'name' => array(
        'description' => 'Name ',
        'type' => 'varchar',
        'length' => 50,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
  );

  return $schema;
}

you should uninstall the module
write the hook_schema function
enable the module.

You should also specify the  primary key in the hook_schema

 'primary key' => array('field_name'),

You can check the drupal link for the hook_schema


How to print a region in views.tpl.php? I have a views-view-unformatted--viewsname--attachment.tpl.php. I want to print region in this file.

I added

function mytheme_preprocess_views_view(&$vars) {
   if ($blocks = block_get_blocks_by_region('regionname')) {
      $vars['region'] = $blocks;
  }
}

to template.php.

and added

echo render($region);

to views-view-unformatted--viewsname--attachment.tpl.php but print nothing.

What is wrong? How can I print region in views.tpl.php?

i tested this with mytheme_preprocess_html and html.tpl.php and it worked.

Create a new region in your theme's .info file.

regions[RegionName] = Region Name

Insert following code in your
views-view-unformatted--viewsname--attachment.tpl.php template file
to insert region between views rows:

print render(block_get_blocks_by_region('RegionName'));

And then put your block into this region.

For more reference go to this.


Problems getting Carousel jQuery plugin working I am trying to get a Carousel on my site, but I am having problems.
I want to install http://www.jqueryscript.net/slider/Full-Width-Responsive-Carousel-with-jQuery-Bootstrap.html.
I have created a content item for testing this on http://xuzo.com/testing/node/26.
Method A: my own stylesheets (not working)
I pasted the HTML from http://www.jqueryscript.net/slider/Full-Width-Responsive-Carousel-with-jQuery-Bootstrap.html and put it in my content item under FULL html format. I have tried to make it work with my own style sheets that I copied from the website above, I put them into my info file, and uploaded them to the server.
stylesheets[all][] = carrousel/bootstrap.min.css
stylesheets[all][] = carrousel/jquerysctipttop.css
scripts[all][] = carrousel/bootstrap.min.js
scripts[all][] = carrousel/jquery.min.js

Since I have the style sheets, I am not sure I had to use CSS injector and JS injector or not.
Method B: external CDN JS styles sheets + my own style sheets (not working)
I put my own style sheets that I copied from the website above into my .info file.
stylesheets[all][] = carrousel/bootstrap.min.css
stylesheets[all][] = carrousel/jquerysctipttop.css

I linked the external CDN files in template.php.
 drupal_add_js('//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', 'external');
drupal_add_js('//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js', 'external');

The page shows up with images, but it is not working.
In CSS injector I tried this code.
#jquery-script-menu {
  position: fixed;
  height: 90px;
  width: 100%;
  top: 0;
  left: 0;
  border-top: 5px solid #316594;
  background: #fff;
  -moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
  -webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
  z-index: 999999;
  padding: 10px 0;
  -webkit-box-sizing:content-box;
  -moz-box-sizing:content-box;
  box-sizing:content-box;
}

.jquery-script-center {
  width: 960px;
  margin: 0 auto;
}

.jquery-script-center ul {
  width: 212px;
  float:left;
  line-height:45px;
  margin:0;
  padding:0;
  list-style:none;
}

.jquery-script-center a {
  text-decoration:none;
}

.jquery-script-ads {
  width: 728px;
  height:90px;
  float:right;
}

.jquery-script-clear {
  clear:both;
  height:0;
}

In JS injector I tried this code.
jQuery(document).ready(function($) {
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36251023-1']);
  _gaq.push(['_setDomainName', 'jqueryscript.net']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
});

I know I am missing something, but what?

I don't see that you have add html elements with bootstrap attributes like data-target and data-slide-to.
When I inspect your page and replace this:

&nbsp;

&nbsp;

&nbsp;

with this: (example from plugin site)

<li data-target="#my<ahref="http://www.jqueryscript.net/tags.php?/Carousel/">Carousel" data-slide-to="0" class="active">

I get dots that actually work.


jQuery.js not loading after enabling custom module I have written my custom module for Drupal 7. In my page_change.module file I have only:

<?php
    drupal_add_js(drupal_get_path('module', 'page_change') . '/page_change.js');
?>

In my page_change.js file I have only:

Drupal.behaviors.page_change = {
    attach: function (context) {
        console.log("text");
    }
};

As soon as I enable my module, Drupal doesn't load jquery.js. It does not even appear in html source in <head> section. When I disable my module, or delete the only line from page_change.module file everything works fine.

I have also tried to load my javascript file by adding

scripts[] = page_change.js

In my page_change.info file (and leaving page_change.module with only <?php ?>) but it doesn't seem to work either.

Why does that happen? What am I doing wrong? Am I missing something?

edit: I have even tried to add inline javascript by adding

drupal_add_js('console.log("text");', array('type' => 'inline', 'scope' => 'footer'));

and it writes text to console, but jquery.js is still missing.

Your custom JS should be wrapped in:

(function($) {
  // custom Drupal behaviors here
})(jQuery);

Give that a shot.


How to exclude views fields from display when a node is flagged We use the flag module to mark items that will have delays in shipping so that the customer knows that those items will be delayed before adding them to cart. In drupal 7, we excluded our "add to cart" button and "more info" button from display and used a global custom text to rewrite them with the following text displaying them inside a btn-bar div class.

[flagged][add_to_cart_form] More info

We then use the following css to hide the add to cart, and more info elements when the flag is present in the button bar.

.btn-bar.pre-order .atc,
.btn-bar.pre-order .moreinfo{
  display: none;
}

In Drupal 8, the functionality of this still works correctly (updating the replacement patterns of course), but there is apparently a security issue with rewriting forms, so the add to cart button won't render properly when being rewritten in a global custom text.

So my question is what is the "simplest" way to hide those 2 fields when that particular node is flagged? Can this be accomplished by adding some code to my custom theme for the view in question?

General approach:

Use the Rules module (which does not yet have a stable release for Drupal 8, but does have the capability in its current state to implement the recipe below) to detect the content is flagged, then do a Rules action which will result in those fields being hidden.

Here is one specific example, but there are many ways, and likely simpler ways to do it than my recipe. I wanted to give you an example that doesn't require coding or extra modules besides the Rules module:

Drupal automatically includes a body class with the content type of the node. So make a rule that will evaluate that a node has been flagged, and if it is, change that node's content-type via the action "Data => set a data value." Now you can easily create the css to hide the fields that you want hidden by using the body class for the content type assigned flagged nodes.

Make sure the two content types use the same fields and have all the same settings for those fields.

Also make sure to set up a second rule which does the opposite so that the content type is returned to the original when the flag is removed.


Commerce Paypal- How can I change the "Order No. at Site Name" string? I'm using the Commerce PayPal module to redirect users to PayPal to pay for their orders.

However, when I do this, the transaction that Commerce provides to PayPal is called

  Order # at [Site name]

However, on my site, the store is just one part of it, and the store has a different name than the rest of the site, so I would like to override this string and replace [Site name] with the explicit name of my store.

However, I haven't been able to track down where I can edit this.  I tried searching for a number of variations on the Translate interface page and I also tried using grep on my modules directory but I haven't been able to locate it.

All of my payment gateway modules, and my recommended best practice for others', is to include a final opportunity before the payment API request is dispatched for developers to alter the request parameters if desired. How you do that in the PayPal modules depends on which payment method you're using. I'm going to assume this is a PayPal Payments Standard (WPS) initiated payment, so the hook you want is:

hook_commerce_paypal_wps_order_form_data_alter()

If it's one of the others, refer to their *.api.php files to find the appropriate hook, but note that some API requests are run through a helper function in the root commerce_paypal.module.