custom form submit in a new browser tab I have a custom form in Drupal 6 and every thing works perfectly except I want the form submit to open in new window.
I tried using the following code as per form api for drupal 6 but it does not work

$form['save_and_print'] = array(
      '#type' => 'submit',
      '#value' => t('Save and Print'),
          '#attributes' => array('target' => '_blank'), // this does not work
);

Was anyone able to achieve this? Please help!

You have to set the target attribute in the form tag itself:

$form['#attributes']['target'] = '_blank';

Put this code somewhere in your form function.

Update:

To get this functionality to a particular button, you have to be tricky.

$form['save_and_print'] = array(
      '#type' => 'submit',
      '#value' => t('Save and Print'),
      '#attributes' => array('onclick' => 'this.form.target="_blank";return true;'),
);

When clicked, this will set the parent form element's target attribute to _blank which opens in a new tab when pressed.
If you clicked the button once and when you click some other button in the same form, it will open in a new tab as well because the previous onclick event set the target attribute to _blank.

To workaround, you have to set this onclick event to ALL submits.

To submit the form in same page/tab:

$form['save'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#attributes' => array('onclick' => 'this.form.target="_self";return true;'),
);

To submit in a new tab:

$form['save_and_print'] = array(
      '#type' => 'submit',
      '#value' => t('Save and Print'),
      '#attributes' => array('onclick' => 'this.form.target="_blank";return true;'),
);

demo


Is it possible to combine two different Template.php functions? How about two different functions like below? Is it possible to combine below two Drupal Template.php functions?

function mytheme_preprocess_node(&$vars)
function mytheme_views_pre_render(&$view)

Example:
function mytheme_preprocess_node(&$vars) {
if some field has option 1 selected
}
AND
function mytheme_views_pre_render(&$view) {
if a view is empty { attach alternative view}
}

You can do all of this inside the views_pre_render

function mytheme_views_pre_render(&$view) {

  if ($view->name == 'my_view_name' && $view->current_display == 'block_1') {
    if ($node = menu_get_object()) { // gets current page node object
      $field_name_val = $node->field_name[LANGUAGE_NONE][0]['value']; // get field value
      if ($field_name_val == 'option 1') {
        // your empty view code conditional goes here
        // if($view->result...
      }
    }
  }

}

You can find out the current_display name look here


Durpal 8 on install new module, insert data in new created table I created a new table into the new schema and I want to insert default data into it.
How can I do this in the module.install file ?

To run tasks when your module is installed, use hook_install(), e.g.

function module_install() {
  \Database::getConnection()->insert(...)->execute();
}


Change order item title in cart I would like to update the title of a order item before it's put in the cart to add some extra dynamic info for the user. I tried this but nothing changes.

In the onCartEntityAdd function:

$item = $event->getOrderItem();

// Some code to check that its the item I wanted then:

$newTitle = $item->getTitle() . ' - some extra info';
$item->setTitle($newTitle);

setTitle call does not seem to do anything, the title in the cart is still just the product name.
The getTitle() call works though.

Thanks for any info.

The problem is probably that you don't save the order item after updating the title.

Add $item->save(); at the end of your code and it should work.


How to enable Gmap module in Drupal 7 I just enabled the Gmap module in Drupal 7. You can see it in the picture below.

In Drupal 6, after the gmap is enabled, you can do the setting for any content type in /admin/content/node-type/story under location information.

But I don't see how to do it in Drupal 7.

I can't neither found it as a field type to add to content.

Gmap for drupal 7 is missing a js file. See http://drupal.org/node/1061444. The discussion may lead you to solution.


drupal module for uploading to s3 originally posted on stackexchange.  Didn't get any replies.  Then I recently found out there's a specific drupal stackexchange so here i am reposting.  TIA!

I have a drupal site and I plan to serve static site files directly from s3 (rewrite). I need to provide a way for the content manager to upload his images directly to s3 from the drupal admin UI so he doesn't have to send it to me to upload via s3cmd or the aws console. Can anyone recommend a module or method for this?

I've tried s3fs however mounting a fuse s3 filesystem and serving from it was painfully slow. If it worked drupal would think the files are all local and i'd be set.

I found this but not sure if it will get the job done for me: https://drupal.org/project/storage_api

I need a module that would allow the drupal admin UI user to graphically browse for a file (image for instance) to upload to the s3 bucket i intend to serve from.

storage_api is the right module for seamlessly transferring data such that the user's upload lands first on the servers local filesystem and by rules can have it automatically propagate to any number of containers (S3, Cloud Files etc..)  And even more you can control the priority in which the files are served from the site simply by ordering them in prefered manner.  the URLs will change automatically. pretty slick.


Combining 2 drupal 7 sites - how to move modules? I am combining 2 drupal sites in to one, was not really my decision. What things I should be careful of and what pitfalls to avaoid?

List of things I will be combining

Content Types - Bundle copy module
View - Export functionality
Content Data - Feeds Importer
Blocks - Block Import Export module
Modules - I am going to install the standard modules from drupal projects and copy over any custom modules. How can I move the modules configurations?
Menus - How to move over the menus settings?
Users - Do not need to be migrated

There is not much taxonomy on the other site.
Anything else I am missing ?
Any suggestions on the sequence to do this?

Thanks.

I don't know for the menus, but for modules that doesn't implement any export functionality (either custom or contrib), take a look into the 'variables' table.

for how unpractical it may sounds, export the table data, keep only the 'module_*' entries of the module you need and insert the in the new site database, after you install the modules. You will have to change the sql from inserts to updates too.

yes, extremely unpractical, but i can't think to an automated routine for it.

also, probably you are forgetting to export users too (and custom roles).


Drush on Windows trouble I had installed Drush for Windows and trying use it.
I open directory (in CLI, in my example: Z:\home\www\drush-test) where I want install drupal and run drush dl command:
Z:\home\drush-test\www>drush dl
Install location Z:/drush/drupal-7.25 already exists. Do you want to overwrite it? (y/n):

But i need install drupal to Z:\home\drush-test\www not Z:/drush/drupal-7.25 (this directory where Drush installed)
Also I trying using drush status in my old project (drupal installed). Drush don't see my drupal:
Z:\home\comp\www>drush status
X-Powered-By: PHP/5.3.13
Content-type: text/html; charset=utf-8

 PHP executable        :  php.exe
 PHP configuration     :  Z:\usr\local\php5\php.ini
 PHP OS                :  WINNT
 Drush version         :  7.0-dev
 Drush configuration   :
 Drush alias files     :

Z:\home\comp\www>ls
CHANGELOG.txt       LICENSE.txt      cron.php     nbproject   update.php
COPYRIGHT.txt       MAINTAINERS.txt  includes     profiles    web.config
INSTALL.mysql.txt   README.txt       index.php    robots.txt  xmlrpc.php
INSTALL.pgsql.txt   UPGRADE.txt      install.php  scripts
INSTALL.sqlite.txt  __files          misc         sites
INSTALL.txt         authorize.php    modules      themes

Z:\home\comp\www>

(Drupal 7 installed in this directory)
Windows 8.1, PHP 5.3

Reinstalling Drush for Windows fix this problem.


Programmatically trigger rules action component I have some problem in triggering an action component.
I tryed to call it from the module function and from the devel/php page.

This is my component settings

As you can see I have one node argument followed by 4 text arguments.
And i'm trying to call it with this code

$node = node_load( 981 );
$return = rules_invoke_event('rules_send_mail',
    $node,
    'mymail@gmail.com',
    '123',
    'nome',
    'sss' );
print_r( $return );

Nothing is printed on the page.. not an array or a FALSE.
The action simply send and email to client_mail.

Can someone help me to understand why is not working?

if its a rule action component than it should be called by

 rules_invoke_component('name', $other_parameters..);

while rules_invoke_event() is suppose to trigger an event on which you might have different rules to act on.


How do I import a library from Github when the module is installed I want to add https://github.com/googleads/googleads-php-lib library to my module Drupal 8 I try to add composer. json in the folder module but is not load when I installed module this is solution to upload this library without command "composer update "?

this is my composer.json

{
  "name": "drupal/googleads-php-lib",
  "description": "Integrates the googleads-php-lib library into Drupal",
  "type": "drupal-module",
  "require": {
    "googleads/googleads-php-lib": "25.0.0"
  }
}

composer.json has no bearing when you enable a module in the Drupal admin. Drupal only looks at the info.yml of a module to ensure any listed dependency (module only) exists and has been met. Using drush also won't work. You need Composer for this.

You would need to require your module via composer require drupal/mymodule - at which point any dependencies listed in require would also be pulled in. For that to work, your module would need to be posted on drupal.org, with the Drupal packages repository added to your root composer.json file.

You could also add a repository endpoint pointed at GitHub, Bitbucket or any other VCS service, add a baseline composer.json file to your project and require it that way, too.

You can also do composer require googleads/googleads-php-lib:25.0.0 from your Drupal root to pull in that package, but I would go the module route (so that package is always tied with the module).


Autosave with TinyMCE I have tried outputting code simliar to the custom_format example thats included with TinyMCE. I enabled the Autosave module, however I never see a "restore drafts" button. The only setting that doesn't wipe out all the buttons in the editor is using "theme_advanced_buttons3". Which also doesn't show a button with the 'restoredraft' value.

Edit: context

I have made some progress on this. I downloaded the TinyAutoSave module from https://code.google.com/p/tinyautosave/ which I believe is more recent than the 'autosave' plugin included with TinyMCE 3.4.4. There may be updates in the latest version of tinymce, but I haven't checked. It seems the codebases have forked, however.

Anyways, I ended up removing autosave from the tinymce.inc file located in sites/all/libraries/wysiwyg/editors. I put tinyautosave/ into sites/all/libraries/tinymce/jscripts/tiny_mce/plugins.

The solution involved was to not use the 'restoredraft' setting, and use the 'tinyautosave' one instead. I have some strange way that builds the wysiwyg settings table but it basically does:

$settings['tinyautosave'] = array('tinyautosave' => 1);


How to display a form in controller method I have a form defined in mymodule/src/Form/myForm.php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class myForm extends FormBase {

/**
 * Specify the form ID.
 */
public function getFormId() {
  return 'mymodule_myform';
}

  /**
   * Build the actual form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Form API code here...

Originally, this routing worked fine and the form displayed at the correct path:

mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _form: '\Drupal\mymodule\Form\myForm'
    _title: 'Add performance'

Then I needed to add a custom access check, restricting to a specific content type:

mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _title: 'Add performance'
    _controller: '\Drupal\mymodule\Controller\mymoduleController::content'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\mymoduleController::checkAccess'

The access check works fine. Now I think I have to display my form in the controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\Entity\Node;

/**
 * Controller for Add Performance single tab.
 */
class mymoduleController extends ControllerBase {

  /**
   * Returns the add single performance form.
   */
  public function content() {
    $form = $this->formBuilder->getForm('Drupal\mymodule\Form\myForm');
        return [
          '#type' => 'markup',
          '#markup' => $form
        ];
  }

This fails to display the form, and I get:

Call to a member function getForm() on null

I tried defining my form builder class inside the controller instead, but same result. What am I doing wrong?

Thanks to Kevin's comment, I realised that I can just return the form AND still use the custom access check reference to a controller method:

mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _form: '\Drupal\add_performance\Form\myForm'
    _title: 'Add performance'
  requirements:
    _custom_access: '\Drupal\add_performance\Controller\mymoduleController::checkAccess'
  options:


How do I programmatically generate a menu based on field values? I'm working on a site where I want to have a menu that displays links based off of the content of a certain field.

For example, lets say it is int field_apples. I want to automatically generate a menu that will have links to lists of articles with each value of apples (or a range of apples such as ≤9 apples).

Apples menu

1 apple
2 apples
3 apples
7 apples
9 or more apples

Each link above will show a list of articles for that particular value of apples.

This could be achieved by using taxonomy to define your terms and the Taxonomy Menu module to create the menu from these terms. Taxonomy is the preferred method for categorising content.


How do I sell tickets? I started a project that required me to create a site selling tickets to a nightclub for special events.

People attending the event must be able to buy a ticket or multiple tickets, and add a ticket holders name for each ticket. They are then sent a confirmation e-mail with their tickets attached as individual tickets with bar codes.

I tried Ticket but this did not integrate with commerce as easily as I had liked.
I tried the COD distribution which has ticket installed, and their own custom module to link it to commerce. However, I personally don't like distributions. I find they have too much un-needed stuff with them, and I don't like waiting on them to update core when security updates are needed.
I also tried the Commerce Tickets module, which looked promising, but the ticket holder name data was not easily accessible, or available in views. As well as a series of bugs, and a maintainer who seemed non existent, this didnt seem like an option either.
I also tried Commerce Booking but that didnt do what I wanted it to, and  if the cart module is enabled a lot of errors are generated

Therefore I determined my only option was to create the functionality myself, hopefully using only contributed modules, and not too much custom stuff. I am posting an immediate answer to provide help for anyone in the same situation. I am not looking for other answers to this question unless you have something really cool to share!

Here is the method I used. It covered all of the functionality I needed, and we ended up with a very robust website, using popular well maintained modules, and getting the exact results we needed.

Modules used

Commerce
Commerce_agree_terms
Commerce_autosku
Commerce_cart_expiration
Commerce_event_ticket (For PDF creation)
Commerce_stock
Date API
Inline Entity Form
Rules
Views

These were the main ones. There are also modules these rely on, and others I used for other purposes. But I am trying to keep this to the ticket functionality only, rather than explain how to build an entire site.

Method

Enable all modules.
Create a commerce product called "Ticket" (Or re-name the default enabled product).
Manage the fields on the "Ticket" content type, and add a date field called "booking window". This should collect a start and end date, and will allow an admin to define when these tickets are available for sale.
Enable Commerce Stock on the Ticket Product to allow an admin to define the amount of tickets available for each ticket.
Create a content type called "Event".
Add an In-line Entity field allowing the user to create new products (Tickets). Allow unlimited values on this field if you wish (This allows a user to add an Early Bird Ticket, Standard, VIP etc.). We also disable "Allow a user to add existing products" as we want unique products to be created for every event. This is where the autosku module comes in handy for auto generation.
Add a date field for the event date.

Once that is done, you have the basic functionality. You can create an "Event" node, add a ticket or multiple tickets (defining price, stock and booking window), add your event date and click save.

Next Steps

Next you will need to manage the display for the content type "Event" and hide the display of the tickets field.
Create a new view Block Display called "Ticket Display" for products. Add a field to show products (Tickets) as an add to cart form.
Add a contextual filter "nid" and set the default value as "get content ID from URL".
Add a filter to the view for the product (Tickets) booking window start date and use relative date "now" to only show products with a start date less than "now" and another filter with end date greater than "now".
Go to structure > blocks, find your view block display, and restrict the block to only show on "event" content types. This will now mean the tickets only show on their referenced nodes, and only if the booking window is open. They will also be disabled if out of stock.

Adding a ticket holders names

Manage the fields of the line items. Store > Configuration > Line item types > Product (Ticket) > Manage fields. Add a field for "Ticket holders name".
On the "Ticket holders name" field settings, make sure you select "Include this field on Add to Cart forms for line items of this type".

Sending tickets to customers

After enabling the commerce event ticket module, follow the modules instructions to generate a PDF for every ticket product.

For a full working demo of this, look here.. http://www.dev.thelhp.co.uk/ Please note this site is in development for now, but will try and charge you when it goes live!


Why can't I access my custom fields in Rules? What I want:
I want to give my products a weight and I want to calculate the total weight of the order.

What I did:

I'm using Drupal Commerce Kickstart 7.x-2.0.
I added a field 'weight' to the Product Variation 'Product'.
I created a custom Rule
Added a condition 'Entity is of type': commerce-line-item == commerce_product
Tried also to add or replace the condition above with the conditio 'Entity has field': commerce-line-item has field 'field_weight'
Create a Loop Action for commerce-line-items
Add a Loop Action but don't find the field 'field_weight'

Can someone explain me why I can't access my custom fields in Rules even though I added specific conditions?

Thanks in advance!

You're not looking for the field on the entity you've added it. You added it to the product, so in addition to your "Entity is of type" on the line item, then you need to check the type of the commerce-line-item:commerce-product for whatever product type you're expecting to find the weight field on. Only then will Rules know that that product has that field.


Drupal Theming and Caching Issues There is a content type in a view who's display is based on a theming template. In this example, the template is called views-view-fields--article-list.tpl.php . This Case Study/Articles list template works great and as expected on the local testing server. Seriously, everything is working fantastico! Changes made to this template act as expected locally.

However, when the file is uploaded to the production server, changes to the template do not seem to be responding at all. Even after the cache is cleared, the changes are not taking effect. In fact, I deleted the template all together to see if that would cause any disruption, and nothing. It still behaves the same way. Also, flushed the cache in the top left of the admin menu.

So, question is...
Is there some sort of database change that needs to happen when I update the template locally and then upload to the server? Or, is there just something missing in general that is not allowing Drupal to re-scan the template files on the production server?

The server resides on bluehost, if that would be relevant, but I believe the issue is something in my Drupal files.

Ayuda, por favor?

---- I thought the below was the problem, but in looking closer, there is a weird caching problem with this file!!! It is still doing this and changes made to it are not refreshing normally. It must have something to do witgh the view's settings.

Here was the source of my confusion. When clearing the cache, the server wasn't responding to the changes I made in the template file. I'm still not sure what the original problem was. :( However, I had removed the template file and placed all the code from that file into the last view's 'Rewrite the output of this field option, and had re-formatted it to the correct format. But, I was seeing everything double (and broken), and assumed it was the old template file adding in its own code, thus the odd double vision!

What I forgot was to go to each field in the view UI and exclude its Display. So, yes  Jimajamma, it was at the end a palm to forehead slapping! Thanks for the troubleshooting ideas.

Have you checked that the file has the right permissions when uploaded to the server? at least make sure the webserver user has read access to it.


Is it possible to change all node assigned on TermA to TermB? We are going to delete TermA, and there are a lot of pages under TermA. How can I assign those pages into TermB (already exist) without manually one by one?

The Views Bulk Operations module can achieve this in one fell swoop.

Build a page view that lists the titles of your nodes and is filtered to nodes of Term A. Add a field "bulk operations" (if on D7) and set it to modify entity values then select your term field that you want to bulk update. You'll then be able to mass update your nodes, and can replace Term A with Term B


is it possible to have multiple image styles for one uploaded image in drupal 8 I have my main story pages. I have one image style set on the content type display page for 880 x 495. I also want to have a image style set for thumbnails sizes of these photos. But as I see it I can only have one or the other. Is there a way to apply multiple image styles to the same uploaded photo field in drupal 8?

You can reuse images using different image sizes - as far as I am aware there isn't a way to do this using the Drupal Field UI - but you could (for example) override the node display using views for more customisation including the ability to use the same image field using multiple image styles.


Image field in content type not displaying the image Created a content type called Gallery and added the image style for that. The images are to be displayed in the page--front.tpl.php

I have fetched the images using this,

                        <?php
                        $nid=11;
                        $node = node_load($nid);
                        $imgcount = count($node->field_img['und']);
                        for ($i = 0; $i < $imgcount; $i++) {
                        $image_uri = $node->field_img['und'][$i]['uri'];
                        // url
                        $masthead_raw = image_style_url('gallery-thumb', $image_uri);
                        ?>
                            <img src="<?php print $masthead_raw; ?>">

                     <?php } ?>

.

The image is not displaying.Please guide me.

You need to convert that public://myname.jpg to an actual URI to pass to an img tag

Try image_style_url

Replace your code with this

    <?php
    $nid=11;
    $node = node_load($nid);
    $imgcount = count($node->field_img['und']);
    for ($i = 0; $i < $imgcount; $i++) {
//$image_uri = $node->field_img['und'][$i]['uri'];
      $yourimagestylename = 'MY_IMG_STYLE';
      $image_uri = image_style_url($yourimagestylename,$node->field_img['und'][$i]['uri']);
// url
      $masthead_raw = image_style_url('gallery-thumb', $image_uri);
      ?>
      <img src="<?php print $masthead_raw; ?>">

      <?php } ?>


How to set Exposed filters in fieldset for specific Views? I found an article that can collapse exposed filters into fieldset. But this will change all Views. How can I set below code for specific Views only? For example, I wanna use this on ViewsA only.

<?php
/**
 * hook_preprocess_views_view
 */
function YOUR_MODULE_NAME_preprocess_views_view(&$vars) {
  // Wrap exposed filters in a fieldset.
  if ($vars['exposed']) {
    drupal_add_js('misc/form.js');
    drupal_add_js('misc/collapse.js');
    // Default collapsed
    $collapsed = TRUE;
    $class = array('collapsible', 'collapsed');
    if (count($_GET) > 1){
      // assume other get vars are exposed filters, so expand fieldset
      // to show applied filters
      $collapsed = FALSE;
      $class = array('collapsible');
    }
    $fieldset['element'] = array(
      '#title' => t('Filter'),
      '#collapsible' => TRUE,
      '#collapsed' => $collapsed,
      '#attributes' => array('class' => $class),
      '#children' => $vars['exposed'],
    );
    $vars['exposed'] = theme('fieldset', $fieldset);
  }
}
?>

This code will work for specific view. Example for "ViewsA"(reaplce ViewsA for your Views name and "my_module" for your module name).

<?php
    /**
     * Implements hook_preprocess_views_view().
     */
    function my_module_preprocess_views_view(&$vars) {
     // Assign to your specific view.
      if ($vars['view']->name === 'ViewsA') {
        // Wrap exposed filters in a fieldset.
        if ($vars['exposed']) {
          drupal_add_js('misc/form.js');
          drupal_add_js('misc/collapse.js');
          // Default collapsed
          $collapsed = TRUE;
          $class = array('collapsible', 'collapsed');
          if (count($_GET) > 1){
            // assume other get vars are exposed filters, so expand fieldset
            // to show applied filters
            $collapsed = FALSE;
            $class = array('collapsible');
          }
          $fieldset['element'] = array(
            '#title' => t('Filter'),
            '#collapsible' => TRUE,
            '#collapsed' => $collapsed,
            '#attributes' => array('class' => $class),
            '#children' => $vars['exposed'],
          );
          $vars['exposed'] = theme('fieldset', $fieldset);
        }
      }
    }
?>


How to set a content type tile base on taxonomy field that user select? I have ask in the past How to convert Content Type Title into Term reference?. Which someone suggest to used the Title Field UI in order to remove it the title and have a Term Reference field as my title field.

However, now I run into few problems where the title field is been expected like admin/page. So I was wondering if possible to set up the title field the same as the a term but automatically. I do not want the user re-type the field Title field, but at the same time I want to limit the user from choosing something that is not from the terms.

So how can I copy the taxonomy term that the user select and set up as title programmatically ?

Update 1

My content type machine name is job_per_template and taxonomy name is field_job_title_template. I have take the code from the answer below and I got this error.

  Integrity check for the imported configuration failed. Error message:
  The data type of the configured argument does not match the
  parameter's value requirement..

Do it with rules and the title module:

{ "rules_title_taxonomy_token" : {
    "LABEL" : "title taxonomy token",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--package" : { "bundle" : "package" },
      "node_update--package" : { "bundle" : "package" }
    },
    "DO" : [
      { "data_set" : {
          "data" : [ "node:title-field" ],
          "value" : [ "node:field-my-taxonomy-field:0:name" ]
        }
      }
    ]
  }
}

Be sure to change "package" to the name of your content type and be sure to use the proper field name for your taxonomy instead of field-my-taxonomy-field.

As far as I know, the above only works with the Title module and the Title Field UI.


Restrict Menu Item from anonymous users and redirect to Login page I created a simple menu link and need it to be visible for both authorized and anonymous users. But when a unauthorized/anonymous user click it should check authorization and if not it should redirect to login page. How can i do this. Thanks

Create a custom module
In your_custom.module

function custom_init(){
global $user;
$current_path = request_path();
if (!in_array(array('your roles','your roles'),$user->roles) && $current_path=="node/add/yourcontent type" ) {
  // for mutiple row
  drupal_goto('/user');
}
}


Logic on Node Add Page for Specific Content Type I created a new content type in Drupal 7 and I want to make a template to customize the node add page for that content type. I want to be able to check if the user is authenticated with Facebook before they can use the node add form. If user is not authenticated then I will show them a paragraph explaining that they need to authenticate via facebook before they can use this form. I want them to always see the form link but they can only use the form if they are authenticated to facebook. I just don't know where to put it. Is it possible to make a template file specifically for that node add page so that I can include my logic?

Hiding options such as publishing and URL aliases is accomplished through the use of user roles and permissions. Visit /admin/people/permissions on your site to see what I mean. Enable the help module for more (contextual) assistance.

If you want to perform additional modification beyond basic access control, then, seeing as to how you are attempting to customise a form, you would need to implement a Drupal hook named hook_form_alter(). You will need to do this in a custom module - if you haven't done this before, it's a lot easier than it sounds :)

There should be plenty of information and guides on SE, d.o as well as Google on how to use this hook to modify forms. But the one reference that you definitely need to be aware of is the Form API reference.

Since you want links to the node-add form to be visible, rather than controlling access to the page based on the FB-authentication status, you can check the status during the form_alter and either add a message and disable the form, or as is usually done, set an error message or notice (using drupal_set_message()) and redirect them to a page where they can log in via FB; the message/notice will be displayed at the destination.


How can I display content from one node to another? With some design in mind, I have to display the some content of one node to another node. For ease of understanding, I have just put some drawing.

Suppose, I have,

Content type: Article which has -> Node/5 which has -> field_123 (Text type)

and I want to show that field content to another node,

Content type: Basic Page which has -> Node/6 which will be ->  copy_field_123 (Text type)

Hence, in short I want to display content of one node to another node. I do not want entire node content to be transferred to another node as it is, but a specific fields which I choose.

Any suggestions, please?

I think after some research I found the solution. Again Thanks to @Niall Murphy and
@drupality For their input.

I think for my purpose Field Reference will be the right module. As it not only allows to choose the particular node, but which field you want to choose from that particulate node.

Although any suggestion is appreciated.


Apple-like button style carousels in Drupal 7? I would like to build a carousel which supports Apple-like scrolling, like at http://www.apple.com/displays/
So you would have a carousel with small "buttons" at the bottom which allow for easy navigation. The jcarousel module seems the preferred module for carousels, however it does not seem to support this type of carousel? I can not find a way to get links to all images/nodes/... to realise this via a different jcarousel template.
I did not find alternatives to carousel implementations in Drupal 7, but I might be mistaken of course :-)

The Views Slideshow module can do this and is stable for Drupal 7.


Why I can not find some css with grep? I'm newbie and I don't know how Drupal 7 work!
I want to remove with and height from below code:

<img typeof="foaf:Image" src="http://ashkanplastic.loc/sites/default/files/styles/large/public/slider-1a_0.jpg?itok=k4X3QU5U" width="480" height="236" alt="">

Could you please introduce to me why I can not find 480 with $ grep -H -R 492?
And please help to remove width and height.

Please check Remove width and height from img tag in Drupal output (for certain content type) for removing width and height from image.

You will never find width and height with grep command because width and height are added by drupal theme function.

Check https://api.drupal.org/api/drupal/modules%21image%21image.module/function/theme_image_style/7 and  https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_image/7 for more details.


Read drupal log programmatically I want to get all the logs, which are available under admin/reports/dblog as shown in the screenshot below:

Below are the two approaches, I can think of:

Access logs programmatically in Python or PHP
Download the database as a SQL file and read the database

I am not sure if the above approaches are possible or not. Any suggestions, please?

Yes, assuming you have the dblog module enabled, that data is in the database, so you can use whatever language or method you want to extract and analyse it.

The data is kept in the watchdog table.


Storing Credit Card Information for later use I'm building a website where registered users would place future order(s). e.g. after 6 months for $20, or even on a specified date may be after one year or so.

In order to charge them on those transaction dates through paypal or any other payment gateway, we would need their credit card information to store somewhere.

What is the best way to complete the task with maximum security.

Please advice.

Edit: Currently I'm using Ubercart, but if any other module can fit for the required scenario, I'm open for that.

These would not be recurring payments, but I would rather call them "post-dated orders". I've never used any payment methods. This is my first site for shopping cart so I've no idea. If paypal can store the CC info for multiple transactions for every site member and give me option to execute the orders on specific dates, I hope that would be fine with me too.

The most secure place to store credit card numbers will be on a third party service designed to securely retain that data. These service providers are PCI Level 1 compliant with code and systems in place to prevent the unwanted or unexpected exposure of sensitive card data.

Many payment gateways support such "card on file" functionality, where they allow you to process an authorization or capture for a credit card and provide you with a token to perform follow-up transactions using that same card data. Such a transaction is generally referred to as a "reference transaction", with example implementations being PayPal's reference transactions, Authorize.Net's Customer Information Manager (CIM), or CyberSource's Managed Billing / subscriptions.

The name and price of these services will vary from payment gateway to payment gateway, but they will always require a similar point of integration in Drupal - a way to retain a payment token and process that reference transaction at a later date; typically you want some sort of customer interface as well, allowing customers to update their information or reuse a credit card on a later order.

To solve the Drupal integration, we created the Commerce Card on File module, which does all this and more within Drupal Commerce. It works through payment method callbacks, allowing any payment method module to implement the callbacks to integrate reference transactions through its payment gateway's API. Obviously, not every payment gateway under the sun is supported, so be sure to check the documentation to find out if yours is supported.

And as the comments on your original question indicate - you should never be in the business of storing card data in your site, which was unfortunately easy to do in Ubercart. Multiple times now I've been part of rescuing sites that incorrectly used the UC Recurring module to retain credit card data in plaintext in the database for later processing. Do not do this - ever.


How can I set a 'global' Exposed filter rewrite for taxonomy terms on a view How would I go about settings a rewrite for display taxonomy (Rewrite filter options), but as a 'global', instead of having to set each individual value for exposed filter?

I can see the there is place to add individual value overrides for the filter display, but my taxonomies are many and may update occasionally.

So the issue is two-fold; The taxonomies to be displayed on the exposed filter are quite long in some cases (which is needed). And they will be adjusted on the fly by content maintainers.

Instead of:
1 | Display 1
2 | Display 2
3 | Display 3

I would be perfect if I can do:

[vocabulary:original:name]|[vocabulary:original:description]

But for some reason it's not working for me.

The additional application of this is that the short tax term can be used on the csv import, but front-end displays the complete long version tax.

So if I can get the actual term to be a 'keyword' and display to front-end users a long term, the back-end user will have a better experience as well.

Currently working with Better Exposed Filters and D7.
Thanks

Found a excellent module Token formatters. Can be used in various places, but for this application it's spot on.

Once installed, the formatter for a entity reference field on a view gets and addition in the dropdown 'Tokenized Text'. That in turn allow for a a wider range of token us. [see all your tokens at Admin -> Help -> Token ].

Drop the Token of your choice and swap out between fields or Taxonomies.

In my case I has an additional field on my Taxonomy terms. All the regular places I tried to reference it only gave termID or termLabel as options. Now I can use the build in features of taxonomy terms, but on one of their custom text fields.


Unable to sort view based on search index by taxonomy weight I have a search index created using search api and I have a view created based on the search index. I have a taxonomy term field called subscription which is indexed. I need to sort my view based on the subscription field and it should be based on the taxonomy term weight and not by the term name. I am able to add the subscription field in my sort criteria but it doesn't seem to be working the way it is expected.

I referred to multiple links but those seem to work only for views based on content and not based on search index.

How do I sort the view(based on Search index) by taxonomy term weight?

I'm not sure if you have figured this out yet, but I found the solution to this, so I'll post it here in case anyone else comes along this page.

If you go to your search index and go to the Fields tab, you'll see at the very bottom there is text that says "Add related fields". It took a while for me to see this there, since it's kind of inconspicuous and under the form submit button. But if you click that and select your taxonomy, it will add the set of taxonomy fields to the available list of fields to index. Check "Weight", then that will be available in your view.


Filter/sort content displays/listings I need to implement the functionality of sorting the content listed to the user based on attributes like alphabetically, popularity or price (ascending/descending). These attributes can also be custom. I need to have it has a widget. I don't exactly know what this functionality is called so apologies if I'm not being clear.

I also need to display text like "Displaying % of %" on top the list which, as far as I've seen, views don't do by default.

An example could be this website.

I'm using Drupal Commerce (D7).

So is there a module for this?

Views allows you to expose sorts, but doesn't create the type of UI you are asking for by default.

What you get by default with views after clicking 'expose' at the top of your sort value is two menus, one for the value to sort by, and one for the sort direction.

The most important thing to remember here is what you get in your view's url after submitting this original exposed filter form: /myviewpath?sort_by=XXXXX&sort_order=XXXXX.

You can write your own custom module, do a hook_form_alter of the existing form, a fancy jquery widget, heck write it in Flash if you really want to, all the view cares about is you passing those two values and that those values are enabled and available for that view.

In terms of getting your own custom values available there have a look at the views sort class documentation and the view_handler_sort_* examples already provided in /views/handlers. Views argsort looks pretty interesting as well if you don't want to write your own sort handler but haven't tried that module myself yet.

For part 2 of your question this summary is already provided by views. Click on header, click on "Global Result Summary", and use the tokens provided to create your summary.


How to list all inactive modules on a multisite? I have kept several hundreds of modules in my D6 Drupal multisite. I have had them there so that when I need any of them I don't have to download it first - I just go to /admin/build/modules and switch on what I want.

The problem is that that list of modules takes ages so long to load that the work becomes inefficient. Also Drupal monitoring services, such as the excellent droptor.com, have a hard time (literally, very time consuming calls) to retrieve the current status of each site. The PHP memory allocation is stretched as well.

In short, I am looking for a programmatic way to select and then delete all inactive and uninstalled modules in any site of a Drupal 6 multisite.

I know there are complications -- module folders often do not correspond exactly to their module names (e.g. module "CCK Privacy" is in folder "privacy"). Also, some modules might actually be in subdirectories in cases where one project ships several modules at once. The problem is especially confounded in case of multisites, where some modules might be inactive for one of the sites, but they need to be in the directory because some of the other sites use them.

(There was an interesting thread on this at http://groups.drupal.org/node/123179 but it did not offer any practical solution for multisites.)

I am not sure of a way to do this programatically, but you could install http://drupal.org/project/enabled_modules and cross-reference the lists.


How to get product URL or URL alias using product ID? I'm using Drupal Commerce and stuck in this problem. I'm creating a custom module that will display a product title and some info.

I want that product to be linked to its node page, and product Object is all I have to my resources. I'm thinking of getting the product URL or alias using product_id but I don't know how. I already searched it but there's nothing clear on the search results I got.

Any suggestions?

After trial and error I found a solution. Here's what I did.

        //$product is the product object that I mentioned above
        $wrapper = entity_metadata_wrapper('commerce_product', $product);
        $nodes   = $wrapper->field_product_node->value();
        $path    = drupal_get_path_alias("node/".$nodes[0]->nid);
        $product->path = $path;


Any twitter boostrap(ish) theme for Drupal 6? I'd like to make a legacy D6 site's theme more responsive. I love to be able to use the omni-present twitter bootstrap theme or something that comes close to it in responsiveness. I know that there is a quite a few for drupal 7+  but could not fine any for D6 on Drupal site.

So I'm wondering if there is any mature D6 Bootstrap theme? And if not, how hard is it to convert a D7 theme to D6?

Either you may start creating your own theme (you can use any light weight theme as base theme) from scratch using Twitter Bootstrap, or you may check the couple of options present on the sandbox project, which contains experimental code for developer use, as below:

HTML5 CSS3 base Drupal 6 theme built using Twitter Bootstrap: https://drupal.org/sandbox/drewkennelly/1276010 (Also check issue queue of it: https://drupal.org/node/1276060)
A Drupal 6 Theme with Bootstrap installed: https://github.com/sdmunoz/Drupal-6-Theme-Bootstrap
Twitter bootstrap theme for Drupal 6 created using zen as base theme: http://www.eliotdill.com/2012/06/twitter-bootstrap-theme-for-drupal-6/

If any of the above suits your requirement, then you can use them and modify it as per your need, instead of creating it from the scratch.


Get labels from fields ordered on block plugin - Drupal 8 I'm trying to create a block with a label list using all labels of a specific field type, entity_reference_revisions.

I created a Block plugin and load the EntityTypeManager service.
I tried:

    $values = array(
      'targetEntityType' => 'node',
      'bundle' => $bundle,
      'mode' => $view_mode,
      'status' => TRUE,
    );
    $entity_view_display = $this->entityType->getStorage('entity_view_display')->create($values);
    $fields = $entity_view_display->get('fieldDefinitions');
    $labels = [];
    foreach ($fields as $field) {
      if($field->getFieldStorageDefinition()->getType() == 'entity_reference_revisions') {
        $labels[] = $field->get('label');
      }
    }

The problem is that I get the fields in a wrong order, and I can't get the weight attribute.

I solved it loading the field definition using entityManager, I got the weight attribute, and then ordered the labels by weight.

$node = $this->requestStack->getCurrentRequest()->get('node');
$bundle = $node->getType();
$view_mode = 'full';

$fields = [];
foreach($this->entityManager->getFieldDefinitions('node', $bundle)  as $field_name => $field_definition) {
  if($field_definition->getType() == 'entity_reference_revisions') {
    $field_name = $field_definition->getName();
    $element = $node->$field_name->view($view_mode);
    $fields[] = [
      'name' => $field_name,
      'label' => $field_definition->getLabel(),
      'weight' => $element['#weight'],
    ];

  }
}

usort($fields, [$this, 'sortByWeight']);


Make a views listing of nodes in Search API with multiple parameters to sort and more Facts:

I'm working on a classified ads (Cars and Parts) website that people can post their ads with the ability to make the ad Featured or Promoted (Using Flag module)

What is a featured Ad: if an ads is featured it will show up and stays at the top of the list and the design is a bit different (like any other websites with featured ads)

What is a Pormoted Ad: Users can promote their ad and boost the ad to the top of the list everyday so it stays at the top, wether it's Featured or not.

On the search results page, I'm using Search API, Search API Sorts and FacetAPI.

Requirements

Since there is a lot of options to filter the search results, I wanted to use Ajax for better user experience and performance, also I want to keep the result page in this order even if it gets sorted or filtered:

Featured Ads (Prioritized by Promoted date Featured Ads then
Submitted Date)
Promoted Ads (Prioritized by Promoted date and submitted date)
Free Ads (Prioritized by Submitted date)

So I want to be able to sort and filter my results but still keep the main priority.

so I tried Ajax Facets module but since it doesn't generate URL the rest of my website functionality kinda breaks!

Also tried Search API Sorts and Facet API for filtering and sorting, but it breaks my priority of displaying the ads (featured, promoted, free), even if I add some criteria in it's views.

Case Study:

A good case study is http://jobs.drupal.org, it has everything that I want except the Promoted part!

Thank you so much in advance.

In Search API you can assign a 'boost' for results depending on defined field:


How to prevent Content type from appearearing in built-in Search results I've got thousands of nodes which were created by importing using a Feeds module. I only want them to be searchable via the views search form, not by the built-in site search.

Is it possible to disable these nodes from being searchable by the built-in search, while still making it available to the search generated by a View?

There are two modules you can check out.

Search Config

  Restrict search results by the content type. This is a role based
  restriction.

Search Restrict

  Restrict by role who can search for each content type.

  Approach of this module is to re-write the search query, so that
  content is indexed and available as search results to users in role(s)
  that have permissions to view it, but not displayed to other roles.

OR

You can write your own query alter function.

function mymodule_query_alter(&$query) {
  $is_search = FALSE;
  foreach ($query->getTables() as $table) {
    if ($table['table'] == 'search_index') {
      $is_search = TRUE;
    }
  }

  if ($is_search) {
    $query->condition('n.type', 'node-type-name', '<>');
  }
}

And yes as webkenny suggested Custom Search as well.

  Basic options

  The module adds options to select:

  which content type(s) to search,
  which specific module search to use (node, help, user or any module that implements search),
  advanced criteria

  For all these choices, there are options to switch between a select
  box, checkboxes or radio buttons, and also customize the selector
  label and the default - Any - text.


Difference between hide() and ['#access'] = FALSE I want to remove the delete button from a standard edit form in certain cases and I'm looking for the right way to do that.

So far I found that hide() marks an element as already rendered so it basically tricks the rendering process.

['#access'] = FALSE does something similar I guess, but still a little different.

In both cases, nothing is rendered concerning the delete button, but does either of them prevent the delete code from being executed on submit (e.g. if a user was manipulating the POST request)?

Or would I need a form_validate() method for that anyway?

Hiding the element is done during the rendering process.  If you look at the code, it just marks the element as already being rendered.

The #access key on the element is used during the form build process (can't find my chart, so I can't tell you exactly which part).  It says that this element is part of the form, but a particular user may or may not have access to be able to use it.

Unsetting the element, just throws the element away and says it is not part of the form anymore.

Of the three options, using #access is preferred: it's the API so you should use it.  When you just hide the element, a user can still submit that element git GET/POST as the Form API thinks it is still valid.  For non-submit elements, I believe the #default_value will also appear in $form_state['values'] when you validate/submit (however I don't recall the last time I tested this).


OAuth2+ OpenID Connect SSO I am trying to implement the OpenID Connect SSO as outlined in Nik Vahalik’s YouTube video and in Patrick Dawkins’ Tutorial.  I have gone step by step through their implementation instructions as well on the documentation page (https://www.drupal.org/node/2274367).

I have the OAuth server running on one Drupal Instance.  I have the client login setup on a different Drupal Instance.  I have the sso.php located in the root of each Drupal instance.

When I click “Login with Generic” on the client site, I get an error that says “Not Found The requested URL /oauth2/authorize was not found on this server.”
The URL bar shows this as its attempted destination:
https://devcondrupal.genieve.com/oauth2/authorize?client_id=devdrupalclient&response_type=code&scope=openid%20email%20profile&redirect_uri=https%3A//devdrupal.genieve.com/%3Fq%3Dopenid-connect/generic&state=7a4e2dc4a66e3aa3b4531b5d523f6371

I am using self-signed SSL certificates on both the OAuth Server site and on the Client site.

I don’t know where to begin troubleshooting the issue as this is my first experience with OAuth / OpenID and there is not much information out there on the web (Drupal-wise).

Thanks for your help.

It turns out that "Clean URLs" need to be turned on for OpenID...  I added "AllowOverride All" to the  section under VirtualHost in my Apache config file.  This allowed me to turn on Clean URLs and the error is now gone.


Attach different CSS classes to first and second link I have a Paragraph type 'Call to action' with one link field field_link.

I have another Paragraph type where I call the 'Call to action' paragraph as an Entity reference revisions field. With Allowed number of values set to 2.

So the editor is able to insert two Call to action links.

I want to attach 2 specific CSS classes to both links:

On the first link:

Button one

On the second link:

Button two

How do I loop through, so I am able to attach different classes?

Update:

In paragraph--call-to-action.html.twig I added:

{% block paragraph %}

{% for item in content.field_link %}
    {% if loop.index == 1 %}
      Button one
    {% elseif loop.index == 2 %}
      Button two
    {% endif %}
  {% endfor %}

{% endblock paragraph %}

But now it's rendering always the 2 buttons? What's wrong here?

I figured how to loop through an entity reference field. Because I am looping from inside a paragraph twig through another paragraph (entity reference) I have to loop the children:

{% for item in content.field_name|children %}

So the children did the trick! Then you can do something like:

{% set link_class = loop.index == 1 ? 'primary' : 'secondary' %}


Moving content from dev directory to production server When developing websites for clients, each developer has all sites under a relative path in his htdocs dir:

/client1site/
/client2site/
/clientsite/ and so on

Most links within the drupal installation, in content or image srcs have to be absolute to this path: /client1site/en/a-nice-article/ in order to work.

But when client 1's site goes to production, links stop to work because now the structure looks like www.client1site.com/en/a-nice-article.

The situation is general, in the sense that you can develop under a path /X/ and have to go to production under a path /Y/.

Can this be solved with an easy way without having to edit all content or image srcs by hand? Can some mod_rewrite wizardry save the day?

Frankly, I have never suffered from any path reference issue that you are describing, speaking of managed files.
As per unmanaged files, which laying around on the ftp server, that you may happen to refer to in raw code or WYSIWYG editors, make sure you don't use absolute paths starting with domain name. Check your WYSIWYG editor settings. Instead, you'd want to:

use links starting with slash - I call them root links
edit the settings.php file and provide an explicit URL of your current site root in the $base_url variable. This is what the root links will refer to as base. Thus, when you move your site to another domain, it should require just changing of that one value.

I'm not sure there is a tool to do global replacements of absolute path you might already have. You could however dig into database and do a global search on it.


Drupal update to specific version (not dev) with git I have a Drupal folder made with command:

git clone --branch 7.x https://git.drupalcode.org/project/drupal.git

Now I want to update it to the actual version (7.67). When I run

git pull origin 7.x

or

git pull origin 7.67

Every time I get the 7.68-dev version, not 7.67. What am I doing wrong?
I know how to get the specific version with composer, but in this situation I need to get it with git pull command.

Just to expand on this for future reference:

Releases in git are created as tags.  To see the available releases, do the initial pull from the repo, then you can see the available tags with the command:

git tag

To check out the specific release, do:

git checkout [tag-id]

You will see a message about previous head and current head.

Check that you are on the correct tag with:

git status

It should indicate that you are currently in a headless state.


Why isn't ['field_name'][0]['#markup'] work for getting taxonomy of this node? I have two content types: Case and News.
In node--case.tpl.php, I'm using echo $content['field_case_category'][0]['#markup']; in order to print the taxonomy term for the page and that works fine. In node--news.tpl.php, I can't use echo $content['field_news_category'][0]['#markup'];; in fact, #markup is not even present in this array at all.

Why doesn't this method work in the second case? What can I do to solve it?
Is there a better/right way to print taxonomy terms in nodes?

The error I get is the following:

  Notice: Undefined index: #markup in include()

Please don't print some result directly. You should print the content of field like below.

print drupal_render($content['field_case_category']);

Hope this solves your problem. Also please check whether your node contains the value for the field_case_category field.


Complex SelectQuery with multiple left joins and conditions with OR I have a view and in hook_views_pre_execute() I have to add multiple left joins with conditions. Currently I'm doing this:

$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');
    $or = $or->condition($field->table . '.' . $field->field, '%' . $string . '%', 'LIKE');
}

$query->condition($or);

but it doesn't seem to work.

It seems that the problem was $field->field. For example if I have a field called field_book_author in database the $field->table would be field_data_field_book_author and the value of the field would be in field_book_author_value.

So the correct code is:

$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');

    if (property_exists($field, 'additional_fields') && (count($field->additional_fields) > 3)) {
        $field_name = $field->additional_fields[3];
    }else {
        $field_name = $field->field;
    }
    $or->condition($field->table . '.' . $field_name, '%' . $string . '%', 'LIKE');
}

$query->condition($or);


Why do modules run multiple times on a single page load? In Drupal 7 created a module which implemented hook_init().

I put an error log message as the first line of the function.

function my_module_init() {
  error_log('running init');
}

On each page load of the site I see the error message multiple times. I was expecting hook_init() to be ran exactly once per page load. Why is it running multiple times?

hook_init() is invoked by Drupal only once for each requested page; it is the last step done in _drupal_bootstrap_full().

  // Drupal 6
  //
  // Let all modules take action before menu system handles the request
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    module_invoke_all('init');
  }

  // Drupal 7
  //
  // Let all modules take action before the menu system handles the request.
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
    // one for this page), so that:
    // - Modules with hook_init() implementations that call theme() or
//   theme_get_registry() don't initialize the incorrect theme.
    // - The theme can have hook_*_alter() implementations affect page building
//   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
//   ahead of when rendering starts.
    menu_set_custom_theme();
    drupal_theme_initialize();
    module_invoke_all('init');
  }

If hook_init() is being executed more than once per each page request, there could be a module that calls module_invoke_all('init'). It could also happens that a module calls drupal_goto(), and redirects the user to another page; this would cause a new page request, and a new invocation of hook_init(), if the page is not served from the cache.

In Drupal 7, there is just a way to check if hook_init() is invoked twice per page request, and it is to implement hook_init() using the following code.

function mymodule_init() {
  watchdog('mymodule', 'Request time: !timestamp', array('!timestamp' => REQUEST_TIME), WATCHDOG_DEBUG);
}

As REQUEST_TIME is a constant that Drupal defines each times it bootstraps (which means each times a page is requested), if you see two consecutive watchdog() entries showing the same value, then hook_init() is being invoked twice, or it is invoked in two different page requests done in less than a second. If the difference is 2 seconds, for example, then hook_init() is invoked in two different page requests.


Why is my website often put in maintenance mode by itself? My website in maintenance mode by itself. But other sites is work well, only this site has this problem. Some people encountered this kind of situation? Thank for help..

Usually, a Drupal site enters in maintenance mode by itself because is having problems to access to its database or when is set on that mode through the option located at "admin/config/development/maintenance".

If you are not able to log in on the site, that could indicate Db problems.

Check...:

at "admin/config/development/maintenance" is checked the option "Put site into maintenance mode". Or with drush: drush vget maintenance_mode
the settings.php if the Drupal database parameters are ok.
the status of the Drupal database, (if the user:password are correct, if the database server is online).
the error logs (MySQL, PHP, Drupal).


Fatal error with the tagadelic module I have this error after the installation of the tagadelic 7.x-2.x-dev module:

  Fatal error: Call to undefined function tagadelic_get_weighted_tags() in /home/www/2374fcf941c82d5986ed6d27587b81e0/web/sites/all/modules/cumulus/cumulus.module on line 120

How can I recover my site?

Log in to your database panel (for example PHPMyAdmin) and run following query:

UPDATE system SET status='0' WHERE name='tagadelic';

Additionally, if you are using Drupal 7, run:

DELETE FROM cache_bootstrap WHERE cid='system_list';

After then you can uninstall problematic module via administration panel.


How do I create a search page? I have the Search API and the Solr search modules installed. In /admin/config/search/search-api, I see my server and index created and with status set to OK. I can see on the index view page that my content is indexed correctly.

I did not use the Solr Search Defaults module because I have removed the default Article content type, and I don't want to recreate it. Without this content type, there is an error when activating the module.

How can I create a search page displaying all indexed results (for anonymous users, not in BO)?

One tutorial shows that Solr Search Defaults module uses views. I've created a view, where in View settings > Show I've selected Ideas index.
In the view, Format > Show is set to Rendered entity. Search index is the view mode. I have a page, but no content is displayed.
No filters are required, and all are exposed.

Other tutorial says I should create a search page in Configurations > Search and metadata > Search pages menu, but I don't have that menu.

Here are my Fields for Ideas index.

Here is another view I've tried, with Show > fields

Here are my error logs, there is a Notice:

Here is what I see using {{ kint(page.content) }} on my Search results page:

If I create a view with VIEW SETTINGS > Show > Content my content IS diplayed correctly.

After installing the searc api module:

1) goto: /admin/config/search/search-api/index/default_index/edit

If you want for example to search for both Users & Content at once, make sure that both entities for Content & Users under the Data sources section are checked.

2) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default_index/fields

This page is used to choose which are the fields you want to be indexed for your search.

So make sure on this page that all the fields you want to search your entities by are added to your entities; If not,
add any field using the +Add Fields button.

3) On the same page: http://site8.dd:8083/admin/config/search/search-api/index/default_index/fields

Any field you add, it has its own data type which you have also the permission to change it.

As per the data type table available at the bottom of the page:

  Fulltext fields are analyzed fields which are made available for
  fulltext search.  This data type should be used for any fields
  (usually with free text input by users)  which you want to search for
  individual words.

so in your view, if you want to use the Fulltext search to search for your contents, every indexed field on this page should also be set to Fulltext data type.

4) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default_index

And make sure that the index Status bar is 100% and so all your contents are indexed to be searchable.

When you have done the above, create a new view as per below:

Show: index default content index
Check Create page box
Display format Grid
Hit save and edit button.

Within the views configuration page:

Under add fields section:

add any fields you want and make sure the field title has the (indexed field) text.

Under the filter criteria section:

add the fulltext search field and exposed to visitors.

Here you go, visit your search page and enjoy.

If none of the above helped you, feel free to ask any other question in comments or update your current question.


page.html.twig default regions I'm creating a custom theme with base theme: stable. I have copied the template/layout/page.html.twig file into my theme. As I am reading the twig file I have noticed that there are some regions that I am not providing but are still being rendered.

Part of the file comment lists the regions available.

/*
 * Regions:
 * - page.header: Items for the header region.
 * - page.primary_menu: Items for the primary menu region.
 * - page.secondary_menu: Items for the secondary menu region.
 * - page.highlighted: Items for the highlighted content region.
 * - page.help: Dynamic help text, mostly for admin pages.
 * - page.content: The main content of the current page.
 * - page.sidebar_first: Items for the first sidebar.
 * - page.sidebar_second: Items for the second sidebar.
 * - page.footer: Items for the footer region.
 * - page.breadcrumb: Items for the breadcrumb region.
 */

I went looking in the stable.info.yml file and noticed there is not an entry for regions: so I am at a loss as how the page.html.twig file is able to render regions that are not listed in the stable.info.yml file.

Questions

How does this work without being defined in the stable.info.yml file.
Are there any other regions that work like this that are not in the page.html.twig file.

If no regions are specified in the theme, the core provides defaults itself.

From the docs page: https://www.drupal.org/docs/8/theming-drupal-8/adding-regions-to-a-theme

  Default Regions:

  page.header: Items for the header region.

  page.primary_menu: Items for the primary menu region.

  page.secondary_menu: Items for the secondary menu region.

  page.highlighted: Items for the highlighted content region.

  page.help: Dynamic help text, mostly for admin pages.

  page.content: The main content of the current page.

  page.sidebar_first: Items for the first sidebar.

  page.sidebar_second: Items for the second sidebar.

  page.footer: Items for the footer region.

  page.breadcrumb: Items for the breadcrumb region.

  If your theme does not declare any regions Drupal will assume this set
  of defaults. These regions correspond with what the default
  core/modules/system/templates/page.html.twig file expects, as well as
  two hidden regions, page_top, and page_bottom - you don't need to
  declare these final two if you override the defaults, however the {{
  page_top }} and {{ page_bottom }} Twig variables should be retained
  in the html.html.twig template.


How to remain logged in when switching languages via domain? I am using Drupal 7 to configure a new single Drupal site that uses two languages (English and French), using Locale with the "Language domain" setting enabled. This site requires both the display and the admin language to be switchable, and almost have it working! I have just one last issue.

When I visit "en.dev.example.com" I can log in everything seems to be working great; when I switch to "fr.dev.example.com" while logged in, I am no longer logged in. I can actually have two different users logged in at once, using the same browser, on each domain.

This is not desired! This Drupal site is not a multi-site, and I don't want it to behave like that. When someone logs in, I need them to stay logged in also when they switch languages. This is because many users will be totally bilingual and need to see the site content in both the languages. This is important, since the content is membership based.

I started out setting the "Path prefix language code" in my language settings which was working well; you could switch languages without problems and stay logged in while doing so. Perfect! Except…

I had to change the method of handling languages to "Language domain" because the URLs created by some modules (namely the Advanced Forum module, but I am sure it will come up in other places) were not respecting the path language prefixes, and giving many 404s. I really need to use the subdomain method!

I created two subdomains via my hosting account, one is "en.dev.example.com" and the other is "fr.dev.example.com" (both using subdomains to give each language equal significance). I changed the "Language domain" for each language, and am now able to see both language versions by using the subdomains I created, as expected.

What can I do to make sure users stay logged in when they switch language after starting their session, while using the "Language domain" option?

I cannot locate any info or forum posts for Drupal 7 on this particular issue... Do I need to make some changes to my settings.php file? I also couldn't find D7 documentation on setting this up (only for path prefixes), so it's possible that I have missed a step.

I have been at the languages settings for a few days now, and I have made real progress, but I feel totally stuck at this point, the last problem! I would absolutely love some advice at this point.

Try adding this to settings.php

$cookie_domain = '.dev.example.com';


What WYSIWYG editor allows me to select styles from a dropdown 'out the box'? I have installed the WYSIWYG module in Drupal 7 and have tried it with CKEditor and TinyMCE. I want users to pick styles from the template css when editing, but here appears to be a bug with the WYSIWYG module (drupal.org/node/1069356) that prevents the style dropdown from working. CKeditor seems to have a similar issue (drupal.org/node/746524), although there does seem to be a patch for this. I am not confident enough to deply the patch though.

Is there a WYSIWYG editor that is able to do this successfully out the box?

CK Editor is the best in my opinion, and it should provide this option out of the box - it is a shame about the bug. In Drupal 6 I use drop down styles for all the line stuff and templates for including more complex block level elements such as jQuery show/hides. I really cant recommend enough how well it works. I suggest that you try the patch before ditching ck editor and seeking an alternative...

Drupal 7 is still pretty new so you will encounter small issues such as you describe, if you are dealing with bleeding edge this is something you have got to expect... otherwise use Drupal 6


Tagging of multiple content items at once I'm very new to Drupal, so please be gentle.

My company is in the process of setting up Drupal as a learning portal, which will have various content types (videos, pdfs, blogs, basic pages) that we will tag for ease of searching and offer 'suggested learning materials'.

While we will try to get our taxonomy defined perfectly up front, we know we'll miss something.

I came across two related questions here, but neither are exactly what I am asking

Add a field to multiple content types at once?
is there a way to change multiple tags at once?

I'll certainly use these questions and answers in the future, but for now my question is:

if we add a new term (rather than change one), is there a way to select multiple content items and add the new terms to the selection in a single action, rather than have to go to each content item individually and add the new tag?

You can create and customize a vbo view, which would allow you select multiple content items and add a taxonomy term to all the selected items at once.

Jason


How can i integrate java application with drupal? I a new to Drupal. As per my knowledge drupal is based on PHP. How can I get the contents from drupal and use in my java web application?

Is there any way to get the contents from drupal schema which I need complete information of drupal table structure, how contents get saved in tables?

This is a very broad question so the answer can only be a broad one...

You can use the Services module to expose resources from your site to interested consumers:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

There's an Example of Java XML-RPC client with Drupal7 and Services 3.x, which (trust me) is the best documentation you'll be able to find.


Creating a "scrapbook" node type using an entity reference field I'm building a site that includes two node types, "scrapbook" and "press clipping". A user can create multiple scrapbooks which are either public or private, and they can also add press clippings to a public pool.

Each scrapbook includes an entity reference field that allows multiple press clippings to be referenced from each notebook. This works fine, but the only way I can add a reference from a notebook to a press clipping is by editing the scrapbook. I want to include a dropdown on each press clipping that allows the user to select one of the scrapbooks they have created and add the press clipping to that scrapbook.

What's the best way to achieve this result?

Personally, I'd move the entity relationship field to the press clipping content type, so you get the convenient dropdown there, and use the reverse relationship, or contextual filter when building a view


How to only allow alphabets and spaces in the middle in Profile2 field I'd like to only allow alphabets in and spaces in the middle of a my Profile2 "real_Name" field. I have found what I think I need: profile2_form_validate_handler but I don't know how to get it to work.

I think it should be similar to user_validate_name, especially for

  if (!$name) {
  if (substr($name, 0, 1) == ' ')
  if (substr($name, -1) == ' ')
  if (strpos($name, '  ') !== FALSE)

and I should use

preg_match('/[^A-Za-z ]/'

I only have a rough idea but I don't know how to make it work and I'd appreciate your help.

I've found the Field validation module that works! I used this regex expression:
^[\x{00c0}-\x{01ff}a-zA-Z0-9]+([- '][\x{00c0}-\x{01ff}a-zA-Z0-9]+)*$

This way I can allow international names and only allow spaces, hyphens and apostrophes in the middle of the name.
It was based on combining

1 https://stackoverflow.com/questions/275160/regex-for-names , and
2 https://stackoverflow.com/questions/2525327/regex-for-a-za-z0-9-with-dashes-allowed-in-between-but-not-at-the-start-or-e


Showing Forum Topic Count 0 because, content access module conflict with Advanced Forum In my project I am working with advanced forum. for this I installed module as below.

advanced forum
ACL
content_access
chain_menu_access

The issue is after adding Forum Topic into forum, the count of topics display zero (0).
Help for resolve this issue.

Finally, I find solution for my issue and post it on issue list of Advanced Forum. Also patch is created, and pushed in to future development.


How to use both #anchor and ?destination parameter in a node/edit url? I have a long page containing a node edit form and I wish to direct the user to a specific part of the page.

My URL is /node/12364/edit?destination=node/12360.

Where in the URL should I add the anchor?

I tried /node/12364/edit#anchor?destination=node/12360 but it doesn't work. The anchor is not used, the user isn't directed to a specific part of the page.

If I enter /node/12364/edit#anchor, it works but I need the destination parameter.

Page fragment is always passed after the query string. Otherwise, the browser will recognize the query string as part of the fragment.

Here's how your URL should look like:

/node/12364/edit?destination=node/12360#anchor

However, if you were asking how to pass anchor to the destination page, you simply need to use encoded hashtag instead. Here's how the URL should look like in this case:

/node/12364/edit?destination=node/12360%23anchor

%23 is encoded # character. See this page for more info.


What might block the creation of thumbnails? My Drupal 8 does not create thumbnail. I have set my files folder's permission to 775 and the folder 2016-10 is not there.

There is no error shown in the log, and the temporary directory is /tmp.

Perhaps you need to look for this file: /var/www/httpd-logs/your_site.com.error.log

So, edit your sites/default/files/.htaccess

# Turn off all options we don't need.
#Options -Indexes -ExecCGI -Includes -MultiViews
Options -Indexes -ExecCGI -Includes


Repeating date (multiple values) I need to add multiple values to the repeating date field.

I have to make the schedule for a university classes. So I might have multiple groups with different schedule (different hours for each group) for the same class.

Now it's dificult to assign the schedule for each group on the same node (I don't think it is even posible), but I think at least I could have multiple values on each repeating date, e.g. each thursday at 12:00 and 14:00, and each friday 10:00 and 16:00.

I'm using the latest Drupal 6 and CCK.
I can't use Drupal 7 at the moment for this project, but minor version upgrades can be possible.

You should take a look at the office hours module. While it might not be created for your use case, it allow you to store repeatedly dates for stuff like each friday 10:00-16:00.


Add user to Organic group after commerce product order with rules I would appreciate any help, I have been searching for a solution for over a week now.

I have tried this tutorial https://drupalcommerce.org/blog/10809/selling-organic-groups-using-drupal-commerce but unfortunately the first component can't be completed because of an error message of data type not matching. Several people have complained about this but I'm yet to find a solution.

I also tried http://s1l.org/selling-access-organic-groups-drupal-commerce but the loop in the component doesn't give me the field that is in the tutorial.

I have also tried the Commerce License module with the Commerce License OG module. It expects the group to exist before the product is created. You are to select the group from a list of groups when creating the product. This doesn't match my use case. My groups are created after a product has been created.

I was able to do this finally by tweaking the tutorial posted on this site: http://s1l.org/selling-access-organic-groups-drupal-commerce. I removed the loop in the components since my field only takes one value and I removed the condition to check if the order has been paid and now it's working.


How to trigger email, account/user and order creation actions when payment is made in paypal, not when user is redirected back I have read many discussions of this sort, but just couldn’t get my head around this issue.

I am testing my site locally and using paypal WPS as my module to process payments. As default, when my users are directed to paypal and makes the payment, they are not re-directed back to my site unless they click one of the paypal links to be redirected back and as a result no user account is created, no order is recorded and no order/welcome emails are fired, unless the user goes back to my site, which I do not want.

So I went to rules and replaced all the ‘Completing the checkout process’ events with ‘When an order is first paid in full’ events, so that I can have all the above actions triggered as soon as the payment is first made on paypal, but unluckily none of these rules are now working and I assume it’s because I am not receiving IPNs on localhost. I did look into the logs.

Here’s a quick list of questions I would need your advice on.

Q1. Am I really having these issues because of not receiving the IPNs in localhost. The way I looked for IPN was by looking into the admin>reports>Recent log messages. Please let me know if it’s the correct way?

Q2. If that is the reason, do I have to put my site live to test the IPNs. It might be a silly question but what if my users attempt to make payments while I my site is live and still in a test phase. Is there a way I can test this all locally first.

I hope it has nothing to do with rules and replacing all the ‘Completing the checkout process’ events with ‘When an order is first paid in full’ events is the right move to create accounts, orders and send emails when the payment is made, rather than when the user comes back to the site.

I am using xampp stack and paypal sandbox account to test my site.

Q1

To test Paypal unfortunattely you need to test on a website which Paypal also can connect to. This is not necessaraly your live site. Maybe you should setup a test/demo environment somewhere else. If you don't want people to access that site you can setup an extra login with htpasswd, but it needs to be disabled during testing of the IPN.
An easy way to do this is using the shield module.

Q2

You can always test using another payment method. For other tests I always use the Payment Example module which is provided with the Payment module in Drupal Commerce.
This way you can test payments without having to deal with receiving IPNs.


How to get a list of all javascript files in a directory Is it possible to get a list of all the javascript files in the libraries directory? So far I have tried using files_scan directory but it's not returning anything:

$dir = base_path() . 'sites/all/libraries/';
$files = file_scan_directory($dir, "/.*\.js$/");
dpm($files);

many thanks.

EDIT

I changed to using DRUPAL_ROOT. This gives the correct path and returns an array of js files but there is a double slash // in the uri just before the file names: /var/www/html/droop/sites/all/libraries//d3/d3.min.js

$dir = DRUPAL_ROOT . '/sites/all/libraries/';
$files = file_scan_directory($dir, "/.*\.js$/");
dpm($files);

libraries_get_libraries should return an array of library directories, with the library name as the key and the directory as the value.

libraries_get_path will get you the path to a specific library (js).

Follwing your approach, this works fine for me:

  $dir = "sites/all/libraries";
  $files = file_scan_directory($dir, '/.*\.js$/');

I think it might be base_path that is breaking it in your example, as it adds a / in front of the (relative) path from the site root.

Combining libraries_get_libraries with file_scan_directory will also get you libraries from profile and site specific directories:

$libraries_array = libraries_get_libraries();
foreach($libraries_array as $library => $directory) {
  $files = file_scan_directory($directory, '/.*\.js$/');
  $js_paths[$library] = $files;
}
dpm($js_paths);

It may be worth noting that these libraries may contain many javascript files that are not actually used by modules.


Creating booking system for items I am thinking of the best approach for a small website selling only two products - two sets of coin printings - one gold, and one silver. There are only 100 products of each set made, all gold are the same price, all silver too.

I need to create a system of 10 x 10 table (100 items) containing numbers, each one cell can be clicked and "reserved" (by ordering) - then administrator will ship the product and mark the cell as "sold", so each number can be bought only one time.

Now I was thinking of several methods to achieve this:

Using Drupal Commerce, which is quite robust for only two products.
And I do not really want to have 200 same products on site differing
only by ID and cell number.  Maybe having only two products, adding
some kind of field in this product with data of which numbers were
already sold and then providing this field in product display would
do the trick.
Using Webform, products can be nodes, there is no need
for checkout, webform components should contain things like shipping
and billing information and product nodes can have the same field
with table as specified upper. Order mails can also be provided by
webform.
Some other already made system for things like this, I was
thinking about booking systems, but most of them are locked on dates
I guess.
Other ideas?

Also the only payment method will be paying directly to bank account, nothing else. Back account creditials will be mailed to customer, they only need to contain order number or something because if all the orders are mostly the same amount, it would be hard to recognize which payment belongs to which order.
Shipping method will again be only one, customer only need to be informed.

Thanks in advance.

Assuming this is about D7, here is a blueprint of just another idea (as in your bullet item "4"):

Create a single node for each number, of content type (say "Golden Coin"), so  10x10 = 100 of such nodes.
Use the Views module to display a 10x10 grid of those 100 nodes, and link each of them to there corresponding node.
Use the Flag module for authorized users to "flag" such nodes, to indicate "reserve this one".
Use the Rules module to make the remaining magic happen, using Rules Events such as "When such node is flagged", with Rules Actions such as "Create appropriate notifications (eg towards the admin)".
Repeat the above for "Silver Coin", or add an extra field to the Flag you'll be using, to select between "Silver" and "Gold".


Mark location on Gmap without Click on gmap I am using Location + Gmap module. When creating a content user have to mark location on gmap. I want to to mark location on gmap automatically when user enter the values in location.

I enabled Geocoding for India and tried after set Google Maps Geocoding Accuracy to Premise, Country Level etc. but it is not marking on Gmap

I tried this documentation, But map is only displaying if I manually mark on gmap. I am using a Location CCK Field.

The location module already geolocates automatically. Go to admin/config/content/location/geocoding and make sure you have chosen a geolocation service for the counties you need.


Wrong Javascript order: Undefined variable: jQuery Since I moved all scripts form the header to the bottom of the page (in the template file of my theme) I have the problem that some scripts of contributed modules (chosen and device geolocation from smart ip) are added before the JQuery library. Using Jquery this leads to an error:

Undefined variable: jQuery

What can I do to get the right order and what could be the reason of the fact that the order is only wrong when the scripts are added at the bottom of the page and not in the header?

Modules, via drupal_add_js() can define the 'scope' and 'weight'. The 'scope' defaults to header, so unless you change this via drupal_add_js() in your template.php file, you can't move print $scripts from your header, or you'll have this problem with, likely, most contrib modules.

To change this, you could do something like this in yourtheme_preprocess_page($vars):

$js = drupal_add_js();
$newJs = array()
foreach ($js as $s) {
  $s['scope'] = 'footer';
  $newJs = $s;
}

drupal_add_js($newJs);


store fid of file_load into profile2 I programmed a multi-step form using the drupal form API. On the first page is
a user image file upload using the drupal managed field managed_file. When the form is stepped thru to the end and submitted, the already in the single steps validated data will be stored into profile2, by creating a profile2 object with profile_create and set the assign the fields.
This all works without problem. But how can I store the FID of the uploaded file to the profile2 user_image field? A s I saw in mysql, the file FID and the measurements of the image are stored in the field table.

I have this (file_load code snippet is untested) in the form submit step, where the data gets stored into profile2:

$profile = profile_create(array
    'user' => $new_user,
    'type' => 'main'));
$profile->field_firstname['und'][0]['value'] = $user_data_collection['t_1_1'];
// ...
if (isset($user_data_collection['t_1_22'])) {
    $file = file_load($user_data_collection['t_1_22']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    $fid = $file->fid;

    // --- how can I store the FID, x and y measurements of the image?
    // ...
}
// ...
profile2_save($profile);

Can somebody give me a hint? I was searching on google but did not find an answer to my question. Thanks in advance!

Update:
This is how I solved it now. Since I work with an "managed_file" Field in the form, and later for displaying the image file via the theme() fct I do not have to care about resizing. This is done due to the image cache / theme fct's with a properly defined image-style.

$profile = profile_create(array(
   'user' => $new_user,
   'type' => 'main'));

//...

if (isset($user_data_collection['t_1_22'])) {
   $file = file_load($user_data_collection['t_1_22']);
   // --- Flag that this file is permanent and should not be deleted.
   $file->status = FILE_STATUS_PERMANENT;
   // --- save file object to the database
   file_save($file);

   // --- get original x/y measurements for this image
   $img_info = image_get_info(drupal_realpath($file->uri));
   // --- store fid. x and y to profile 2
   $profile->field_image_user[
      'und'][0]['fid'] = $file->fid;
   $profile->field_image_user[
      'und'][0]['width'] = $img_info['width'];
   $profile->field_image_user[
      'und'][0]['height'] = $img_info['height'];
}

//...

// --- save profile data
profile2_save($profile);

So all seems to work and have the solution that I needed.

I think you are asking how to save user picture. Users table holds the place for picture.

$account = user_load($new_user->uid);
user_save($account, array('picture' => $fid));

EDIT

Profile2 module is based on entities using Entity API module. You can use entity_metadata_wrapper('profile2', $profile->pid) to get a metadata object. This object will hold the properties (native profile2 fields) and Fields (additional properties plugged in via field api or Field Admin UI)

$profile = profile2_load_by_user($account, 'main');
$profile_w = entity_metadata_wrapper('profile2', $profile->pid);
$proflie_w->field_myfield->value(); // This is a read operation
$proflie_w->field_myfield->set('new value'); // This is write operation
$proflie_w->save(); // Finaly save the things

You can bypass metadata wrapper.

$profile = profile2_load_by_user($account, 'main'); // Loading existing profile instance
OR
$profile = profile2_create(array('user' => $account, 'type' => 'main')); // Providing a new profile instance
$profile->field_myfield = "new value";
$profile->save();

NOTE: you can check all your listed properties using foreach operation on the wrapper object.
e.g.

$profile_w = entity_metadata_wrapper('profile2', $profile->pid);
foreach($profile_w as $key => $obj){
   debug($key) // give you name of your property


Drupal Commerce: How to theme Product Field On the product display node of Drupal commerce, you have the "Product field".
This displays all the products that are attached to the product display.
The products are displayed in a drop down menu.

By default, any fields on the product are displayed above the drop down menu. How can I theme this field, so the field are displayed below the drop down menu.

I have figured this out.

1) Create a file named:  node--NAME-OF-CONTENT-TYPE.tpl.php

2) Insert the following in the file:

<?php print render($content['field_product']); ?>
<?php print render($content['product:NAME-OF-FIELD-ATTACHED-TO-PRODUCT']); ?>

<?php print render($content['field_product']); ?> is the add to cart drop down menu, so if you put the fields below it, they will appear under the add to cart drop down menu.

3) Clear cahces (at YOURSITE.com/admin/config/development/performance)


Organic group module- teacher student layout dashbord drupal7- Organic group. Each teacher manages a class composed of several groups. Teachers only have access to their own groups. By connecting each teacher is directed to a page (or dashboard homebox) containing: its student groups with each group their latest posts, a link to their blogs , a place to send (create) a post to all groups or a specific group. Each group of students connect with the user name and password of the administrator of the group (one group member has the right to connect) and are directed to a page that contains: All posts sent by the group, members of the group, a place to send (create) a post (blog entry) only to the teacher, and a page explaining the course. How much do I create roles (teachers and students only?) which modules should I use? og, og_menu, og-audience ...

Thats possible out of the box.. see http://nodeone.se/en/permissions-and-roles-for-groups


How to set webform to show previous submissions to users? I've got a webform I'm maintaining, and I'm not sure how to expose or suppress the "View Previous Submissions" link on a per=role basis. The previous submissions link is visible to the admin, but it's not visible to the user. I've looked at the role based permissions the webform settings but nothing looks obvious.

Be sure to confirm "Access own webform submissions" and "Edit own webform submissions" permission for the roles in question.