How do I make a withdrawal? I'm implementing a site where users pay for submissions and reviewers get paid. Drupal Commerce with Commerce Credits allows me to buy credits using Paypal and to pay on site with credits for submitting content.

Reviewers receive credits for performing the review, when they reach a certain amount I want them to offer the possibility to withdraw credits through Paypal.

I had a look at modules like Commerce Funds (broken) and Commerce-Marketplace (withdrawal not implemented yet) and Paypal Adaptive Payments (not public anymore), did I miss anything?

Is there anything I can do to automatize this process with rules? I could transfer credits to a withdrawal user account and manually make the transaction with Paypal. Any hints how to automatize this process and trigger a Paypal payment to users credit card?

I suppose this can be done, but it won't be easy. There will be quite some components and you will have to write some code. Disclaimer is that I have not tested anything of this code, but I hope this to be useful to you.

This example is based on the commerce_funds_withdraw_action() on line 932 of the Commerce Funds Withdraw Module, part of Commerce Funds.

Most important is this part, which performs the actual transfer using PayPal Mass Pay (Read the integration guide for details about PayPal business accounts and contacting customer support to enable the feature.):

$response = commerce_paypal_api_request($payment_method, $nvp);
if($response['ACK'] == 'Success') {
  $withdraw->status = 'Transfered';
  $amount_paypal = $withdraw->amount;
  $withdraw->amount = commerce_currency_decimal_to_amount($withdraw->amount, $withdraw->currency_code);
  commerce_funds_withdraw_save($withdraw);
  $amount = array(
    'amount' => $amount_paypal,
    'currency_code' => $withdraw->currency_code,
    'reference' => $withdraw->uid,
  );
  commerce_funds_debit(user_load($withdraw->uid), $amount);
  drupal_set_message(t('Money were successfully transferred to @user_email.', array('@user_email' => $user->mail)), 'status');
}

If we remove all commerce funds transaction tracking, we are left with:

$response = commerce_paypal_api_request($payment_method, $nvp);
if($response['ACK'] == 'Success') {

  // Deduct credits from the account here, or do it in Rules later.

  drupal_set_message(t('Money was successfully transferred'), 'status');
}

The actual communication with the API is handled by commerce_paypal_api_request(), a function of the Commerce PayPal module, which requires 2 parameters;

$payment_method: The payment method instance array associated with this API request.
$nvp: The set of name-value pairs describing the transaction to submit. (See MassPay API Using NVP of the API documentation.)

Since there is no offical payment method to use, we create a custom payment method option:

$payment_method = array(
  'settings' => array(
    // Fill these to match the data configured with PayPal
    'server' => '',
    'api_username' => '',
    'api_password' => '',
    'api_signature' => '',
    'log' => array(
      'request' => FALSE, // Log outgoing request TRUE/FALSE.
      'response' => FALSE, // Log response from PayPal TRUE/FALSE.
    ),
  ),
);

And the NVP:

$nvp = array(
  'METHOD' => 'MassPay',
  'EMAILSUBJECT' => 'Withdraw',
  'CURRENCYCODE' => $currency_code,
  'RECEIVERTYPE' => 'EmailAddress',
  'L_EMAIL0' => $receiver_email,
  'L_AMT0' =>  $amount,
);

Now for getting this all together in a custom module and a Rules actions:

Create a rules_paypal_deposit folder for your module, with the following files:

rules_paypal_deposit.info:

name = Rules PayPal Deposit
description = Deposit funds to a paypal account using rules.
core = 7.x
dependencies[] = rules
dependencies[] = commerce_paypal

rules_paypal_deposit.module:

<?php
/*
 * This function performs the actual transfer
 */
function rules_paypal_deposit_do_deposit($receiver_email, $amount, $currency_code) {
  $payment_method = array(
    'settings' => array(
      // Fill these to match the data configured with PayPal
      'server' => '',
      'api_username' => '',
      'api_password' => '',
      'api_signature' => '',
      'log' => array(
        'request' => FALSE, // Log outgoing request TRUE/FALSE.
        'response' => FALSE, // Log response from PayPal TRUE/FALSE.
      ),
    ),
  );

  $nvp = array(
    'METHOD' => 'MassPay',
    'EMAILSUBJECT' => 'Withdraw',
    'CURRENCYCODE' => $currency_code,
    'RECEIVERTYPE' => 'EmailAddress',
    'L_EMAIL0' => $receiver_email,
    'L_AMT0' =>  $amount,
  );

  $response = commerce_paypal_api_request($payment_method, $nvp);
  if($response['ACK'] == 'Success') {

    // Deduct credits from the account here, or do it in Rules later.

    drupal_set_message(t('Money was successfully transferred'), 'status');
  }
}

rules_paypal_deposit.rules.inc:

<?php
/**
 * Implement hook_rules_action_info()
 */
function rules_paypal_deposit_rules_action_info() {
  $actions = array(
    'rules_paypal_deposit_actions_deposit' => array(
      'label' => t('Transfer funds to a PayPal account'),
      'group' => t('Rules PayPal Deposit'),
      'parameter' => array(
        'receiver_email' => array(
          'type' => 'text',
          'label' => t('E-mail to transfer to.'),
        ),
        'amount' => array(
          'type' => 'decimal',
          'label' => t('Amount to transfer (format: 12.34)'),
        ),
        'currency_code' => array(
          'type' => 'text',
          'label' => t('3 Letter currency of the transfer, see the PayPal documentation', array('@url' => url('https://developer.paypal.com/docs/classic/mass-pay/integration-guide/currency_codes/'))),
        ),
      ),
    ),
  );
  return $actions;
}

/**
 * The action for rules_paypal_deposit_actions_deposit
 */
function rules_paypal_deposit_actions_deposit($receiver_email, $amount, $currency_code) {
  rules_paypal_deposit_do_deposit($receiver_email, $amount, $currency_code)
}

You can choose to add the PayPal API settings server, api_username, api_password and api_signature as Rules parameters as well and add the parameters to rules_paypal_deposit_actions_deposit() and rules_paypal_deposit_do_deposit(). Or just define them in the code.

I really hope this is of use to you. It was written in a bit of spare time because I thought it was a nice puzzle. Do not get mad if it doesn't work ;)

Obviously this needs proper testing on the PayPal API sandbox first.


WebForm CSS Styling - Radio Buttons Giving all of the other components are simple. However the radio button seems a bit challenging.  I've added class to the following

.checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"], .radio input[type="radio"], .radio-inline input[type="radio"] {
margin-left: -20px;
position: absolute;

however doesnt seem to work. I'm looking for an HTML5 style layout.

It's pretty difficult to help you here. Are you trying to make your radio buttons inline?

If you are using Bootstrap theme with everything else working right, according to: W3Schools you should be able to just name it class="radio-inline" and then target .radio-inline class in CSS with what you are trying to achieve.


How to add my own images to the views slide show? I am new to Drupal. I have been trying to make a slide show on the front page but I am facing an issue on how to upload images of my choice in the slide show. I.e. the images that I have in my computers folder.

I have created a view and placed an image field in it, everything is set. I have also added the block to the main page content. All I can see on the front page is the slider title obviously since i have not been able to add any images.

Can any body tell me how to set my own images to the slider?

I don't want to use fixer slider.

I have used views slide show and some other js files for cycle.

Edit: Here is a screenprint of the view I defiined so far:

First you need create a content type for your slider (admin/structure/types/add), let alias it slider, then add your desire fields to it ( maybe a image field and title as a slider slogan ), then create a image style for your slider in admin/config/media/image-styles/add ( create a image style according to your slider image in your design), then   in views  change filter to show only images form slider content type.

For more details do  "How to Build Drupal 8 Slideshows" step by step.


Tpl for page having url like product/checkout/%/% I have created a page with hook menu with url product/checkout/%/% where % will be userid and product id.
How can I add a page tpl for this url ?

In your page callback, you would have to set '#theme' on a renderable array.

You can use an existing theme function, or create your own using hook_theme.

If creating your own and you prefer to use a tpl, you can set the template option in hook_theme and bypass having to create a theme callback function.


Blank spaces opening RSS XML file - How to solve? All of the sudden, we are experiencing problems with our RSS feed which comes with the Drupal core 7.x . It is no longer valid due to two spaces before the opening XML tag. The following error is what I get in the feed validator:

  line 1, column 2: XML parsing error: <unknown>:1:2: XML or text declaration not at start of entity

So I am aware of other related posts on Stack Exchange and tried the things mentioned in:

Approach to removing extra space at beginning of RSS file?
xml sitemap module : XML declaration allowed only at the start of the document [closed]
RSS Feed does not validate using Views RSS module

These are the things we did do so far:

Checked all PHP-files on the website for containing blank spaces before the opening tags. There were a few, we fixed them all but no help.
Changed the default theme to another theme, making sure it is not theme related.
When I create a custom RSS feed with Views, the same two blank spaces show up before the XML opening tag.
I checked every page, block and view that has manually written PHP tags everywhere and deleted every space that could cause this.
All modules and Drupal core is updated to the most recent versions.
I checked on the Drupal forum for related issues in XML Sitemap, Metatag, RDF, Schema.org (modules we are using) with no success. I disabled every one of the above mentioned modules one by one, but with no success.
Eventually we exported the complete website, except the sites/default/files/ folder which contains no PHP files anyway, and imported it local. The blank spaces are gone in the local setup.

What makes it a bit difficult too, is that I have no idea when the RSS feed went broken. It can be between a week and a few months, making it difficult to filter out when I updated some contrib modules.

So we are quite desperate in finding this, especially since the problem doesn't exist in a local setup. We have a news website so having a working RSS feed is pretty important.

We must be overlooking something, but have no idea what it can be.

Some more troubleshooting ideas:

Do the spaces only appear on the RSS page, or also on other pages? That could tell you whether the problem is in a central place or a template/include-file that is only loaded for the RSS feed.
You can use var_dump(get_included_files()) (ideally in the template, just before the XML is generated) to see a list of all PHP files that have been included so far. This might help with investigating - look for closing PHP tags at the end of the files, print statements, etc.

Also, an idea for a dirty workaround (may cause other problems, but could be worth a try if it's urgent): ob_start() buffers all output, while ob_end_clean() deletes it. So if you put an ob_start() in the top of your index.php and an ob_end_clean() at the start of the RSS template, this might let you discard the spaces. (It shouldn't affect anything else, because the buffer is flushed automatically if it's still open when the script ends.)


Assign the node to a user I'm using Drupal 7 and workflow module for Article content type.
There are two roles author, editor. There can be as many number of authors as how many we want, but there are only four editors.
Workflow states: Review, Back to Author and Publish.

Worflow offers very good publishing process throught it's rules and actions. Authors create articles, and change the workflow state to Review and save it. Editors have two choices either to publish the content or return it back to the author of the article. Works cool!

But what I want is to make the authors to choose one of the editors(there 4 of them), that editor is going to be assigned to this article, and only he/she can edit this article while the worflow state changes into Review. Currently any user with Editor role can edit the articles with Review state.

I use workbench, which accomplishes the same thing as workflow.  There is a module in the workbench collection called Workbench access that I use to send content to specific editors in the workflow.  I use it for my school newspaper so that writers moderate content to the editors of their specific section (i.e. news, sports, arts, lifestyle, etc.) then the Editors send the content to me for final approval and publication on the site. Hope this helps!


Sticky header block module? I am searching for a way to make a block behave as a drupal-highlighted area, similar to the header here. In other words, stick to the header and move along as the user roles down.

I was wondering if there is either a module that can do that, to sort of wrap the block's content or a custom workaround in my module.

I know that there exist some themes which can do that, but I would like to implement a theme-free solution.

Thanks!

This is just a CSS thing!  There a tutorial here on how to achieve it, but you're pretty much just looking at some CSS like the following.

Edit: The tutorial has now gone, but the CSS contained is very similar to that shown below, and a quick search in your favourite search engine will return similar results.

#BLOCKID {
    position: fixed;
    top: 0;
    left: 0;
    height: 160px;
}

Just apply the CSS to your chosen block and you're off.


How can I detect AJAX request inside Drupal? I am looking for Drupal way of detecting AJAX request. I need to check this inside hook_form_alter (embedding views with AJAX support)

For Drupal 7 there's nothing special in the API, just use plain PHP:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  // AJAX request
}

For Drupal 8, the Symfony request object has a helper method:

// Example for brevity only, inject the request_stack service and call
// getCurrentRequest() on it to get the request object if possible.
$request = \Drupal::request();
$is_ajax = $request->isXmlHttpRequest();


Need a WYSIWYG plugin Straight to the point, I need a WYSIWYG module for Drupal 6; here are the requirements:

Easy to change the toolbar button
Able to add custom style
Able to upload image and put into content
Able to upload flash and render it inside content
Able to upload file and show it as download link inside content

Anybody familiar with Wordpress WYSIWYG editor? That is something like what I want.

Use the WYSIWYG module...  TinyMCE allows for media to be added such as Flash, so you can use that plugin.

For files/images you can use the Insert module OR IMCE (along with IMCE Wysiwyg API Bridge) to add the images/files to the content.

Remember Google can be a wonderful thing ;)


Drupal installed with Drush doesn't display home page I installed Drupal with Drush and it all works fine and the welcome page appears as well. But when I try to log in (with whatever account) it shows me the: "Object not found! The requested URL was not found on this server...." page.

I am on Arch Linux. I checked the httpd.conf file and mode_rewrite engine is enabled:
  "LoadModule rewrite_module modules/mod_rewrite.so"

I was also suggested to check the .htaccess file extension, but it has no ".txt" extensions.

Also, I went to index.php?q=user url and it did respond: opened the User account page.

I am still suspecting something with httpd.conf and .htaccess fils, but they look fine to me. I failed to find any resource related directly to this problem.

Just to clarify further. Both /drupal and /drupal/index.php urls are displayed without errors. But when I try to log in as an admin (or any user) and submit it, it shows the error page I described above. Which is a problem, because I can't even enable clean urls, as it requires permissions for that.

I checked if the httpd.conf file (as suggested by comment below) is configured
 to read the .htaccess file:

AccessFileName .htaccess

And although the file was missing that section, I found out that httpd.conf file
 reads .htaccess file by default, if not configured otherwise. Despite this, I added that line, but it still shows the same error when logged in.

Also, the following are the httpd.conf lines:

DocumentRoot "/srv/http"

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order deny,allow
    Deny from all
</Directory>

I think your true problem is that clean URLs aren't working (as evidenced by index.php?q=user does work).  It may also suggest another Apache configuration problem.

Make sure your httpd.conf is configured to read .htaccess

AccessFileName .htaccess

I don't know the last time I saw a system that didn't have this (sometimes was different on older WAMP installs).

Then, browse to http://example.com/index.php?q=admin/config/search/clean-urls

Set clean URLs if you can.

If you can't set clean URLs, then you have an Apache configuration problem.

If browsing directly to http://example.com/index.php works, but http://example.com/ doesn't, then I suspect your configuration doesn't allow Apache overrides for that DOCROOT.  That would also explain why clean URLs aren't working.  The general option you need to set is AllowOverride.  My general setup looks like:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias *.example.com

  DocumentRoot /var/www/example/docroot

  <Directory /var/www/example/docroot>
    Options -MultiViews
    AllowOverride All
  </Directory>
</VirtualHost>

The AllowOverride line will

disable index listings for directories
allow the htaccess to reset the index order to use index.php first
override other options that may be set in your httpd.conf


Main Navigation Menu: Throwing out the old and making a new I've fought blood, tooth, and nail with the built in Main Menu in Drupal 7, and finally I've given up.

What I've done instead is implemented a block which I've placed into the Main Navigation area, and used pure CSS to control the menu. So far, I think it looks and works great.

There's only a few problems:

The company which I am writing this site for has a few users with administrative privileges whom only have a very small and limited knowledge of HTML.

I've installed the CKEditor (WYSIWYG HTML editor) module for the blocks, which has made everything much easier for them, but whenever they edit the raw HTML for the menu (which they don't like doing) this editor removes all of the CSS classes from the menu and destroys it.

Also, because of my block approach to the menu, they don't have the very nice Configure Links page that you would have with the built in menu.

What I would like to do:

I would like to make a new menu module which will work like the built-in Main-Menu, yet not extend it (I've tried both Superfish and NiceMenus, both of which extend the built-in menu, essentially inheriting all of its bugs).

I would like to make a Configure Links Administrative Page that will allow an administrator to configure the links as you would for the built-in main menu.

My Question:

Does anyone know how to view the source for the Main-Menu module, or if a replacement Main-Menu module exists that I can cut and hack apart?

So far, I haven't been able to find any of the source for the Main-Menu module or any replacements. I've only found extension modules like Superfish and NiceMenus.

If nothing exists yet, would anyone be able to point me in the direction of where to start, or (this may be too much to ask) walk me through how to do it and work on this project with me? I am very new to Drupal (I didn't know what it was two months ago) yet I have some extensive knowledge in software engineering.

I understand this has been tried several times, and proposed several times, yet I've not been finding any follow-ups to these questions. I thought this post might have been helpful, but I felt like I was just running in circles after reading it...

Thanks for the help everyone! I'll be looking forward to your responses!

Search for a module called nice menus.

Another option is to create a custom block and inside it query the db yourself for the main menu links.
You can also add the contextual list links button to your block.


How to make [uc_order] token globally available? In admin/config/people/accounts , I want user password in welcome mail.

Currently it is

username: [user:name]
password: Your password

I want this

username: [user:name]
password: [uc_order:new-password] // this token is already available in order setting page admin/store/settings/checkout

Now question is is there anyway to make uc_order token available in user account setting page?

I think you are going about this the wrong way.

You can make the uc_order token globally avaialbe, but it would be a bit messy since some users wont have an order and other people have more than one order.

Instead you should use hook_mail_alter to actually insert the password from the order. You could search for [uc_order:new-password] and if found load the correct order and replace the value with the value from the order.


How to avoid caching on access callbacks? I am using Views Access Callback module to set my custom callback access check. I have written a custom module and implemented the hook provided by this module. I have added a condition to return TRUE and FALSE. But the access callback get cached.

/**
 * Implements hook_views_access_callbacks().
 */
function my_custom_views_access_callbacks() {
  return array('my_custom_module_access' => t('Allow my views access.'));
}
function my_custom_module_access() {
  $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
  if (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] == Crypt::hashBase64($password)) {
    return TRUE;
  }
  return FALSE;
}

I have added callback like above. So when I drush cr from command line it will return FALSE because there is no session in terminal. So when I access the view in browser it still shows access denied because of cache I guess.

My question is how to handle this callback without being cached?

I did this using following way :

function my_custom_preprocess_page(&$variables) {
  $url = Drupal\Core\Url::fromRoute('<current>');
  if ($url->getInternalPath() == 'my-view-page') {
    $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
    if (!isset($_SESSION['my_custom_pass']) || (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] != Crypt::hashBase64($password))) {
      throw new AccessDeniedHttpException();
    }
  }
}

Edit:
We can add our dependency to access object in our access hook.

/**
 * Implements hook_node_access().
 */
function my_custom_node_access(NodeInterface $node, $operation, AccountInterface $account) {
  $access = new AccessResultNeutral();
  $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
  if (!isset($_SESSION['my_custom_pass']) || (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] != Crypt::hashBase64($password))) {
    $access = new AccessResultForbidden();
  }
  $access->addCacheableDependency($_SESSION);
  return $access;
}


Limiting Date (Hours) In Form How can i limit Hours in Date field ? like it begins in 12 untill 21:00 .
Any idea would be appreciate it ?

The 'date restrictions' module might be what you need https://www.drupal.org/project/date_restrictions


Is there a better way to create an alternative URL Alias Pattern? Say for example my alias pattern for one node is set up as:

style-[node:field_style]/[node:title]

There may be a case that node:field_style is blank so I would like to use another field and a slightly different url alias pattern:

type-[node:field_type]/[node:title]

I am thinking about just using hook_pathauto_pattern_alter() but wondering if there is a better way?

I'd create a token for that specific data; I'm not sure it's necessarily better (or worse) than using the alter hook, but it has the advantage of being reusable elsewhere in the site.

A simple (untested) example:

function MYMODULE_token_info_alter(&$data) {
  $data['tokens']['node']['field_type_or_title'] = array(
    'name' => t('Field type or title'),
    'description' => t('Value from field_type if available, node title otherwise.'),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    if (isset($tokens['field_type_or_title'])) {
      if ($items = field_get_items('node', $node, 'field_type')) {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($items[0]['value']) : $items[0]['value'];
      }
      else {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($node->title) : $node->title;
      }

    }
  }
  return $replacements;
}


How can I disable a form's default validation functions? I have created my own validate handler:

/**
 * Validate handler.
 */
function my_module_validate($form, &$form_state) {
  $values = $form_state['values'];
  if ($values['type'] == 'line') {
    form_set_error('type', t('MY VALIDATION.'));
  }
}

which is called from a button element:

'preview' => array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#validate' => array('my_module_validate'),
  '#weight' => 8,
),

which produces this result on submission of an empty form:

The only validation function that I want to run is my own, from my own handler - the last error message - yet all the default validation functions run as well. How do I disable these?

Thanks.

UPDATE:

The solution provided by @superdrupal looks 'correct', but I cannot get it to work. Here's my code:

'map' => array(
  '#type' => 'select',
  '#title' => t('Map'),
  '#required' => TRUE,
  '#options' => array(
    'map1' => t('Map 1'),
    'map2' => t('Map 2'),
  ),
  '#element_validate' => array('my_module_map_validate'),
),

...

// Buttons/link.
'preview' => array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#limit_validation_errors' => array(array('map')),
),

...

/**
 * Map validate handler.
 */
function my_module_map_validate($element, &$form_state, $form) {
  drupal_set_message('Hello world!');
  if (empty($element['#value'])) {
    form_error($element, t('xyz'));
  }
}

which, rather than throwing the error: 'xyz' on submussion of an empty form, produces this result:

As per function form_set_error: "If #limit_validation_errors is set on a clicked button, the button must also define a #submit property (may be set to an empty array)." So your preview button should be:

'preview' => array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#limit_validation_errors' => array(array('map')),
  '#submit' => array(),
),


create tabs with hook_menu() for custom module since two hours im trying to create tabs in my custom modules backend.

I've tried severals suggestions but couldn't get any of them to work.

this is my current hook_menu() :

    function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  return $items;
}

I simply want two tabs called: 'tab1' and 'tab2'.

Can someone give me an working example? This should be really simple, but right now it seems impossible

You need to define a 'root' path which is a normal menu item, and then add another item for each of the tabs. The first of these will inherit the properties of the root item, and the second will define its own callbacks.

Combined with the MENU_LOCAL_TASK and MENU_DEFAULT_LOCAL_TASK type constants, you should get the tabs you expect:

function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  $items['admin/config/system/social_links/tab1'] = array(
    'title' => 'Tab 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/config/system/social_links/tab2'] = array(
    'title' => 'Tab 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'some_callback',
    'access arguments' => array('some permission')
  );

  return $items;
}


hook_user_login being called twice? I'm storing the session details from Drupal to share with another system, so users don't have to log in twice for each system.

It appears that my hook_user_login is being called twice.  Right now I'm just calling:

mymodule_user_login(&$edit, $account) {
  debug(session_id());
}

to see if the session I'm storing is the same as the session being used.

I'm getting the debug statement twice, with two different session_id values.
Am I missing something here?

I know this is not an answer (I don't yet have enough reputation to post a comment); I am also uncertain if you are still looking for answer. It is possible sometimes for distributed modules to call user_login_submit.

For example, the D7 LDAP module's _ldap_authentication_user_login_authenticate_validate calls user_login_submit, which causes the user login form to fork two calls to user_login_finalize, both of which triggers hook_user_login. If you are still experiencing this problem, one possible way to debug your application is to use PHP XDebug, and dsm function traces.

After you have installed XDebug, you can use xdebug_call_function() on user_login_submit, user_login_finalize, user_module_invoke to see where the two calls of hook_user_login are coming from. I hope this helps.


What are the photo gallery/album module choices for Drupal 7? I am looking to make a Flickr like site that user can create albums, upload photos.
With Drupal 6, this can be easily done by CCK, Node Reference, Views.

For Drupal 7, it seems difficult since Node Reference is not available yet. (There is a module called Reference, but in dev)

So are there any modules that can achieve the ugc photo albums functionality?

Thanks.

An album essentially is a grouping of like nodes.

In drupal this grouping can be done a number of ways. I would suggest using a fixed taxonomy (not free tagging) for the album. This way views can list list all photos (nodes) from a particular tag and you can create thumbnails for instance for display.

You could also group by author for another group of nodes (e.g. 'my photos')


How can I avoid getting "This route can only be accessed by anonymous users"? I'm trying to use REST login from a React native app. When the user tries to log in, the app calls:

var data_node = {name:this.state.username,pass:this.state.password};
axios.post('http://IP/user/login?_format=json',data_node)
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error)
  });

If the call succeds, in test, the next time I try to authenticate the user, I get this error because the user has been authenticated in a previous call for which I haven't saved data, so I cannot call user/logout.

  This route can only be accessed by anonymous users.

How can I avoid it, forcing a new login?

This issue happens because you are trying to access the user/login route when you have cookie maintained at your app level. You need to make sure you clear the cookies before visiting that route.

You can use https://github.com/joeferraro/react-native-cookies to make sure all the cookies are cleared before you try to log in.


SMS password recovery I'm currently using D7. When my users attempt to request a password reset, 95% of the time, these reset emails land in their spam, or are blocked by whomever their email provider is. That being said, I'm looking to implement a way for my user to regain access to their account by receiving this password reset link via SMS instead.
Currently, my site collects the user's phone number on registration, and I have the Twilio module installed. All of that said, there doesn't seem to be a Drupal Rule that I can execute for "When anonymous user requests password reset".
Ideally, I'd like to have a Drupal rule search my user list for the user that contains the input email, and then simply send the generated password reset link to the phone number on file (also attached to the found User's account).
Is this possible?

You might want to investigate using the SMS Framework module along with Twilio SMS Integration instead - they have more users and there is more active and more recent development with these modules. They also have D8 ports, so you are covered for when you decide to upgrade to D8. But the answer below will work whether you use the above two modules or whether you just use the Twilio module.
When you say "Drupal Rule" I'm going to assume you mean a Rule made with the Rules module.
A Rules module Rule requires an Event, one or more optional Conditions, and one or more Actions. In this case, the Action would be to send an SMS message. The SMS Framework module does provide an Action for Rules, which is named "Send sms". You can use this action to send the SMS message. All you need now is an Event.
You want an Event that is fired when the anonymous user submits the password reset form. Drupal core does not have any hooks or events for password reset. This Event does not come with Rules. I know of no contributed modules that provide this Event. So you will have to write a few dozen lines of code. You can also do this without Rules, but you will also have to write code and it will be more code than with Rules.
Writing an Event is not hard, but it does require coding. A tutorial on how to do that is outside the scope of this issue. Below I will outline the basic steps and point you to some documentation. What you need to do is:

Implement hook_rules_event_info() to declare your event to Rules and define the variables that will be stored in the event. These variables will probably the telephone number and the user email address plus whatever other information you may need to complete the task.
Implement hook_form_alter() to alter the user_pass form so that it executes a custom submit handler.

Your custom submit handler should use the submitted email address to look up the user's telephone number.
Your custom submit handler will then call rules_invoke_event() to invoke your own custom event. You will pass this event the telephone number and the email address.

There are many examples of this that can be found. Some randomly selected pages which discuss this are:

https://www.drupal.org/docs/7/modules/rules/3-developer-documentation/events
https://drupalize.me/videos/declaring-events-rules?p=1152
https://drupalize.me/videos/invoking-rules-events?p=1152
https://www.powercms.in/article/how-create-custom-rules-event-programmatically-drupal-7
https://azimut7.com/blog/custom-rules-event-drupal7


How do I display a taxonomy term if another term is active for a node? I have a content type that has taxonomy terms for Category, like Blog, Publication, and Project. Depending on which term is selected, the content is displayed under blogs, publications or projects. If the category selected is Project, then the user has to select the focus area from another vocabulary (not a child vocabulary) - Focus Area 1, Focus Area 2... through to Focus Area 10.

Currently, my pathauto pattern displays the Category/Node_Title - [node:field_post_category:entity]/[node:title]

My objective is that I also want to display the Focus Area term in the node url, but ONLY if the category chosen is 'Project'. In that case, I want the url to be project/focus_area_n/node_title. So the focus area is displayed in the node url only if the category is project. Is there a Pathauto pattern, or any other method that I can use to accomplish this?

I need to do this so that I can control the display of a few blocks in the sidebar that will show up depending on what the URL is.

Thanks in advance...

It was actually quite easy! No custom-coding required. I just added the token for the other vocabulary to the URL alias pattern, and it now appears, when it's present. When not present, the regular URL is formed.

So now the new pattern is [node:field_post_category:entity]/[field_focus_area:entity]/[node:title]

Drupal is great!


Drupal 8 - Add custom HTML with script to embed on a page as block I need to add a custom form that has scripts and styles into a page as a block. Its dynamic, so I couldn't attach the scripts (#attached) as libraries. I just need to place the contents as is.

$build['test'] = [
  '#markup' => $test_code,
  '#allowed_tags' => [
    'script',
    'style',
    'form',
    'input',
  ],
];

I tried it as shown above, but this wasn't working. So, I removed, scripts and style as shown below and that works:

$build['test'] = [
  '#markup' => $test_code,
  '#allowed_tags' => [
    'form',
    'input',
  ],
];

Any possible solution to render the contents without filtering scripts and style.

You can use :

$build['test'] = [
  '#children' => $test_code,
];


Referencing a referenced entity's fields on a form I'm setting up a contact form and would like to implement the following functionality:

On my form I currently have an entity reference field that references the content type 'Home Team' using a select list.
I would like to add another field to my form that populates with a select list of field data based on the content that is selected in the above entity reference field.

To help explain, each 'Home Team' has a field called 'home games' that is a list of text in the format 'Team Name - Date'.

I'd like it to be so that when a user chooses a team from the first select list, the second select list is then populated with that team's home games.

I think that the answer might be by using the Field Reference module, however I'm not sure how to implement what I am needing to do.

You can use DFV - Dependent Field Values. It's a great module and does exactly what you're asking
The module's page says:

This modules enables site admins and developers to make the allowed values of a field depend on another proviously selected field's value.
You can use views with arguments to let views return the allowed values for a dependent field.

I'm using it myself, it's quite simple to use: you create a view of type Dependent Field Value with a contextual filter, which in your case is the NID of the node in the first field, the team (remember to add the relevant relationship in the view's Relationships section).
Usually you'll want to add two fields to this view, e.g. the home game's NID and the home game's title. After adding the two fields, click on the settings of the  dfv list format. Choose the home game's NID as the Key Field an the home game's title as the Title Field. The view is done!
You didn't explain how is your contact form made, but I suppose that you use webform. So: you just have to go to the second field's settings, check the "Enable dfv settings", choose the parent field (team) and the view you just created.


hook_node_presave () showing error When I am inserting a new article there is an error -

  Notice: Undefined property: stdClass::$field_tags in
  hook_node_presave() (line 344 of
  D:\wamp\www...)

The code for line 344 is-

function mltag_node_presave($node) {
...
$count = count($node->field_tags[$node->language]); //line 344
..
}

This error only shows up when adding a new article, and not when editing an article.
The line 344 is just to count the number of term-ids in the textfield for tags.
Any suggestions ??

EDIT - field_tags is the name of the default Tag textfield added in the add-article page

I think you need to do an isset($node->field_tags[$node->language]), if it is empty $node->field_tags[$node->language] will not exist. Could you check if it is only articles with the empty field_tags that are affected?


Where to save larger module content/settings? I'm creating blocks in modules and wish to have the block body (content) editable by admins. I'm using hook_block_configure and hook_block_save to accomplish this. Where is a good place to store the block body when edited by the admin (variable is apparently not suitable for larger values like this)?

I was thinking of just creating a custom table in hook_schema but that seems a lot for just one or two rows of data. Plus I would be doing this for several modules that need to provide blocks but also have their content editable by the admin. That's why it would be nice if there was a general storage table like variable but for larger values.

What would be a better way to accomplish this?

Have you looked at Nodeblock?

There is not a general storage table like variable for larger values.

I would consider creating a content type; using the nodes from that content type to programmatically create the blocks, using taxonomy to get finer control if necessary; then admins can just edit the block content like they would a node.


How to know where to place a block in the body of my page I am new to drupal7 and I am trying to create blocks and new content on the body in drupal7 using css and php. Can you help with directions please.
 Thank you

If you're new to Drupal 7, I also encourage you to look into placing your blocks using the Context module, rather then hard-coding their location through theming or something like that.  It's also more flexible than what you can just do through the block admin interface.

Here's a simple example of using the Context module to place a block in a certain location on a single page or a specific content type:

Once you've downloaded and enabled the module, go to admin/structure/context
Click the "Add" link to add a new context
Fill in the first few fields as shown below (name, tag, conditions to be met to fire this context)

Before saving, in the "Reactions" section, select which blocks you want displayed and WHERE when the conditions above are met


Drush ard is working for D6, not for D7 > bootstrap error Noticed something strange today:

drush ard @sites is working in the folder /drupal6/sites/, but not in /drupal7/sites/. When i go to a specific folder, the command runs as expected (drush ard foobar.com in /drupal7/sites/foobar/)
So, Drush is working ;-), it's working in Drupal 6 but not in 7. Can someone advice me where to look? Did some googling, but i can't find a good answer.

Drush status gives

Drupal version                  :  7.26
Site URI                        :  http://foobar.com
Database driver                 :  mysql
Database username               :  [username]
Database name                   :  [databasename]
Database                        :  Connected
Drupal bootstrap                :  Successful
Drupal user                     :  Anoniem
Default theme                   :  Garland
Administration theme            :  Garland
PHP executable                  :  /usr/bin/php
PHP configuration               :  /etc/php5/cli/php.ini
PHP OS                          :  Linux
Drush version                   :  6.1.0
Drush configuration             :
Drush alias files               :
Drupal root                     :  [path to root]
Site path                       :  [path to site]
File directory path             :  [path to files]
Private file directory path     :  [path to files]
Temporary file directory path   :  tmp

The error with drush -d ard @sites is:

Command archive-dump needs a higher bootstrap level to run
- you will need to invoke drush from a more functional Drupal
environment to run this command*

This seems like a permissions' issue on your server. Make sure that the user that you are running the command as, has the appropriate permissions in the Drupal 7 directory.

An easy way to fix it is change the owner of the Drupal7 dir by using something like:

chown -R username:usergroup /path/to/drupal7/dir

or if you are working in a debian based environment you can run the command with super-user-do like:

sudo drush ard


How to theme a menu block? I have created a custom menu (lets call it "mynav") and in my theme I've created a template specifically for it (block--menu--menu-mynav.tpl.php) which contains:

<div id="mynav" class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print $content ?>

This works fine.

However I'd prefer to apply the id to the unordered list that is generated and contained in $content. I guess I need to create a function MYTHEME_links__system_mynav_menu like this:

function MYTHEME_links__system_mynav_menu($variables) {
  return "TEST"; // Generate HTML here (
...)
}

but it doesn't seem to have an affect.

What am I doing wrong?

In order to theme the unordered list, you need to call theme_menu_tree(). You can edit your template.php in order to call this.

function THEMENAME_menu_tree__MENUNAME($variables){
  return '
' . $variables['tree'] . '
';
}

Then, if you want to theme your links, call theme_menu_link().

function THEMENAME_menu_link__MENUNAME($variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Now, the problem with Drupal 7 is that there is a major bug when it comes to displaying the active trail of custom menus.

See issue
Issue #520106 - No way to dynamically set active trail
Issue #942782 - Custom menus never receive an active trail

You are basically out of luck if you want some true custom menus. These issues are very long standing in the drupal community so I am not sure if they will be fixed anytime soon. I don't know if there is some PHP that can help with it. You can turn to some alternative modules in order to help ease functionaltiy, like Menu Attributes and Menu Block. They both can help get around the cruddy menu system in Drupal 7.


How to prevent Drush pm-update from backing up symbolic links? In my Drupal installation folder, I have symlinks to external folders with 80+ GB of data.  When I backup/update Drupal using Drush, Drush also archives the 80+ GB of data. How do I prevent Drush from backing up the contents of symlinks?

Also, when Drush restores the backup, the symlinks are not preserved as well. Drush replaces symlinks with the actual content.  So after the backup/update of Drupal core is done, my Drupal installation folder ends up being too huge.

Can you please suggestion solution to both of the above problems?  I am okay even if I have to write code to patch Drush or anything else. Just need help pointers in correct directions.

This should probably be in the Drush issue queue. Maintainers can help you work through issues if you want to make a patch.  Be sure you are using the latest version of Drush.  By intention, it looks like Drush should only behave as you describe if the --dereference option is specified; without that, it should not follow and archive symlinks.  Run Drush with --simulate to see what actual tar commands, etc. Drush is running.  Post results and followup questions to the issue queue.


How to find the count of items in a block? I have a block named views-view-fields--our-services--block.tpl.php i need to find the no of nodes under this block.How do find the total no of nodes displaying inside a block?

In your view, for HEADER (located in the middle of the edit view screen) Add a Global Result Summary. Then just use the @total token like in the picture below. This will count the number of rows in your view.


View display nodes with taxonomy term found in URL Using Drupal 8

I have a working setup my problem is when I try to access a taxonomy term that is made up of two words.

Set up.

View : shows nodes of content type A
Has relationship (required) with a field in the content type that stores the taxonomy term (one or more terms need to be associated to each content type)
Has contextual filter (that uses previous relationship) to get the taxonomy term from the URL. The filter gets the default value from Raw value from URL with Path component: 2 , and it has Use path alias instead of internal because the URL has the taxonomy term name. It also has Specify validation criteria by Taxonomy term name by Transform dashes in URL to spaces in term name filter values so that fan-art can be correctly matched to taxonomy term fan art.

I have no problem with taxonomy terms made up of one word, it's the ones made up of two words that are giving me a headache, any ideas?

I gave up trying to understand why it doesn't work and resorted to using Has Taxonomy term ID instead.

The URL contains the taxonomy term ID so only a Contextual Filter is needed. In raw value the URL is taxonomy/term/[id] , so all that needs to be done is tell the Contextual Filter to Provide default value from Type Raw value from URL and Path Component 3. I also added a Specify validation criteria WhenThe Filter Value is available or a default is provided, of Validator Taxonomy term ID and chose the appropriate Vocabulary.


Correct image path to use in template files of custom themes I'm creating a custom theme. Under my theme's folder, there is an images folder where I've put some pictures. I want to use these images in my various template (.tpl.php) files using HTML <img> tag... but the problem is how do i get correct path for these images (the src attribute)?

I've searched for a while but didn't get any solutions. Please help.

EDIT: I'm using nice urls (http://mydrupalsite.com/a/b/c/d) - type URLs. So, if the image src begins with / (or any relative path) it would break.

I think these functions could be useful in your templates:

print base_path() . path_to_theme();

path_to_theme() Return the path to the current themed element.
base_path() The base path of the Drupal installation.

for example, I have an image called bg-bar.png inside images directory in my template directory called garland. then I can use base_path() and path_to_theme() to get the path to the image, for example inside node.tpl.php:

print '';

Update: if you want to use the current domain, you can use global $base_root:

  $address = ''.base_path() . path_to_theme() .'/images/bg-bar.png';
  global $base_root;
  echo '';

I hope information be useful.


How can users write a bio on their profile page? I'd like my users to be able to write a bio on their profile page. Therefore, I added a long text field called 'Bio' to the user accounts. I created a view that shows the user's bio and wanted to add a link to only let the user edit his/her bio. Unfortunately, I only found a link that redirects the user to a page where he/she can edit his/her whole profile - which isn't exactly what I want.

Did I miss something?

I tried to solve this in another way. I created a content type called 'Bio' and a rule that creates a 'Bio' node with title My bio automatically when a user is created. Users don't have permission to add another bio, but they can edit their own 'standard' one. Now, I don't want the title field to be displayed on the edit form, because I'd like the titles to remain My bio.

How can I do this?

Re: the second/existing option, if you have a custom module already, could do a form_alter() on the node form to remove the title field.  Or, you could look into the auto_nodetitle module that does this for you:

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

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

  Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.

If instead you wanted to stay/go back to the first option, you could create a menu link/path like user/%/edit/bio that presents the user_profile_form that has been form_alter()ed to show only the bio field based upon the fact that it was called from this new path.


Is there a notification api module? I like to have a general api for sending notification. I am not sure if there is out there somewhere for Drupal.

For instance, is should be possible to provide a node id and some criterias for which users to send notifications to. The options could be something like "not to the node author", "all who has commented on the node except specific ones (perhaps a comments that has just been written), true/false on sending notification to user who already got a notification about new comments, etc.

There are probably other notification scenarios that could be supported. It would be nice with a general notification framework for Drupal. It seems to be lacking right now (I have looked at subscription and notification). However, I am new to Drupal and might have missed something.

There is a Notifications module for Drupal that creates a framework for sending out notifications. There are already many modules using the framework. There's a development version of an extension module called Notifications Rules for integrating this with the Rules module if needed.


Adding rel=canonical meta tag in comment paginated node pages I posted this question: Google showing pages with ?page=2 urls and also read this post from Google: http://googlewebmastercentral.blogspot.in/2013/04/5-common-mistakes-with-relcanonical.html

I understand that node comments whether paginated or not are of low importance with respect to the node content itself. So all the paginated node pages reached by clicking links in the bottom just above "Post New Comment"( as in attachment) should have rel=canonical pointing to the main node page.

So these pages:

example.com/node?page=1
example.com/node?page=2 and so on

should have "rel=canonical" in the head section of html page pointing to example.com/node.

Though as mentioned in the Google's blog, even "rel=prev" or "rel=next" may also be desirable in case of such urls.

So I need help how to add rel=canonical in those paginated node page. How can I do it?

It can be done using Nodewords module as described here:

  Nodewords project allows you to add meta tags to Drupal pages, both
  manually and automatically based on various settings. Paying attention
  to meta tags, such as keywords, description and canonical URL, may
  help obtain better search engine positioning.


How do I enable the ETag header? I'd like my JSON:API responses to return the e-tag header so that consuming remote sites can determine (e.g. with a HEAD request) if they need to ditch their cached responses and re-fetch.  There is no last-modified or e-tag headers being sent at all - for any Drupal page for that matter.  How can I enable this?  Thanks!

I do see X-Drupal-Dynamic-Cache and X-Drupal-Cache headers, but this isn't enough to go on.

Running Drupal 8.6.10 and JSON:API 8.x-2.4.

I changed the "Browser and proxy cache maximum age" setting in Configuration > Development > Performance and it appeared to do the trick.  It was previously set to "no caching".


Adding JavaScript and CSS to a particular menu page I have set up a Drupal 7 web site with a few custom blocks and menus written by me.

I have a non-Drupal PHP script displaying users (some of them are external, i.e. not stored in drupal tables) as a table with the DataTables jQuery plugin.

I would like to rewrite that script as a Drupal menu, so that it can be called as http://preferans.de/top.

The content of my.module is the following.

function my_menu() {
  $items['top'] = array (
    'title' => 'Top',
    'description' => 'Top',
    'page callback' => 'my_top_callback',
    'access callback' => TRUE,
    'file' => 'my.top.inc',
    'file path' => drupal_get_path('module', 'my'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

The content of my.top.inc is the following.

function my_top_callback() {
  return array (
    'top_table' => array (
      '#type' => 'markup',
      '#markup' => generate_html_table_with_php(),
    ),
  );
}

My problem is that I don't understand how to add the CSS and JavaScript code, so that it is available for the /top page, but not for any other Drupal paths.

I should probably call:

   drupal_add_css('/demo_table_jui.css', 'file');
   drupal_add_css('/smoothness/jquery-ui-1.8.4.custom.css', 'file');
   drupal_add_js('/jquery.dataTables.min.js', 'file');
   drupal_add_js('
       $(document).ready(function() {
         $("#rating").dataTable( {
            "bJQueryUI": true,
            "sPaginationType": "full_numbers"
          });
        ', 'inline');

(Please see the head-section of my original non-Drupal script).

How do I limit these calls to the /top page and where should I perform these calls?
Should I put them in a hook, or by adding some properties to my menu?

Generally, CSS and JavaScript files are added with hook_init(), which allows those files to be aggregated together, when aggregation is enabled.

Using hook_init() (I suggest you not to do this, anyway) you could conditionally add the files basing on the page being visited.

function my_init() {
  if (arg(0) == 'top') {
    // Add the files.
  }
}

The reason I don't suggest you to do this is that the hook would be called for every pages, including the ones you are not adding the files. hook_init() is generally used to add files to each page.

You can add those files in the menu callback (a.k.a., the page callback); if the menu callback is a form builder function, then you can use the #attached property, as the following code.

$form['#attached']['css'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
);

$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);

About the inline code you are adding, I would recommend you to put also that in a file, and to use Drupal behaviors instead of $(document).ready(). If you need to pass arguments to the JavaScript code, you can use JavaScript settings (see drupal_add_js() to understand in details how to pass settings to JavaScript code).
Managing JavaScript in Drupal 7 explains in details how to manage JavaScript code in Drupal 7, and the section titles Behaviors reports how Drupal behaviors are changed in the latest Drupal version.


Storing uploaded files according to node ID When a file/image is uploaded via Drupal, they go into a common directory specified by the administrator.

However, is there a way to specify where the files will be uploaded, according to their node ID? For example, say, a person creates a page and Drupal assigns it an ID of 1234; thus, the uploaded files will go into {specified_location}/1234_files/.

You can use the File (Field) Paths module in combination with the Token module for this.

Enable module
Go to admin/structure/types/manage/your_content_type/fields/your_file_field
Make sure Enable File (Field) Paths? is enabled.
Under File (Field) Path settings you can now use e.g. myfiles/[node:nid]


Moving from Custom MySQL-Based Blog to Drupal I currently have a database with the following schema:

Table: Articles Columns: ID, Title, Author, Content

Table: Authors Columns: ID, AuthorName, EmailAddress

Table: Categories Columns: ID, CategoryName

I'm interested in moving this over to Drupal. I do NOT actually need to preserve the authors or categories tables because we are revamping those sections in the migration. However I DO need to save certain rows (or all, if easier) of the articles table. This includes keeping the author ID linked to it. I'm willing to do manual queries in order to select which rows I want to move over to the new table, but I'm not sure exactly where I should do this. So my question is: How can I move these articles over to Drupal in the easiest, most seamless fashion?

You can create nodes from external databases using the Feeds SQL module (requires Feeds). You should create a content type for the fields you want to import, and use the Feeds UI to select the external database table(s), add a query, and map the output to the fields in your content type.

Here are a couple of settings that you need:

Preparation: add your new source database to settings.php:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_database',
      'username' => 'drupal',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'database_to_migrate' =>
  array (
    'default' =>
    array (
      'database' => 'database_to_migrate',
      'username' => 'migrateusername',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
)

Now: go to the Feeds UI, and start configuring:

1. Basic - attach to - your new content type
   Import on submission - checked

2. Fetcher - click "Change" -> select "SQL fetcher", save

3. SQL Fetcher - click "Change" - select your source database

4. Parser - click "Change" -> select "SQL Parser", save

5. SQL parser - click "Change" -> Enter your query, select your database, save
   Verify that your query performed as expected, results are displayed.

6. Processor - select "Node Processor" for nodes

7. Node Processor - Settings: Here, you can choose the content type (again),
   the author associated with the new node, format, expiration, and other parameters.

8. Node Processor - mapping: Here, you have to map the fields from the sql query
   to the fields in your content type. After you save, you can map the next field

Since you only have a couple of users/authors, you could create accounts for them manually. In your SQL query, you can select the users as well as the content/title/etc., and the new articles will then be associated with the appropriate authors.

This has worked well for me with a limited number of nodes (<1000). For large-number of nodes, I ran into time-out issues, and had to add a limit to the SQL query. Eventually, I just created a drush script to add the nodes from the command line (I had to add >50,000 nodes).

Edited to add: I used this with Drupal 7. Please read the documentation for the modules for updated information: https://drupal.org/project/feeds, https://drupal.org/project/feeds_sql


Effective use of tokens view mode? Most probably because of the naming coincidence with the Token module, I cannot find any tutorial or reference as per how to effectively use the Tokens view mode that I can see in perhaps all entities in Drupal.

I smell this serves some particular purpose but cannot get a clue.

This allows you to change the output of field tokens without disturbing the default display of the field.

For example, you might want the Body field displayed as formatted text by default, but plain text whenever it is output as a token.

Take a look at http://drupal.org/node/1299662 for an example of how to use.


Create View with 2 rows of diferent Content Can someone help me on whow can i create a View Like This?
I Found this view a a theme template at http://demo.megadrupal.com/?theme=md-thenews .

This view is composed by 2 rows. The first one has an image, a title and a teaser and the other rows has a list of articles.
I've also tried the views_field_view plugin, but the output is not the same.
Thanks for you help.

Code behind the view in the image:

        .... //Views Fields

    .... //Views Fields

</div

Views Node Split module does what you are trying to achieve.

  This module allows site administrators or builders to have a different view mode for the first nodes of a view result


What is the difference between t() and l()? If I understand correctly, t() is the Drupal translations function, is l() simply calling the localization settings for translation specifics, or is there something more to it then that?

The l() function is primarily for links. It takes the parameters of $text, $path, array $options = array() to properly translate links. It also returns a HTML string containing a link to the given path.

It's use looks something like this:

<?php
  l(t('Link text'), 'about-us', array('attributes' => array('class' => array('about-link'))));
?>

Another note is it looks as though it's going away in D8, as it currently has no entry in the APIs for 8. Instead, Drupal 8 will use the class:link like so:

$link = Link::fromTextAndUrl($text, $url);

t() is much more general and is used to translate strings. It also takes a different set of arguments ($string, array $args = array(), array $options = array()).


Separate home page per domain in multilingual setup (i18n) I have a multisite Drupal with 2 domains, that should have separate home pages, but I can't get it working. I've created a node for each.

Now, I've tried to configure it in the Configuration > Site information > Default Home Page panel. There is note on top of the page: "This form is domain-sensitive, be sure you select the proper domain before saving." ; Therefore I guess that "home page" parameter is per domain?

But it doesn't work : each time I change this field (value : node/92), all domains are affected.

Is it supposed to work? Is there another way to do it?

I would

Setup a "Page manager"-page, and call it "Front".
Set the homepage to "/front".
Create one variant for every domain in the front-page. Fill with relevant content.
Create a ctools "Domain access plugin". That wouldn't be many rows of code, see my brief tutorial
Use the access plugin to setup a selection rule for every variant/domain.


Angular application and Drupal services I am creating an Angular application using headless Drupal. I am using Drupal services module for web services.

I am trying to implement login mechanism in this app. Login is working fine but to handle authenticated requests, it is necessary to use "Cookie" header in each service call.

My app doesn't allow to use cookie header. In my browser console it says as

"Cookie unsafe header is not allowed". Is there any other way to fix this?

I have similar setup where i use drupal as back-end and connect to services with Angular app (Ionic App) and i am describing the sequence below; however, you need to consider the below reference if you are doing cross domain
https://stackoverflow.com/questions/35007572/angular2-xhrfields-withcredentials-true/
And you have to setup CORS (This is my config for reference)
API/*||POST,GET|Content-Type,x-csrf-token,Authorization|true

Login to your drupal service
End Point: /user/login
Payload:{"username":"username","password":"userpass"}
Content-Type: application/json
Method:Post
Result: User information & Token

Request

Get the Token and use it in subsequent requests by setting the header to X-CSRF-Token
End Point: /node/100
Payload:Empty
Content-Type: application/json
Method:Get
Result: Node information

Request With X-CSRF-Token header

Logout from drupal service (Token must be set as well)
End Point: /user/logout
Payload:Empty
Content-Type: application/json
Method:Post
Result: [true]


Difference and relationship between View, Page, Panel and Mini Panel? I'm quite familiar with Views but for others, especially page, panel and mini panel introduced by the module, Panels. Can anyone provide some simple but elegant description between them?

Views are used to create lists of things.

One difficulty with Views, is that when used on their own, views tend to become fairly static. Let's say that you have a view that lists "Friends of user X". In your view, you must know define where to find user X. This will mostly be either a contextual filter, possibly using a relationship, but whatever configuration you have, it becomes a static part of the view. This leads us to Pages.

Pages provide the rest of your site with Context. Continuing on the example above, a Page can figure out how to find user X at run-time, and then feed that as an argument to other components, such as the friend view. This means you can re-use the same view, and all the rules that go with it, on both the same page more than once, but also across pages, and having it base it's results on different users every time.

If you want to show the browsing users friends, and my best friends friends, on the same page, you tell the current Page about those two contexts, use the same View twice, and give each instance of that View, a different context as argument.

A page on it's own however, doesn't have a visible interface, neither back- nor front-end, which is were Panels comes in.

Panels Provides a GUI on top of Panels, allowing you to configure Page manager, as well as adding further functionality to Pages, such as render caching.

Mini Panels Essentially embeds an "small" Panel rendering into another Panel. You can think of it as a very intelligent version of a block, capable of defining layouts, requiring parameters, and more.


Conceptual question about taxonomy structure Imagine i want a directory of different organisations in different locations. Let's say i have

hospitals
retirement homes
yogashops
health-insurance agencies
(...)

in

Boston
Detroit
Denver

I would create an overview listing of the cities to link them to the organistaions-categories of each city. These would be links to a view of all organisations of the chosen type in the chosen city.

What i already have is a vocabulary "organisations" and a vocabulary "cities". I have created a view with a contextual filter "organisations" which lists all items of an organisation-term:

organisations/yogashops

But how can i prepend the selection of a specific city?

Do i have to create a vocabulary of organisations for every city? Even if they are the same?

How can i reuse my "organisations"-vocabulary?

EDIT: Would it be an alternative to create a node for each city and then use them as entity reference for the categories?

If I understand the question correctly you want to prepend the city name as an argument on the view, so you would have:

  organisations/denver/yogashops

well you could equally have the city appended:

  organisations/yogashops/denver

The question has no mention of Views, but I would recommend that you create a view with the contextual filters of organisation and city:

I recently set up something similar for global dealerships /find-a-dealer/europe/fr


Suggestions for adding Advanced Search features to a block (using the dashboard)? Is it possible to do the following:

Add a Search box to a block through the dashboard?
Have an Advanced Search on multiple fields in that block?
Have the results of the search open in a new page?

I understand that there are options to do this with code, but my client would like to manipulate as many areas as possible through the dashboard.

Any suggestions?

Search form is itself a block; you should add this box to a region. Let the client configure blocks; they can move the block from admin/structure/block.


Using fivestar_get_votes() to show the votes on a node I need to display a multi-axis review system using Fivestar in node.tpl.php in Drupal 7.

I created the content type according to this tutorial, which is for Drupal 6, and I need to know how I can call votingapi_select_results() and fivestar_theme() in Drupal 7.

Initially, I tried the following code.

$design_rating = votingapi_select_results(array('entity_id' => $node->nid, 'tag' =>'design', 'function' => 'average'));
print_r($design_rating );

It caused a fatal error.

Later, I used fivestar_get_votes() as in the following code.

$design = fivestar_get_votes('node', $node->nid, 'design', NULL);
print_r($design);

I got an array.

  Array (
    [average] => Array (
      [vote_cache_id] => 128
      [entity_type] => node
      [entity_id] => 18
      [value] => 80
      [value_type] => percent
      [tag] => design
      [function] => average
      [timestamp] => 1332162918
    )
    [count] => Array(
      [vote_cache_id] => 127
      [entity_type] => node
      [entity_id] => 18
      [value] => 1
      [value_type] => percent
      [tag] => design
      [function] => count
      [timestamp] => 1332162918
    )
    [user] => Array(
      [vote_id] => 8
      [entity_type] => node
      [entity_id] => 18
      [value] => 80
      [value_type] => percent
      [tag] => design
      [uid] => 1
      [timestamp] => 1332162918
      [vote_source] => 122.164.241.37
      [function] => user
    )
  )

I don't know how to use it to show the result shown from the Fivestar module. How can I do it?

i tried with below code in node.tpl.php and it displayed result as '3' not a fivestar widget.

$variables=array('rating'=>60,'stars'=>5,'tag'=>'design');
echo theme('fivestar_static',$variables);

Am i missing anything in it? or is there any other procedure to call theme function in node.tpl.php in drupal 7?

Fivestar module for Drupal 7 implements fivestar as a field. Assuming the field name is field_fivestar_awesomeness you can print it anywhere with:

$fivestar = field_view_field('node', $node, 'field_fivestar_awesomeness');
print render($fivestar);

There are some display and language options, see more in the api docs.


Where in The Database does File Usage Data Come From How does data in file/[id]/usage get compiled?

From what tables does it determine a use?

Is there a way to track down how/where it gets this data and troubleshoot?
Does it take include revision data?

I couldn't find any /usage path in core. You must be using a custom or contrib file manager module.

  From what tables does it determine a use?

According to file_usage_list the file usage info is stored in the file_usage table, so I bet the custom or contrib module must be reading from there.


Where to place PHP code for a node if not in the node body block itself? Up until now, I have found it most convenient and easy to place PHP code into my node by placing it in the node body and enabling the PHP filter. However, I have been informed that this is incorrect and unsafe.

Furthermore, I also know that it would be incorrect to place PHP code in node.tpl.php.

Could someone please tell me where the correct place to place PHP code for a node would be?

One of two places, hook_node_view() or hook_preprocess_node(). They can both be used in a module file, but only the latter will work in your theme's template.php file.

hook_node_view() example:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_node_type') {
    $args = array(':nid' => $node->nid);
    $my_value = db_query('SELECT my_field FROM {my_table} WHERE nid = :nid', $args)->fetchField();

    $node->content['my_value'] = array(
      '#markup' => 'My value is: ' . $my_value,
      '#weight' => 10 // Controls the display order of this piece of content
    );
  }
}

hook_preprocess_node() example:

function MYMODULE_preprocess_node(&$vars) {
  $vars['content']['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}


Field Collections not displaying in Content Template I'm using Content Templates (Contemplate) module to style a node display for a content type that uses Field Collections. When I view the node's display page before changing anything in the Content Template, the Field Collections display fine. As soon as I tick the "Affect body output" checkbox to adjust the template, the Field Collection content no longer shows up on the display. The header is there, but the content is gone.

How can I get the Field Collection content to display? Is there an incompatibility issue with Content Templates and Field Collections?

This is a Drupal 7 site... and, before you ask, I need to use Content Templates for theming due to a somewhat locked down development environment.

Not necessarily an answer, but a viable workaround:

The Field Collection content is available to views, so I made a view block that prints out the Field Collection content where the contextual relationship is the node's NID. That block gets displayed on this content type only. With some Javascript trickery, I'll be able to position it where it needs to go.

I'm open to a real answer, but for now, this is all I've got.


How to skip the ReferenceAccess constraint on a file upload by an anonymous user? I have a contact form for job applications with a file field on it so users can upload their CV. Because of privacy / security, the uploaded CV's must be stored in the private filesystem.

Unfortunately, a problem occurs when an anonymous user tries to add a CV and submit the form. Since the anonymous user does not have access to the uploaded file, the file field's ReferenceAccess constraint (\Drupal\Core\Entity\Plugin\Validation\Constraint\ReferenceAccessConstraint) kicks in and throws a validation error: You do not have access to the referenced entity (file: 1). As a consequence, the user is not allowed to submit the form.

Is there a way to tell Drupal to skip the ReferenceAccess constraint when anonymous users reference a file that they just uploaded themselves?

Update: I came to realize that this does not happen when using the core  file field, only with the File Entity module.

That constraint is validated by \Drupal\Core\Entity\Plugin\Validation\Constraint\ReferenceAccessConstraintValidator. ReferenceAccessConstraintValidator::validate uses the following code.

  /* @var \Drupal\Core\Entity\FieldableEntityInterface $referenced_entity */
  $referenced_entity = $value->entity;
  if ($referenced_entity) {
    $entity = $value->getEntity();
    $check_permission = TRUE;
    if (!$entity->isNew()) {
      $existing_entity = \Drupal::entityManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
      $referenced_entities = $existing_entity->{$value->getFieldDefinition()->getName()}->referencedEntities();

      // Check permission if we are not already referencing the entity.
      foreach ($referenced_entities as $ref) {
        if (isset($referenced_entities[$ref->id()])) {
          $check_permission = FALSE;
          break;
        }
      }
    }

    // We check that the current user had access to view any newly added
    // referenced entity.
    if ($check_permission && !$referenced_entity->access('view')) {
      $type = $value->getFieldDefinition()->getSetting('target_type');
      $this->context->addViolation($constraint->message, [
        '%type' => $type,
        '%id' => $id,
      ]);
    }
  }

(In particular, see the line containing $referenced_entity->access('view').)

We can hook into the file's access control to alter the outcome, with hook_entity_access() or hook_ENTITY_TYPE_access().

Another solution could be to create a new field type which inherits everything from Drupal\file\Plugin\Field\FieldType\FileItem, except for the ReferenceAccess constraint in its plugin definition. You can do this in two ways:

Create a new plugin class that extends the original class, and copy and modify its docblock, including the @FieldType annotation.
Implement hook_field_info_alter(), copy the file plugin definition to your own, and make the necessary adjustments there.


How do I change icons in the "Mobile sliding menu" module? I want to change the menu-item icons for the Mobile sliding menu module. I have set up the icomoon library and changed the CSS file according to the documentation. I have added custom icon classes to the menu items (which works as long as they are not as block in a mmenu). The mmenu always overwrites this with its own markup.

I have found some occurrences of menu icon assignments in the source code, but I don't want to hack modules.

mmenu.api.php describes some hooks.

/**
* Allows modules to add more mmenu icon classes.
*/
function hook_mmenu_icon() {
  $icons = array(
    'path' => array(
      'home' => 'icon-home',
      'about' => 'icon-office',
      'contact' => 'icon-envelope',
    ),
    'block' => array(
      array(
        'module' => 'system',
        'delta' => 'main-menu',
        'icon_class' => 'icon-enter',
      ),
    ),
  );
  return $icons;
}

/**
 * Allows modules to alter mmenu icon class settings.
 */
function hook_mmenu_icon_alter(&$icons) {
  $icons['path']['home'] = 'icon-home1';
}

I have no clue how to use these. I have tried to put them in my template.php like this.

function mythemename_mmenu_icon() {...}

It's not working. Apart from that, this wouldn't be a user-friendly solution. Ideally it would support icon-api. So any help is highly appreciated.

Here is what I ended up with, after using hook_mmenu_icon() and configuring the Icon API to use the icomoon bundle.

How I did it?

First of all, I opted for using the Icomoon module, which allows me to import my own defined icons collections, assembled using the icomoon app.

This is an example of a custom collection I created (and the renaming/mapping of icons to the menu points I had in mind).

After, I had to go to the administration interface of Icon API providers and import the icons (/admin/config/media/icon/import). I named the imported bundle 'icomoon', which will be important for the code I wrote. This is what that admin interface looked like.

The code

The code you need will use hook_mmenu_icon(), since you want to define your own path to icon class associations.

This is what my code looks like.

/**
* Implements hook_mmenu_icon().
*
* Here we map URLs to icon classes.
*/
function YOUR_CUSTOM_MODULE_mmenu_icon() {
  $icons = array(
    'path' => array(
      'home' => 'icon-home',
      'node/1' => 'icon-node1',
    ),
  );
  _inject_inline_css($icons);
  return $icons;
}

Notice the use of Drupal's internal paths as the key to the $icons array. This is needed by the module (inside mmenu_get_icon_class()) in order to assign our custom CSS class to the menu item that points to it.

The rest of the code is quite custom and just a random idea of how you could go about doing the assignments you need. Probably there are better approaches.

/**
 * Function for injecting Icon API icons as CSS background images.
 */
function _inject_inline_css($icons) {
  // Load a bundle provider from the Icon API.
  $bundle = icon_bundles('icomoon');

  // Sanitization, normalization.
  if (empty($bundle)) {
    return;
  }
  if (!isset($bundle['settings']['extension'])) {
    $bundle['settings']['extension'] = 'png';
  }

  $css_data = array();

  // Configure an existing icon class, 'home'.
  $icon_path = $bundle['path'] . '/' . strtoupper($bundle['settings']['extension']) . '/home' . '.' . $bundle['settings']['extension'];
  $icon_info = image_get_info($icon_path);
  $icon_url = file_create_url($icon_path);
  $css_data[$icons['path']['home']] = array(
    'background-image' => 'url("' . $icon_url . '")',
    'background-size' => 'contain',
    // Or, as an alternative.
    // 'background-size' => '$icon_info['width'] . 'px ' . $icon_info['height'] . 'px'',
    'background-repeat' => 'no-repeat',
    'background-position' => 'center',
  );

  // Add a custom icon class, 'node/1'.
  $icon_path = $bundle['path'] . '/' . strtoupper($bundle['settings']['extension']) . '/node1' . '.' . $bundle['settings']['extension'];
  $icon_info = image_get_info($icon_path);
  $icon_url = file_create_url($icon_path);
  $css_data[$icons['path']['node/1']] = array(
    'background-image' => 'url("' . $icon_url . '")',
    'background-size' => 'contain',
    // Or, as an alternative.
    // 'background-size' => '$icon_info['width'] . 'px ' . $icon_info['height'] . 'px'',
    'background-repeat' => 'no-repeat',
    'background-position' => 'center',
  );

  // Generate and add inline CSS, mapping the mmenu icon classes to the icomoon icons.
  $css_string = '';
  foreach ($css_data as $class => $css_properties) {
    $css_string .= '.' . $class . ' {';
    foreach ($css_properties as $css_property => $css_value) {
      $css_string .= "$css_property: $css_value;";
    }
    $css_string .= '}';
  }
  drupal_add_css($css_string, array('type' => 'inline'));
}


Get title from Route I am trying to print out a few links on a custom page template. I would like to use the title and url from each route.

I am trying to print out the title from the route.

I know I can get the url from:

$url = Url::fromRoute('route.name');

and I know I can get the current page title from

$request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route); }

but I am not sure how to request the title from a specific/ different route.

Thanks in advance.

The only way to get the page title of any URL/route would be to actually request the page and see what the title is. The reason is that any module or the theme could alter the title from what it normally would be, like fx metatags module.


Attach view of content by author only to the user page I am using the EVA: Entity Views Attachment module to create a view of content by author, to attach it to each author's user page.  So, for example, when viewing /user/1, I will see a list of all the content created by user #1.
I've been able to do this successfully, but too successfully: Not only does this list show up on the author's user page, but it also shows up on every single piece of content that user has written.
Obviously, I don't want it to show up there.
How can I fix this, so that it only shows up on the user page?
These are my settings.

Entiti content settings

Entity type: User
Bundles: User
Arguments: id

Contextual filters
Content: Author UID

When the filter value is not available

Provide a default value: Type: User ID from route context

I'm working with Drupal 9, if that makes any difference.

I haven't used this module, but according to the project page:

The placement of the view in the entity's content can be reordered on
the "Field Display" administration page for that entity, like other
fields added using the Field UI module.

So you should be able to configure this at Manage Display for users: /admin/config/people/accounts/display.  You can customize the display separately for Default and Compact, and you can create more view modes (different display configurations) as necessary.
Another way to do what you're doing (attach a view to users only on the user page) would be to use Layout Builder, which is included standard with Drupal.

Make a view that shows the user's content with contextual filters in a block.
Enable Layout Builder module.
On /admin/config/people/accounts/display, check Use Layout Builder, open Layout Builder, and then add the block.


Database table cache_views_data is extreme large, what size is normal? I have a Drupal 7 site with ~70,000 nodes and ~500,000 terms. During some investigations for the cause of substantial performance problems, I found out that the database table cache_views_data is about 18 GB big.
Is this normal?

UPDATE: I am using time based and contend based (Views content cache) caching.

There is no normal size, it depends on your site, but I think that there's some error because this table grows exponentially.

My site was down because the size of this table. In my case, with a few views & something like 1000 users this table was 29 Gigabits. I deleted it and then everything went back to normal.

I suggest you to keep an eye on the tables of your database, specifically this table.


How to display a profile form using profile2 module Profile2 is a module that uses entities to create profiles that are separate from the user account.

From within my module, I want to be able to display a form to edit the profile entities. Possibly using drupal_get_form or maybe Profile2's API or any other method.

What is the best way to go about this?

I did something like this recently. Since profile uses fields, this make things pretty simple. For the form you could do something like this:

function my_profile_form($form, &$form_state) {
  global $user;
  if (!isset($form_state['profiles'])) {
    $profile = profile2_load_by_user($user, 'profile_machine_name');
    if (!$profile) {
      $profile = profile_create(array(
        'type' => 'profile_machine_name',
        'uid' => $user->uid
      ));
    }
    $form_state['profiles'][$profile->type] = $profile;
  }

  // Use field attach form and handle the fields yourself:
  field_attach_form('profile2', $profile, $form, $form_state);
  // Or use profile2 API which is simpler
  profile2_attach_form($form, $form_state);

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  return $form;
}

Since all the profile form only is the fields that are attached to the profile, you can simply attach the fields yourself to the form, using Drupal core APIs:

field_attach_form adds the fields to the form.
field_attach_validate handles validation.
field_attach_submit to handles adding the values to the entity (profile).
Lastly you would need to save the profile entity using profile2_save.

After browsing the profile2 module code, I found that it provides a wrapper function to attach the fields to the form and save the form. This is simpler, but in doing so, you loose a little control. To use this you need to use the profile2_attach_form. Doing this will also handle the validation and saving of data.

To use the above code you should be able to c/p it, rename the form and replace profile_machine_name with the actual machine name of the profile you want to display the form for.


Create referenced node on the fly in Drupal 7? I have a node called "house" which references another node called "room". When I create a house, i.e. go to node/add/house, there will be a block where I can choose all the rooms I've created. What I want instead is to create the room on the fly, right on that page, and then reference it automatically. So basically, next to where you can choose rooms, you must be able to click a button that says "create new" and then ajaxically it must then open a an area on the page where you can create room.

Does that make sense? Is there a way to do this? I have the entity reference part of things setup, but before I look into trying to figure out which hook to plug into, perhaps someone knows of an inherent way that already uses entity?

You should use the Inline Entity Form module.

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.


How come javascript:void(0) is creating a 404 page? We have a need to have an  to have href="javascript:void(0);" so that some action can take place on the page without refreshing the page. HOwever, this is generating a 404 page and we need assistance in how to best get rid of the 404 but also keep the functionality so that the action can take place without page refresh.

Code in question:

Some action

If you are writing some JS, you can add something like:

$('a#the_link_ID').click(function(event) {
  event.preventDefault(); // This prevents to follow the link.
  // ...
  // Here goes your code.
});


Form results not displaying - D7 Below is my code. Form results are not displaying below the form. What am I missing ?

When I use print_r($form_state['storage']['results']); I'm getting the results.

But it is not displaying in the form.

Any ideas/suggestions will be helful.

function file_search_form($form,&$form_state) {
  $otpions = _get_country_titles();
  $form['countries'] = array(
    '#type' => 'select',
    '#title' => t('Country'),
    '#options' => $otpions,
    '#required' => TRUE,

  );
  $form['entities'] = array(
    '#title' => t('Entity'),
    '#type' => 'textfield',
  );

  if(isset($form_state['storage']['results'])) {
    $form['result'] = array
    (
      '#value' => t('The results of the form are: !results', array('results' => $form_state['storage']['results'])),
    );
  }

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

  $form['#submit'][] = 'webform_options_submit';
  return $form;

}

function webform_options_submit($form, &$form_state) {

  $args = array(':entities' => '%'.$_REQUEST['entities'].'%', ':countries'=>$_REQUEST['countries']);
  $result = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid",$args );
  foreach( $result as $item) {
    $form_state['storage']['results'] = $item->filename;
  }
  $form_state['rebuild'] = TRUE;

}

Added type markup below the submit code in $form_state['storage']['results'] and that does the trick...

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

if(isset($form_state['storage']['results'])) {
        $form['result'] = array
        (
          '#type' => 'markup',
          '#markup' => t('The results of the form are: !results', array('results' => $form_state['storage']['results'])),
        );
      }


How to implement date filters with operators like = in a JSON query string? We use Drupal 7 and the Service (Version 3) module. First we created a view using a date with a "between operator" as a filter, which works fine. Then we added a service view as .json format inn which we try to pass that date operator in the query string of it, but we cannot get that to work.

The query string we are using looks similar to this example:

http://example.com/drupal/api(endpoint)/sampleview.json?field_invoice_date_value<='2013-12-31'&field_invoice_date_value>='2013-11-31'

To produce the output of the view in json format, we used the (amazing!) Services Views module. We added the service view path to the services resource. As mentioned above, the date filtering is working fine in the view (as confirmed by our testing of the view, without using JSON). But if we try using JSON then the between operator for the date is for unknown reasons not (yet) working.

Below are 5 screenshots to further explain what we're trying to implement (and what we got to work so far).

1. Service View

2. Date filter

3. View output

4. Adding service view as service resource

5. JSON query string variations

  http://web.com/drupal/api[endpoint name]/chart(view service pathname).json?field_invoice_date_value>=2013-11-01&field_invoice_date_value_1<=2013-12-31

The above string is NOT working, note the filter in it like so:

  "field_invoice_date_value>=2013-11-01&field_invoice_date_value_1<=2013-12-31"

Other filters are working correctly, like this one:

  http://web.com/drupal/api[endpoint name]/chart(view service pathname).json?facility_name_value='test'

Since we need the JSON output using that 'between date', we also tried this variation, which is NOT working either:

  http://web.com/drupal/api[endpoint name]/chart(view service pathname).json?field_invoice_date_value='20131210--20131213'

When testing with the string above, we received the following error message too:

"Cannot create references to/from string offsets nor overloaded objects in common.inc on line 6579"

My question: Please let me know how to implement the date between operator in a JSON query string, or any other ideas you have to further debug this issue.

OK, below is what appears to be the solution for it ... We need to pass the query string as follows (all string, sorry for the formatting ...):

  http://web.com/drupal/api[endpoint name]/chart(view service pathname).json?field_invoice_date_value[min][year]=2013&field_invoice_date_value[min][month]=12&field_invoice_date_value[min][day]=1&field_invoice_date_value[max][year]=2014&field_invoice_date_value[max][month]=1&field_invoice_date_value[max][day]=1

Things to notice in what is shown above:

No (more) <= or >= (can't use that in such JSON string).
Use notations like [min][month], [max][day], etc. instead (rather self explaining ... if you know about this syntax of course).

Done, works as designed ...


Product comparison with Drupal Commerce How can I implement a product comparison with the Drupal Commerce module?

For example, if there is a list of products, will the user be able to click on checkbox of 3 products, and click the "Compare" button to see a table where products, features, and prices are compared?

I think that this page could be useful for you: Product comparison in Drupal. This tutorial explains how to to implement a node comparison with Flag and Views modules: in short creating an Include in comparison per-user node flag, which users will use to mark the interesting nodes. Then, creating a table view with the nodes previously marked.


How to sort only own webform submissions in a view? I have a view that lists all users webform submissions.

I want to be able to have the view show the name of the user instead of his id and display only his own webform submissions.

Image-1

The solution was to specify as Filter criteria "webform submission:user " and in fields I added the same criteria. Then I customized it by creating a label name.

The video tutorial Drupal Views Module: Creating lists of content on your Drupal site really helped me discovering Views and find an answer to my question (I recommend it for every beginners like me).