Commerce Recurring Framework - Get active subscriptions? For the Drupal Commerce Recurring Framework module I have a quesiton

Is there a way to get a user's active subscriptions programatically?

Bonus: Is there a way to delete a user's active subscriptions programmatically?

Thanks if anyone answers!

For Drupal 7:
Yes, you can find the data at the {commerce_recurring} database. With each recurring entity the user id has saved (uid column).

Here's an example how to get all subscription (recurring entities) from a user.

$uid = 1; // the user id
$result = db_query('SELECT * FROM {commerce_recurring} WHERE uid = :uid', array(':uid' => $user_from_order->uid));

Now you can loop over the subscriptions / recurring entities.


How to set multiple domains for one language I have a multilingual site with Drupal 7 using subdomains like en.example.com to detect the language. Everything works like expected, but I have a mobile version of the website witch I want to be accessible by domains like en.m.example.com etc. How do I do this? I can set in admin/config/regional/language only one domain per language, but would have to set two in order to get that working, like:

for English:
en.example.com & en.m.example.com

for German:
de.example.com & de.m.example.com
etc.

(I would like to have the same structure as Wikipedia has.)
The problem is, that using subdomains for language selection, Drupal creates all internal links as absolute pathes. For example, a menu link will be created as:

test

and not as

test

So, I could create a domain alias with Apache, to send requests from en.m.example.com to en.example.com, but all internal links would bring the user back from  the mobile version to the normal. How can I solve this problem?

Once you've set up Drupal to serve different languages in different domains, you need to instruct your web server to send requests from multiple domains to the same Drupal site.

In Apache, you'll need to edit the .conf (httpd.conf) file and add aliases to all the different domains. For example:

ServerName en.example.com
ServerAlias en.m.example.com

In addition to this, you'll also need to point the domain name server (DNS) to your server for all the domain names in different languages.


Alternate links in a multilingual site Drupal 7 I have a multilingual website currently on localhost. I want to add the alternate links to each page like this: rel="alternate" hreflang="x".
How do i do that?
What about the canonical urls? I have already installed SEO suite module enabled.

You can use Meta Tags module for canonical links.

  The Meta tags module allows you to automatically provide structured
  metadata, aka "meta tags", about your website. In the context of
  search engine optimization, when people refer to meta tags, they are
  usually referring to the meta description tag and the meta keywords
  tag that may help improve the rankings and display of your site in
  search engine results.

  Meta tags have additional uses like the Open Graph Protocol used by
  Facebook, specifying the canonical location of content across multiple
  URLs or domains.


Multiple shopping cart view in cart page I want to show shopping cart view in different style on mobile view .
how can I clone shopping cart view to show it on another format like unformatted list or what is your approach to show this views on mobile on none table format ?

Thank You

Try https://www.drupal.org/project/commerce_responsive_ui as a starting point. This module uses different displays (no tables) for the cart and checkout views.


How to deal with /system/files references when upgrading to D7? After migrating a site from D6 to D7 with drush site-upgrade, I notice that some public contents in the D6 version refered to pictures with URIs like for instance /system/files/logo.png, instead of the more efficient /sites/default/files/logo.png
There's no system directory on disk and no URL rewriting that I can see, so I assume the first form goes to Drupal for routing.

The problem is that with D7 post-upgrade, such references lead to a "Page not found" error so the pictures are broken.

As a test, if I drop somefile.png into /sites/default/files/, D6 seems to be happy to serve http://example.com/system/files/somefile.png despite the fact that the file is not known anywhere in its database. But D7 apparently doesn't do that.

Is /system/files a hardcoded path component that means something to D6 and not D7?
In /admin/config/media/file-system, the download method is set to "Public local files served..."

How to solve this with Drupal 7? Is there a configuration setting somewhere that I'm missing?

Why it happens

In D6, the system module provides the following menu entry that ties system/files to the file_download callback:

In system_menu() function:

  $items['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

Then in file_download(), if the file exists and no hook_file_download() objects to the download, it gets served.

On the other hand, D7 expands on that with a page argument set to private:

  $items['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'page arguments' => array('private'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

It has the effect of preprending the private:// scheme to the filename, which file_download processes by requesting the registered file stream wrapper for  it.
By default (no private path set in /admin/config/media/file-system), this scheme is not registered, and that's why GET /system/files/logo.png finally fails with a 404 status.

How to fix

Setting the private file system path to sites/default/files (the same as the public path) makes it work.

However it's not a good long term fix, both because routing public static files through Drupal is much heavier than direct access by httpd, and because it precludes the use of a real private space should the site need it in the future.

The long term fix is to hunt for these /system/files/xyz references and replace them by /sites/default/files/xyz.


How can I protect a disabled form from being submitted? I need to protect URL alias from being submitted.

I've tried setting #disabled, #access, unset(), and what not. It hides the form, but the user is still able to modify the form on the client-side and submit it.

How do I prevent this form from being submitted on the client-side?

My current module code

<?php
function mymodule_form_alter(&$form, &$form_state){
  if (empty($form['type']['#value'])) return;
  $form['#after_build'][] = 'mymodule_after_built';
}

function mymodule_after_built($form, &$form_state) {
  $form['path']['#access'] = FALSE;
  $form['path']['alias']['#access'] = FALSE;
  $form['path']['alias']['#value'] = $form['path']['alias']['#default_value'];

  return ($form);
}

UPDATE:

To clear the question, I am not asking how to hide the form, but how to prevent the end-user from manually altering the code and submitting the form I just hid.

End-user can just edit source code and add <input type="text" id="edit-path-alias" name="path[alias]" value="" size="60" maxlength="255" class="form-text"> and still enter the alias.

Found the issue! It seems to be a Drupal bug.

#access set in #after_build does not completely override the #access settings, set in hook_form_alter.

In theory, a form is altered by hook_form_alter and hook_form_alter is altered by #after-build. When I try setting #access in hook_form_alter, to alter the form, everything works. However, when I try setting #access permissions in #after_build, to alter hook_form_alter, it only hides the form, still allowing anyone to submit it, by altering the code on the client side.

As a temporary solution, I disabled URL alias permissions, by unchecking "Administer URL aliases" and "Create and edit URL aliases".


Change default Scald legend or caption output I am sure the setting must be somewhere, but I only want to have the title as a default caption, the author field is irrelevant and the people updating content have to delete it each time.

Update:

I have found that going to Administration > Structure > Scald > Image (/admin/structure/scald/image/player/full/image_figure) I am able to alter the caption for that player, but not for the default player.

I have also found a hook in scald.api.php hook_scald_player(), but this is used like an info hook and using hook_scald_player_alter() does not alter the value:

function mymodule_scald_player_alter(&$players) { // tried referencing
  $players['default']['settings']['caption'] = '[atom:title]';
  return $players; // tried returning
}

It seems that you can alter the settings of players as much as you like, but it won't change the caption text because the pattern is hardcoded in the function theme_sdl_editor_legend() of the Scald module.

So we need to overwrite the output by something of our choice.

The previously mentioned theme function can be overwritten in your themes functions.php. Probably you use a Drupal Core or contributed theme as administrative theme, those template.php files you should not change. Thus the preferred method is below (a custom module).

Below you find a simple example of how to get rid of the "by" part in a custom module.
Effectively we just completely overwrite the output of theme_sdl_editor_legend() using an implementation of the hook_scald_dnd_library_item_alter() hook. You can change $item['meta']['legend'] to any string you like using data from $atom.

/**
 * Alter a scald library item.
 *
 * Implements hook_scald_dnd_library_item_alter()
 *
 * @param $atom
 *   The atom object.
 * @param $item
 *   The scald library item.
 */
function MODULE_scald_dnd_library_item_alter($atom, &$item) {
  $item['meta']['legend'] = "
   <div class='meta'>
    <!--copyright={$atom->sid}-->{$atom->rendered->title}<!--END copyright={$atom->sid}-->
  </div>
 ";
}


How do I reference an image from text/description field? In some cases, I am entering some text and an img src tag in descriptions and text fields on my content pages rather than use an image field, for example the Header field on a view.

I cannot work out the location to use. I thought images/imagefilename.jpg would do the job, but alas no. I also want to avoid the old http://hostname.com/images/imagefilename.jpg for vairous reasons.

My images are in themes/mytheme/images.

Unless the location of your Drupal install changes (sub directory versus root directory), the easiest way would be to use a relative path from the site root to the image.

You could get the file path with a PHP snippet. Note that the PHP filter module needs to be enabled, and the PHP code text format selected, for this to work.

<?php $path = base_path() . path_to_theme() . '/images'; ?>
<img src="<?php print $path; ?>/imagefilename.jpg" />


Managing blocks in a responsive theme I'm just starting a responsive theme based on Omega, concentrating on the mobile layout at first.

There are certain blocks that will probably be deemed too 'heavy' to include on the mobile layout, and other blocks that will need to be introduced specifically for that layout (watered-down menus, toned-down user-bar etc).

I could easily hide the unwanted blocks on the mobile layout with CSS, and include the mobile-specific blocks on the default layout and hide those (so they're only shown for mobile), but that seems like quite a backwards way of thinking about it. If the blocks aren't shown, the extra overhead they incur would really be unacceptable (especially considering the number of extra db queries that the content in hidden blocks would add).

I'm thinking there must be a nice clean way to intercept the block decision-making process early on in the page build, and exclude/include blocks based on some os-detection, but I'm drawing a blank on how that might be possible.

I'm also going to throw in the fact that Varnish is running in front of this site, which should make things more fun :)

Are there modules/known strategies out there that can help with this?

I should add that using the Context module isn't an option as the site is already fully-fledged, and moving it into Context would be a massive undertaking at this point.

I can't go into a lot of details, as I've not used either module for ages (I build all my sites with Context from the word go and I've not picked up responsive on something I haven't built for a while, so I've not had this problem before), but I think you should be able to put something together with Mobile Tools and Spaces.

Spaces

  Spaces is an API module intended to make configuration options generally avaliable only at the sitewide level to be configurable and overridden by individual "spaces" on a Drupal site. It has been described as:

  A way to make one Drupal site act like several sites
  A way to provide much more configurable, full-feature Organic Groups or user homepages
  A generalized API for contextual configuration

Mobile Tools

  The Mobile Tools module provides Drupal developers with some tools to
  assist in making adjustments to your site based on the visitor's
  device.

The project page for MT does say it's not ready for production though, which might be a problem - it depends when  it was last updated, as the last commit was this month.

*EDIT

I COMPLETELY FORGOT ABOUT THESE!

Browscap

  Browscap provides an improved version of PHP's get_browser() function.

Browscap block

  Browscap Block adds visibility options to block configuration settings
  to allow you hide or show blocks in mobile devices.

Browscap does depend on your server setup, but if you can use it then the second module gives you extra visibility settings for each block on the block edit page.


Are there any other settings besides php.ini to allow file upload? I have a problem with drupal upload file (core module) bigger than 1 MB. For images smaller than this, the upload run smoothly, the progress bar correctly shows the progress and when completed it display the uploaded images as expected.

However, when I tried to upload image bigger than 900 kb, the problem start to arise. The throbber progress indicator show progress until about 98% and then restart again from 0% and never completed and stuck.

In Firebugs it shows that the request was aborted when the progress reach 94%-98% depending on the size images I uploaded. And it only happend when the file > about 900 kB and never for smaller images.

I already changed the php.ini as suggested here and I verified through phpinfo() it is correct setting. I also change the max_input_time and max_execution_time in httpd.conf

In fact, when uploading images, I monitor temporary folder /tmp and it shows temporary file progressing from 0 to the size of the file and restarting from 0 again. Thus, it indeed receive the file, no issue on the size of the file.

I also check the permission, 777 on /tmp and 755 on default/files and it is no problem as I can easily upload 500kb images.

Can anyone help? is there any other settings in the server I have to look into?

Thanks

Please read through this documentation:
https://www.drupal.org/node/97193

Depending on your HTML form and server configuration if you have a 1MB filesize limit; uploaded files close to your maximum filesize may not successfully upload to a webserver because a file is sent as apart of a multi-part HTTP transmission.

You want to assure post_max_size is typicaly 2x or 3x larger than your upload_max_filesize. Brief discussion on this can be found here:
https://stackoverflow.com/a/15077229/1491507

Googling PHP maximum post size and file sizes should lead to similar documentation on php.net and other resources.


Disable jquery.ui.theme.css only for front end? I'm using jquery tabs on my page but they loaded some default styles that I didn't want. Thus I removed them with the following code:

drupal_add_library('system', 'ui.tabs');

function mytheme_css_alter(&$css) {
   // List of disabled drupal default css files.
   $disabled_drupal_css = array(
      // Remove jquery.ui css files.
      'misc/ui/jquery.ui.core.css',
      'misc/ui/jquery.ui.theme.css',
      //  'misc/ui/jquery.ui.tabs.css',
   );

  // Remove drupal default css files.
     foreach ($css as $key => $item) {
         if (in_array($key, $disabled_drupal_css)) {
            // Remove css and its altered version that can be added by jquery_update.
            unset($css[$css[$key]['data']]);
            unset($css[$key]);
         }
     }
}

This seems to do the trick, but I also noticed that my backend is not loading it's styles properly. I guess some of it uses the jquery.ui styles.

How can I load these only for the logged in user but not for

I would use user_is_anonymous() function like this:

function yourtheme_css_alter(&$css) {
  if(user_is_anonymous()) {
    $exclude = array(
      'misc/ui/jquery.ui.core.css' => FALSE,
      'misc/ui/jquery.ui.theme.css' => FALSE,
    );
    $css = array_diff_key($css, $exclude);
  }
}


How do I change the image style for avatars displayed in comments I'd like to use a custom image style for the comment avatars, but I don't know where the setting in Drupal is to change it.

I thought if I changed the user image style at admin/config/people/accounts/display that might work, but it doesn't. There's no image field at admin/structure/comment/manage/comment/display, so I can't change the style there.

I did this on a site a couple weeks ago on another site, but I can't remember for the life of me how I did it. I don't think I needed to make code modifications. Help?

You can modify the image style used for displaying avatars in comments by editing the "compact" display mode for user accounts.

The setting can be found at /admin/config/people/accounts/display/compact. Or by navigating the administration interface:

Admin -> Configuration
Account Settings
'Manage display' tab
'Compact' sub tab.
On the 'Picture' row, click the edit field settings button (Cog image) located on on the right.
Then select your image style.


Where to write hook_commerce_payment_method_info() in drupal8? I am migrating one of the drupal commerce related module from Drupal-7 to drupal-8.As I am newbie to D8, struggling to get proper structure in drupal-8. I have a hook that is hook_commerce_payment_method_info(). I am confused to where to write this hook. I am guessing it will be in .module file. please share your suggestions to me. So that I can move in right direction. Thanks in advance.

Payment methods are now called Payment gateways and they are plugins, like anything else.

So, look for the @CommercePaymentGateway annotation, like in this example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment_example/src/Plugin/Commerce/PaymentGateway/Onsite.php and the others in that folder.


advise for managing and troubleshooting modules I think anyone using Drupal runs into this sooner or later. You're trying to get to some solution and you start adding modules. Then somethings start breaking. The last time I had this problem, I uninstalled and then reinstalled the modules by enable/reenable the check boxes on the module page.

This time I have a lot of new content types and views and wot wot, and I'm scared. (>_<) I don't know if I'll lose these bits. I've exported my views, I've dumped the database. But I'm still nervous. What advise would you give, or reassurance?

Unchecking the module does not uninstall it, it is just disabled. The schema related to the module is only removed when it is first disabled and then uninstalled.

If disabling and then enabling can solved your issues then do it.

But disabling and then enabling a module would not do any thing harmful except to remove and then add its record in system table and would invoke few hooks like hook_menu, hook_theme etc.


List all Ubercart product fields found in uc_product_field_extra_fields() I am trying to use the Fields API to list all of the Ubercart product fields (cost, model, sell_price, weight, etc). I have tried

entity_get_info('node')
field_info_bundles()
field_info_instances('node', 'product')
field_info_extra_fields('node', 'product', 'form')

field_info_instances() gives me the image field and the catalog taxonomy, but none of them return the fields added by uc_product_field_extra_fields(). I thought for sure field_info_extra_fields() would return it, but all I get back is title and path. What is the correct API call to list these fields? I don't need them in display form or anything like that.

I'm using Drupal 7.12 and Ubercart 3.0.

It turns out that in uc_product_field_extra_fields(), the extra fields are defined for 'display' and not for 'form'. The correct call is field_info_extra_fields('node', 'product', 'display');


Show multiple content in a view in drupal 7? I have a content-type named Accessories. Where I can create content related product i.e. Product name, product detail, etc. I have a view named shop where I can display all products of the content-type i.e. Accessories.

Now I want to create a view where I can show the product detail. I can't find-out how to do this.

Please help to create Views to show my product details.

The "content related product i.e. Product name, product detail*" in your question is a bit ambiguous ... (not sure how to correctly interprete) ...

1st possibility:

It may mean that you only have a single content-type (named "Accessories") with some fields added to it, i.e. product name, product detail, product image, etc.

In that case, you should the "add" button to the right of Views "Fields" (1st column of the Views UI). First to add a field like Product name, and then for product detail, product image, etc.

2nd possibility:

It may mean that you have a content type "Accessories", and another type like "Product" or something.

In that case, you should add a Views "Relationships" (3rd column of the Views UI).


How do I add a title attribute to the search submit button, exposed search, and reset buttons? I want to add the title attribute to the search submit button, the exposed filter search, and the reset button.

How can I achieve this?

I have found the answer of my question.

I have used the following code in my form_alter function.

if ($form_id == 'search_block_form') {
   $form['actions']['submit']['#attributes']['title'] = t('Search');
  }
  if ($form_id == 'search_form') {
   $form['advanced']['submit']['#attributes']['title'] = t('Search');
  }
  if($form_id == 'views_exposed_form') {
    $form['submit']['#attributes']['title'] = t('Search');
   $form['reset']['#attributes']['title'] = t('Reset');
  }
  return $form;

It solved my problem.


How to assign value from one file field to another programmatically? I have a webform which have a file field. In the user profile I have also created a file field.

I am using the webform for user registration So I am assigning the values from the webform to the user profile fields programmtically on webform submit.

But I am unable assing the uploaded file in the webform to the user profile file field.

I am using the following code for assigning the file.

  $user->field_user_file['files']['und'][0]['value'] = $form_state['values']['submitted']['field_webform_file'];

but it did not work.

Any Idea what should I do for this?

I have done it. Here is the code that I used to solved the problem.

  $file = file_load($fid);
  $user->field_user_file = array(
    'und' => array(
      '0' => array(
        'fid' => $file->fid,
        'filename' => $file->filename,
        'filemime' => $file->filemime,
        'uri' => $file->uri,
        'status' => 1,
        'display' => 1
      )
    )
  );


How to create a Custom Content type without Title? I'm trying to make an auction website. Therefore I made 2 Custom Content Types:
1)Item for sale
2)Offer(Bid) from user(with node reference url to Sale item)
I need to receive only 1 field(Price) from the user while making a Bid (creating the second content type).

I deleted the 'Body' field from my Content Type but I could not find a way to remove 'Title' field because it is mandatory(required) field :(
The user that makes a Bid(offer) has nothing to do with Title (he doesnt need to know that he's creating a content)

How can I remove the 'Title' field?

You can use the Auto Nodetitles module.

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).


Running updatedb fails with UnknownExtensionException error I am attempting to update my site's database after updating three modules: Configuration Update Base, Search API, and Simple XML Sitemap. Running drush updatedb produces the following error:

Drupal\Core\Extension\Exception\UnknownExtensionException: The module devel_generate_example does not exist. [error]in /Applications/MAMP/htdocs/mysite/core/lib/Drupal/Core/Extension/ExtensionList.php:265
Stack trace:#0 /Applications/MAMP/htdocs/mysite/core/lib/Drupal/Core/Extension/ExtensionList.php(579):
Drupal\Core\Extension\ExtensionList->get('devel_generate_...')
#1 /Applications/MAMP/htdocs/mysite/core/includes/update.inc(318):
Drupal\Core\Extension\ExtensionList->checkIncompatibility('devel_generate_...')
#2 /usr/local/Cellar/drush/8.1.12/libexec/commands/core/drupal/update.inc(134): update_get_update_list()
#3 /usr/local/Cellar/drush/8.1.12/libexec/commands/core/core.drush.inc(462): update_main()
#4 /usr/local/Cellar/drush/8.1.12/libexec/includes/command.inc(422): drush_core_updatedb()
#5 /usr/local/Cellar/drush/8.1.12/libexec/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#6 /usr/local/Cellar/drush/8.1.12/libexec/includes/command.inc(199): drush_command()
#7 /usr/local/Cellar/drush/8.1.12/libexec/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#8 /usr/local/Cellar/drush/8.1.12/libexec/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#9 /usr/local/Cellar/drush/8.1.12/libexec/drush.php(12): drush_main()
#10 {main}

I have confirmed that Devel and all of its submodules (including devel_generate and devel_generate_example) are installed. I have attempted deactivating, uninstalling, and reinstalling them, but I am still getting the same error. Does this look familiar to anyone?

Drupal can't find the module when it's scanning the codebase. You'll have to debug to figure out why. Run drush eval 'print_r(array_map(function ($ext) { return $ext->subpath; }, \Drupal::service("extension.list.module")->getList()));' to have Drupal dump what modules it can see and try see why it can't find the install location location (file permissions?).


Missing tabs in Media Library widget in Drupal 8.8 I'm trying to set up Media Library widget in Drupal 8.8. But for some reason, no tabs are available for selection in the widget settings. Please see following screenshots:

Do I need to install some additional module? I wasn't able to discover any settings, which would allow me to do this.

This can happen when the field is not configured to reference any media types. It's a quirk of the underlying entity reference system that can be exposed under some circumstances.

The solution is to edit the field settings and ensure that the field is configured to reference at least two media types. (If only one media type can be referenced, the widget has no relevant settings to display.)


How do I apply cufon.js only for Internet Explorer, in template.php? I have some font problems in Internet Explorer, so I am trying to apply font-family through JavaScript. It works, but the JavaScript code runs for every browser.

How do I run JavaScript code only on Internet Explorer?

This my code.

drupal_add_js('sites/all/themes/blogbuzz/js/cufon-yui.js');
drupal_add_js('sites/all/themes/blogbuzz/js/Helvetica_CE_35_Thin_100.font.js');
drupal_add_js('(function ($) {
  $(document).ready(function() {
    Cufon.replace("#content-header");
    Cufon.replace("#client_tle");
    Cufon.replace("#block-block-16");
  });
})(jQuery)', "inline");

You can't apply JS only to one browser using Drupal functions. What you can do is:

CSS workaround:

apply CSS only to IE
assign some style that will not be visible, but also will not be present in non-IE, like white 1px border on white background
use css() jQuery method to test if element has property you expect it to have in IE, and if true, execute your code.

JavaScript way:
Use jQuery Browser Plugin or similar solution to identify browser inside your js file. Execute your code if it's the browser you need it executed in.


Redirecting a user to a different home page I am trying to create a site where any logged-in user is redirected to a page that is specific for that user, when the user logs in.

Suppose that U1, U2, U3 are three users on that site. U1's home page should be http://www.example.com/u1; if U1 created any link, the link should be displayed on http://www.example.com/u1, not on http://www.example.com/u2, or http://www.example.com/u3.

I also want different admin panel for each user logging in.

You can do this with a combination of the themekey module and the login destination module. For both, you would start by creating specific user roles for the your three user types, ex

userrole1
userrole2
userrole3

Then setup these two modules and have all users with userrole1 redirect to a specific page after logging in:

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them.

And then use themekey to switch the theme / output based on the specific user role:

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.


How do you add table column sort functionality to an EntityFieldQuery? I have an EntityFieldQuery that gets displayed in a table. How do I add clickable sort-by-column functionality? When I use regular db_select queries I can sort using the following code:

 $query = db_select('tablename', 't')
   ->extend('PagerDefault')
   ->limit(50)
   ->extend('TableSort')

 // ...

 $query = $query->orderByHeader($header)
 $results = $query->execute();

Everything looks good and when the table is displayed I can click on the columns and they are hyperlinks and I can sort just fine. However, now that I have an EntityFieldQuery I can't seem to duplicate the functionality. This is what I have so far:

$header = array(
  'title' => array(
    'data' => t('Date'),
    'type' => 'field',
    'specifier' => array(
      'field' => 'field_articledate',
      'column' => 'value',
    ),
  ),
);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$query = $query->tableSort($header);
$query = $query->pager(100);

$results = $query->execute();

A one-column header appears and it says "Date" as expected, but it is not a clickable hyperlink. What am I doing wrong? What is the correct syntax?

I know this thread is a little old but adding 'field' to the array fixes the issue.

e.g.

$header = array(
  'title' => array(
    'data' => t('Date'),
    'type' => 'field',
    'specifier' => array(
      'field' => 'field_articledate',
      'column' => 'value',
    ),
    'field' => '', //There is an Isset call that prevents links from showing without this.
  ),
);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$query = $query->tableSort($header);
$query = $query->pager(100);

$results = $query->execute();

See: https://www.drupal.org/node/885014#comment-3464666 for a comment on the issue.


How can I change which view wins over two using the same path? I have two views in Drupal 8.

The standard Taxonomy term (content) view, path: /taxonomy/term/%
My custom view for just one term at path: /term-alias

When I go to my custom term, I see the view for all terms (#1), when I want to force it to #2.  How can I do that?

Use the internal path of the term:
/taxonomy/term/123

Route matching operates only on internal (unaliased) paths and route #2 having more fixed parts wins.
See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Routing%21RouteCompiler.php/function/RouteCompiler%3A%3AgetFit/9.0.x


Restricting blocks to certain URL paths without sub paths How can it be achieved, to make a block appear for the URL path /foo/* but not for /foo/*/bar?

That's not possible with the default path visibility condition.

If you need that, then you need to write your own condition plugin that allows to both have a white and a blacklist instead of just one or the other.


Getting nodes based on what the user has in their profile I have a term reference field in my user accounts and I have nodes that are also tagged with that same vocabulary.

I have a view set up to display all the nodes, but I want it to display only nodes that have the terms that the users has checked in their account.

Example:

Node: Shirt
Term(s): Blue

Node: Skirt
Term(s): Green, Blue

Node: Dress
Term(s): Red

Node: Shoes
Term(s): Purple

My user has terms: Blue, Red

I would like to see nodes: Shirt, Skirt, Dress

One of the possible solution can be

Create a view to show the nodes with contextual filters as
taxonomy,remember to allow multiple taxonomy terms may be separated
by '+' in the contextual filters.

Create a custom menu item in your custom module and in the page callback of which grab the taxonomy terms in the global user object
and call the above created view programmatically.

Here is a snippet showing how you can call your view programmatically
with contextual filters.
views_embed_view("your_view_name", "your_view_dsiplay", $taxonomy_terms_+_separated)

See the following screenshots.
In my test installation, I created the following taxonomy terms:  test1,test2,test3,and test4. I created 4 nodes too, each of them using one of those taxonomy terms (node1 => test1, node2 => test2, etc.).
The following is the screenshot of a view page showing the nodes using the taxonomy IDs passed as contextual filters.

These are the screenshots of the view configuration for those for contextual filters.


Updating to Drupal 7.x-dev until next stable release I am currently using Drupal core 7.7 and Commerce 7.x-1.0-rc3 which requires changes that are only currently present in Drupal core 7.x-dev.

If I upgrade to 7.x-dev now in order to get the updates that the latest Commerce version needs, am I committing my project to following dev branch, and is there a danger of not being able to come back to stable cleanly, when the next stable release comes about?

It's not a live site, so temporary instability a dev branch may introduce is not necessarily an issue if I'll end up back on stable soon.

EDIT: Additionally, instruction for how to upgrade core from stable to dev using Drush would be super: Drush: Update core from stable to dev  :)

No you are not: the Drupal core development workflow makes minor versions just tags of the main 7.x development branch. Periodically, the branch maintainer decides enough things have been committed to the branch to make a release worthwhile, and a new minor version release is packaged.

So let's say you download a snapshot of 7.x-dev dated 2011-08-15. At the end of the month, Drupal 7.8 is released. Drupal 7.8 would contain all of the changes you had received in the 2011-08-15 snapshot, and anything else committed between that point and the end of the month. It's essentially the same as if you downloaded a new development snapshot on 2011-08-30.

So, if you need to use the dev branch, feel free to do so with relative impunity.


Context for panel not activating for custom menu item I'm loading a group node from a custom menu item I've created in a module. The reason I've created a custom menu item is because I wanted to use a different path than the one associated with the node.

I have a panel with a selection rule set to all group nodes. The custom menu item works and loads the group node, however, the panel is not being activated. I think it is something to do with the way I am loading the node from my hook_menu function which is preventing the context from being activated. The code I'm using is:

function mymodule_menu() {

$items['course/course-1/resources'] = array(
    'title' => 'Resources',
    'access callback' => TRUE,
    'page callback' => '_getpage1',
    'page arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'menu-course-menu',
    'weight' => '1',
);

return $items;

 }

function _getpage1($arg1) {
    $path = drupal_get_normal_path("course/" . $arg1);
    $node=menu_get_object('node',1,$path);
    return node_page_view($node);
 }

Is there anything I need to add to activate the context for the group?

Many thanks,

Ben

ADDTIONAL INFORMATION:

I have two variants set up.

For the first:

Selection rule: Node is an OG group AND path matches "course/*/resources".

Context: No context is set

Relationship: OG Group from node

For the second:

Selection rule: Node is an OG group.

Context: No context is set

Relationship: OG Group from node

The first variant is supposed to be activated for the same group node when the path "course/course-1/resources" is used, and the second is supposed to be activated when the path is simply "course/course-1". At the moment only the second variant is being activated. When the path "course/course-1/resources" path is used it just shows the Course 1 group node in it's default layout with no panels being used.

I like to test a panel answer before I post it, but will be gone for a couple days, so I'll give you my speculation on what may be causing this.  I suspect your page panel path is /course/%course and so that is the only path that is intercepted.  It does not matter that you have a variant for resources because it never gets tested. The basic panel definition has already rejected it.  Try changing the basic path to /course/%course/!other.  The !other variable is optional so the panel should intercept 2 and 3 level paths matching the pattern.  Your variant should then be triggered.

The variable labels in the path (%course & !other) are used to identify associated contexts listed on the context/relationships tab for defining the variant and the specific label name does not matter.  Hope this works. If not, I'll check back in a couple days.


How to display data collected in a form on a page templated in module's tpl file? I'm new in the use of Drupal and I have some troubles with the module I'm writing.
This module generates a form that writes datas in some tables. It works fine, the datas are correctly writen in the database.

My module.module file contains the following functions :

function myform_xml_menu()

function myform_xml_form($form, &$form_state)

function myform_xml_form_submit($form, &$form_state)

The big question is : how to display the submitted datas ?

I've already tryed writing a second module called "Display" :

<?php

function display_menu(){
$items['display'] = array(
    'title' => 'Display',
    'page callback' => 'display_contents',
    'access callback' => TRUE
);

return $items;
}

function display_contents(){

$query = db_select('form_xml', 'f');
$result = $query
        ->fields('f')
        ->execute()
        ->fetchAll();

$output = '
Id	Name	Description
';

foreach($result as $key){
    $output .= '
';
    $output .= ''.$key->id.'	';
    $output .= ''.$key->name.'	';
    $output .= ''.$key->description.'	';
    $output .= '
';
}
$output .= '
';

return $output;
}

It adds a menu item and display my results correctly too. But I feel making it wrong or unproperly...
I've read many docs speaking about displaying module's results in blocks or pages.

How can I embed my results in a Drupal page in order to be able to manage its display using a .tpl file ?

You need to use hook_theme in your module to manage content in tpl file.

Example,

Creating template file using the hook_theme function

    /**
    * Implements hook_theme
   */

    function example_theme(){
      return array(
        'exampletheme' => array(
            'template' => 'exampletheme',
        'arguments' => array('example_array' => NULL),
          ),
      );
    }

Now, we can use "exampletheme" theme to display content. Below is the page callback function for the menu item.

 function example_callback(){

  $array = array(1,2,3);

  return theme('exampletheme',  $array);
}

Now, you need to create "exampletheme.tpl.php" file and you can render the "example_array" in the tpl file.


Fetch Drupal nodes as json by url/title Our Drupal system has the Services module enabled and is able to return nodes as json using the following url format

http://www.example.com/my_endpoint_path/node/123.json

But I want to retrieve a node using the URL alias I set in the URL path settings tab. I hoped the following would work

http://www.example.com/my_endpoint_path/my_pages_URL_alias.json

But it does not. Is there a way to configure Drupal/Services to fetch nodes by that URL rather than the node id?

In Service Module API, Some hooks are presents to help you.
You need to alter or add your own implementation of this service.

The second link is a file where you have the default service implementation.
You can try to alter this configuration with your own by using "hook_services_resources_alter".

I can't test but you can try and custom this snippet :

function YOUR_MODULE_services_resources_alter(&$resources, &$endpoint) {
    $['node']['operations']['retrieve']['callback'] = '_your_retreive_method';
    $['node']['operations']['retrieve']['args']     = array(
        'name' => 'node_alias',
        'optional' => FALSE,
        'source' => array('path' => 0), // Put your path index here
        'type' => 'string',
        'description' => 'The alias node to get',
    );
}

function _your_retreive_method($node_alias){
    // transform your alias to nid
    $path   = drupal_get_normal_path($node_alias);
    if($path !== $node_alias && ctype_digit($nid = str_replace('node/','',$path))){
        return _node_resource_retrieve($nid);
    }
    return false;
}

Links :

Service API Docs
File with an implementation of a service


Why does default.settings.php suggest writing the value of the hash salt in an external file? The default.settings.php file contains the following comment:

  For enhanced security, you may set this variable to the contents of a file outside your document root; you should also ensure that this file is not stored with backups of your database.

  Example:

$settings['hash_salt'] = file_get_contents('/home/example/salt.txt');

Assuming the attacker was able to create a PHP file inside my Drupal installation, in which way does writing the hash salt in a file increases the security? In any case, the attacker would be able to read the value for $settings['hash_salt']. Eventually, the attacker could change the value for $settings['hash_salt'], but does doing this make any sense for the attackers to do?

The main reason to do this is to prevent the salt from accidentally being committed to your content versioning system.

Most advanced hosting environments (both Drupal hosts and all-in-one Drupal stacks) provide ways to do this.

Similarly, it is useful to go through the trouble of abstracting DB settings and the like, both for security and to make it easier to move your code from one environment to the next.


Add captcha to webform I'm working on a drupal 8 project, I've created a webform and trying to associate a captcha to my webform using captcha contrib module.
I've a personalized template for my webform in which I render the webform fields.
I've associate the captcha to the webform under /admin/config/people/captcha/captcha-points and test as anonymous user it is always unable to associate captcha to the webform.

Should I print captcha in my webform template file? if so how to do it?
Should I add an element Captcha to my webform fields? if so is that element by default use captcha contrib module settings?

Any help is appreciate.

To captcha protect a webform you NEED to add a captcha element to it. When captcha contrib module is enabled on your site the available captcha challenge types are available to be used on a per webform basis.

The template twig file is mostly for design puproses.

If the placement of captcha within the form is not to your liking you should copy the default webform template from /modules/contrib/webform/webform.html.twig to your theme /themes/custom/MYTHEME/templates/webform--WEBFORM_MACHINE_NAME.html.twig and perhaps place each element seperately.

The default webform.html.twig is

<form{{ attributes }}>
  {{ title_prefix }}
  {{ children }}
  {{ title_suffix }}
</form>

And in our own copy we should take out {{ children }} and replace with individual elements but also we have to make sure form ids and actions are included manually and it the final template should end up looking similar to this

<form{{ attributes }}>
  {{ title_prefix }}
  {{ element.elements.first_name }}
  {{ element.elements.last_name }}
  {{ element.elements.captcha }}

  {# necessary elements #}
  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.actions }}

  {{ title_suffix }}
</form>

Where captcha for example is the machine name of the captcha field


Update hooks and features_revert I have a problem in a custom module I can not figure out, I have an update hook like this one:

function article_update_7003() {
  features_revert(array('article' => array('field_base')));
}

But it does not revert the feature. But if I run that update, and manually change it to:

function article_update_7004() {
  features_revert(array('article' => array('field_base')));
}

And run it, the feature is reverted. Anyone that knows what is going on? I tried to duplicate it the first time, but that does not help...

function article_update_7003() {
  features_revert(array('article' => array('field_base')));
  features_revert(array('article' => array('field_base')));
}

It is my understanding that the update hook only runs once per update. The function is hook_update_n where 'N' is the instance of the update hook. Each time you want to revert your feature upon a code update you need a new update hook. This is why if you increase the number it works. If you are increasing your version numbers when you regenerate your feature, and also reverting your feature in code with an update hook, those numbers should match, and you will have an update hook for every version increment.

Source: Drupal API.


Restrict people from sites Is there any module that can restrict people from accessing certain pages when they are not logged in?

There's a contrib module, contentaccess which is fairly easy to use and permissions can be managed on a node by node basis.

There's a good article about Drupal content access control here


Request for invalid marker set I've installed gmap module and configured it so that I'm using custom markers. It worked well till today (I've re-deploy website).

I'm able to choose my custom marker 'Accountant' in a settings (see screen below).

However when I load map I get an error message: "Request for invalid marker set"

I've googled it and did not find a clear explanation what is wrong.

Please advise what could be an issue.

There is an update "REGENERATE MARKER CACHE" option in gmap settings.

By pressing "Regenerate" button Drupal will update JS file stored in

/sites/default/files/js

Make sure you have access to that file.


Check db_merge status whether inserted or updated I am using db_merge() in my code, and I would like to print a status message with drupal_set_message() that reports if the record has been added or updated.

Is it possible?

MergeQuery::execute() returns MergeQuery::STATUS_INSERT when the data was inserted in the database table, and MergeQuery::STATUS_UPDATE when a row was updated.

MergeQuery is the class of the object returned from db_merge().

public function execute() {
  if (!count($this->condition)) {
    throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  }
  $select = $this->connection->select($this->conditionTable)
    ->condition($this->condition);
  $select->addExpression('1');
  if (!$select->execute()->fetchField()) {
    try {
      $insert = $this->connection->insert($this->table)->fields($this->insertFields);
      if ($this->defaultFields) {
        $insert->useDefaults($this->defaultFields);
      }
      $insert->execute();
      return self::STATUS_INSERT;
    }
    catch (Exception $e) {
      // The insert query failed, maybe it's because a racing insert query
      // beat us in inserting the same row. Retry the select query, if it
      // returns a row, ignore the error and continue with the update
      // query below.
      if (!$select->execute()->fetchField()) {
        throw $e;
      }
    }
  }
  if ($this->needsUpdate) {
    $update = $this->connection->update($this->table)
      ->fields($this->updateFields)
      ->condition($this->condition);
    if ($this->expressionFields) {
      foreach ($this->expressionFields as $field => $data) {
        $update->expression($field, $data['expression'], $data['arguments']);
      }
    }
    $update->execute();
    return self::STATUS_UPDATE;
  }
}


moving of a database [drupal-commons 6x25]: Which tables can be emptied safely? I am running Drupal Commons 6.x25  (released February 2012); I have installed it yesterday locally on a lamp, on OpenSuse 12.1. Now I want to move it to the web server, but I have noticed that the fresh database—without any special module, beside the ones that are shipped with commons—is extremely large (16 Mbit).

Sometimes, the moving of a database can be too hard since the database is a way too large. Which Drupal tables are safe to manually clear using PhpMyAdmin?

What about all the "cache_" prefixed tables be emptied without causing problems?

Background: well - sometimes i have some troubles in meging the 16 db at once... but i continue to try to move a drupal-commons in a single step without any emptiying. BTW to which extend we can lower the db-size of 16 mb - 10 or 5 mb probably.

I used to empty all "cache" prefixed tables, "watchdog" table and session table.


Hierarchical select hook form alter I have a problem with getting my module_form_alter to work for hierarchical select. I am running on Drupal 7 and my content type is called mytemp and I'm pretty sure my form-id is mytemp_node_form. I have a taxonomy called ICA which my hierarchical select references to.

I get the following error when I run it:

  Warning: Invalid argument supplied for foreach() in arjmod_form_alter() (line 8 of /var/www/hcms/sites/all/modules/arjmod/arjmod.module)

I would like to have my hierarchical select appear with a fixed row height but I can't get it to work.

This is my code:

<?php
function mymodule_form_alter (&$form, &$form_state, $form_id){
  if($form_id == 'mytemp_node_form'){
    foreach ($form['taxonomy'] as &$vocab)
      if($vocab['#type'] == 'hierarchical_select')
        $vocab['#size'] = 10;
}} ?>

Please point me in the right direction.

Looks like $form['taxonomy'] is not an array.

There are some options for hierarchical selects maybe this is all you need:

http://localhost/admin/config/content/hierarchical_select


How to view to user only the node that referenced to him? I have a Content Type with a user reference field.

I want that the user can display\access only to the nodes that referenced to him.

Can I do this with Views?

I already tried the modules Node access user reference and Node access node reference with no success because they have a huge bug. When the module is enabled many View becomes inaccessible ( https://www.drupal.org/node/1311460 ).

Entity Reference and Rules Solution.

Install both modules
Add an entity reference field with unlimited values to your content type. Make sure it references users.
For views, create a content view and add a contextual filter for the field you created. My test contextual filter was called Content: User Ref Test. Your contextual filter will have the same name as the field you created.
In the contextual filter's settings, click Provide Default: User ID from logged in User. This will only show content where the user has been referenced.
To make the content safe from typing in the url, create a Content is Viewed rule for that content type.
In the conditions, choose "list contains item". The list is the entity reference field and the item is the logged in user. At the bottom of the condition, you then negate the rule. It should look like NOT Item in List "Parameter: List: [node:field-user-ref-test], Item: [site:current-user]
Add a second data comparison condition that allows the admin (or you could do this by user role) to view the content. Negate this condition as well. NOT Data Comparison > Parameter: Data to compare: [site:current-user:uid], Data value: 1
Add a system redirect to the homepage and a message explaining why the user couldn't view the content.

If it doesn't work, check to make sure the entity reference field is set to unlimited because that's why we use the list in rules.


Comment notify options confusing for users I am using the Comment Notify module so that users can be notified when someone responds to their comments in forums. On a users account page the options are very confusing - there is a tick-box to receive notifications, and also a drop-down, which only contains two options: "No notifications" and "Replies to my content". The text below the drop-down is also confusing.

Have I got a configuration issue, or is this working as designed?

As discussed in the comments: no, you haven't got a configuration issue, and yes the module is working exactly as designed.

If your users are likely to find that confusing, you can use hook_form_alter() in a custom module/theme to change the text to something that makes more sense. Or even hide one or more of the options altogether, if that's what you need.


How to show taxonomy terms and tags? i have two separate contents in two different content type. The other one is in the basic page, other one is in the content type i made(regional malls). The taxonomy terms or tags is showing in basic page when i publish but my problem is in the regional malls content, when i published, taxonomy terms or tags does not show up, any ideas why is this happening?or advise how to overcome this?

Create separate .tpl for content types and then put the code to print taxonomy term

<?php if($node->field_category): ?>
<div class = "top_tag">
  <?php print $node->field_category['und'][0]['taxonomy_term']->name;?>
</div>
<?php endif;?>

put this code in template.tpl.php

function mytheme_preprocess_page(&$vars) { // replace mytheme with your theme name
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

hope it helps you!


How do I prevent my content's title from appearing in the  tag of my RSS feed? I have a newly migrated Drupal 8 site and am noticing that the RSS feed displays the Title of a node twice in my feed reader. This is because a node's title is output both in the feed item's <title> and within the item's <description>.
For example:
<item>
  <title>My Clever Title</title>
  <link>http://example.com/node/123</link>
  <description>&lt;span data-quickedit-field-id="node/123/title/und/rss"&gt;My Clever Title&lt;/span&gt;

  &lt;div data-quickedit-field-id="node/123/body/und/rss" class="field field--name-body field--type-text-with-summary field--label-hidden field--item"&gt;
  Lorem ipsum... my content displays here....
  </description>
  ...other tags here...
</item>

So now, a feed reader like Feedly displays my content like this:

My Clever Title
My Clever Title
Lorem ipsum... my content displays here....

Note: In my RSS Manage Display, the content type is set to display the "Default" (not-trimmed) body field.
How do I prevent my RSS feed from inserting the post's title into the the <description> tag?

I haven't tried to reproduce this on my end, but I found a Drupal.org thread with advice that may be relevant:

https://www.drupal.org/project/drupal/issues/2946812#comment-12501714

  using 'Show: content' looks like a bad idea to begin with.

  I can get some nice clean output:

  Choose 'Show: Fields' (so not 'Force using fields', just plain fields output)
  Close the dialog without setting the required fields (just click the X in the top right corner)
  Add some fields (title, body, a url, node id)
  Go to Row style options (so click on the 'Settings' link behind 'Show: Fields'
  Fill out the required fields with the fields you've added
  Add more fields if you need them to fill out the required settings

If you build the description this way, you should easily be able to omit the title field. Good luck!


Splitting up content fields into different regions My situation is as follows: I have a content type Seminar, with fields A, B, and C.  I have regions Header, Footer, Content, and Sidebar Left.  There are some fields in Seminar I want displayed in the Content region, but also in the Sidebar Left region.

How do I go about doing this?  Apologies if this has already been answered before.  I am a developer and am not hesitant to dive into hook and preprocessor functions.  I have the Views module installed, but have never used it (this is my first Drupal site, if you can't tell :P).

Cheers.

EDIT: This is for Drupal 7.

There is no easy out of the box way to add the content of a node to different regions on the page.    There is multiple ways to tackle this problem.

Non-coding way: Views & Blocks

Create a view

Type: Block
Contextual Filter: Content: Nid

default value: grab from current page

Fields:  Whichever you want
Filter:

Content Type: Seminar

(plus whatever additonal settings you want)

Then go to administrator block page
Move the newly create view block, to the region you want it displayed.   It should only display on the seminar node pages.

Repeat for all regions

Coding Way with theme_preprocess_region():

code would look something like this

MYTHEME_preprocess_region(&$variables) {
  if (isset($node) && ($node->type == 'seminar' )) {
     //add new variable here.
  }
}

This is for Drupal 7 only.   Now its avaiable in your region.tpl.php.


Taxonomy vocabulary not showing up as existing field in new content type I have 2 taxonomy vocabularies which I want to reference in new content types but I cannot see them under "add existing fields" when creating a new content type. Also tried referencing one taxonomy vocabulary from another and couldn't.

Saw this post on drupal forum and followed the suggestion of changing admin theme but it didn't work for me.

BTW, I'm using Marinelli theme.

Kind regards,

Jio

To use taxonomy with your content nodes, you have to add fields to your content types that allow you to assign taxonomy terms.
To add a field for your taxonomy to a content type:

Go to Structure > Content types.
Find the listing for the content type you want to modify, and then
click its manage fields link.
In the Add new field section, enter text for the Label and Name
columns.
In the Field type column, select Term reference from the drop-down
menu.
In the Widget column, use the drop-down menu to select from the
following widgets:

  Check boxes/radio buttons - The taxonomy terms are listed in a check box on the content creation page for this content type.
  Select list - A list of the taxonomy terms are displayed on the creation page for this content type.
  Autocomplete term widget (tagging) - A text box is added to the content creation page for this content creation page.

Selected or entered taxonomy terms are assigned to the content node when the node is saved or published.
Click Save.
In the Vocabulary drop-down menu, select the vocabulary you want to
use with this content type.
Click Save settings.

A taxonomy term field is added to your content type, using the label you chose. When you create content of this type, you will now find a field on the creation and edit forms that allows you to assign taxonomy terms to the content node.

Thank you.


change node types file fields widgets programatically? I have installed multi_upload_filefield_widget.

I would like to change every file widget of every file type fields of every node type programatically.

i would need to automate this change since i have multiple sites and multiple content type.

  //when enabling the module
  function multi_upload_filefield_widget_enable() {
        //code to loop through all node types fields for one site

       // if type is file
            // replace widget 'file' to 'multiupload
            //save content type with this new value
}

Here is where i am at

       $types = node_type_get_types();

       foreach ($types as $type){
           $fields=field_info_instances("node",$type->type);

            foreach ($fields as $field){
               if ($field['widget']['module']=='file'){
                    $field['widget']['module']='multiupload_filefield_widget';
                    $field['widget']['type']='file_mfw';
                }
                 // my fields don't get saved !?
                //field_attach_update("node", $field);
                 //field_update_field ( $field );
             }

          $fields=field_info_instances("node",$type->type);
          print_r($fields);
        }

How can i save these modified fields ?

any help would be appreciated

It seems like this could do the job:
Programmatically change form widget type for a field


How to put description on top of the input box, for a new field added to comment form? I have added a new field to my comment form and this is how my comment form look liks:

So you can see it does not look nice, I want to have the description on top of the input box, where I say: Which paragraph do you want to put comment on?(Enter 0 if you ant to put comment on the whole article). So How can I do it?

This is the function that I have used to add the new field to comment form:

  function Annotations_form_comment_form_alter(&$form, &$form_state, $form_id) {
$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Which paragraph you want to put comment on?(Enter 0 if you want to put comment on the whole article.)') . "<br>",
    '#required' => TRUE,
    '#size' => 10,
    '#maxlength' => 2,
    '#default_value' => !empty($form['#entity']->paragraph_id) ? $form['#entity']->paragraph_id : NULL, // set the default value to the current paragraph value
    '#weight' => $form['subject']['#weight'] + 1, // place after the subject field by setting the weight to +1 of subject weight
);

$form['#validate'][] = 'annotations_form_comment_form_validate';
$form['#submit'][] = 'annotations_form_comment_form_submit';

}

You need to add a description field to your array:

$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Your Title'),
    '#description' => t('The paragraph you would like to put a comment on (enter 0 if you want to put the comment on the entire article'),
    ...
);

This way the explanation will show up under the field.


Should a fresh install of Drupal have failing tests and what to do with the failing tests? I'm delving into the world of SimpleTest in Drupal. I started off by doing a fresh installation of Drupal 7 and running all the tests. I noticed there are a few tests that are failing, along with 1 test throwing an exception. Should a completely fresh install of Drupal 7 (or Drupal in general) have failing tests? I understand that in HEAD not all tests are going to pass. But, does Drupal get released along with a test suite that includes still failing tests?

I've tried searching the Drupal Core issue queue for some of the failing tests but haven't really found anything.

Edit

Based on comments so far, it seems that it is not intentional that a release of Drupal would include failing tests, even if for known issues that haven't been resolved as part of that release. Given that assumption, what is the best thing to do from there?

All tests are run on every patch that is posted on drupal.org, fully automated. Nothing is commited unless all tests are passing (It happens that something is commited that breaks the tests (for example if the tests only fail sometimes or the fail was not triggered on the patch for some other reason. However, development comes to a complete halt in such cases until the tests are working again.

But, these automated tests are run on equally configured, highly tuned linux servers (they currently run all of the core tests in ~40 minutes, I'm not going to ask how many hours it took you :)).

So, what is possible is that your system is somehow configured differently, uses different version of PHP, MySQL, the OS or something else. The tests should of course pass on every supported environment, so what I would recommend is creating a core issue, list the not-working tests (including the exact failures, e.g. with screenshots) and a detailed description of your set-up including your versions of PHP, MySQL, Apache, OS, extensions and so on.

I know that DamZ does regularly run all tests on different setups, including PostgreSQL, Windows and so on and I'm pretty sure that most except the Linux/MySQL env still have known failures. Edit: The site for this is on http://drupaltesting.org/, but it looks like it's been broken (the test environment, not the tests) for a few months now..


Drupal function field_get_items vs user_load In Drupal, I want to read a custom field value for a group of users while logged into an admin account. I only need 1 field value from each user, the same field and I do not need this information cached.

When I use user_load it requests the user object as I only need one field this is very inefficient.

So I investigated field_get_items, but I cannot see how to use this function without first using user_load.  I have attached my code and MARKED the line that is giving me an issue.

how can I use field_get_items without using user_load, if not possible is there a efficient way of doing this?  Please don't mention user_load_multiple
with user_load does setting , $reset = TRUE prevent Drupal caching the data or does it force a cache reset, get the data from the DB and then re-cache the new data?

Code I use:

$user_a = array();  //  This is the array of URIs we need to query
foreach ($user_a AS $uid){
  $account = user_load($uid, $reset = TRUE);  // access the user objects, one at a time
  $fullname[$uid] = $account->field_fullname[LANGUAGE_NONE][0]['value']; // extract value
}

$user_a = array();  //  This is the array of URIs we need to query
foreach ($user_a AS $uid){
  **$account = user_load($uid, $reset = TRUE);**
  $fullname[$uid] = field_get_items('user', $account, 'field_fullname');  // extract array
  foreach ($fullname[$uid] as $item) {
    $fullname[$uid] = $item['value'];  // extract value
  }
}

No, You can't use field_get_items without the loaded user object. As the entity has to be passed as the second argument as illustrated in documentation.

Any reason why you hate user_load_multiple? As user_load itself uses user_load_multiple.

If you don't want to retrieve that huge amount of arrays. You can consider building your own query to retrieve just the field you want.


How to programmatically modify an exposed filter? I have an exposed filter on the Title field for my content type; i would like to use the same filter for applying the following condition: select all where (field_value) like %node.Title% OR %author.Title% where Author is a term reference to an Author vocabulary.
I've tried to do this but i wasn't able to solve it.
How can i do it? Have tried using views_query_alter but without success.

Maybe you should make a hook_form_alter to build only one box.

And in the validation or submit give the box value to both form_state options.

Another options is to use hook_query_alter to build your own query.

Oskar


How to get the commerce subscription status for current user on particular product page? How can I get the product subscription status for current logged in user on particular product page. Suppose user can subscribe for a video tutorial and we have video as a product then how can we know that current user had already subscribed to this product or not.

I'm actually in thought of adding comment to your question, but my reputation count made me convert my comment to answer. (Yes, I'm a beginner!)

For your question:
You have multiple products in your page and there exists a distinct 'commerce sp time' per product. So, the process flow would be,

When an end user subscribes to a particular product:

Disable the subscribe button of that product (may be a video tutorial) and change its value to 'subscribed'.
Set a schedule for the user with respect to 'commerce sp time' of that product, to trigger a custom PHP code (probably, enabling the susbcription button of that product).

All my concern is, Is this useful?
I had already achieved this feat technically, so would you..


How can I render [webform_submission:values] in a table? I am trying to figure out from where [webform_submission:values] gets rendered. This is how it looks right now in the email submission.
Label 1
Value 1

Label 2
Value 2

I want this in a table format. Is there a possibility to change the render code to do this?

You can use the Webform tokens from submitted data as following guide:
[webform_submission:values:?]

Omit the '?' to output all values. Output all values as HTML using [webform_submission:values:html].
To output individual elements, replace the '?' with…

element_key
element_key:format
element_key:raw
element_key:format:items
element_key:delta
element_key:sub_element_key
element_key:delta:sub_element_key
element_key:sub_element_key:format
element_key:delta:sub_element_key:format
element_key:delta:format
element_key:delta:format:html
element_key:entity:*
element_key:delta:entity:*
element_key:delta:entity:field_name:*
element_key:sub_element_key:entity:*
element_key:sub_element_key:entity:field_name:*
element_key:delta:sub_element_key:entity:*
element_key:checked:option_value
element_key:selected:option_value

All items after the 'element_key' are optional.
The 'delta' is the numeric index for specific value
The 'sub_element_key' is a composite element's sub element key.
The 'checked' or 'selected' looks to see if an 'option_value' is checked or selected for an options element (select, checkboxes, or radios)
The 'option_value' is options value for an options element (select, checkboxes, or radios).
The 'format' can be 'value', 'raw', or custom format specifically associated with the element
The 'items' can be 'comma', 'semicolon', 'and', 'ol', 'ul', or custom delimiter
The 'entity:*' applies to the referenced entity
Add 'html' at the end of the token to return HTML markup instead of plain text.

For example, to display the Contact webform's 'Subject' element's value you would use the [webform_submission:values:subject] token.

Then you can use your custom style by adding them into table or list


Using Custom Formatters module to output an image's URI I'm trying to make a formatter which prints an image's URI instead of the image itself. My problem is I don't know what the formatter is expected to return. The help information is apparently not working on my install.

So, what does it expect as it's return value? This is what I've tried:

function image_path_formatter($vars) {
    $element['content'] = $vars['#items'][0]['uri'];
    return $element;
}

My view has this in content:

Edit formatter

You should take a look at the file module, which does a lot of this already

For Drupal 7:

/**
 * Implements hook_field_formatter_info().
 */
function file_field_formatter_info() {
  return array(
    'file_default' => array(
      'label' => t('Generic file'),
      'field types' => array('file'),
    ),
    ...
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function file_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'file_default':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'file_link',
          '#file' => (object) $item,
        );
      }
      break;
    ...
  }
  return $element;
}

You could copy this and create your own theme function, all it needs to do, would be to print the uri and you're done.


How to implement something to differentiate nodes? I wonder how I could implement something in my Drupal site where nodes can be different and managed separately.

For example, in my site I want to add to nodes as shops, and every vendor must manage his/her shop, post news, add images, etc.

Any suggestions

You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to pass/link the node id of the result of a view (say, content type A) to another view of content type B, which are referenced in content type A? I have three content types: Newspaper, Headlines, and Local. All entities have  standard Title/Body fields. Newspaper has two additional multiple value fields named Headlines and Local that are referencing the respective content types.

I ultimately would like two very similar RSS views (one for Headlines and one for Local) that would show respective nodes that are linked from a Newspaper content. I am able to do this using Views Relationships. The problem is how to display only referenced nodes that are linked from the latest Newspaper content type.

I also contemplated on the possibility of first creating a separate view that displays the latest Newspaper, but I can't figure out how to pass it to another view, if it's even possible.

Here's some concrete information:
Say for example, I have the following content

Newspaper

June 19, 2018
June 18, 2018

Headlines

Blah
Bleh
Meh

Local

Something Happened
Nothing Happened
Nothing Happened again

Here's a visual on what I'm trying to get.

The whole reason for this is that I'm working with a newsletter application whose templates can take in several feeds. The particular template has a different style per section. I was planning to pull in a separate feed per section so the section can be styled independently. Even though the would-be feeds are separate, I need them to be in sync with one another and make sure they're pulling from the same Newspaper content.

You can do this with the help of the Views Field View module by embedding one View display into another.

In your case you want to have one View showing only the one latest Newspaper, and the other helper Views Display listing Headlines referring to the latest Newspaper that will be embedded into the first Display.

Here are the steps how to do it:

Create a Newspaper View
Add Sort criteria "Authored on" (Descending)
Use pager: Display a specified number of items | 1 item

You should now have only your latest Newspaper node listed as a result. You don't need any Relationships or Contextual filters here.
Add a new field Content: ID, Exclude it from display and Rearrange fields so this one is on top
Create a new Views Display of type Embed in the same Views
Keep the filters (Newspaper) but override the Pager to show all items
Add a new Field Content: Headline and under Multiple field settings make sure you're NOT using Display all values in the same row, it should not be ticked
Add a new Contextual filter Content: ID for this display only and configure it:
When the filter value is NOT available
Provide default value
Content ID from URL

Now if you enter the node ID of the latest Newspaper node into the View Preview argument field you should see a list of Headlines referencing that node.
Save the View (Important! The next step won't work without it)
Edit the original View Display (from step 1 above) and add a new Field Global: View (Embed a view as a field.)
Under View settings for this field select the View you're currently editing. You may need to Save the View again at this point.
Then under Display option under it choose Embed and fill in the Contextual filters fields with the node ID token from the Replacement patterns below it. It will probably be something like {{ raw_fields.nid }}

You should now have a list of the latest Newspaper node with Headlines referring it also listed.

Even though the View is set to display Newspaper nodes, through the Entity reference field and an ID contextual filter you only see Headlines listed.

Descendant sorting and pager limited to one is making sure it's related only to the latest Newspaper.

Using a different View display to show Headline nodes enabled us to list them one Headline per view row. If we did that in the original Display we'd had to list them all on the same row, because if we didn't we might not get all the Headlines listed because of Pager limit. And Headline count per Newspaper probably varies so we can't predict anyway.

In the end Views Field View enabled us to embed one view into another one and pass argument to it.

Now repeat all the steps for the Local content type (clone and edit).

Your original Views Display will probably be Feed, but it would have been too complicated to include it in this explanation.


How can I get and format the node created date in field.html.twig? The date is being rendered from field.html.twig template from {{ item.content }} from "items" array. After Using a twig filter date {{ items.content|date("long") }} it only outputs current date not the date node was created. How could I achieve node submitted date instead of the current date.

Having a field template you always can get the parent entity via element['#object']. And from there you can get everything else, also the creation timestamp. You then can format it using Twig's date() filter or with format_date() in a predefined Drupal date format.

In any variation of field.html.twig (field--field-myfield.html.twig etc.) do:

  {{ element['#object'].getCreatedTime | date('F j, Y') }}

  {{ element['#object'].getCreatedTime | format_date('html_datetime') }}

Source: Sample taken from Accessing the original entity in field templates is hard.


Make a Search view have the same options as a Content view I have created a Content view that works perfectly, believing I would later add facets to it once Solr is up and running.

Now that Solr works together with Search API, I realize that to use facets I need my view to be a Search view.

Unfortunately now with the view being a Search view I can no longer use:
Contextual filter - Content: Has taxonomy term ID (with depth)
Relationship - Flags: my flag (by any user)
Field - Flags: Flag link
Field - Computed fields: (values are all 0)
Field - Content: Path (Found a work around for this one)

Is there a way to make my Search view behave like a Content view and therefore have access to all needed functionalities?
Or may be could I use facets on my Content view? None of my tests worked though.

H,

This is something I'm still searching for an authoritative solution to/answer on.

This is apparently known issue with Flag and Views, with most people taking programmatic approaches to solve their particular problem.

There's a patch to that should address at least some of your problems here. https://www.drupal.org/node/1362298. This seems to be the closest anyone is to a solution at the moment.


Custom field for Search API with multi values I'm using latest version of SearchAPI (1.18) and SearchAPI Solr (4.1.10).
I've a custom field that I want to have multiple values (I use it for faceted search with Facets module). In the previous version of SearchAPI the second example worked.
If I use this code, SearchAPI save "Array" as value:
<?php

namespace Drupal\archivio_utils\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 *
 * @SearchApiProcessor(
 *   id = "periodo",
 *   label = @Translation("Periodo"),
 *   description = @Translation("Periodo"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class Periodo extends ProcessorPluginBase {

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    if (!$datasource) {
      $definition = [
        'label' => $this->t('Periodo'),
        'description' => $this->t('Periodo'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      ];
      $properties['search_api_persona_periodo'] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();
    /* @var \Drupal\node\Entity\Node $entity */
    /* @var \Drupal\node\Entity\Node $carriera */
    if ($entity->bundle() == 'persona') {
      $fields = $this->getFieldsHelper()
        ->filterForPropertyPath($item->getFields(), NULL, 'search_api_persona_periodo');
      foreach ($fields as $field) {
        if (!$field->getDatasourceId()) {
          $values[] = 'test1';
          $values[] = 'test2';
          $field->addValue($values);
        }
      }
    }
  }
}

If I replace code where I wrote values with this:
$values[] = 'test1';
$values[] = 'test2';
foreach ($values as $value) {
   $field->addValue($value);
}

I obtain this error:

[error]  Drupal\search_api_solr\SearchApiSolrException while indexing
item entity:node/10008:it: Solr endpoint http://solr:8983/ bad request
(400). ERROR: [doc=3igm00-archivio_indice-entity:node/10008:it]
multiple values encountered for non multiValued field
ss_persona_periodo: [test1, test1] in
Drupal\search_api_solr\SolrConnector\SolrConnectorPluginBase->handleHttpException() (line 1016 of
/var/www/html/web/modules/contrib/search_api_solr/src/SolrConnector/SolrConnectorPluginBase.php).

How can I add multiple values to this custom field?

You can add this:
foreach ($fields as $field) {
    $field->addValue($custom_field);
    $field->addValue($custom_field);
}


Commerce product options on product basis I am using Drupal Commerce and I would like to create product attributes. So customer can adjust some attributes before he would buy an item.

I know, that there are some commerce modules, that enable attributes / options of product. But I cannot find such module, that would enable setting attribute options separately for each product.

I have found Pricing Attributes module, but I can set options only globally, not separately for each product. I can set separately only price and enable/disable options. But I am not able to add new options.

Is it possible to add new attributes options to product using  UI with some commerce module?
If not, can anybody help to find documentation or API, how could I set product options programatically by myself without existing attribute modules?

Drupal Commerce generally conceives of attributes as those things about a product that a customer might specify on the Add to Cart form to drill down to a particular SKU, i.e. a particular variation in a group of products. From this perspective, you wouldn't have the ability to randomly add options to a product for selection on the Add to Cart form; you'd define attributes as fields on your product type and create a unique product for each potential variation.

You can use line item fields and expose them to the Add to Cart form, allowing the customer to enrich the line item with additional information required for fulfilling the product that do not affect the SKU. There are videos showing both of these different features in our video library:

http://www.drupalcommerce.org/videos

Finally, I met Joshua Needham at BADCamp, and I believe he intends to put some time into the Commerce Product Options module. This was a suite of modules initially developed by hunziker and then left on its own for a year or two. If Joshua is able to get commit access, I'd expect to see some work in there that allowed for product by product configurable bundles of options that are exposed through the line item form. I'd pull up a link for that but drupal.org is down atm. : )


Rankings and Dates in Views (data architecture) I'm working on building a small name ranking database, but I'm having some issues coming up with how to architect the data. Here's the scenario:

You have a list of 100 names with rankings by year.

|  Name  | 2012 rank | 2011 rank | 2010 rank
--------------------------------------------
|  Carl  |    1      |     4     |    15
| Frank  |   40      |    18     |    34
|  Lou   |    8      |     6     |     4

et cetera and so forth. If each name was a node, how would that content type be set up so you can filter rankings by year?

Would you have a new field for each year that has the ranking in it? ie: Field name: 2012 Rank, value: 8.

Just curious how someone might approach this.

I could propose using Entity Reference or Field Collection for the second item (Rank).

So, Rank should have 2 different fields eg an integer field (Ranking) and a taxonomy term reference (Year).

These modules will allow you for better data manipulation, Views integration, sorting etc.


Is someone trying to hack my site? I was looking at my drupal site log messages and I´ve been having very weird ones as the ones attached.

I was wondering if someone is trying to hack my site, if so, how can I prevent that? I have all my site up to date. But it seems I need to take more measures.

thanks in advance

What you see in the log is malicious, so: Yes, somebody is rattling the doorknobs on your site to see if some door is not locked.

However, what you see is nothing unusual. I think you'll find similar entries in every watchdog log for a Drupal site that is "in the wild" (i.e. outside of a firewall).

Should you take more measures? IMHO, no. There is nothing in the messages you've posted that indicates that you're being targeted. These are random shots in the dark by script-kiddies - and they're all misses.

One of the reasons we use Drupal is because the core is pretty resistant to this sort of thing out-of-the-box.  Just make sure you keep your site updated. And don't install experimental or badly maintained contributed modules without checking them for security holes yourself.


Get node field image in " hook_node insert " I'm getting the values of the node that I'm about to create with my custom module and the function " hook_node_insert " but I'm not receiving the data of my image like the path and name.

I'm just getting the fid, is that useful?

Is there any other method to get the data?

Thanks guys !

Drupal gives this by single file load from database:

$objFile = file_load($fid);
$imgabspath = objFile->uri; //getting file page (Example of image file absolute path)
print file_create_url($imgabspath);  //This is your file absolute url
$filename = objFile->filename; //getting file name

Still you are not getting result proper then there is some problem into $fid so confirm it by:

$node = node_load($nid);
// assuming file field has been added to the node has field_example_file machine name.
if (!empty($node->field_example_file)) {
  // $img will contain an array, which has the data of a file (file object converted to array I suppose..)
  $img = $node->field_example_file['und'][0];
}
$fid = $img['fid'];//This is your fid...

NOTE : file_create_url() always creates an absolute URL, either using the global $base_path that you have defined, or using the one that Drupal guessed during bootstrap. Also note that file_load() doesn't return title and alt attributes of field_image.

Thanks!


Installing the Waypoints plugin I’m using Drupal 8.5.4 and I have installed the Advanced CSS/JS Aggregation module. I’m trying to install the Waypoints plugin without success via the module: jQuery waypoints (still on alpha1 for D8). Is there a way to simply install the plugin manually?

Yupp, simply download the Waypoints library, extract and rename the folder to just waypoints, then put it into themes/custom/MYTHEME/libs or into modules/custom/MYMODULE/libs and follow one of the following instructions:

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

Basically all you have to do is to create the corresponding MYTHEME/MYMODULE.libraries.yml file

waypoints:
  js:
    libs/waypoints/lib/jquery.waypoints.min.js: {}
  dependencies:
    - core/jquery

and then attach the library to all pages via hook_page_attachments() or hook_page_attachments_alter() inside the MYTHEME.theme or MYMODULE.module file.

<?php

function MYTHEME/MYMODULE_page_attachments_alter(&$attachments) {
  $attachments['#attached']['library'][] = 'MYTHEME-or-MYMODULE/waypoints';
}


Users are unable to approve a one way relationship I've set up a one way relationship with the User Relationships module When one user requests a relationship to another user, the table that should allow the other user to approve/deny the request has no operations automatically populated.

To be more specific lets say this is a Manager relationship to an employee. Where User A is the manager and User B is the employee. User A requests to be User B's Manager. User B receives the request and follows the link to the page where he/she would normally approve the relationship.(example.com/user/[uid]/relationships/received) When User B arrives on the page there is a table showing the request, but under the Operations column there is nothing in the cells.

I initially thought this was a permissions issue, but when I looked it appears that both users have the permissions they should need to accomplish this.

For reference I'm using version 7.x-1.0-alpha5 of the User Relationships module.

It looks like this actually was a permissions issue. In order for someone to be able to accept a relationship request, they also need permission to make the request.

In order to accomplish what I needed I also had to enable the "User Relationship Implications" module.


Skip a step on a multipage form based on field input I'm using field group module to create a multipage content creation node. I have one field that if "checked" should make the next button skip to final page of form.

For example a 3-page form, if on the first page the user checks "no" on a field, they will skip the second page when they click next and go to the third and final page.

You can give a try on this module Conditional Fields.

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. A simple use case would be
  defining a custom “Article teaser" field that is shown only if a "Has
  teaser" checkbox is checked, but much more complex options are
  available.


Why is the backup of the site not behaving the same as the original? I've cloned my site onto a testing server prior to making changes (database and all files), but it's not behaving like the original, and I'm unable to login.

The site was at www.original.com/drupal/ and www.original.com/node/3 works.
The test site is at www.test.com (note no /drupal) and www.test.com/node/3 gives me an Apache 404 error page.

Why are the two sites not behaving the same?
No Drupal specific content resides above www.original.com/drupal.

The problem was caused by .htaccess not being processed due to the "AllowOverride None" directive in my "httpd.conf" file.

Changing to "AllowOverride All" and restarting Apache cured it.


search-api solr is nor performing OR search I am trying  to provide the OR feature for my solr search . when user type words, the search should be able to return result which matches with any word present in the query .
I changed the default operator from AND to OR in my schema.xml ,
After change it looks :<solrQueryParser defaultOperator="OR"/>
however , It still doesn't perform OR search . The result is empty when I type multiple words .
I am using search_api with solr  I have aplplied the changes to my drupal solr configuration as well as solr server .what could be wrong ? any pointers is really appreciated
Thanks

You can implement the hook :

hook_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query)

Have a look to your query & params and see if the solr query is what you were expected, if it's not you can alter it.


Reducing attached items within node.tpl.php I have multiple images attached to a content type that I have set up with fancybox. Currently when viewing that node, all images are displayed. I only want to show the first image, then the rest within gallery mode.

I an struggling to figure out how to limit the diplays within (node.tpl.php) to only show the first attaced image.

I like the Gallery Formatter module for my galleries. It's the Colorbox module is nicely integrated with galler formatter to give you a cool lightbox popup. Gallery Formatter will use the first image in your multi-value CCK image field as the first slide image, so you can drag the order of the images in the node form into the order you want them to appear in.

If you want to display the first image of your multi-value CCK image field separate from your gallery (like in a view that gives a preview of each gallery), I would first create an ImageCache setting that you want to use to display that image, and then output that image in your node template like so:

<?php print theme( 'imagecache', '[your_image_cache_preset_name]', $node->field_gallery_images[0]['filepath'] );?>


Fetching client time using JavaScript and comparing them with values stored in the database I am developing a module, where:

The administrator enters time in (0-23) format.These values gets saved in database.
In the front end (for the website users) I need to fetch the current client time (not the server time), maybe using JavaScript, and then comparing it with the stored time (in PHP variables with current time fetched using JavaScript).

I want to do something like the following.

// $time_one: from the database.
// $time_two: from the database.
// $currentTime:  client current time.

if (currentTime > $time_one && currentTime < $time_two) {
  // Display some message.
}

How can this be done? Can PHP and JavaScript be mixed in the module file?

Send server time to the client side via js variables: drupal_add_js, see example.


Get selected value from Dropdown list of views I have a drop down list of different views for the users to select on a content type page in Drupal 7. I need to get the value of selected view from the drop down and display it in the form of selected view.

$value = $_GET['select id'];
$view = views_get_view('value');
print $view->preview('default');

I am not sure from where I should get the ID of the drop down field.

Not sure I fully understand the issue it would help if you asked a direct question. Here are some thoughts though.

To get a list of applicalbe view checkout this funciton form the node reference module:

function references_get_views_options($entity_type) {
  // Filter views that contain a 'references' display. This actually returns a
  // list of displays (the same view appears several times).
  $displays = views_get_applicable_views('references display');

  // Filter views that list the entity type we want, and group the separate
  // displays by view.
  $entity_info = entity_get_info($entity_type);
  $options = array();
  foreach ($displays as $data) {
    list($view, $display_id) = $data;
    if ($view->base_table == $entity_info['base table']) {
      $options[$view->name . ':' . $display_id] = $view->name .' - ' . $view->display[$display_id]->display_title;
    }
  }

  return $options;
}

The key function here is the "views_get_applicable_views(&display_type)". The rest of the function just filters the list for an entity type (node, taxonomy term, comment, or user are the common defaults). Then formats the data as an options list.

You can embed this list in a form as so (I wrote this code to do a similar task to what it sounds like you are doing:

$views_options = references_get_views_options('node');
if ($views_options) {
  $views_options = array('' => '<' . t('none') . '>') + $views_options;
  $element['view_and_display'] = array(
    '#type' => 'select',
    '#title' => t('View used to select the nodes'),
    '#options' => $views_options,
    '#default_value' => $default_view,
    '#description' => 'description',
  );

In the submit handler you save the view option. Something like:

$view = $form_state['values']['views_and_display'];

Then in the view hook of the content type you run an embed.

$view_info = explode(':', $display['settings']['view_and_display']);
$result[0]['#markup'] = views_embed_view($view_info[0], $view_info[1], $args);

Hope that helps. I wrote a module that did something similar for a client not too long ago so this is all working code form that module. It actually registers a display handler to output a node reference field as a view so it would give me a list with exactly the correct fields desired.