Database Size, suggestions on Dev > Staging > Production Our Drupal 6 Database is currently 75mb and the site has not even been launched yet. This is making it a bit difficult to export/import between our Dev/Staging/Prod as it is taking some time. I am concerned that in the future the database will become increasingly difficult to the point where it times out.

So how big are some of your Drupal Databases?

I have been exporting the entire database after clearing cache. Is there a simpler way, for example should I only export certain rows ? - leaving all the Cache tables?

Use backup and migrate module.

http://drupal.org/project/backup_migrate

It has an advanced backup options page, where you can choose tables and data to exclude.


Point to directory with .htaccess mydomain.com currently points to public_html/. I want to use .htaccess to direct it to public_html/live/mysite.com/ . How can I do this?

I believe I need to add a directory to one of these lines (line 102-105 of .htaccess):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

You probably wouldn't use .htaccess for this.  If your webserver is Apache, your apache virtual host configuration is what points your domain to a directory on the server.  On an ubuntu linux server your virtual host file would normally be in /etc/apache2/sites-enabled/mysite.com

If you are using a shared webhosting service (like Dreamhost) that uses an account configuration tool like Cpanel you can usually change your web directory using that tool.  Look under options for "Domain Names" or DNS.

Don't mess with .htaccess unless you really need to--you can mess up your site or render it insecure.  If you do edit .htaccess, make a backup of the original file.


Redirect Anonymous user to login page I want if user not logged in and visit any page of my website except my REST VIEWS routers I redirect him/her to  login page in drupal 8,  I found this solutions for drupal 7 but didn't find any solution for Drupal 8,

Redirect anonymous user to login page
How to redirect anonymous users to login page using Rules module?

You can test a user's status very early with event subscriber in a custom module that subscribes to KernelEvents::REQUEST.

First, you register the event subscriber in mymodule.services.yml in your module folder:

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber
    arguments: []
    tags:
      - {name: event_subscriber}

Then add RedirectAnonymousSubscriber.php  for your custom event subscriber in your module in the /src/EventSubscriber/ folder.

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {

    if ($this->account->isAnonymous() && \Drupal::routeMatch()->getRouteName() != 'user.login') {

      // add logic to check other routes you want available to anonymous users,
      // otherwise, redirect to login page.
      $route_name = \Drupal::routeMatch()->getRouteName();
      if (strpos($route_name, 'view') === 0 && strpos($route_name, 'rest_') !== FALSE) {
        return;
      }

      $response = new RedirectResponse('/user/login', 301);
      $event->setResponse($response);
      $event->stopPropagation();
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkAuthStatus');
    return $events;
  }

}


How can I move the location of the advanced search form? This has been giving me troubles for some time now. I am in the process of changing my search results page on my drupal 7 site. I have modified both the search-result and search-results template files to change how my results are displayed on the page.

However I can't figure out how to move the placement of the advanced search form. It is driving me crazy. I have created my own "advanced search" button, and want to give it the dropdown functionality that the default "advanced search" link has.

I know that I can change the "node_form_search_form_alter" function from node.module to alter the guts of this form, but thats not what I want. I just want to place it on the screen somewhere else.

I can't for the life of me figure out how to do this. I have gone through every template file, and the advanced search form just seems to magically appear. Any help would be GREATLY appreciated.

In the image below, you can see the default advanced search link, but I want to move it to my button that I have added, on the right of the page.

One option is the Advanced search block module which makes the advanced search form available as a configurable block.

  Provides the advanced search form (normally displayed above search results) as a block. The block includes default values for the advanced search fields making it easy to refine searches.

From a brief glance at this module's code, it looks like it hides the default form and re-creates the advanced search form in a block.


Is there a best form for security surrounding updating an entity of an unspecified type? In Drupal 7, I have a field on both nodes and users that I'd like to update from a single function.  What's the most efficient and what is best practice for updating by entity id?

I want the client to hit my Services REST API endpoint with an entity id and value.  So far I've got:

function json_field_resource_update($entity_id = NULL, $data = array()) {
  global $user;

  $entity_type = 'user';
  $entity = entity_load_single($entity_type, $entity_id);
  if (!$entity) {
    $entity_type = 'node';
    $entity = entity_load_single($entity_type, $entity_id);
  }
  if (!$entity) {
    return services_error(t('No user or node entity found by entity_id !entity_id', array('!entity_id' => $entity_id)), 406);
  }
  if (!entity_access('update', $entity_type, $entity)) {
    return services_error(t('Permission denied for !user to update entity !entity_id', array('!user' => $user->name, '!entity_id' => $entity_id)), 403);
  }
...

The purpose of the above is to first check whether this entity Id refers to a user or a node then perform the appropriate access check.  This works ok, but am I missing some magical all-in-one Entity API function or something?

I think the entity metadata wrapper is semi indiscriminate aslong as the field is the exactly the same on both entities. So you can just wrap it and then use the default set/get methods

// All your code (it looks fine)
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->FIELD_TO_SET->set(VALUE);
$wrapper->save();

More info on the metadata wrapper


Is there a Rules Condition for 'is user:' or 'is root user'? I am creating a rule that will help to manage permissions, but I only want it to run for the user with uid=1.

Is there a way to add a Rules Condition based on user data? Is such a condition prone to problems, and should I instead need to create a new permission?

Sure there is such Rules Condition. As an example, have a look at the Rule I included in my answer to "How to stop a Views block from displaying to admins, such as user/1?".

The Rules Condition included that answer performs a Data Comparison to check if the value of site:current-user:uid is not equal to 1 (in your case you'd want to check if it is equal to 1).

Note: This specific Rules Condition comes in handy for anything you want to enforce (or prohibit?) for super user user/1 (which typically skips all permissions), similar to what the question was about in the linked question here.


Assigning a student to a teacher I've looked around for a couple hours but am not sure the best way to do what I need.

I need to set up a student teacher relationship so that when a student logs in on some pages viewed by the student the teachers picture and information will show up.

For example: the student logs in and is taken to the members area. Then the student clicks on lessons then on week 1 lesson 2. When the page for lesson 2 comes up it would have in the corner a picture of the teacher they are assigned to along with the teachers name, contact information...

What would be a good way to do this?

You can also use the Relation module to implement this. It depends on how teachers are assigned. Are teachers assigned to students ? or lessons ? based on this you can create a relation using the UI and assign teachers. For displaying information relation module integrates well with views, rules, cck and is very easy to create one.

I also used the module in my project where communities can have objectives and goals. I use the relation module to create relations and use the views to display the connections from the community.

I would also recommend you to watch relation tutorial if you want to learn more about it.


How do I transfer anonymous data the user when he registers? I have a system for storing data (e.g. accessibility settings like colour contrast) for anonymous and authenticated users. Authenticated users have the data in a dedicated table.

For anonymous users I'm using CTools object cache so if the person keeps the session he won't lose his accessibility settings. (I might use this for storing searches as well.)

I could use Session API but there is a potential issue with European cookie law - yes, this is about site usability which theoretically trumps that law but it's a very public site so the client doesn't want any trouble, valid or not.

Okay, so here's the point: If a person registers I need to go from CTools to my custom storage. The actual process of doing that is simple enough but when a person registers, their session ID changes, so once they are logged in (e.g. when hook_user_register() gets called) the old session ID is dead and gone.

Any ideas how I can keep the old session ID, or transfer the data from not-logged-in to logged-in? (Putting the data in form_state in the user_register_form goes some of the distance, but not all of it.)

In fact it turned out to be simple (after spending a long time trying to be clever).

In hook_form_user_register_form_alter() add a value field to the form...

$form['mydata'] = array(
  '#type' => 'value',
  '#value' => $mydata,
  // in any form you like
);

Then in hook_user_insert() that data is in the $edit array, and already added to the $account object. Make sure you unset it from the $edit array otherwise it'll get put into the 'data' field. Anyway by this point the $account has a uid so it's possible to save the data.


Region won't show on front-page I'm customizing a theme and need to have a leaderboard on top of the page. Everything good - on all pages but not the home (front-page)... Any ideas what I did wrong?

I've added a region to the .info file

regions[topad] = Leaderboard header

and printed that region to the page.tpl.php like that:

 <?php if ($page ['topad']): ?>
   <div id="topad">
        <?php print render($page['topad']); ?>
   </div> <!-- /#topad -->
 <?php endif; ?>

I added a block with the leaderboard infos to the region and told it to show up on every page (also tried specific pages with "" - didn't work).

I'm happy for every hint.

Thank you!

Best

Chris

Do you have a specific template for your front page?  Is your front page pointing at a node?  Or just a list of recent updates?


why my custom jquery code stopped working on a multipage webform after upgrade to WF x6 I have a long questionnaire as multi-page webform and I do many mostly simple counting and addclass using jquery done via a custom module I made for the purpose. This was perfectly working before on Drupal 8 with WF x5 but not anymore after upgrading to Webform x6 (dev) on latest Drupal 9.02.
The below sample code only works if I move the related form to be on first page while it doesn't load on later pages!
(function($, load) {
    $('input.countme').change(function(){
        var a =  $("input.countme:checked").length // count all checked checkboxes with the css class "countme"
        $(".cm_score").val(a)  //update the value of the textfield that has the class ".cm_score"
    });
})(jQuery);

Below is myModule.libraries.yml
wfcount:
  version: VERSION
  css:
    theme:
      css/webform.css: { preprocess: false }
  js:
    js/wfCount.js: { preprocess: false }
  dependencies:
    - core/jquery

Following the tips in this post, I changed the code as follows and it worked:
(function ($, Drupal) {
 Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    $('input.countme').change(function(){
        var a =  $("input.countme:checked").length // count all checked checkboxes with the css class "countme"
        $(".cm_score").val(a)  //update the value of the textfield that has the class ".cm_score"
    });
 }
};
})(jQuery, Drupal);


Config changes only propagated via manual form submit My question is related to the Search API Drupal 8 module. I am modifying my configuration via config file updates. After I am installing my custom module, I can see my config reflected in the search index field settings via the configuration form. However, after I re-index I cannot find content via my newly defined fields. This works only, if I open the search index fields configuration form and submit it manually via webbrowser. No config changes - just hitting the save button.

Tried clearing the cache, entity updates, rebuild tracking information, rebuild the search index - nothing helps.

Can I implement anything into hook_install() from my custom module to propagate the necessary config changes properly to my database?

I think I have solved it by myself. I am re-saving the search index by myself via hook_install().

  $index_storage = \Drupal::entityTypeManager()
    ->getStorage('search_api_index');
  $index = $index_storage->load('search_content');
  $index->save();


How can I block users from registering with disposable email addresses? I have a site where users send messages to one another using the Private Message module, and they are notified of messages by email.

On this site, there are a variety of spammers, scammers, and abusive users who attempt to register multiple accounts using disposable email addresses.

I know it's impossible to block every possible disposable email address domain, but is there anything in the Drupal world that can help me?

I considered white-listing valid domains, but my user base is too diverse for this.
The only project I could find on drupal.org has been abandoned.
There are third-party APIs such as this one.

At the moment, I'm blocking them manually using this code:

/**
 * Custom validation function from the Domain Registration module (1.0).
 *
 * Checks if the domain in the email address is on a list of blocked domains.
 * @param $form
 * @param $form_state
 */

function MYMODULE_domain_registration_user_register_validate(&$form, &$form_state) {
  $default_message = t('You are not allowed to register for an account on this site.  Contact support for more information.');
  $mail = explode('@', $form_state['values']['mail']);
  $exact_domains = array(
    'ad.drupaler.org',
    'drupaler.org',
  );
  $partial_domains = array(
    'pp.ua',
    'guerrilamail',
  );
  if (isset($mail[1]) && !empty($exact_domains)) {
    if (in_array($mail[1], $exact_domains) || MYMODULE_contactinfo_check_banned_words($mail[1], $partial_domains)) {
      form_set_error('account', variable_get('domain_registration_message', $default_message));
    }
  }
}

Like you mentioned it is impossible to block all disposable domains.

If you want to end the madness, the most effective solution would be: Upon registration you send a confirmation link or code to a mobile phone number

Take a look at:

SMS Framework module
VoIP Drupal module

Using Unique field you could make sure that the phone number can only be used once.

Checkout: How to send SMS messages (Drupal Tutorial)


content.field_name does not render anything i've made a twig file for my 'test' content type called node--test.html.twig. That works fine using {{ content }} to print the node.

I've a custom field with the machine name field_text, the following prints fine:
{{ node.field_text.value }}

For some reason i cant get {{ content.field_text }} to work. I also can't get content.body or any other subset of content to work in any node type.

I must be doing something really daft - thanks for the help

content.<field_name> should work.
try adding {{ dump(content|keys) }} to your template, does it show anything?


FileDepot sql errors I have recently installed drupal6 and filedepot. Things were working ok, but I was getting some errors come through so I patched it with this http://drupal.org/files/issues/filedepot-group-by.patch

But now I am getting these errors

warning: pg_query(): Query failed: ERROR: syntax error at or near "REGEXP" LINE 1: ...FROM nextag_items WHERE type='filedepot' AND tags REGEXP '(^... ^ in /usr/share/drupal6/includes/database.pgsql.inc on line 139.
user warning: query: SELECT itemid FROM nextag_items WHERE type='filedepot' AND tags REGEXP '(^|,)1(,|$)' in /etc/drupal/6/sites/default/modules/filedepot/nexcloud.class.php on line 504.

Any one know any thing about them. Or know of a better document managment system for drupal 6?

I assume you're using postgres instead of mysql, AFAIK postgres doesn't support REGEXP.

As an alternative you can look at atrium_folders but it has not as many features as filedepot and it needs open atrium.


Deleting translate interface strings programmatically or using drush I need to delete some translated strings added using t() function, I've about 17000 string to delete is there a way to delete it using a SQL query or drush command? in which table those strings are stored?

Thank you.

Drupal 7 store translate interface strings in :

Table source locales_source
Table Target locales_target


Custom rendering exposed filters in Views I'm sorry if this is dumb question, but I'm creating a search page for a content type using Views in Drupal 7.   I am developing multiple exposed filters to achieve this, however, when the filters are rendered, they are done so side by side.  I would like them to stack on top of each other with the "Search" button at the bottom.

Is there something obviously simple I am missing or does anyone know how to do this?

Copy the views-exposed-form.tpl.php which is located at <drupalroot>/sites/all/modules/views/theme to your own theme folder. And it should be easier for you to style it. Here is a tutorial you can follow


Force page open in overlay I want to force admin pages open only and only in overlay. As you know if a link with an admin path is clicked it opens in overlay (if enabled). But if you write the URL to the browser, or use some deep link, or you are already in administration theme, the links expectedly wouldn't open in overlay.

How could I force the pages, even if the URL is entered to the browser's path, to open in overlay.

For example, if I type in the browser:

  www.example.com/admin/people

It should always open as:

  www.example.com/#overlay=admin/people

You can use the context overlay module to achieve this, this way you can easily configure what pages should be opened in an overlay.

You'll need to install:

Context (https://www.drupal.org/project/context)
Context Overlay (https://www.drupal.org/project/context_overlay)


Dynamic menu item based on Views argument Is it possible to have a dynamic title on the menu item based on the argument that Views is receiving? I'm using the title on the menu item on the breadcrumb and my breadcrumb changes based on the argument.

I never used breadcrumbs and i am quite new to Drupal but i think breadcrumbs get their copy from the URL arguments  ( which is also where view is getting its arguments, well in most cases). Though the menu items get their copy from the taxo (if you use a taxonomy menu block) or whatever name you gave them in the menu section of the site admin.

Therefor the only solution i would see, is to create you owns menu template in which you can use function such as drupal_get_path_alias() to populate your menu.


Not able to show node comments on a view -content pane I' a bit stuck with this. I am using panels in Drupal 7. I have created a new content type. I am crating a page (page manager) and I am using a view content pane inside a panel in the page. In that view I am filtering nodes of that particular content type I created. I am not using fields but the full content of the node and I can't figure it out why it doesn't show comments. If I change to page view, for example, I can see the comments, but not using content pane.

What am I missing? Might it be something about the template?

Thanks in advance for your help.

I have been playing around with comments in views for a while. It seems there is a kind of bug as checking "Display comments" on the Full content settings doesn't seem to work. You can solve this, using display suite as the format used by views, which comes with the option "Comments -load comments for every node to display" which does work as expected.

I hope it can help to someone else in the future. :-)


Change quantity of product kit based on attribute It's a shop where you can buy drinks. For every bottle/can there has to be an extra item with bottle/can deposit visible to the user.

So for this I added the cans and the deposit as single items. Every can has 3 attributes for the packaging unit of the tray: 6x250ml (default), 12x250ml, 24x250ml.

After that I added a product kit with 1x "can tray 6x250ml" and 6x deposit. This works fine. But if the user selects 1x "12x250ml" the deposit will just calculates the normal 6x.

Now I thought about manipulating the cart before it is visible to the user. For example: Take the quantity of the item, calculate the deposit by the checked packaging unit and multiply by the item quantity. The calculation is pretty simple.

What function/hook can I use to do this?

I tried to deal with hook_uc_cart_item_presave($entity) but it seems, that the function gets triggered once for every product in the product kit. I can't find a solution to check the quantity on the main item as well as the checked attribute and then pass it to the second run for the deposit item.

It seems that - against the official docs of ubercart - the hook hook_uc_cart_alter IS available for Drupal 7.

Found the answer here on Drupal Answers in an old question: https://drupal.stackexchange.com/a/94497/53491

With the available $items-object I iterate through my cart as I need it. Works perfect.


How to use or operator in a view? I have a view page and I want to show two content type same time. What I want is simple: I have two content types and these content types have own type fields. Like this:

Content Type 1 - Cars (this have a type field names "BMW")

Content Type 2 - Motorcycle (this have a type field names "Ducati")

I want to show all BMW Cars and Ducati Motorcycles at the same page. How can I do that with view filters? I try that but it is not working:

In my example;

Cars = Post

Motorcycle = Feed

BMW = Type (= iframe)

Ducati = Type (or foto, video, ...)

Only two filters can do that for you -

Content : Published(= yes)

OR,

Content : type(= Feed) And,
Content : field_car(= BMW)

OR,

Content : type(= Post) And,
Content : field_motorcycle(= DUCATI)

Apply pager for the view with 10 or 15 content on one page, etc.


Add comment link to a view I created a new content type (News). I then added a new node.  After doing these, I created a 'view' of the node. In the view I added the "Add comment link" as a field.

I have the following issues:

In the "Add comment link" settings of the View, if I do not select the "Show teaser-style link" option, the link does not appear on the view page.
When I select the "Show teaser-style link", the "Add comment link" appears on the page as expected. However, the link redirects to the original node page.

What I would really like to do is show the 'full node form' on the view page without it redirecting to the original node.

If you want to render full node change the view settings as follows

In your view change the FORMAT settings as follows


How to correctly get Form API single checkbox value variable from database? I created an additional_settings fieldset for node type forms that holds a single checkbox:

$form['MY_SETTING']['enabled'] = array(
  '#type' => 'checkbox',
  '#title' => t('Enable'),
  '#default_value' => variable_get('MY_SETTING_' . $form['#node_type']->type, FALSE),
);

When I check the checkbox and save the node type form the value gets stored like that: MY_SETTING_MY_NODETYPE[0] = 'enabled'. The #default_value only understands TRUE and FALSE and doesn't work with enabled. I've sneaked in other modules (p.e. comments module) and have seen that they solved that with constants. But how to apply a constant in that form logic and let it be saved to the database?

You could use constants in place of string literals, sure, but that's not related to the issue you're having. That's simply a matter of converting the statement you already have to a boolean.

Which is as easy as:

$bool_enabled = variable_get('MY_SETTING_' . $form['#node_type']->type, 'disabled') == 'enabled';
$form['MY_SETTING']['#default_value'] = $bool_enabled;

Incidentally, the string "enabled" evaluates to TRUE in PHP, so it's not possible for it "not to work with enabled", it's just that 'disabled' also evaluates to TRUE, so you won't ever see a falsey value.

Personally I think the simplest solution is store the variable as an integer, 1 or 0. Then you can just assign it straight to the form element and let PHP's implicit integer -> boolean conversion take over. That's how all core (and contrib, that I've seen) modules handle it.


Using hook_language_types_info_alter I am attempting to modify the way the language negotiation is done on a site.

I've implemented a new language negotiation method:

/**
 * Implements hook_language_negotiation_info()
 */
function MODULE_language_negotiation_info() {
  return array(
    'MODULE_provider' => array(
      'file'        => drupal_get_path('module', 'MODULE') . '/MODULE.module',
      'weight'      => -4,
      'name'        => t('URL (Combined)'),
      'description' => t('Determine the language from the URL (Path prefix and domain).'),
      'cache'       => 0,
      'callbacks'   => array(
        'language'    => 'MODULE_language_provider_callback',
        'url_rewrite' => 'MODULE_language_url_rewrite_callback',
      ),
    ),
  );
}

In the case of a single language, the $language is being detected properly, the $language_content is being detected properly, but the $language_url is not being detected properly.

After some digging into this, I found that in the locale.module there are three language types defined - language, language_content and language_url:

/**
 * Implements hook_language_types_info().
 *
 * Defines the three core language types:
 * - Interface language is the only configurable language type in core. It is
 *   used by t() as the default language if none is specified.
 * - Content language is by default non-configurable and inherits the interface
 *   language negotiated value. It is used by the Field API to determine the
 *   display language for fields if no explicit value is specified.
 * - URL language is by default non-configurable and is determined through the
 *   URL language provider or the URL fallback provider if no language can be
 *   detected. It is used by l() as the default language if none is specified.
 */
function locale_language_types_info() {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  return array(
    LANGUAGE_TYPE_INTERFACE => array(
      'name' => t('User interface text'),
      'description' => t('Order of language detection methods for user interface text. If a translation of user interface text is available in the detected language, it will be displayed.'),
    ),
    LANGUAGE_TYPE_CONTENT => array(
      'name' => t('Content'),
      'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_INTERFACE),
    ),
    LANGUAGE_TYPE_URL => array(
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK),
    ),
  );
}

So, pressing onward, I implement hook_language_types_info_alter and add my callback function to the list of callbacks for the language_url language type:

function MODULE_language_types_info_alter(array &$language_types) {
  $language_types[LANGUAGE_TYPE_URL]['fixed'][] = 'MODULE_language_provider_callback';
}

The issue I am facing is that the hook_language_types_info_alter is called after drupal_language_initialize, so all of the language types have already been determined before the hook alters the language types.

Also, all of these language types are stored as variables. I could in theory modify the variable, but I would rather do this the correct way using hooks.

How do I modify the language_url language type before drupal_language_initialize?

variables was definitely the key here. In my hook_language_types_info_alter hook, simply updating the variable with my callback did the trick:

/**
 * Implements hook_language_types_info_alter()
 */
function MODULE_language_types_info_alter(array &$language_types) {
  $config = variable_get("language_negotiation_" . LANGUAGE_TYPE_URL);

  // put my callback first, since the first one to return a language wins.
  $newconfig['MODULE_provider']['callbacks']['language'] = 'MODULE_language_provider_callback';
  $newconfig['MODULE_provider']['file'] = drupal_get_path('module', 'MODULE') . '/MODULE.module';
  $newconfig += $config;

  variable_set("language_negotiation_" . LANGUAGE_TYPE_URL, $newconfig);
}


Commerce- How can I add a custom field to Account Information on checkout I am using Commerce but I do not require customers' billing or shipping information.  However, I do need them to provide their name.

Since I have a field for the name in the user profile, I want to require anonymous users (only) to provide their name.  By default, in Commerce the Account Information pane requires users to input their e-mail addresses if anonymous and is hidden if they are authenticated.

This is exactly the behavior I want, so I was hoping to add my name field from the user profile to the Account Information, but I can't find a way to do that.

Approach I tried and rejected

By adding the name field under Checkout settings-> Order-> Manage display, I was able to add the field, and using the Commerce Fieldgroup Panes module I could even display it in a custom fieldgroup.  However, when taking this approach, authenticated users are prompted for their names and their names aren't prepopulated.

I think you are looking for Commerce User Profile Pane module.

  Commerce User Profile Pane is a module that allows you to capture a
  Drupal Users profile fields directly in the Commerce checkout pages.
  This is similar to the Commerce Billing Profile or Commerce Shipping
  Profile panes, but instead of storing extra fields in the Commerce
  Profile entity, this will allow you to store it directly in the Drupal
  core User entity. This is useful when you want a quick registration
  process without the user having to fill a long user registration form,
  but you still want to retain the option to complete the User profile
  info in the checkout phase.


use jquery to add a div wrapper to a dynamically created drupal modual div I need to add a div with class=row around a bunch of divs that are being dynamically created by a drupal module (cant do it in the view either)

i was trying this, but since it is created dynamically, it does not work:

$("#row").prepend("<div id='edit-secondary-wrapper'/>");

this is the div that the module spits out that i want a row around

id='edit-secondary-wrapper'

You may be looking for this

$("#edit-secondary-wrapper").wrap("

");

This wraps the div with id 'edit-secondary-wrapper' with a parent div with class 'row'.


Creating a responsive menu system for a site with a lot of content I am currently creating a website which has a lot of content - text. For this I need a serious menu structure with 5-10 menu items per menu and at least 15 menu-blocks per main menu item.

Further it has to be accessible via mobile.

Till now I have used panels and added menus inside the panels. But mobile isn't to happy about that and the list-names in the menus overlap the content.

How would you go about solving this issue? I trust you experts here! :-)

for creating responsive menu you have lots of projects

below are some

https://www.drupal.org/project/responsive_menus

https://www.drupal.org/project/responsive_navigation

https://www.drupal.org/project/responsive_dropdown_menus

https://www.drupal.org/project/responsive_menu

try any one will help you out.


Quick Edit setup and usage I added quick edit to my site. Made sure all the correct libraries are in place and see the quick edit button in the gear next to the content, but am not getting any way to save the changes.

The screenshot shows what I see when I click in the content area.

I have CKEditor in place. Have tried CDN and Libraries version without success.

Is there a certain type of field or class I need to add to fields?

Looking at the errors you are reporting, it seems that you haven't downloaded the actual javascript ckeditor library.

You can do it manually, as described in http://docs.cksource.com/CKEditor_for_Drupal/Open_Source/Drupal_7/Installation.

or you can script it (update the version if needed):

wget http://download.cksource.com/CKEditor/CKEditor/CKEditor%204.5.4/ckeditor_4.5.4_standard.zip
unzip ckeditor_4.5.4_standard.zip
mv ckeditor $SITENAME/sites/all/libraries
rm ckeditor_4.5.4_standard.zip


Add translatable text in template file I am going to add a custom string by t() function in node.tpl.php. However, where should I add the translated string for the original string?

You can go to admin/build/translate and translate your defined words, it's search is case sensitive


Bulk opening of several node edit screens is there a way to open up several nodes to edit at once? At /admin/content I can mark all of the nodes that I want to edit, but I still have to click each edit link individually.

Is this something that I could do by adding an action to the "Update Options" dropdown?

Edit
The reason for the mass editing is that I have added a new field to a content type. I would like to add unique values to that field for preexisting nodes.

As far as I am aware, no module will do this out of the box. However in saying that there is a potential solution in:

Installing Views Bulk Operations (VBO)
Writing a custom action that happens on each selected node

From the VBO page:

How can I write an action that performs a function on all selected nodes AT ONCE?

You need to write a node operation instead of an action. Whereas actions get called once for every selected node, node operations are called once only, and they are passed an array of selected nodes. Check out sirkitree's article for the same concept applied to user operations.
Note: If you use Batch API to execute your actions, VBO will revert to calling the action once per node instead. This is because it doesn't make sense to batch one single action.


How to detect entity translation without using path prefix or domain? We have a situation where we want to have Content Translation enabled. It is our understanding that this is using Entity Translation(from D7) that is now in D8 core. This also means that there will be one Node (ID), but there will be a table to hold translations for the fields.

Goal:

Enable Content Translation for Article content type and make all fields translatable
Create an English page call Test-Page
Click Translate and add translation to Spanish
Enter in the Spanish content for the body and title field

Expectation:

As a site visitor, When i clicked on the Language Switcher and select Spanish, I should see Spanish content
As a logged in user (admin or content editor) when i view the English version I should see English content on the edit screen for body and title
As a logged in user when editing the Spanish translation I should see the Spanish translations for body and title.

Issue:

Whenever we click on the Spanish translation we are always served up the English content
When i change the language using the Language Switcher to Spanish, we are still served up the English content

How can we setup the translations so that the issues above do not occur?

I am adding an answer so others can see what i had to do.

To resolve this we did the following:

Enabled the custom settings for language detection
Enabled "Selected Language"
Set "Selected Langauge" with the highest row weight so it is done first
Enabled "URL" with the second highest row weight
Modified Admin Content (/admin/content) view to output a customized URL that has "?language_content_entity="
Now on click of edit or translate of the that page, it will redirect to the correct language and all my issues are resolved.


Doing a post to create a node using Drupal services endpoint with Postman app I got my endpoint setup and I'm able to to do a get request to return a bunch of nodes. But I'm having issues doing a POST to create a new node.

I see that I would first need to do a user login post as seen in other tutorials. I tried doing that with the following settings in postman, but I'm getting a blank response. What could I be doing wrong? I've enable user resources as seen below also.

In that  petition you are calling the path user.login, but in services is user/login, with a slash.

Also, maybe you are not preceding the path with the base name of your api (normally is /api). So the url should be /api/user/login. You can see the path in 'Edit' tab, in 'Path to endpoint' field.

I recommend you the module services tools which gives you a page  where you can see the urls of the endpoints. This module contains a submodule called services_definitions, enable it to have this page available.


Check access to entity for logged in user in Drupal 8 I have added private message module for one of my project which has it's own entity. I need to check whether the user is having access to that entity content or not. The module has it's menu item defined in the module's routing.yml

e.g.:

entity.private_message_thread.canonical:
  path: '/private_messages/{private_message_thread}'
  defaults:
    _entity_view: 'private_message_thread'
    _title: 'Private Messages'
  requirements:
    _entity_access: 'private_message_thread.view'

How could I check whether the user has view access to the above menu path?

You can check annotations of those entities and find access handler.

e.g.

/**
 * Defines the Private Message Thread entity.
 *
 * @ContentEntityType(
 *   id = "private_message_thread",
 *   label = @Translation("Private Message Thread"),
 *   handlers = {
 *     "view_builder" = "Drupal\private_message\Entity\Builder\PrivateMessageThreadViewBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\private_message\Entity\Access\PrivateMessageThreadAccessControlHandler",
 ...

As you can see, there is access handler. Now you know how it works.

  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    if ($account->hasPermission('use private messaging system')) {
      switch ($operation) {
        case 'view':
          if ($entity->isMember($account->id())) {
            $messages = $entity->filterUserDeletedMessages($account);
            if (count($messages)) {
              return AccessResult::allowed();
            }
          }
          ...


TinyMCE - Drupal 7 - Insert images not functioning I'm having trouble inserting images via TinyMCE  (I've also installed WYSIWYG). I can insert images into an article just fine and all looks as it should while I'm editing an article, but if I preview or save the article and then view it, the image doesn't show up, instead I see:

[img]/sites/default/files/myimage.png[/img]

I've tried making the content with full html, and I've installed the media module and selected an option under text formats that is supposed to convert media tags into html.

What am I missing?

Disabling the BBCode option in my TinyMCE Wysiwyg profile worked for me.


Help me understand themes with sidebars and how to populate the sidebar from drupal BACKGROUND

I'm converting a static html site to drupal.   We have some pages that have content and a sidebar and some pages that just have content without a sidebar.

I plan on simply adding a new field called 'sidebar' to the article and base page content types.  I can then modify the theme to render this field.

QUESTION

Is their any reason why adding this new sidebar field to the content type is considered bad practice?

If I want to place a block in the sidebar region it could simply be after or before the data entered into the sidebar field correct?

I'm a total newbie to drupal,  I understand these are basic question but I couldn't find a definitive answer on the web regarding this.

Thanks

In Drupal, themes have regions. The sidebars are regions, just like the header, footer, conternt etc regions. Over simplifying a bit, content is places in blocks, then the blocks are placed in the regions, and changing the theme usually requires the blocks to be allocated again. Fields are part of the content, not the theme. There is no 'sidebar field'.

I would suggest that you set up a drupal test-bed, and play with it for a while before you take the leap of trying to migrate a site. Drupal is powerful, but there is no way to bypass the learning curve. You need to roll up your sleeves and work with it for a while.

Good luck.


Send mail to users including receiver's username I have searched settings of Contact (in Drupal core), Simple news and Mass contact modules but haven't found a way to include receiver's username in the mail body.

Any suggestions how to do this?

There isn't a setting for that, but when a user sends an email to another user, using the contact form of the other user's account, the Contact module sends a message that start with (I sent an email to myself from Drupal.org):

  kiamlaluno,

  kiamlaluno (http://drupal.org/user/55077) has sent you a message via your contact form (http://drupal.org/user/55077/contact) at drupal.org.

  If you don't want to receive such e-mails, you can change your settings at http://drupal.org/user/55077.

The first line contain the receiver's username.

The following snippet is part of the code present in contact_mail(), the function that alter some of the messages sent from Drupal.

case 'user_mail':
case 'user_copy':
  $user = $params['user'];
  $account = $params['account'];
  $message['subject'] .= '[' . variable_get('site_name', 'Drupal') . '] ' . $params['subject'];
  $message['body'][] = "$account->name,";
  $message['body'][] = t("!name (!name-url) has sent you a message via your contact form (!form-url) at !site.", array('!name' => $user->name, '!name-url' => url("user/$user->uid", array('absolute' => TRUE, 'language' => $language)), '!form-url' => url($_GET['q'], array('absolute' => TRUE, 'language' => $language)), '!site' => variable_get('site_name', 'Drupal')), $language->language);
  $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE, 'language' => $language))), $language->language);
  $message['body'][] = t('Message:', NULL, $language->language);
  $message['body'][] = $params['message'];
  break;

Other modules can change the content for the sent emails, if they implement hook_mail_alter(). This means that other modules could remove content from the email sent via the contact form; it also means that another module could replace the username used in the first line with the first and last name provided by the receivers in their user profile.


How to create complex conditional clauses / queries? I've been reading the documentatoin on conditional clauses and also studied the api description for db_and() and db_or() but I fail to create a $query with 3 ->conditions:

select all between 0 and 100
but exclude 23, 48 and 97
select also 107, 123, 126 and 128

That's what I have tried so far:

$query->db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN'));

But I get the following error:

PHP Fatal error:  Call to undefined method SelectQuery::db_or() in [... first line]

I've tried to play around with the syntax like that:

$query->condition(->db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));

But again getting errors like that:

PHP Parse error:  syntax error, unexpected T_OBJECT_OPERATOR, expecting ')' in [... first line]

I also tried working with variables:

$cond01 = array('my_field', array(107, 123, 126, 128), 'IN');
$cond02 = array('my_field', array(0, 100), 'BETWEEN');
$cond03 = array('my_field', array(23, 48, 97), 'NOT IN');
$db_and = db_and();
$db_and->condition($cond02);
$db_and->condition($cond03);
$db_or = db_or();
$db_or->condition($cond01);
$db_or->condition($db_and);
$query->condition($db_or);

But this again yields drupal errors like that:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'where clause'

How to create a complex conditional database query with both AND and OR statements?

Actually your final method is a right way, however the condition function is expecting 2 or 3 arguments(else only one DatabaseCondition instance as Molot said) and if you're not passing DatabaseCondition instance then your first argument should be the table column name. But you're passing an Array as the first argument. That's why you got unknown column 'Array' error.

So you should revise it like below,

$db_and = db_and();
$db_and->condition('my_field', array(0, 100), 'BETWEEN');
$db_and->condition('my_field', array(23, 48, 97), 'NOT IN');
$db_or = db_or();
$db_or->condition('my_field', array(107, 123, 126, 128), 'IN');
$db_or->condition($db_and);
$query->condition($db_or);

Further note your second approach is also right, however you put a extra -> before calling the db_or() function. So you should write it in the following way,

$query->condition(db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));


How import Feeds into entityforms Does anyone know if there is a way to use Feeds to import into Entityforms?
 I have a CSV file of usernames and spent some hours at a specific event and would like to import it into it's corresponding form rather than entering it in all by hand.
How can I import Data from CSV file into EntityForm`?

Other than Migrate (which I have not tried yet), the only thing I have found was to use Feeds Import with the contributed patch for a Generic Entity Processor to import Entityforms.

https://drupal.org/node/1033202#comment-7710367

I currently have Drupal 7.23 and Feeds 7.x-2.x-dev (7/6/13) and I patched the feeds module successfully with the patch at comment #217.  This then gives you the option of having an entityform as a bundle.

I created a test entityform, a small test csv, and a new test feeds import.  The import completes successfully, but there's no content in the submissions.  Maybe you'll have better luck than I.  My next step is to checkout the latest from git and try again.  If that doesn't work, I guess I'm going to have to learn how to write a migrate module.

FYI, I have successfully used the Feeds Import module using the node processor that comes with the module for custom content types if you don't need it as an entityform.  There are several good Feeds videos out there is you're not familiar with the module.

Please reply if you find something else that works.


Views query alter add orderby function FIELD() I can't figure out how to add following expression to the views query:

ORDER BY FIELD(field_dataid,3,2,1,4)

QueryPluginBase only gives the option to add:

$query->addOrderBy('node_field_data', 'nid', ASC);

But doesn't give the option to add an expression.

The Sql interface has the options to add an expression:

  $query->addExpression('FIELD(node_field_data.nid,3,2,1,4)', 'order_field');
  $query->orderBy('order_field', 'ASC');

But this doesn't work with the views query object.

So how can i add orderby expression to the views query object?

There is a similar answer here: https://drupal.stackexchange.com/a/200662/79998

You should either use $query->addField() to add the expression and then append or unshift in $query->orderby array,
or you can use directly $query->addOrderBy() to add the expression and order, if it's ok to be added last.

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,3,2,1,4)', 'ASC', 'order_field');


How to get the site name in drupal 6? In some situations, I need the site name of a Drupal 6 site which is given while installation of the site.

How can I achieve it?

In both Drupal 6 and Drupal 7, you can use variable_get.
The CMI initiative will likely deprecate this function in Drupal 8.

$name = variable_get('site_name', '');

Notice the blank '' at the end, which is the "default" value, in case a variable isn't defined.


Poll Listing, Where admin can rate and user and rate a poll? I need to develop a page, where we need to display a list of polls which are published.

and

Need to create a content by admin where user and admin, both can rate it.

Does anybody suggest a contributed module or Do i need create custom Module for it?

You could use the Advanced Poll Module.

Advanced Poll is a replacement to Drupal's poll module and provides multiple voting systems, decision-making tools, and management options.

For more details you could go through the README.txt of this module.


How to hide core fields in Content types? Drupal-6

I created a content type and added some fields. I can manage how to show them in Diplays Field. But there are some 'core fields' which I can not hide in Displays Fields.

I need to hide the 'menu system field'. Can I do this? How?
It would be great to hide it just for an specific role.

I uploaded a picture to show what I mean.

There are two ways you can do this.

You can do this with permissions for some items. 'Menu settings' is controlled by 'administer menu' permission.

If some item is being put onto the page which can't be controlled by permissions then you can use a form alter hook to remove them. I tend to set #access to false rather than completely removing the item from the form.

There is a big explanation of examples of how to alter forms here


Comments with Facebook Auth User and anonymous I'm working in a site that needs some special behavior for comments.

The user will have anonymous and users connected with Facebook.

For comments, the site needs to allow anonymous comments posting but if the user is connected with Facebook the page will permit to the user make the comment with Facebook or as some anonymous user.

I been googling for a couple of hours some module that provides this functionality out of the box but I was not able to find one.

Does anyone knows some module to recommend me ?

Thanks in advance !

You could try the disqus module, which uses the disqus service.

It is arguably better than using facebook comments because it also allows people to comment using other social network accounts, not just facebook.

It also allows guest commenting.

Depends on your requirements though as to whether or not that is an acceptable solution.


How to Associate Drupal content type with CiviCRM groups? I have created the 10 contents in Drupal. This contents are Article content type and also created the new group(group name: students) in civicrm.

Now I want to associate these content with the student group in civicrm.

could you please anyone tell me how to achieve this one ?

With the CiviCRM Entity module, many CiviCRM API entities are exposed as proper Drupal entities. You can then create Entity Reference fields to reference particular entities. So on your node types, create an entityreference field, target CiviCRM Groups, and you will be able to reference the groups this way


Captcha session reuse attack detected error message in form with anonymous user I am experiencing a problem with the Captcha module 7.x-1.3 version (under Drupal 7.39)

I don't use webforms
My form is a simple Contact form
My form does not contain any AJAX field
My form does not contain any file or image upload system
I configured the captcha Module, giving the good name for the form

form_id : xxxxxx_contact_form
Challenge type : Image (from module image_captcha)

In the Configuration (admin/config/development/performance)

The page cache for anonymous users is unchecked = NOT ACTIVATED
The cache for blocks is unchecked = NOT ACTIVATED

The code of the Captcha for my form is :

$form['xxxxxx_contact_captcha'] = array(
  '#title' => t('Vérification'),
  '#type' => 'captcha',
  '#captcha_type' => 'image_captcha/Image',
);

When a user is connected the form submission works well without any problem
BUT when NO user is connected (= anonymous session), i get the following errors :

  CAPTCHA session reuse attack detected.
  The answer you entered for the CAPTCHA was not correct.

(in french) :

  Attaque à base de réutilisation de session de CAPTCHA détectée.
  La réponse saisie pour le CAPTCHA est incorrecte.

EXAMPLE :

For example, with a "TT7Zi" Captcha image, when I submit the form (in anonymous) : I get the following errors on the screen :

  CAPTCHA session reuse attack detected.
  The answer you entered for the CAPTCHA was not correct.

And in the logs (watchdog) I get two times the same entry  :

  Message   xxxxxx_contact_form post blocked by CAPTCHA module: challenge
  Image (by module image_captcha), user answered "TT7Zi", but the
  solution was "542dda8e8d7fda2358b4b2f319ef198b".

Any solution for this issue will be really helpful.
Thank you all.

The problem comes from the fact that it is NOT necessary to add the form_id and Captcha method in the Captcha Configuration when you use a custom form.

If you do this, when the form is generated on the page, the Captcha module is called TWO TIMES instead of only one, and this causes some troubles in the database, because when you call the form page, and when you submit it, TWO lines are created in the captcha_sessions table instead of only ONE !!

So, you will have :

Line number | Token    | Code
------------------------------------------------
N           | AAAAA... | TT7Zi                   <=== FIRST CALL
N+1         | BBBBB... | dccedb00fa1234567890... <=== SECOND CALL (ABNORMAL)

Then, when you submit, a new line is created in the captcha_sessions :

Line number | Token    | Code
------------------------------------------------
N           | XxXxX    | Zjj7R    ( UPDATE of the whole former TT7Zi line )
N+1         | BBBBB... | dccedb00fa1234567890...
N+2         | CCCCC... | 542dda8e8d7fda2358b4b2f319ef198b <== SECOND CALL !!

That's why the generated WATCHDOG error line says :

  user answered "TT7Zi", but the solution was "542dda8e8d7fda2358b4b2f319ef198b".


How to add custom css files in a theme from drupal.org? I am using the Zen theme on my site, but would like to add custom CSS files that the theme should use. How can I achieve this?

While you can add your own styles to the Zen theme, it would require that you hack the theme.

What you should do instead when using Zen, is to use it as a base theme, and create what's call a subtheme. That is a theme that will use the styles, templates etc from the Zen theme, but where you can custom overrides, alterations and additions without changing Zen itself.

There is a detailed handbook page where you can read about how this is done and what to be aware of.

Within the Zen theme there is also located a start kit for your subtheme that will help you to do most of what needs to be done, and documentation on what to do in the README file in the theme.


How do I alter a template file in a multishared child-site? The site I am working on is the child-site (is that the correct terminology?) of a larger parent site.
The company I am working with uses the main, parent site as a sort of framework or base. It has a basic theme that the child sites use and build off from.

I want to alter the HTML of a pane element. The original template file for this is located back in a module directory of the parent site. There is no equivalent module or folder structure on the child-site.
I don't want to change the template file on the parent site as this would affect the other child-sites.

I've read up that you can copy the template and place it into the child-sites structure. Is this true?
If so, would I need to re-create the directory path to replicate that of the parent site's?
What's the correct way to go about this?

This is a bit tricky since normally template files are located in the Theme's folder and not in a module's folder.

You could create a /modules folder under yourchildsite.com folder and copy the parent site module and paste it there. Then modify what you need.

I am not 100% sure this will work, but I hope it does.


How to display the first child of a book with the title of the book and keep the url by using a view Is it possible to display the list of the first child of every book with a view? I couldn't figure that out so I added boolean to the book content type to check which child is the first child. If that's not possible I'll just keep it the way it is, but the main problem is overwriting the the name of the first chapter (keep the url) with the name of the book. I wanted to do that with the custom text field, but I don't see the replacement pattern of the book name, so is that even possible?
I'm using Drupal 8.
Thanks in advance!

It's not at all a problem to override the link text with another field. Title field settings have the Rewrite results with the Override the output of this field with custom text, with available tokens listed below that under Replacement patterns.

To get the top level Book information add the Relationship Top Level Book.
Edit the Title Field and make sure it uses the Relationship, this will display the main Book title for each of the book Pages in the results, instead of the Pages titles. (I'm assuming you've created the Content Views showing Book pages.)
Edit the field settings to Exclude from display and untick Link to the Content while keeping the Formatter Plain text, so the main book link doesn't interfere with overriding.
Add Field Link to Content, configure it under Rewrite results with Override the output of this field with custom text, Output this field as a custom link, enter token for your title field into the Text field, something like {{ title }}

Now you have links for each Views result that link to Book Pages but the link text is the main Book title.
Book pages weight
The real problem is showing only the first Book pages. Weight is available as a Field within Views, so you can show and sort the book pages in the results according to their set order. Lowest numbers float to top, large numbers fall to the bottom, as is always the logic with weight in Drupal.
But there doesn't seem to be a Filter available for the Weight, at least I'm not seeing any right now, so it doesn't seem possible to filter out only the first child page of every Book.
It is possible to work around it by creating a separate Views Display for each Book you have in Drupal. Set Sort criteria to Book Weight, and Pager to only show 1 result. This way only the first Book page will be shown, but you'll have a separate Block for each Book to show this.
If you have more than one level of the book pages use the Filter Depth with the value 2. (1 depth is the main Book page and 0 is for book pages that don't belong to any Book.)
You can make it look like it's the same Block with some styling after you display all those Blocks in the same theme region.


How do programmatically create fields for content types, and ADD them to the the content type form Say I have this field, "map_description". I know I would this function to define the field:

$field = array(
  'field_name' => 'map_description',
  'cardinality' => 1,
  'type' => 'text',
);
field_create_field($field);

And I have this code which I'm not sure what it does but I'm told that I'll need it:

 $instance = array(
    'field_name' => 'map_description',
    'label' => 'The map description.',
    'bundle' => 'my_content_type',
    'entity_type' => 'node',
    'widget' => array(
    'type' => 'text_textfield',
 );
 field_create_instance($instance)

Those two code bits are both in my install hook and run when I install the module. But while the fields are in fact created, I have to manually assign them to the content type via "manage fields", is there a way to have the fields automatically assigned to the content type?

You're almost there.

From your code:

'bundle' => 'my_content_type',

Replace my_content_type with the name of the content type you want it attached to.

Here's a full example of adding a Alias text field to the Article content type. (from monarchdigital.com)

/**
 * Update hook to add a field to a node.
 */
function my_module_update_7000() {
  $field_name = 'field_alias';
  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'text',
      'settings' => array('max_length' => 64),
    );
    field_create_field($field);

    // Create the instance.
    $instance = array( 'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Alias',
      'description' => 'The article alias.',
      'required' => TRUE,
    );
    field_create_instance($instance);

    watchdog('my_module', t('!field_name was added successfully.', array('!field_name' => $field_name)));
  }
  else {
    watchdog('my_module', t('!field_name already exists.', array('!field_name' => $field_name)));
  }
}


Webform Component with multiple fields I would like to make a custom module that integrates with webform (7.4).

I need to have a combo field which could be added to a form as one field but consists of 4 text areas.

I have found a discussion on this topic here -> http://drupal.org/node/965068 but first its confusing how he does it at the end he just says he figured it out, but also this is a solution for 6.3 and i need for the 7.4

Any help would be greatly appreciated.

You could use https://www.drupal.org/project/webform_addmore.

A more flexible solution would be to use the Entityform module in combination with https://www.drupal.org/project/field_collection.


How do i do some search feature like this I have a requirement like this show in image

Like left hand side i need to show some fields data and when i click on the links i should filter out the data in content area. and its should be like a AND operation ? I need to use VIEWS and what else modules are needed for this thing to be completed?

This is related to the issue on D7 Faceted Search module here.

Using specialized search systems (Solr, Sphinx, Xapian, or others) is the way to go.

You can get results with Solr, the Apache Solr Search Integration module, and customizations.


In which table in the database are the email messages stored? I would like to know what the table the email messages (Emails section at admin/config/people/accounts) are stored in?

Config: Drupal 7

Any help is appreciated.

They are stored as system variables in the {variable} table, and normally accessed with variable_get() and variable_set().  The variable names are

user_mail_cancel_confirm_body
user_mail_cancel_confirm_subject
user_mail_password_reset_body
user_mail_password_reset_subject
user_mail_register_admin_created_body
user_mail_register_admin_created_subject
user_mail_register_no_approval_required_body
user_mail_register_no_approval_required_subject
user_mail_register_pending_approval_body
user_mail_register_pending_approval_subject
user_mail_status_activated_body
user_mail_status_activated_notify
user_mail_status_activated_subject
user_mail_status_blocked_body
user_mail_status_blocked_notify
user_mail_status_blocked_subject
user_mail_status_canceled_body
user_mail_status_canceled_notify
user_mail_status_canceled_subject

Look at the code for user_admin_settings(), which is a standard system settings form and has the variable names in it, and _user_mail_text() which has all of the default text.


Use Arrays in Twig Template from Custom Block I'm attempting to use arrays in a twig template from variables in a custom block.

In my custom block I have

public function build() {
    $query = \Drupal::entityQuery('node')
        ->condition('type','product')
        ->sort('created', 'DESC');

    $nids = $query->execute();
    $i = 0;

    foreach ($nids as $nid) {
        $node = NODE::load($nid);
            $imageurl[$i] = $node->get('field_product_page_display')->entity->getFileuri();
            $title[$i] = $node->get('field_title')->value;
            $imageurl[$i] = str_replace("public://", "", $imageurl[$i]);
            $i += 1;

        }
    return array(
        '#theme' => 'product_display',
        '#imageurl' => $imageurl,
        '#product_title' => $title,
        );
}

In my mymodule.module file I have

function mymodule_theme($existing, $type, $theme, $path){
    return array('header' =>
        array(
            'variables' => array(
                'header_title' => 'Default Title',
                'header_size' => 'h1',
                'text_align' => 'center',
                'uppercase' => FALSE,
                'grid_size' => 12,
                ),
            ),
        'product_display' =>
            array(
                'variables' => array(
                    '#imageurl' => [],
                    '#product_title' => [],
                    ),
                ),
        );
}

in my product_display.html.twig file I have

{% for product in product_title %}
    {% for image in imageurl %}

                            {{ product }}

    {% endfor %}
{% endfor %}

I know for sure that my custom block.php file is able to retrieve the data properly because using Debug() on $imageurl or $title displays all the information. However using Dump() in product-display.html.twig shows the #imageurl and #product_title arrays as empty.

There is a syntax error in your hook_theme. Use this instead:

function mymodule_theme($existing, $type, $theme, $path){
return array('header' =>
    array(
        'variables' => array(
            'header_title' => 'Default Title',
            'header_size' => 'h1',
            'text_align' => 'center',
            'uppercase' => FALSE,
            'grid_size' => 12,
            ),
        ),
    'product_display' =>
        array(
            'variables' => array(
                'imageurl' => [],
                'product_title' => [],
                ),
            ),
    );

}

The # sign in a render array is used to differenciate a key that has a meaning in the rendering versus an element. It shouldn't be included in the theme definition.


Online streaming and on air/broadcast function for a Drupal website I'm trying to figure out how to build a website for a tv using Drupal.

Going around the web I found different modules and Videola distribution.

About the Videola distribution, I have not find any tutorial or something close to it.

I've found Kaltura , Live Streaming and VideoWhisper

has anyone here got experience with these modules?

Thanks in advance.

Octopusvideo might suite for your requirement, this is in D7 and have lot of functionality.


'Add new comment' link/button does not display on custom entity A new comment type is created and added as a field (say x_comments) to a custom entity. The comments show up and work as expected. However when the x_comments field is configured to disable 'Show reply form on the same page as comments' the 'Add new comment' link/button does not get rendered on custom entity pages. When this setting is enabled the comment form is displayed as expected.
Inspecting Drupal core's Article content type has custom Links pseudo field where 'Add new comment' link/button is displayed. However my custom entity does not have such a pseudo field, even if it did comment module would not know about it.
Please share clues on how to make the 'Add new comment' link/button be displayed?
The buildCommentedEntityLinks method is not being called on custom entity which creates the 'Add new comment' link. Hmm

Turns out one needs to implement field formatter for other entities instead of hook_links_alter. So one can perhaps add a Pseudo field formatter to get this markup rendered on custom entities with an approach described here
The hidden gem is noted in the comments for the node entity.
  /**
   * Implements hook_node_links_alter().
   */
  function comment_node_links_alter(array &$links, NodeInterface $node, array &$context) {
    // Comment links are only added to node entity type for backwards
    // compatibility. Should you require comment links for other entity types you
    // can do so by implementing a new field formatter.
    // @todo Make this configurable from the formatter. See
    //   https://www.drupal.org/node/1901110.

    $comment_links = \Drupal::service('comment.link_builder')->buildCommentedEntityLinks($node, $context);
    $links += $comment_links;
  }


How do I add extra cost with cash on delivery? I have implemented and eshop with commerce module in drupal 8. How can I add extra cost in case the customer chooses the cash on delivery method? I use payment module. Is there any solution or some other alternative? I tried rules also, but there is not any event that is triggered on payment method selection.

It's been a long time since this has been asked, but I'm adding my input here since I bumped into this while looking for the exact same thing for one of my projects. The way I found as the cleanest and most straight forward, while reading through the documentation, is the use of an order processor class that would check the current order for the use of the payment method in question and add an adjustment accordingly. You can have a look here on information as to how to setup an order processor https://docs.drupalcommerce.org/commerce2/developer-guide/orders/order-refresh-and-process.
The class has to implement the \Drupal\commerce_order\OrderProcessorInterface and it has to provide an implementation of the process method.

class MyCustomProcessor implements OrderProcessorInterface {

    public function process(OrderInterface $order) {
        $payment = $order->get('payment_method')->first()->entity;
//   or
        $payment = $order->get('payment_gateway')->first()->entity;

//... your logic here depending on what you'd like to do

        $order->addAdjustment(new Adjustment([
            'type' => 'fee',
            'label' => 'Payment method fee',
            'amount' => new Price($fee, 'EUR')
        ]));

    }
}


How to add a class for forgot password link? I need to add a class for the forgot password link. How can I do using Drupal?

This is the actual link:

Have you forgotten your password?

My expected link is this one:

Have you forgotten your password?

How can I achieve this, without using jQuery?

Why don't you create a custom block in "admin/structure/block/add," and then add that link with that class into the block? Place the block where you want to place it. It should still fulfill the same requirements.


How do I get multiple references from the autocomplete? I am using the following form element.

$form['group']['one'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Tags'),
    '#target_type' => 'user',
);

I submit values similar to the following ones.

  user00 (0), user01 (1), user02 (2), user0x (3)

What I receive from the form is the following:

  one = 3

It only picks up the last ID.

How can I get all the references entered in the form element? How does the form element handle the references to not existing entities?

The comma is used to separate multiple references, but looking at the code in Name::valueForm() I would say the form element needs to use a property more.

  $form['value'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => $this->t('Usernames'),
    '#description' => $this->t('Enter a comma separated list of user names.'),
    '#target_type' => 'user',
    '#tags' => TRUE,
    '#default_value' => $default_value,
    '#process_default_value' => $this->isExposed(),
  );

Settings #tags to TRUE makes the the form element accept multiple values.

The format of the values assigned to the form element is evident in EntityAutocomplete::validateEntityAutocomplete() (its validation handler), which uses this code.

  $input_values = $element['#tags'] ? Tags::explode($element['#value']) : array($element['#value']);

  foreach ($input_values as $input) {
    $match = static::extractEntityIdFromAutocompleteInput($input);
    if ($match === NULL) {
      // Try to get a match from the input string when the user didn't use
      // the autocomplete but filled in a value manually.
      $match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
    }

    if ($match !== NULL) {
      $value[] = array(
        'target_id' => $match,
      );
    }
    elseif ($autocreate) {
      /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface $handler */
      // Auto-create item. See an example of how this is handled in
      // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
      $value[] = array(
        'entity' => $handler->createNewEntity($element['#target_type'], $element['#autocreate']['bundle'], $input, $element['#autocreate']['uid']),
      );
    }

The form element value is an array of item whose target_id key is an object of the requested entity.

(From that code, it is also clear that #tags makes the form element accepts multiple references separated by commas.)

As for the using reference that aren't found, you can decide what the autocomplete does by setting #validate_reference: If you set it to TRUE, and #autocreate is not set to TRUE, the autocomplete will accept only existing references.


Drupal aggregate css crashes IE7 If I turn on aggregate css in my performance config and then load my site in IE7, the browser crashes.   Any ideas why that might be?

Thanks,
Paul

There is a size limit of 300kb per file and a limit of 32 files.

http://joshua.perina.com/africa/gambia/fajara/post/internet-explorer-css-file-size-limit

http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/ad1b6e88-bbfa-4cc4-9e95-3889b82a7c1d


Show a list of my product with my coupon discount I have 50 products. I used ubercart module and uc_coupon for my e-commence website. I have many different type of coupons for different products and I always make human mistakes and confuse.

Here is my question: Is there anyway to show a list of products with price and discount as well?

==UPDATED==

Looks like you need views integration for the UC Coupon Module, not fully supported yet.

Maybe you want to try and port this patch to Drupal 7?


How can I switch menus after a user logs in I'm trying to create a register/login links in the format "Register or Login" which is display for anonymous users and switched out with the user menu when a user is logged in.

I know I can preprocess those links as variables in template.php but am not sure how to access the user menu from template.php in order to write an if statement.

Ultimately, if I could do something like Forrst (images below), then tahts what I would love to end up with, but for now just trying to keep it sweet and simple.

From This:

To This after login:

You might do that with a simple block, rather than creating a menu, preprocess it to add the word between and check if the user is logged in.

Simply select anonymous/authenticated user under the "Roles" in block visibility settings.


Drupal Commerce: Set Order as Paid in Full I am trying to import records from a CSV file (from another non-drupal database) for a membership site I am porting to Drupal 7. I have Drupal Commerce, Commerce Recurring Framework set up. Everything works as it should when you go through the proper work flow. However, I have 2000+ records that need to be added to the site and going through that process doesn't make sense. In other words, I am writing a script to set up the order and then recurring entity for each user.

I have code that creates my order, the issue is that Commerce is looking for a payment to be made before it creates the recurring entity for the order. Again, that doesn't make sense from a time perspective, not to mention all of these members have already paid as these are being ported. So my question is how to I trigger the order paid in full event that will trigger the creation of the recurring entity being created? Or is there a way to just create the recurring entity?

Here is my code:

<?php
foreach ($records as $record) {
$product_sku = $record['sku'];

$order = commerce_order_new($user->uid, 'completed');

commerce_order_save($order);

$product = commerce_product_load_by_sku($product_sku);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

commerce_line_item_save($line_item);

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

commerce_order_save($order);
}
?>

Thanks,
Aaron

If you want to trigger the paid in full event you just need to make the order balance 0. You can do that by adding a payment transaction for the full amount to the order. The event is then triggered when that new successful transaction is saved.

The relevant Commerce function is

commerce_payment_commerce_payment_transaction_insert

/**
 * Implements hook_commerce_payment_transaction_insert().
 *
 * When a new payment transaction is inserted that is already completed, check
 * the order balance and invoke a Rules event if the order is paid in full.
 */
function commerce_payment_commerce_payment_transaction_insert($transaction) {
  // If the inserted transaction was marked as a success and placed against a
  // valid order...
  if ($transaction->status == COMMERCE_PAYMENT_STATUS_SUCCESS &&
    $order = commerce_order_load($transaction->order_id)) {
    // Then check to make sure the event hasn't been invoked for this order.
    if (empty($order->data['commerce_payment_order_paid_in_full_invoked'])) {
      // Check the order balance and invoke the event.
      $balance = commerce_payment_order_balance($order);

      if ($balance['amount'] <= 0) {
        // Invoke the event including a hook of the same name.
        rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);

        // Update the order's data array to indicate this just happened.
        $order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

        // Save the updated order.
        commerce_order_save($order);
      }
    }
  }
}

The key part is here:

// Invoke the event including a hook of the same name.
rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);
// Update the order's data array to indicate this just happened.
$order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

// Save the updated order.
commerce_order_save($order);

In any case, you'll need to create a valid transaction for the order to trigger the commerce_payment_order_paid_in_full event. Rules reacting to that event will expect the transaction object as an assumed parameter.


How to render full profile2? I am tring to load a full profile2.
I a trying the following code
<?php
$uid = user_load($node->uid);
$profile2_p = profile2_load_by_user($uid, 'profile2_profile');
print render($profile2_p);
?>

I get an error saying object can't be used as array.
If I print_r $profile2_p then I get an array relating to the correct profile2 entity. How can I render this entity?
Thanks

Looks like you can get a renderable array using profile2_view():
/**
 * View a profile.
 *
 * @see Profile::view()
 */
function profile2_view($profile, $view_mode = 'full', $langcode = NULL, $page = NULL) {
  return $profile->view($view_mode, $langcode, $page);
}

https://git.drupalcode.org/project/profile2/-/blob/7.x-1.x/profile2.module#L1084
See also that modules hook_user_view() which does the same:
https://git.drupalcode.org/project/profile2/-/blob/7.x-1.x/profile2.module#L399
/**
 * Implements hook_user_view().
 */
function profile2_user_view($account, $view_mode, $langcode) {
  foreach (profile2_get_types() as $type => $profile_type) {
    if ($profile_type->userView && $profile = profile2_load_by_user($account, $type)) {
      if (profile2_access('view', $profile)) {
        $account->content['profile_' . $type] = array(
          '#type' => 'user_profile_category',
          '#title' => $profile_type->getTranslation('label'),
          '#prefix' => 'type . '">',
        );
        $account->content['profile_' . $type]['view'] = $profile->view($view_mode);
      }
    }
  }
}

With a single entity in your code, you can:
render($profile2_p->view($some_view_mode));


Show full post on front page? When I publish to the front page, it shows part of the posts. My posts consist of just a file upload. However, the user must click on the post/click on the "Read more" button to see the file upload. How would I make Drupal display this file on the front page within the post?

If you are using Drupal 7 you may change the teaser format for the content types promoted on front page. Navigate to "Home » Administration » Structure » Content types » YOUR CONTENT TYPE » Manage display" and click the "teaser" sub tab; then change the format for the body field from "Summary or trimmed" to "Default".

Notice that this will affect some other pages (taxonomy and views).


Can you get any view to list content based on a field value? I am trying to get a list view in a panels node template to show content based on a text field of the currently viewed node.

Just to give you more information I am including my setup below:

Content Type A - textfield called 'ref'.
Content Type B - textfield called 'a_ref'.

Content Pane View to show list of Content Type B but filtered depending on the node being viewed.

Node template on Content Type A with two regions (Left and Right).

On the Left I am displaying fields of the node being viewed.
On the Right I want to show the Content Pane View with a list of Content Type B where 'a_ref' is equal to 'ref'.

I am trying to figure out how to use contextual filters between the node template and content pane but to no avail.

I hope anyone out there can enlighten me on the way it should be done.

Thanks in advance for any help,

Kevin

Solution

Get the view, and the view alone to do what you want. You need a contextual filter on the field you want to match against. Test the view out in the views UI.
Add a content pane display, this requires the views content module to be enabled. In the pane settings, find argument inputs settings (Sorry, no UI in front of me, that setting could be something else). In here you can tell Views what type of data the View should expect for the contextual filter. Pick From context. You'll be presented with a looong list of available options, it's easy to get this wrong, be careful. Scroll down until you under Node find the field you are trying to match against. If you have multiple fields with the same label, there is no easy way to know which is which. Yes, it's crap, you will have to go trial-and-error until this gets fixed. Save the view.
Go into Panels. Ensure that the new view is visible under the View panes category, not just Views. Add the view, tell it which node to get data from, which is usually just one, save.

Troubleshooting

This setup is non-trivial for a lot of users. I find that the common most problem people hit is configuring the view to require a certain type of input. If you can't get this to work, there are two things to try.

The Panels process for identifying which Views are valid, seemingly can get stuck sometimes. Clear caches, and resave both the View and Page.
In the Views arguments configuration, set the argument to be optional. This is not really what you want, but if this causes the View to show up in the Panels UI, then we know the problem is that Panels does not have access to the information that the View says it wants, which at least narrows the problem down a lot.


Administer Users by Role module - show users I'm using Administer Users by Role module and I crated a view of users.
That view displays all the users.
Lets assume there is 'Admin', 'Editor' & 'Member' roles.
Admin can see all the users.
Editor can see only Members (not other Editors and not the admin).
I need that so I can use Views-Data-Export module.

How to create such a view? or any other suggestions?

I don't know whether this is correct or not but you can try this,

function mymodule_views_query_alter(&$view, &$query)
{
 global $user;
 $role=implode(', ', array_slice($user->roles, 1));//get the current user role
if ($view->name == 'your_view_name')
{
  switch ($role) {
    case 'administrator':
//  drupal_set_message("administrator");
     // $query->add_where(); put your where condition
     // $view->query->set_group_operator('OR');
        break;
    case 'editor':
//  drupal_set_message("editor");
     // $query->add_where(); put your where condition
     // $view->query->set_group_operator('OR');
        break;
    case 'Member':
    //  drupal_set_message("Member");
      // $query->add_where(); put your where condition
     // $view->query->set_group_operator('OR');
        break;
        }
    }

}


MySQL 5.5 performance in Windows 7 My collegues and I are working on a Drupal 7 project. From time to time, we need to do a clean install on our machines (to get the latest updates working).
However, when installing the Drupal database, my collegues laptop is much faster than mine, despite the fact I've got the latest and most powerfull laptop (Windows 7 Enterprise, 64-bit and 8GB of RAM).

What causes this lack of performance in installing the new Drupal website? I reinstalled MySQL 5 times, and still I don't see any improvement.

This is funny. I just answered a question about MySQL 5.5 being slow in the DBA StackExchange. You will have to configure it to perform better. It is not automatically configured for high performance by default.


Preview image after uploading using Form API I uploaded an image file using the managed_file Form API type, but after uploading the image it does not appear as a thumbnail beside the field. What is rendered is the file name of the image with a link to the image and a small icon.

How do I show the thumbnail of the image after uploading it (like the image preview from the core Image field)?

Also how can I show a default image beside it (if it has a default value)?

This is my code:

$form['logo'] = array(
      '#title' => t('Logo'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#default_value' => variable_get('logo', ''),
      '#upload_location' => 'public://',
      '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(0.3*1024*1024),
  )

Define the theme in the field, and simulate the code structure to preview the image that you just upload. My solution is as follows,

$form['abc_field']['abc_filename'] = array(
        '#type' => 'managed_file',
        '#title' => t('abc image'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(1 * 1024 * 1024),
        ),
        '#theme' => 'abc_thumb_upload',
        '#upload_location' => 'public://abc/'
    );

In your hook_theme(),

return array(
    'abc_thumb_upload' => array(
        'render element' => 'element',
        'file'           => 'abc.module',
));

In your theme_abc_thumb_upload(),

function theme_abc_thumb_upload($variables) {

    $element = $variables['element'];

    if (isset($element['#file']->uri)) {
        $output = '

';
        $output .= 'uri) . '" />';
        $output .= '<input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
        $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

        return $output;
    }
}


Two formats in one view Let me see if I can explain what I need.

1) I need some tabbed buttons listed first:

View All | Category 1 | Category 2 | Category 3

2) For each button, clicking the tab should opens an area to display:

Other tabbed buttons (to the left).

Current | Future | Past

Each of the buttons/views has a grid and a table display each (to the right).

Grid | List

Those are all views (example: Category 1 - Current - Grid format view, Category 1 - Current - Table format view).

I can probably use quicktabs module to display my top level tabs, but how to achieve #2?

I did something similar using the module Views Field View.

Module Page Description:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


What is the best practice for showing a specific node within a specific page? I'm using the boostrap_carousel module which creates a custom content type for a slideshow. I'd like to have a block for one of these carousels to show on the home page. I'd also like to have a carousel embedded on most of the interior pages. What's the best practice to render a specific node that would be created using that content type within the front page and within another node?

You could try creating a new block view, which selects a specific carousel node, and then choose where you want the block to appear.

Views Slideshow does something similar, where you can create a slideshow in a block from a number of existing images.


Expose two filter blocks from the same view using drupal 7 ? I'm not sure how to overcome this. So far I have managed to do it by simply duplicating the view, but this is not a good idea.

The view needs to have two exposed filters. These blocks are styled different and sit in different parts of the site, so they need to be independent.

Is it possible to expose two filter blocks from one view?

An alternative to this is to

Clone your page display - but do not change the cloned pages path...
Override and modifty the filters for that cloned display

You will have an exposed block with different filters that submits to the original view.


Want to process node edit in two different ways On every node page there is an edit and submit, you can set when the edit is available and such.

So, what I want to do is this.

When a regular user uses the edit button(which I want to be available for all site users), I want it to open the node and allow someone to directly edit it.  Just like when the owner edits it, it will open everything and allow the user to make changes.  But instead of actually saving the changes to that node, I want it to create a new node that copies the old one and saves this other user's changes.

When a moderator or the creator of the node edits, I want it to edit the node directly and saves the changes to that specific node.

I need to either create two buttons that show up differently on page for certain users, or use the same button but use some form validation technique to check the permissions of who is submitting the form and do the above accordingly.  Are there any ideas?  Any help is greatly appreciated!! Thanks

You can use revisioning module

Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.

Using this module when you edit a node, a new revision is created and it goes to modaration mode.

For more info check the module page


Get nodes with the same term a node I'm trying to make a block, with views, that shows me a list of nodes that has the same term of the node that I'm viewing:

I open node/1 that has a term reference field to the term "10"
I want to display other nodes that have a reference to the same term

I use a contextual filter, but how should I pass the term?
Have I to use a php value as default argument?

Oh, it is really easy with powerful Views module.
There is cool option for contextual filters “Content: Has taxonomy term ID” and “Content: Has taxonomy term ID (with depth)” — Load default filter from node page, that's good for related taxonomy blocks.

Tip: don't forget to exclude node, which is current!


How can I populate a node field based on a user field? I have an "address" field among the user fields. Here users can specify several entries for their addresses.
They can create orders (these are custom content type nodes). The order node has a "shipping address" field. Users should be able to choose one address from their previously stored ones and use them on the order form.

How can I do this? What I have in mind is adding a custom js that makes an ajax call and fetches the addresses from the user fields. Is it a good idea or is there any simpler method?

It would be fine too if I can make a reference field to the user datas and users would see a combo box to choose their address from.

I believe you could achieve this with the Rules module. Checkout Learn Rules with NodeOne, part 7: Conditions on loaded objects. In part 8 you will see how to Use PHP to populate CCK fields. Although this is for Drupal 6, you should be able to use a similar approach in Drupal 7.


copying out Hierarchical Select terms into other textboxes I have one Hierarchical Select with 4 depth term. What I need is to copying out every depth term level to other fields/textboxes  at the same form as described by the attached image.

And also, how can every time we change the Hierarchical Select value, it also should change the corresponding fields/textboxes.

Thank you for the help.

------------   extra information on the problem ------------------

@Yogesh

I have mininal knowledge on javascript/jquery, where to save the *.js file and how to call it properly.

I just read from one tutorial that it should save to a "js folder" and called it from the template .info file.  So, following are two images that trying to tell you what I've been doing.  Kindly help me to examine every detail of the images and hopefully you can tell where a did a wrong.

and i call the script from /sites/all/themes/zen/zen.info
with command: "scripts[] = js/isian.js"

Please advise,
Thank you

You can use Drupal JavaScript API for setting the values of fields, based on selection made by user in Hierarchical Dropdown field.

The below sample code is for fixed number (3) of fields, you can further extend this to dynamically set the values of n number of fields using jQuery $.each().

(function($){
  Drupal.behaviors.exampleModule = {
    attach : function(context, settings) {
      // On hierarchy change event.
      $(".hierarchical-select .selects select").change(function(event) {
        updateFieldsValue();
      });

      function updateFieldsValue() {
        var First = $.trim($(".hierarchical-select .selects select[name='field_hierarchical_dropdown[und][hierarchical_select][selects][0]'] option:selected").text());
        var Second = $.trim($(".hierarchical-select .selects select[name='field_hierarchical_dropdown[und][hierarchical_select][selects][1]'] option:selected").text());
        var Third = $.trim($(".hierarchical-select .selects select[name='field_hierarchical_dropdown[und][hierarchical_select][selects][2]'] option:selected").text());

        // set value of Fields.
        $("input[name='field_prop_1[und][0][value]']").val(First);
        $("input[name='field_prop_2[und][0][value]']").val(Second);
        $("input[name='field_prop_3[und][0][value]']").val(Third);
      }

    }
  };
})(jQuery);

You can find more details about Drupal Behaviors on 'Better understanding of Drupal behaviors' and 'Understanding JavaScript behaviors in Drupal'.


How to automatically update entity that is created programatically? Using Entity API, I can create entities easily like this:

// SomeEntity class extends ContentEntityBase
$entity = SomeEntity::create(['my_id' => 'id123']);
$entity->save();

Works fine as long as my_id is unique. When it's not, I get EntityStorageException with message complaining about my_id not being unique. I could first try to load entity to see if it exists and update it manually but that seems like unnecessary overhead.

Is there a way to automatically save or update existing entity programatically?

Not really. To figure out if an entity exists, you have to check that somehow.

If you're trying to optimize, you could run an entity query instead of loading it completely. But in case you want to update, you need to load the original entity anyway, so just do that.

$entity = SomeEntity::load(['my_id' => 'id123']);
if (!$entity) {
  $entity = SomeEntity::create(['my_id' => 'id123']);
}
$entity->save();


Embed rate number up down widget in panel node I am using rate module and the number up down widget, and in the settings for this module I had set it to appear at the top of content. It was appearing fine. However, now I am using a panel for this node and the widget no longer appears as expected. I need to embed it into my panel. How would I go about this? I have done a few searchs and found rate_embed, but I am not having any luck getting this to work. I have tried the following. My rate widget is called 'points', and its settings are at /admin/structure/rate/:

function:

<?php rate_embed(&$node, $machine_name, $mode = RATE_FULL); ?>

What I tried:

<?php print rate_embed($node, 'points', $mode = RATE_FULL); ?>
<?php echo rate_embed($node, 'points', $mode = RATE_FULL); ?>

this was giving an error that rate_embed was acting on a non-object.

You can try the following code.

 $up_down = rate_generate_widget('1', 'node', {current node id}, RATE_FULL, TRUE, FALSE, NULL);
 print render($up_down);