Create Drupal Commerce stores as a Service I'd like to leverage the power of Drupal Commerce to sell completely unrelated products and thus would like to create 2 different stores and brands. I could of course create a Drupal multisite but this is overkill and I really want to have only one site and one Drupal Commerce setup. If tomorrow I want to create new stores, I'd be able to do so with this layout without having to go through the headache of managing different installs.

My idea is thus to try and set up Drupal Commerce as a service with the following in mind:

Each store would be completely isolated from the others (products,
clients...)
Provisioning a new store would only be a matter of assigning a role to a new user
Say the root domain is mysite.com, I'd like to have one
store at mysite.com/store1 and the other at mysite.com/store2 (using
subdomain would be pretty much the same)

I've been thinking about using Organic groups but it's not obvious to me if a) it is the right tool and b) how to achieve that with the module.

Any pointer or feedback would be very much appreciated.

Thanks!

This is known as the "marketplace" use case.

There is a 250-comment discussion on this in the Drupal Commerce issue queue:
http://drupal.org/node/990204
See http://drupal.org/node/990204#comment-5880498 for a fairly simple implementation plan.
Of course, it goes into details that your project might not need, but you can just ignore those.

Quoting the relevant part about the basics needed:

  1) An entity that represents the store. That can either be the user, a store entity clicked together through the ECK module, or a store entity provided by a module.

  2) Entityreference. Then a bunch of entityreference fields that point to the "store" entity (or user). One on products, one on product displays, one on orders.

  3) Form alters that hide the entityreference fields on product displays and products (or just use a "hidden" widget) and fill it in with the known value (you always know which store the user has. If not, give him a dropdown...).

  4) A custom submit handler for the add to cart form (replacing the existing submit handler) that adds a product to an appropriate order (since there's an order per store for each customer), and if the order doesn't exist yet, creates it and sets the value of the entityreference field.

  5) Custom view for cart/ that shows all active carts to a customer.

  6) Custom views filtered by the entityreference field that show the merchant the products and orders for his store.

Organic Groups fits neatly on top. You then need to figure out how you're handling payments, see the linked issue for various approaches.


Why can my view not access the data of a new node when using Rules event After saving new content? Using the Rules module and Drupal 7, I set up a rule "After saving new content of type X".

This is what I want to happen when adding a new content of type "X":

  Based on its nid, call a view, which returns back a JSON, from where I fetch the info to work later. The info I need is on this view, not in the node I am inserting, but to get this view I need the nid and some other info from the node I am creating

The problem is that even if I get the nid of the new node, when I call the view it just returns an empty result. It seems like the data it's still not on Drupal database, so the view results empty. I tried to add a sleep(10) before calling the view, giving some time to Drupal, but no success.

The Content is published, and I added also a 'Save entity' Action to the Rule

Hope with this code here helps to understand; it's in Editing action "Execute custom PHP code", "After saving new content of type X"

dsm($node);  //I can see al attributes from the node I am inserting

$url="http://localhost/bopa/?q=export_cultivos/$node->nid";

dpm($url);

//it gives me a correct URL, that tested later directly on the browser, works
//If instead of $node->nid I use an existing nid, I get back results correctly, so the code below is correct

sleep(10);
$data=file_get_contents($url);

$data2 = json_decode($data,true);

dsm($data2);
//EMPTY array

IMO your "issue" (about "It seems like the data it's still not on Drupal database, so the view results empty") is because of the event (= "after saving new content") you are using, which might simply not be the right event.

Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).


8: How to specify multiple css media types in a libraries.yml file Entering the list "screen, print" doesn't work:

base:
  version: VERSION
  css:
    theme:
      css/styles.css: { media: screen, print }

The resulting HTML should be:

<link rel="stylesheet" type="text/css" href="css/styles.css" media="screen,print" />

css/styles.css: { media: "screen,print" }      # outputs media="screen,print" (WORKS!)
css/styles.css: { media: ['screen', 'print'] }  # outputs media="screen print"


Painless way to import content from old custom CMS I am building a Drupal site (first ever) for a company that wants to move off of an outdated custom built CMS.

They have alot of content and we are pretty much keeping the content layout (fields) the same. And of course they want to have there content in the new Drupal site.

The Drupal database structure is pretty complex and I doubt a few simple insert queries will do the trick. I have written Python scripts to do stuff like this is in the past but not with a DB as complex as what Drupal sets up.

What options do I have for importing the old content into Drupal?

"Painless" data migration? You're kidding, right? :)

There are numerous answers suggesting the Migrate module. It is certainliy an option, but one I've never liked. I've done dozens of projects with migrations of content from external systems into Drupal (sometimes from multiple external sources simulteneously), including projects with millions of pieces of content, and I'll argue 'til my death that a Batch API implementation in a custom module is the way to go.

No two migrations are the same. Each individual migration will involve 'proprietary' cleanup, data sanitization/changes, etc. The only way to have total control is with an entirely custom script. Don't settle for an easy "80% of the way there" via a generic tool and then struggle for weeks as you bash yourself against that 20% that the tool doesn't handle.

Do it custom, use Entity Metadata Wrappers, and track legacy <--> new content ids in a separate db table.

It may also be an option to simply 'dump' the existing content, markup and all, into a 'legacy' content type and call it a day without moving things into fields and complicating your life. You should sit down with the client and figure out exactly what they want/need, and what they're willing to settle for. Sometimes a simple solution that is just "okay" is a heck of a lot better than the multi-month project that's "awesome."


How to embed and render an entityform I have an entityform called 'foia_generator' and I'm trying to embed it as a contact form on a page (the tutorial I used is for embedding entityforms in blocks) ... hence my problem...

function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    echo drupal_render($render_estimate_form);
    return $form;
}

This displays the form but it's not 'inside' the normal bounds of the site (using bootstrap subtheme) i.e. it's not rendered properly - it appears before the regular divs like the navbar etc... and spans the entire width of my screen.

If I can't do it this way can I programattically embed the 'entityform' on my 'contact page' as an entityreference field, (rendered)?

Thanks

Seems like a odd piece of code you've got there, for instance this will render your form randomly in the page:

    echo drupal_render($render_estimate_form);

Which is probably what you're noticing already, that example you're linking is for render that piece of code inside a template but for what you describe you're rendering it in a form inside a block, I'd try something like this instead (untested):

function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    $form['foiagen'] = $render_estimate_form;
    return $form;
}


How are values passed from the database to the templating system? I haven't quite figured out how Drupal passes the values from the database or the back-end to the theme variables in the template.

Which function does it use to disperse the variables to the corresponding template?

The function that does the job is theme_render_template(), which contains the following code.

  // Extract the variables to a local namespace
  extract($variables, EXTR_SKIP);

  // Start output buffering
  ob_start();

  // Include the template file
  include DRUPAL_ROOT . '/' . $template_file;

  // End buffering and return its contents
  return ob_get_clean();

The function is called from theme(), which uses the following code.

// Default render function and extension.
$render_function = 'theme_render_template';
$extension = '.tpl.php';

// The theme engine may use a different extension and a different renderer.
global $theme_engine;
if (isset($theme_engine)) {
  if ($info['type'] != 'module') {
    if (function_exists($theme_engine . '_render_template')) {
      $render_function = $theme_engine . '_render_template';
    }
    $extension_function = $theme_engine . '_extension';
    if (function_exists($extension_function)) {
      $extension = $extension_function();
    }
  }
}

// In some cases, a template implementation may not have had
// template_preprocess() run (for example, if the default implementation is
// a function, but a template overrides that default implementation). In
// these cases, a template should still be able to expect to have access to
// the variables provided by template_preprocess(), so we add them here if
// they don't already exist. We don't want to run template_preprocess()
// twice (it would be inefficient and mess up zebra striping), so we use the
// 'directory' variable to determine if it has already run, which while not
// completely intuitive, is reasonably safe, and allows us to save on the
// overhead of adding some new variable to track that.
if (!isset($variables['directory'])) {
  $default_template_variables = array();
  template_preprocess($default_template_variables, $hook);
  $variables += $default_template_variables;
}

// Render the output using the template file.
$template_file = $info['template'] . $extension;
if (isset($info['path'])) {
  $template_file = $info['path'] . '/' . $template_file;
}
if (variable_get('theme_debug', FALSE)) {
  $output = _theme_render_template_debug($render_function, $template_file, $variables, $extension);
}
else {
  $output = $render_function($template_file, $variables);
}


Switch Site Name depending on URL I'm looking to switch my Site Name (admin/config/system/site-information) depending on what url I'm at.  So if I was at www.example.com/cat I could have the site name be Cats and if I was at www.example.com/dog I could have the site name be Dogs.

Doe anyone know of a module that has this functionality?

I know that this is similar to a multisite, but I just need to create a bunch of tiny blogs and a multisite seems like overkill.

One approach would be to use the Domain Access module.  Not sure if you can use it with subdirectories, but you can use it with subdomains.  Basically, you would create an "affiliate" (module's term for a site) for dogs and one for cats, and configure as needed.


Delay ajax call on textfield to allow for typing I would like to delay ajax from firing in the same way that the autocomplete seems to work. For example, if a user it typing, the ajax will not run until 500ms has elapsed since the last keyup.

I am currently looking at drupal.behaviors but not able to make it work.

Drupal.behaviors.mymodule = {
  attach: function(context, settings) {
    $('input.andtimer', context).delay(500).ajaxStart();
  }
};

This is the form element to which the behavior is attached.

$form['my_input'] = array(
  '#type' => 'textfield',
  '#default_value' => $value,
  '#ajax' => array(
    'callback' => 'my_callback',
    'event' => 'keyup',
    'wrapper' => 'my_wrapper',
    'trigger_as' => array(
      'name' =>  'my_button',
  ),
  'progress' => array('type' => 'none'),
  ),
  '#attributes' => array(
    'class' => array('andtimer'),
  ),
);

This jsfiddle shows what I am trying to achieve.

Would How to override Drupal.ajax.prototype.beforeSend? be a route to take this down?

The following works for the first 'set' of inputs with the class .andtimer. It is not working for any other set, the ajax always continues with the first set. Any ideas how to fix this?

(function($, Drupal) {
    Drupal.behaviors.bform = {
        attach : function(context, settings) {

            var events = $('.andtimer').clone(true).data('events');
            $('.andtimer').unbind('keyup');
            var typingTimer;
            var doneTypingInterval = 300;
            $('.andtimer').keyup(function() {
                clearTimeout(typingTimer);
                typingTimer = setTimeout(doneTyping, doneTypingInterval);
                function doneTyping() {
                    $.each(events.keyup, function() {
                        this.handler();
                    });
                }

                return false;
            });
        }
    };
})(jQuery, Drupal);

Using $form['my_input']['#ajax']['event'] = 'finishedinput' as suggested and

var typingTimer;
var doneTypingInterval = 600;

$('.andtimer').on('keyup', function (e) {
  clearTimeout(typingTimer);
  if ($(this).val) {
    var trigid = $(this);
    typingTimer = setTimeout(function(){
      trigid.triggerHandler('finishedinput');
    }, doneTypingInterval);
  }
});

Works for each 'group' of inputs where the count of filled inputs needs to be obtained.

One option is to use a custom jQuery event, eg. something like finishedinput. Set $form['my_input']['#ajax']['event'] = 'finishedinput' and provide some JS to trigger your custom event after an appropriate delay (similar to the JS in the fiddle).


OutboundPathProcessor is not appending $options array? I have a simple OutboundPathProcessor that should append a query string and a URL fragment, but nothing is happening.

mymodule.services.yml

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MyModulePathProcessor
    tags:
      - { name: path_processor_outbound }

MyModulePathProcessor.php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

class MyModulePathProcessor implements OutboundPathProcessorInterface {

  function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

    $options['query']['foo'] = 'bar';
    $options['fragment'] = 'baz';

    return $path;
  }

}

It seems the $options array is passed by reference, and in fact LanguageNegotiationUrl::processOutbound is placing multiple values in the $options array.

Why doesn't my code work?

I just figured out that it does work if I add a URL prefix using $options['prefix'] = 'prefix/';, so some options are getting applied.
Why aren't fragment and query used?

It seems there is a bug report for that. I found a reference to that issue in a inline comment inside LanguageNegotiationContentEntity::processOutbound().

At the moment, after applying the patch from that issue, query parameters get added to the URL as you would expect and without any need to instantiate 'prefix', but fragment doesn't. More work/comments should go into that issue to assist with resolving it.

As an alternative and in order to get fragments to work, you could try extending the Drupal\Core\Routing\UrlGenerator and replace the url_generator.non_bubbling service. (See https://www.drupal.org/node/2026959.)


the menu is not being displayed when the first parameter is user My problem is as follows the path user/%user_uid_only_optional/profile is not displayed.
If I try a variation of this and instead of having user, I replace user with usr the menu items is displayed. I know there was an issue with the page callback and I understand the issue of why it didnt work. That a boolean variable is not an expectable parameter for the page callback.

Line 1: line one is taken from the pro development book.
Line 2: line two shows the title (the title is displayed this line
works)
Line 3: description is correct i checked syntax
Line 4: the page callback seems fine unless this isn't the correct
format. I am quite sure that it follows what is in the
documentation.
Line 5: the number of arguments are needed is one. Since I have only
one %
Line 6: access arguments seems to be ok i checked the different
permission in drupal under users and that is the edit person that i
used.
Line 7: I looked at the menu type and it discusses at the parents
level if you want to use the local version of the menu you type

$items['usr/%currentuser/edit'] = array(
    'title' => 'Profile', // The link text
    'description' => 'My Profile',
    'page callback' => 'editprofile', // the function to be called when link is clicked [below]
    'page arguments' => array(1), // arguments for the callback function 'profile_use_page'
    'access arguments' => array('edit own profile'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu', // You'll need to have a menu named my_menu for this to work
                              // If not specified, it will default to 'navigation'
  );

    function editprofile($user_id) {
      return 'user_id'. $user_id;
    }

From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7:

"page callback": The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

So page callback has to be omitted to fallback on the parents callback or has to be a function.


How do I retrieve node data for a referenced node in a template file? I have two content types, Event and Gallery. Each Event has a node-reference field to a gallery. I am now trying to style the gallery node page from inside the template file. I need to have a way of creating a link which links back to its parent, the Event.

How can I find this information?

it seems you need to know value of node which is referring the current node.
I am assuming machine name for the refernce field you have on event content type as "field_event_gallery"

In your custom module or template.php
// function to get backrefernce value.

function mymodulename_get_back_refernce_value($current_nid) {
  $nids = array();
  $results = db_select('field_data_field_event_gallery','n')
            ->fields('n',array('entity_id'))
            ->condition('field_event_gallery_nid',$current_nid)
            ->execute()
            ->fetchAll();
  if(is_array($results) && count($results) > 0) {
    foreach($results as $result) {
      $nids[] = $result->entity_id
    }
  }
  return $nids;
}

Now in your theme template.php use template_preprocess_node(),something like below

function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'gallery') {
    //get referring nids
    $referring_nids = mymodulename_get_back_refernce_value($variables['node']->nid);
   if(count($referring_nids) > 0) {
     foreach($referring_nids as $referring_nid) {
       $referring_node = node_load($referring_nid);
       $variables['parent_event_link'][$referring_nid] = l(t('View parent event: @event_title', array('@event_title' => $referring_node->title)), 'node/' . $referring_nid);
   }
  }
}

finally in your template loop through $variables['parent_event_link'] and print it.

My codes are not tested, you have to debug to make them workign for you


extend('PagerDefault') doesn't call pager_default_initialize My code:

   $num_per_page = 1;

   $query = db_select('redagavimas', 'r')
      ->fields("r");
   $query->join('dusers', 'd', 'd.id = r.user');
   $query->join('companies', 'c', 'c.id = r.company');
   $query->join('documents', 'doc', 'doc.id = r.doc');

   $query->addField('d', 'name');
   $query->addField('d', 'surname');
   $query->addField('c', 'name', 'company');
   $query->addField('c', 'id', 'companyID');
   $query->addField('doc', 'name', 'docname');
   $query->addField('r', 'user', 'did');

   $query->extend('PagerDefault')->limit($num_per_page);
   $query->extend('TableSort')->orderByHeader($header);

   ....

   $result = $query->execute();

   ....

     '#suffix' => theme('pager', array( 'tags' => array())),

I don't see any pager; If I call somewhere pager_default_initialize(), then I see the pager. What I did wrong?

EDIT :

I try:

echo $query->extend('PagerDefault')->limit($num_per_page)->getCountQuery();

and get query, which return >100 rows.

As documented on the See the Extenders page on drupal.org:

  To use an extender, you must first have a query object. From the query object, the extend() method will return a new object that should be used in place of the query object. For example:

$query = $query->extend('PagerDefault');

  The above line takes a select query, creates a new PagerDefault query object that contains the original select query, and returns the new object. $query may now be used as if it were the original query object but with additional methods now available.

  Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost. For example, the following will not do what you expect:

So, you first line should looks like:

$query = db_select('redagavimas', 'r')->extend('PagerDefault')->fields("r");


How to Set Hidden Form Field Values Permanently via Form Alter I have a webform that gets some hidden form fields set based on the referring URL.  Within hook_form_alter, I can successfully set the hidden values with $form[elements][NAME]['#value'].

function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

 //Get referring Program path/URL
 $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');

 if ($form_id == FORM_ID) {

    $prog = getLeadProgramContact($previousUrl);
    $form['elements']['referrer']['#value'] = $prog->field_email->value;
    $form['elements']['program_name']['#value'] = $prog->getName();
     }
}

However, when the form gets submitted, it appears hook_form_alter is called again, breaking everything, since the referring URL is now itself.

How can I permanently set hidden field values on initial form render?  Anything I try with hook_form_alter seems to fail.  I have also tried "#default_value"

Ok webforms are a bit tricky ... but this will work i don't really care to set hidden fields just set the data direct to the entity.

if this is not a multy step form you could probably ad another submit handler in your form alter aka ...

function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if ($form_id === FORM_ID) {
     $submit[] = 'MODULE_form_alter_submit';
  }
}
// then
function MODULE_form_alter_submit(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     // get the data you need.. via this ..
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $prog = getLeadProgramContact($previousUrl);
    // or ($_GET) or session or cookie whatever you chose.. Then set    it

    // GET the form Object.
    $webform_submission_object = $form_state->getFormObject();
    // GET the submission object.
    $webform_submission = $webform_submission_object->getEntity();
    // Optioanl default values if need to play with them ..
    $orig_data = $webform_submission->getOriginalData();
    // set form state
    $form_state->setValue('referrer', $prog->...);
    // set submission field value.
    $webform_submission->setElementData('referrer', $value);

    $form_state->setValue('program_name', $prog->...);
    $webform_submission->setElementData('program_name', $value);
    // Save it so it cant go away.
    $webform_submission->save();

  }
 }
}


Overriding core forum function is there any clean way to override _forum_topics_unread function call from template_preprocess_forum_list without hacking the core?

No, hardcoded function calls can not be replaced.

The only thing you can do is add your own preprocess function for "forum_list "(yourmodule_preprocess_forum_list()), and then call another function to overwrite the value returned by the function.


Why will drupal not recognize my configuration? I am trying to import configuration from one site to another.  I have copied the directory full of config files from an older site to my new site.  When I try to run Drush cim, the files all show up as they will be created.  However, after answering yes to the prompt I get
This import is empty and if applied would delete all of your configuration, so has been rejected. in Drupal\Core\Config\ConfigImporter->validate() (line 756 of
/home/vagrant/code/indigo-signs-pantheon/web/core/lib/Drupal/Core/Config/ConfigImporter.php).
The import failed due for the following reasons:                                                                                [error]
This import is empty and if applied would delete all of your configuration, so has been rejected

I found this question and tried changing the UUID like suggested, but it didnt change anything I still get the same error.
Any suggestions

This import is empty

This error might occurs when the config directory is not configured in the settings.php.
Check for the config directory settings in new site. It will mostly have a different directory configured.
Change to the same folder path as in the old site.


Predefined webform configuration for specific content type I'm new to Drupal, I need to create a job list page with an application form for each of the job listings presented in it.

I've created a "Job" content type, and installed the webform module

When I create a new Job, I'm able to create a form and present it in the content of the job.
The problem is that it has to be done for each specific job listing manually

Is there a way to set the configuration of the webform attached to a specific node by its content type?
A code based solution is preferred - but one that is based on action in admin UI is also blessed

Thank you very much!!

Yes, You can able to do it using admin UI.

Follow below instruction.

Add new field (boolean type) at webform content type.

Make this field as a checkbox.

Add "Entityreference" module

enable it

Create entityreference view using views UI for webform content type and add above created boolean field in FILTER CRITERIA  select operator > is one of "yes"

I have attached snapshot for views UI

Now edit manage field on job content type

Add new field on job content type give the name and select "Entity Reference" in data type.

Now select "select list" option for widget click on next button.

Next page will be shown Entityreference option at there you need to section "view" for the first drop down "Views: Filter by an entity reference view" and second "View used to select the entities" pick you entity reference view which you have created prviously and save it.

Snapshot for above description

Now you will able to select created webform on job node.


Drupal doesn't invoke a hook function until I don't clean the cache I created a module, and implemented hook_form_alter() using the following code.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mymodule_form_id') {
    $form['#validate'] = array('mymodule_form_validate');
  }
}

Drupal can call the function correctly, and run well for several days.

But one day Drupal did not call the function anymore, until I cleared the cache. Why?

The reason why clearing the caches fixed the issue is because all hooks are cached in Drupal 7 via module_implements(). My guess is something odd happened to your cache and thus your hook went missing from the cache.


How to generate a List of Dates with Start/End sorted by Month in Drupal7? I have installed Drupal7 and created a content type (why not call it 'event' for now) to which I added a date field (lets name it 'event-date'). Some event-dates have start- and end-dates.
Now I want to generate a list of these events sorted by Month, where every event is listed in one line, even the events with start- and end-dates should have one line for every day the event lasts - not only the start-till-end-row listing.
for example instead of

JANUARY
Mo, 04/02/2013 - 20:00 to Th, 06/02/2013 - 20:00  Event1

I need

JANUARY
Mo, 04/02/2013 Event1
Tu, 05/02/2013 Event1
Th, 06/02/2013 Event1

How could I realize that? thnx!

You will have to use Views and Group by Month then by Day.

http://www.jeremyfrench.co.uk/node/1461


Get submitted value of a select list error on #options - Drupal 7 I have seen this block of code in a few places as the correct method:

$selected_index = $form_state['values']['select_field'];
$display_value = $form['select_field']['#options'][$selected_index];

So here is my code for it:

$key1 = $form_state['values']['field_setup_time3'];
$reservationStartPadding = $form['field_setup_time3']['#options'][$key1];

But I get this error with my code:

Notice: Undefined index: #options in ... blah blah blah

I am using a List (integer) running a select list with 4 options in it. Is options not the right choice here? I just need the numerical value from the user selected dropdown list when they submit the calendar booking.

Thanks!

Thanks to tenken and Clive I was able to figure it out.

$key1 = $form_state['values']['field_setup_time3'];

This line outputted as a string. Since I was only using integers in my select list, the label and key value were the same. I removed both lines of code and replaced it with this (after some playing around with devel):

$reservationStartPadding = $form_state['values']['field_setup_time3']['und'][0]['value'];

This outputted the value as a number and not as a string. I was able to use it from there in my future code correctly.


How to require one of many modules in your own module? Let's say my module needs functionality X. This functionality can be provided by two other modules. For example, front-end with two backends to store data, and at least one backend is needed for frontend to work. Is there a way in Drupal to mark it?

In GNU/Linux and BSD operating systems there usually is a marker like provides, for example Bison provides Yacc, and everything that would need a Yacc can work with only Bison installed. That's about what I'm looking for here.

One option is to feature detect the modules using function_exists() or class_exists(), and then use some logic to pick the one you want.

You can also wire up a hook_requirements() to hard fail in the $phase == 'install' step or soft fail in the $phase == 'runtime' step.

How you handle the failures really depends on your application.


hook_menu shows in menu but not show page I made module, and want to add settings page.

Menu Item appear in settings dashboard, but when try access page it display dashboard with menu items again, thought URL is correct.

return array(
    'admin/store/settings/vsl_spl'=> array(
        'title' => 'SPL Settings',
        'description' => 'SPL Settings Page',
        'page_callback' => 'vsl_spl_page_test',
        'type' => MENU_NORMAL_ITEM,
        "access arguments" => array('access administration pages'),
        'position' => 'left',
        'weight' => 10,
    ),
)

and callback function is just for test yet

function vsl_spl_page_test(){
    return '
Test
';
}

Page opens with status 200 but content is wrong.

It's just a typo. Remove the underscore from page_callback.


Drupal 7.8, Webform 3.x w/ AJAX - #process callbacks cannot be found for select components We've written some custom module code to AJAXify Webforms using Drupal 7's new #ajax actions.

There's one small snag with the forms though. We're returning the form element for processing when it does not validate, and the form is rendered and returned to the client. This works well for everything except for components that require additional processing (using #process callbacks, e.g. webform_expand_select_ids, webform_expand_checkboxes). When the form is submitted via AJAX, Drupal isn't loading Webform's component includes so it cannot find the callback functions.

To get around this, I've added code to the core form.inc to load the component's include file so form_builder() has access to it, which obviously isn't the best way to achieve this. This allows checkboxes/selects to be rendered properly at least.

function form_builder($form_id, &$element, &$form_state) {
    if (module_exists('webform')) {
        module_load_include('inc', 'webform', 'components/select');
    }

...

Is there a way to force Drupal to load a required module when using the AJAX system?

I've used the steps outlined at http://envisioninteractive.com/drupal/add-ajax-to-a-webform-in-drupal-7/ which works well, except for these few issues.

There is the form_load_include() function that is invoked during the initial form build and before form_builder(). You can include this in a hook_form_alter().


Separate permissions for administering user configuration and administering users In Drupal 7 there is one permission for administering users, "Administer users".

This covers both the main user management page at 'admin/people/permissions', and the configuration of settings/fields for the user entity at 'admin/config/people/accounts' and 'admin/config/people/accounts/fields'.

A very common requirement for a site that's being released to a client is that they can administer the users (fair enough right?), so they need the "Administer users" permissions.

However, granting that permission also gives them access to edit the user entity settings/fields, which is very undesirable (no client should be able to change the underlying structure of the user once it's been set up, for obvious reasons).

This must be something a lot of people have to deal with...what methods/modules/custom code do people use to get around this limitation in the user module?

One method is to create a new permission

function MYMODULE_permission() {
  return array(
    'administer user configuration' => array(
      'title' => t('Administer User Configuration')
    )
  );
}

and then re-assign the pages under 'admin/config/people' to that permission:

function MYMODULE_menu_alter(&$items) {
  foreach ($items as $path => &$item) {
    if (strpos($path, 'admin/config/people') === 0) {
      $item['access callback'] = 'user_access';
      $item['access arguments'] = array('administer user configuration');
    }
  }
}

Then the user role in question can have the 'Administer users' permission, but not have access to the admin/people/config pages.

This feels messy at best though.


Is taxonomy a good choice for managing Code Lists, instead of creating tables of their own? I have a project where there is a set of code lists (code/label), Airport codes for example.

I am hesitating between creating my own tables, with two columns code/label and using Taxonomy (fieldable \o/ )
Any suggestions ?

Since there isn't anything common between codes and labels, I think you should create your own table.

Also see How to Decide Between Using Taxonomy Terms and a CCK Field


Can local actions have multiple parents? I have a module that I am working on that defines some local tasks and local actions for node pages, eg

$items['node/%node/foo'] = array(
  'title' => 'Foo',
  'page callback' => 'foo',
  'type' => MENU_LOCAL_TASK,
);

$items['node/%node/bar'] = array(
  'title' => 'Bar',
  'page callback' => 'bar',
  'type' => MENU_LOCAL_ACTION,
);

This works mostly great.  'Foo' appears as a new tab on node pages, and 'Bar' shows up as a local action on the 'node/%node' page.

I would like my 'node/%node/bar' local action to also show up on the 'node/%node/foo' page as a local action.  Is this possible?  I have tried playing with the 'tab_parent' and 'tab_root' parameters, but this only seems to work with local tasks and it also doesn't seem to allow multiple parents.

I believe it's always Many (Local Actions) to one (Parent Item) relationship as hook_menu documentation says

  MENU_LOCAL_ACTION: Local actions are menu items that describe actions
  on the parent item such as adding a new user or block, and are
  rendered in the action-links list in your theme.

If you want to change the parent of local action you can do it using tab_parent

  $items['node/%node/bar'] = array(
      'title' => 'Bar',
      'page callback' => 'bar',
      'access callback' => TRUE,
      'tab_parent' => 'node/%/foo',
      'type' => MENU_LOCAL_ACTION,
  );

Above displays action link in node/%/foo instead of node/% , tab_parent accepts single string argument... So we can rule out option of sending multiple parents using array.. For deeper analysis you can refer

function menu_local_tasks() in menu.inc which is responsible for action items and local tasks rendering..

If you would like to see it in action both places you can try below..

As @awm pointed out in comment we can add it to other pages using hook_menu_local_tasks_alter, Here is how node module does to include node/add menu item as local action to admin/content using hook_menu_local_tasks_alter

/**
 * Implements hook_menu_local_tasks_alter().
 */
function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'node/add' on 'admin/content' page.
  if ($root_path == 'admin/content') {
    $item = menu_get_item('node/add');
    if ($item['access']) {
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
}

So you can do same for your own implementation using below code

/**
 * Implements hook_menu_local_tasks_alter().
 */
function YOURMODULENAME_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'node/add' on 'admin/content' page.
  if ($root_path == 'node/%/foo') {
    $nid = arg(1);
    $item = menu_get_item('node/'. $nid . '/bar');
    if ($item['access']) {
      $data['actions']['output'][] = array(
          '#theme' => 'menu_local_action',
          '#link' => $item,
      );
    }
  }
}

Results in


How stop HOOK node form submit My question is in the title, when i add a new element of entity "intervenant" I check, if there is already an intervenant with the name used in form_state, if the query returned me a result, i want to stop the insert into and be redirected in my front page.

I used return FALSE;

But it's didn't work.. You can see my code :

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'intervenant')
    ->fieldCondition('field_int_projett', 'target_id', $idProject, '=')
    ->fieldCondition('field_int_numero_lot', 'value', $lot, '=')
    ->fieldCondition('field_int_intervenants', 'target_id', $intervenant_id, '=')
    ->propertyCondition('status', 1);
$intervenant_externe_pjt = $query->execute();

if(!empty($intervenant_externe_pjt['node'])) {
    return FALSE;
}

How can i stop the submit, if it's possible ?

Thanks

Stopping a submit is best done in a validation function. You need to have this code in a custom validation handler that you add to the form, and then you set a validation error on it.

Learn how to add custom validation to an existing Drupal form

Redirecting on form validation fail seems to be a problem. Look here for workaround:

Redirect form in validation fail

As to hook_node_submit, the docs have this to say:

  Act on a node after validated form values have been copied to it.

  This hook is invoked when a node form is submitted with either the
  "Save" or "Preview" button, after form values have been copied to the
  form state's node object, but before the node is saved or previewed.
  It is a chance for modules to adjust the node's properties from what
  they are simply after a copy from $form_state['values']. This hook is
  intended for adjusting non-field-related properties. See
  hook_field_attach_submit() for customizing field-related properties.

This hook is not a good place to try and stop submission, as form validation has already passed. It is therefore assumed that the node should be saved to the db.


Easiest way to get term entities from a term reference field? I always end up with lots of juggling to get seemingly simple things, like "All term names".

$field_terms = field_get_items($entity_type, $entity, $tags_field);

if ($field_terms) {
  $tids = array();
  foreach ($field_terms as $field_term) {
    $tids[] = $field_term['tid'];
  }
  $terms = taxonomy_term_load_multiple($tids);

  $tags = '';
  foreach ($terms as $term) {
    $tags .= $term->name . ',';
  }
  $tags = rtrim($tags, ',');
}

Can anyone share any neat tricks for making the above easier?

The part that really annoys me is the first loop, that I need just to untangle the field api array.

This one annoys the bejesus out of me too. Things are slightly nicer using the entity API module, but it's still not pretty.

I've resorted to including a helper function in most projects now to extract an array of values for a single field column:

function _field_get_column_values($entity_type, $entity, $field_name, $column_name) {
  if ($field_items = field_get_items($entity_type, $entity, $field_name)) {
    $values = array();
    foreach ($field_items as $item) {
      if (isset($item[$column_name])) {
        $values[] = $item[$column_name];
      }
    }
    return empty($values) ? FALSE : $values;
  }

  return FALSE;
}

Using that your code would shrink a little:

if ($tids = _field_get_column_values($entity_type, $entity, $tags_field, 'tid')) {
  $terms = taxonomy_term_load_multiple($tids);

  // ...
}

It's still not a great solution, but I find it saves a fair bit of time on projects that need a lot of custom code.


Dynamically populate one select based on another I'm new to Drupal and well aware this question has been asked before, but I couldn't find a situation similar to mine, or maybe I didn't understand it.

I have three content types:

Team with fields Team Name.
Game with fields Team 1 and Team 2, an entity reference to the Team content.
Vid content type which has a select box for games (entity reference) which I'm able to populate.

On selection of game, the teams (Team 1 and Team 2) should be populated in the select box of another field say Pass.

One game can have two teams, several teams exist and each team can be involved in different games.

I've tried the hierarchical select module, conditional select, entity reference limit option, creating views and populating the entity reference, and tried Rules as well, but either I couldn't work through it or couldn't find the right setup.

Can someone point me in the right direction to solve this problem?

Try conditional_fields

Update multiple fields with ajax callback in form


validate commerce order pre-placement A product in Drupal Commerce 2 has limited stock. Users can add-to-cart so long as there is a current stock value > 0, and stock is decremented at the order-placed stage. If a second concurrent user passes the order-placed stage first and has used all available stock, when user 2 gets to the order-placed stage I want to take action  (remove item from cart, show a message, do something if no other items in cart..).

I am catching 'commerce_order.place.pre_transition' event, and can manipulate order items, but I'm not sure if I'll mess up other DC processes. Would it be better to have a CheckoutPane plugin to do something pre-placement at/after the Review stage, or something else? The action needs to be taken just pre payment attempt.

I created a CheckoutPane plugin which worked well in order-information step as it can can include form fields so can use form-validate function to stop progress until cart manually corrected.
In theory the stock could change between order-information and review steps. The panel is automatically processed in review step but it is only a display string not a form so cannot enforce anything here.

It is possible to use  HOOK_form_FORM_ID_alter (mymodule_form_commerce_checkout_flow_multistep_default_alter) which is called on submit of review step - so can add a validate function and stop things

The Pane approach gives a better UI space for explaining things to user as HOOK.. can mostly only generate a validation error.


Image wrapper by img tag with external url I want to customize image field so as I am able to add external url and display in node without save locally.

The image is already online to another site. For example www.example.com/imageurl.jpg. The only thing I want to do is to wrap this on a drupal field like this <img src="www.example.com/imageurl.jpg"/>

Is there any solution?

Thank you

You can use the Media module to get external images via their URL and show it in the node page.

By saving locally if you mean 'locally' in the server that is running Drupal then it doesn't do that. To achieve it you will need a separate server like Amazon S3 to store your images alone.


D8: The same content type, but different url path aliases pattern based on paragraphs. Possible? I have several paragraphs nested into one content type. Users can add only one type of paragraph. Is it possible to create a url alias pattern based on paragraphs? For instance, I have paragraphs "car", "bike", and "boat" in one content type "garage". If the user adds a "car" paragraph the url alias should be garage/car/etc, and for boat garage/boat/etc etc. Possible? It is generating the same url pattern for now.

Since you mention that you only have a single allowed paragraph, something like [node:paragraph_field:entity:type:target_id] might work, but untested. That will use the machine name of the referenced paragrap type.

If not, you can always implement a custom token on nodes and then do whatever you want using hook_token_info() and hook_tokens().

I also agree with others that this seems like a somewhat strange architecture and usually list/term fields are used for such a categorization, this will most likely also work better if you ever need to do something like an exposed filter in a view and so on.


How to show new added filed to comment table in comment form page I am writing a module which is adding a new filed to comment table, and in the comment form I want a new filed to be displayed, saying: : " Which paragraph you want to put comment on?".

I have already added the new filed to comment table, I just do not know  what hook should I use, so this new filed will be also shown on comment form.

First, you need to make sure Drupal knows about your paragraph field. Adding it to the database alone won't work. Use hook_schema_alter() to alter the DB schema information for the comment table. Do this by adding something like the below to your module's install file (a PHP file you name mymodule.install in your module's folder):

function MYMODULE_schema_alter(&$schema) {
    $schema['comment']['fields']['paragraph'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'default' => 0,
        'description' => 'Paragraph of the comment.',
    );
}

Be sure to flush your caches to update the schema.

Now you need to alter the comment form, and process the paragraph value. Something like the below should work:

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

    $form['#validate'][] = 'MYMODULE_form_comment_form_validate';
    $form['#submit'][] = 'MYMODULE_form_comment_form_submit';
}

function MYMODULE_form_comment_form_validate(&$form, &$form_state) {
    if (!is_numeric($form_state['values']['paragraph'])) {
        // Validate the paragraph value to make sure it is numeric. Non-numeric values will break because we created paragraph as an integer field
        form_set_error('paragraph', t('Only numeric values are allowed for paragraph number.'));
    }
}

function MYMODULE_form_comment_form_submit(&$form, &$form_state) {
    // update the paragraph field in the comment table
    db_update('comment')
    ->fields(
        array(
            'paragraph' => $form_state['values']['paragraph'],
        )
    )
    ->condition('cid', $form_state['comment']->cid)
    ->execute();
}


Page title with substitution on views page I have a view page that requires a dynamic page title. It is a simple substitution of the label field.

If I use {{ label }} it works fine for the title displayed on the page, but it doesn't substitute the label for the actual page title (in meta)

I was able to fix this by using hook_views_post_render using the following code

// Set the route title.
$route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
$route->setDefault('_title', $title);

$view->setTitle($title);

However, the title only works if the page is not cached. For the cached pages, the page title is missing. This feels like a bug in drupal, but I am hoping that there is a simple way to get this done.

You can't change the route object in a hook. Use a RouteSubscriber to add a dynamic _title_callback to the view route.

Otherwise setTitle() should work. The bug you've described is not a bug. It's about caching in general. When you add dynamic data you also have to add the cache metadata, which defines what kind of dynamic data this is.

For example if the dynamic title depends on the node 123:

$output['#cache']['tags'][] = 'node:123';


How to disable automatically generated comments in node, but enable programmatically created comments? I decided to programatically print comments un Views using PHP footer. The problem is that they now appears twice (my code + default). When I disable comments in content type settings, both disappear. How can I disable the default comments and keep my comments printed by php code? I tried to edit node.tpl file. but there is no section responsible for showing comments there (I use Garland).I do this because I am using a complicated views structure and I would like the comments to be displayed below the node, but not at the end of the whole view. Any advice appreciated.

Configure comments to be show in separate page, and you'll be able to show them with your view. Also, you've to hide the comment link if you do it.


Changing '#view_mode' in content type's render array I have a content type in Drupal 8 project that has image, name, info and body field as a default display, and image,name and information as a teaser display. I am able to display this content type with teaser view at the page, but right under that i would like to get the default display along with body field so i can create a bootstrap modal with that.

I am using hook_node_view in the module level to change the #view_mode of that render array to 'full' instead of 'teaser'.

function team_bio_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

if($entity->bundle() == 'about_us'){
 if($view_mode == 'full'){
  if($display->getComponent('field_team_bio')){
    $build['full_view'] =  $build['field_team_bio'];
     $build['full_view'][] = array(
       'full_view' =>array(
         '0'=>array(
            '#view_mode'=>'full'
         ),
         '#weight'=>'103'
       )
    );
    kint($build);

  }
 }
}
}

i can display the content type right under teaser views, but i can't change the view_mode to full. This is what i see when i kint($build):

Current contents have name like '0','1','2','3','4', and they have the view mode that are 'teaser' but i dont how to pass 'view_mode' to 'full'in render array, I am not sure if there is specific name for that or not. Trying this:

     $build['full_view'][] = array(
       'full_view' =>array(
         '0'=>array(
            '#view_mode'=>'full'
         )

didnt change the view_mode neither. So my question: What is the best way to change these view modes to full for the contents? Should I search these numeric keys in the array and pass them to another array then change view_mode like that? Or is there an easier way to approach the problem?

function team_bio_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if($entity->bundle() == 'about_us'){
    if($view_mode == 'full'){
     if($display->getComponent('field_team_bio')){

       $team_bios_full = [
        '#theme' => ['team_bio_full_wrapper'],
        '#weight' => $build['field_team_bio']['#weight'] + 1,
       ];

    foreach(Element::children($build['field_team_bio']) as $delta){
      $team_bio_full = $build['field_team_bio'][$delta];
      $team_bio_full['#view_mode'] = 'default';

      $team_bios_full['#team_bios'][] = $team_bio_full;
    }

    $build['team_bios_full'] = $team_bios_full;
  }
 }
}
}

Then I passed team-bios-full-wrapper into class and render it.Like this:

{%
  set classes = [
  'team-bios-full-wrapper',
  ]
%}
<div{{ attributes.addClass(classes) }}>{{ team_bios }}</div>

Sorry i have different variables, i just rethought and rewrote the code. Hope this helps out someone.


Dependency Injection in Custom Field Widget I am trying to inject the entity query service into a custom field widget.  This is the relevant code:

/**
 * Plugin implementation of the 'address_options' widget.
 *
 * @FieldWidget(
 *   id = "address_options",
 *   label = @Translation("Addresses"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class MyCustomWidget extends WidgetBase {

  /**
   * The entity query factory service.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQuery;

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, QueryFactory $entity_query) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityQuery = $entity_query;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity.query')
    );
  }

The following error results:

  Recoverable fatal error: Argument 6 passed to
  Drupal\custom_module\Plugin\Field\FieldWidget\AddressWidget::__construct()
  must be an instance of Drupal\Core\Entity\Query\QueryFactory, none
  given, called in
  /homedir/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line
  130.

Is it not possible to use dependency injection in this case or am I missing something?

What you are missing is to implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface, which defines the create() method.

See \Drupal\file\Plugin\Field\FieldWidget\FileWidget for an example.


How to delete all data in one field of a particular content type? We have a content type basic page that has a Date field (field_bp_date). We want to use the hook_update to delete all data in this field. We are having trouble figuring out what is the best way to simply delete all data in the field_bp_date field on the basic page content type?

Ideally we would like to do the following:

function mymodule_update_7001(...) {
    $content_type = 'page';
    $fieldDataToDel = 'field_bp_date';

    //some function/hook to delete all the data
    ....
}

If you only need to do this once you could use Views Bulk Operations https://www.drupal.org/project/views_bulk_operations

/admin/structure/views

Click "Add new view" link
Show "Content" of type "YOUR_CONTENT_TYPE"
Click "Continue & Edit" button

Under the FORMAT section change Show: click 'Content' change to 'Fields'

Click 'Apply' button
Click 'Apply' button again

Under FIELDS section click the 'Add' button

Checkmark 'Bulk operations: Content'
Under SELECTED BULK OPERATIONS choose 'Modify entity values' checkbox
Scroll down a little, you will see OPERATION SETTINGS choose that date Field you want to edit.
Click 'Apply' button
Click 'Save' to save that View

Go to the View Page you just created.

Under Operations choose 'Modify entity values'
Select one or all of them (I suggest you do one as a test).
Click the 'Execute' button.
This page will allow you to set the Date to anything you want, even nothing. TIP! for Date if you want no date you need to change all values to blank. You can't delete just the hours, you need to set all of them to blank, which gives you the result you requested.
Click the 'Next' button.
Click the 'Confirm' Button.

Congrats. Go back and run it on all of them, if it went as expected on the one test node.


How can I remove the default value _none in a select list? Created a content type and added a field "list(text)".
Under field settings marked the field as required.( Please make a note of an option for default value where the value is set to None by default).
Started creating content and given all the mandatory fields and left the value of the select-list field to default like 'select a default value' and try to submit the content.
The form gets submitted without HTML5 validation(i.e it is not showing a popup that the field is required to the user while filling the form.) but server side validation is in place so one can observe form error after submitting the form that field list is required.

Noticed the reason behind the HTML5 validation not working is the value for the option is a string '_none'.

How to remove the default value "_none" from select-list.

First unset the value like below.

unset($form['field_registration_type']['widget']['#options']['_none']);

Then set your drop down value to null, like below.

$form['field_registration_type']['widget']['#options'] = ['' => 'Select'] + $form['field_registration_type']['widget']['#options'];

Now your drop down value is null and your validation will work as expected.


Translate website with prefix URL when everything is on domain The website I'm working on has multiple languages and the detection is based on domain name.

I want to add another language, available only to developers, but do not have a domain name for it now. So I would like to know if it is possible for ONE language to be found via prefix, an example structure would be:

http://www.a.com (french)
http://www.b.com (english)
http://www.a.com/ru/ (russian)

Thanks.

No

Not with the core code.

Avaliable solutions

Language Domains would allow you to create alternative domain prefixes, like ru.example.com and www.example.com leading to different languages.
Domain Locale - this one I never used, but it promises to "customize language sets per domain"


How can I get a GMap Marker field to be a target in my Feeds importer? I have site that needs to import a CSV of hundreds of locations to be displayed on a GMap. I have set up an importer in the Feeds module that successfully imports a CSV containing Title, address, longitude and latitude. The properties all appear on my GMap view correctly.

Now, I would also like to assign different colored markers for various location types that I am importing. I have my content type properly set up with a GMap Marker Field (if I manually assign a Marker to each node they appear with the correct markers on my map view). However, on my Feed importer Mapping page, the GMap Marker field is not appearing as a target option in the dropdown list.

How can I get the GMap Marker field to appear as a target option in the feeds importer?

Mapping targets for fields are not automatically available. For each field, a Feeds target must be written. Feeds targets for fields provided by Drupal core should be provided by Feeds itself, but Feeds targets for fields provided by a contrib module, should be provided by that contrib module.

You can do the following:

Open an issue in the GMap issue queue and request a mapper for the GMap Marker field.
Implement the Feeds target yourself. For documentation, see https://www.drupal.org/docs/7/modules/feeds/the-developers-guide-to-feeds/the-developers-guide-to-feeds#mappingapi. While the process explained there still works, the documentation is slightly outdated. The recommended way of adding a target now is to use the hook hook_feeds_processor_targets() instead of hook_feeds_processor_targets_alter(). Also in the target callback, the language of the target can be found in $mapping['language']. See feeds.api.php for more information.


Export and import content from one drupal site to another? I want to export content with comments and user data with content relation from one Drupal site to same version of another site. In another site there is no content and users data it has only some new module installed and it's configuration.

For this which is best way migrate/ node_export/ Backup and Migrate

If you're exporting into an empty site, the Backup and Migrate module is the one you want.  It will let you clone all contents on a Drupal site, including comments.  (Or only certain tables such as thos associated with nodes and comments, if that is what you want).

The Node Export module will only let you import/export nodes.  Comments, for instance, is not nodes.

The Migrate module is a more general framework for migration (including migration data not originating from Drupal into a Drupal site).  It gives you a lot more control over the process, but I think it is overkill if all you want to do is to export and then inport into an empty site with the same version of Drupal.  Incidently, if you still want to use Migrate, check out Drupal-to-Drupal data migration.  It is based upon Migrate, but designed to specifically migrate (and refactor) data from one Drupal site into another.


How to sql-sync database between two remotes which share the same host? I've two remotes: @source and @destination.
I'm trying to transfer the database from dev to test environment by using sql-sync:
$ drush -vy sql-sync @source @destination

But at the end drush complains that:

The source and destination cannot both be remote.
rsync error: syntax or usage error (code 1) at main.c(1166) [Receiver=3.0.9]

Both remotes are on the same machine, but they're using different path.
I'm using latest drush 7.0-dev.
Is there any workaround?

Here is how drush sql-sync works between two remotes:

Logs into remote @destination via SSH and creates destination database if needed via sql-create.
Backs up database on @sourceby performing sql-dump on source unless told otherwise and saves it into drush-backups folder.
Logs into @destination remote via SSH and executes rsync to transfer database from Source to Destination.

Example: rsync @source:drush-backups/db.sql.gz @destination:/tmp/db.sql.gz

To make this work, you have to make sure that:

both local and remote drush have the same version (either 6.x or 7.x),
on Destination the @source alias should be accessible for drush,
rsync tool doesn't support two remotes, so only one may be remote.

Based on above it seems you can't use sql-sync drush command to transfer the database between two remotes in drush 7.x (see: #161).

As for workaround, first dump the database from your source onto your local and transfer back to the destination, in example:

drush @source sql-dump | drush @destination sql-cli

This should transfer the database between two remotes without sql-sync limitation.


Attaching file to node field I have a problem. I'm trying to attach file to node field by this code

function calculator_page_form_validate($form, &$form_state) {
$file = file_save_upload('file', array(
    // Validate extensions.
    'file_validate_extensions' => array(),
    ));
    // If the file passed validation:
    if ($file)
    {
            // Move the file into the Drupal file system.
            if ($file = file_move($file, 'public://cunning_files', FILE_EXISTS_RENAME)) {
            // Save the file for use in the submit handler.
            $form_state['storage']['file'] = $file;
        }
        else
        {
            form_set_error('file', t("Failed to write the uploaded file to the site's file folder."));
        }
    }
    else
    {
        form_set_error('file', t('No file was uploaded.'));
    }
}
function calculator_page_form_submit($form, &$form_state)
    {
        $file = $form_state['storage']['file'];
        // We are done with the file, remove it from storage.
        unset($form_state['storage']['file']);
        // Make the storage of the file permanent.
        $file->status = FILE_STATUS_PERMANENT;
        // Save file status.
        file_save($file);
        $file->display = 1;
        $file->description = "";
        // Set a response to the user.
        drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));
        global $user;
        $node = new stdClass();
        $node->title = $file->filename;
        $node->type = "file";
        //node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
        $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
        $node->uid = $user->uid;
        $node->status = 1; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
        // Term reference (taxonomy) field
        //$node->field_tag[$node->language][]['tag'] = $form_state['values']['tag'];
        add_terms_for_node($form_state['values']['tag'], &$node);
        $file->display = 1;
        $file->description = "";
        $node->field_file[$node->language][0] = (array)$file;
        // 'node' is default,
        // Other possible values are "user" and  "taxonomy_term"
        $node = node_submit($node); // Prepare node for saving
        node_save($node);
        //drupal_set_message( "Node with nid " . $node->nid . " saved!\n");
    }

What am i doing wrong? Thank you for help and sorry for my poor engrich it isn't my natural language.

I found mistake. I accidently named field_file as field_fiele. Damn it four houers from life. Code works correctly.


How to add an image within a header? I am new to Drupal and currently working on a theme from scratch. I have been using the tutorial How to create a simple Drupal 7 theme from scratch to help me. I have got most the things working required for the site I am working on apart from the header. I would like to add an image to the header which would be floated to the left of the text.

So far I have tried to create a content type with an image and assign it to the header block I have created. When I tried assigning a content type the header disappeared.

Any suggestions?

I would not create a content type just for adding a single image to the header in any case, but even more so in this case as it appears that is you website's logo (is that right?).

If it is your logo then the best way to achieve this is via the settings of your theme. Almost all themes have a setting for the logo image.

Go to admin/appearance then click the settings link for your theme.
You will see a "Logo image settings" section on the settings form, which usually by default has a check box "Use the default logo", which will be checked by default.

You can un-check that check box and then enter a path to your logo image file, however the easier and better way is to leave that check box checked and then in your theme directory replace the default logo with your own, by renaming your logo image to logo.png and copying it over the one that is already there.

On that theme settings page there is also a section for "Toggle display".
In this section make sure that "Logo" is checked.

Then the site will be using your logo, which normally by default will be in the header already.

Then you just have to use a little css to position it as you want it, or if it is not in the right place for you, edit the page.tpl.php of your theme and move the logo to where you want it, then tweak styles with css as needed.

If you only want the logo on the home page, make a copy of your page.tpl.php in your theme and call it page--front.tpl.php - This means it will only apply to your front page (see drupal 7 template suggestions for more info).

Then you can have the logo printing on the front page but you can remove it from your normal page.tpl.php so it doesn't appear on other pages.

If I was wrong about it being your site logo or it is the logo but for some other reason you don't want to use the site logo setting, you can do one of a few things.

If the image is purely decorative, it is generally considered a good idea to make it a css background image, in which case just add the image to your theme's images directory and add some css to your theme to set it as the background image of your text block in your header and use padding so that the contents don't overlap the image.

If the image is not purely decorative and it actually has meaning to the user, you want screen readers to read it as an image so disabled users can see it.

In this case you need to use an img tag.

So you can do one of these things:

Make the page--front.tpl.php and manually add an img tag in the place you want it, put the image in the images directory of your theme, then style with CSS.

The other option is to create a custom block via the block UI.

To do this go to admin/structure/block and click the "Add block" link.
In the block body field add the img tag you want.
The easiest way to do this is make sure you have a wysiwyg text editor (for example, ckeditor or wysiwyg module) and use it for block creation.
Then you can upload an image directly via the wysiwyg editor instead of messing around uploading files manually to your server, which is not ideal.

In this way you can either make a block for your image and a block for the text to the right of it, or if they directly relate to each other you can add them in the same block.

Then in the block visibility settings you can make it so that it only shows on the home page (or you can use some other block management system to do that if you prefer).


Include file with functions in node.tpl.php and execute them on node content First at all, I know that this isn't the correct way to do this in D7, but I need to do in this way.

I've included a file in node.tpl.php:

include DRUPAL_ROOT . '/sites/all/themes/mytheme/inc/node_functions.php';

In this included file I have a function which, afterwards I want to call from a node's content-body.

Currently, if I call the function from a node content, I get a WSOD. I also checked if within a node-content the function exists, with a PHP function:

function_exists('name_of_my_function')

but it returns FALSE, so the function no exists in this 'scope'.

In summary, I want a collection of helpful functions included/attached to a node, but I don't want to write the include/require statement everytime I'm creating a node. I only want to simple 'call' those functions. So, how can I do it?

Thanks in advance.

Implementation Issues

Included a file in node.tpl.php
I have a function which, afterwards I want to call from a node's content-body

Sorry but I think these are not following best practices. As you can see If these was possible then it would have worked because it's just including a PHP file and calling a function in it but I think Drupal doesn't do it that way and runs the PHP in the body field way before node.tpl.php w/c results to no included PHP file at that time yet.

Suggested solution

Might I suggest, it's better for us to:

Create a custom module
Add your helper functions there with any structure of the files you can but following Drupal standards.
Use Drupal hooks if needed because if you place your functions in the .module file, it will be available already for use.

One example of this way is after adding your helper functions into the .module file and want to execute/run functions when viewing the node, you can use hook_node_view. Maybe add some scripts, remove data, alter data and etc. and you can also do conditional statements there if you want to run specific things for a specific content type.

This just doesn't align your site with best practices but makes it easier to maintain in the long run with less technical debt.

Hope this helps you to be able to call/execute your needed functions on nodes.

UPDATE

You can remove the PHP file inside your theme and transfer the functions/codes inside it in the .module file. After that, you need to Clear All Caches then that will make your functions available or callable.

You don't need to use the include_once or hook function.


Get single edit field from a content type I'm writing a module with a custom form. I would to add in this a form a field from an existent content type, with values.

For example: I've a content type "article" wth a node reference field "field_ref".

In my custom form I want to get this "field_ref" field, with values.
Is it possible?

I think that I could get the entire form and then get only the field but I don't like this solution :)

You can build a custom autocomplete text field to filter node reference results. Check this link http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7 to build autocomplete text field.

You just need to change the query in above implementation.


Custom submit handler: how to create node? I created a form_node_alter for a content type called "banner" and I made a custom submit handler named "mymodule_check_submit_handler()".
Everything is ok, I can do what I want in the submit handler function but I don't know how to create the node of type "banner" once I executed my custom code.

Searching for a solution I found this code:

$values = $form_state->getValues();
$node = entity_create('node', $values);
$node->save();

But now I got this error: Error: Call to a member function getValues() on array in mymodule_check_submit_handler()

How can I create the node in my custom submit handler?

After some searches I post the solution to myself!

This is the right code to use:

$values = $form_state['values'];
$node = entity_create('node', $values);
$node = node_submit($node); // Prepare node for saving
node_save($node);


How to edit content of panels Custom text that was made reusable? I'v created a Custom text element for page manager and made it reusable, and I'm not able to edit it now in Panels. Is it possible to edit such Panels elements after they were made reusable?

Thanks

If you go into the panels from the structure menu... you will see "Manage custom content" on the top right.


Saving form fields on custom entity I'm having problems saving my custom entity to the db. I created a custom entity called 'review' using hook_entity_info() with a custom controller. I have specified some parameters in the controller using:

      public function create(array $values = array()) {
      global $user;
      $values = array(
      'rid' => '',
      'uid' => $user->uid,
      'nid' => $_GET['nid'],
      'created' => REQUEST_TIME,
      'changed' => REQUEST_TIME,
      'published' => 1,
      'quality' => '',
      'design' => '',
      'versatility' => '',
      'design' => '',
   );
   return parent::create($values);
 }

Everything seems to be working just fine but when I try to submit my form to create a new entity not all fields are saved in the db.

I attached the value of the fields in the form using field_attach_form('review', $review, $form, $form_state); and in my submit function I have this:

$review_submission = (object) $form_state['values'];
field_attach_submit('review', $review_submission, $form, $form_state);
$review = entity_create('review', array('type' => 'review'));
$entity = entity_metadata_wrapper('review',  $review);
$entity->save($review_submission); //This saves info but not fields

This creates a new entity but the fields 'quality', 'design', 'versatility', 'relevance' are not saved. However if I use this instead in my submit function:

review_submission = (object) $form_state['values'];
field_attach_submit('review', $review_submission, $form, $form_state);
$review = entity_create('review', array('type' => 'review'));
$entity = entity_metadata_wrapper('review',  $review);
entity_get_controller('review')->save($review_submission); //This saves fields but not info

those fields are correctly saved BUT then 'rid', 'uid', 'nid', 'created', 'changed', 'published' are not saved.

What am I missing? How can I saved the entity info and the values from the form fields?

As far as I understand, you need to provide these values manually before the save, for example:

$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
$entity->uid = $user->uid;

or copy them directly from $form_state['values'].

I've found entityFormSubmit method from Inline Entity Form module which is manually copying all fields which are not fields to entity properties, so gave me the idea for this code:

$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);


Is it possible to override a field module's implementation of hook_field_validate()? I need to override hook_field_validate() for a particular field (provided by the Video Embed Field module). The description for that hook states:

  Validate this module's field data.

So the idea is that it's only invoked for the module that implements a particular field, which makes sense.

Unfortunately there's no altering mechanism in place (that I can find) so the implementations of those hooks are pretty much hard-coded. Also the hook is never run through module_implements() (as you would expect), so in turn is not available to be overridden using hook_module_implements_alter().

Does anyone know of a way, however unclean, of overriding hook_field_validate() for a particular field implementation, without hacking any core/contrib modules?

There is hook_field_attach_validate(), which is invoked by the single function that invokes hook_field_validate(), namely field_attach_validate(), which is called by field_attach_form_validate().

I did not find an obvious way to get rid of the original validation function, but a quick hack would be to remove the errors, that the original validation function produced, from the $errors array in your hook_field_attach_validate() implementation.


Im trying to pass an array as an argument in a page callback I am attempting to pass an array as a page argument in a page callback in one of my modules. The scenario is this: The user selects some photo prints and I'm trying to add all the selected photo prints to the cart. So I'm trying to pass an array through a url to use it in a function. And the photo prints can be from different photo albums. There is code to do it if all the photos are from the same album so Im currently perusing that as well. This is code I "inherited" by the way.

The URL looks like /add_selected_prints_to_cart/Array. As you can see, instead of an array of values, it's just Array.

This is the page callback:

// Add the selected prints to the cart.
$items['add_selected_prints_to_cart/%'] = array(
  'page callback' => 'add_selected_prints_cart',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'access arguments' => array('view own gallery'),
  'type' => MENU_CALLBACK
);

Like I said, I am just trying to figure out how to pass the array. Once I figure out that, the other part is easy.

Maybe there is an easier way to do this.

That happens because the code you are using is similar to the following one.

$url = url('add_selected_prints_to_cart/' . $array);

If each photo has an ID that can be used to univocally identify each photo, in the same way a node ID univocally identify a node, you could use code similar to the following to create the URL. I assume the structure of the $photos array is the following one.

array(
  'photo ID 1' => array( /* data for the photo with ID equal to 1 */),
  'photo ID 2' => array( /* data for the photo with ID equal to 2 */),
  'photo ID 3' => array( /* data for the photo with ID equal to 3 */),
  // ...
);

$url = url('add_selected_prints_to_cart/' . implode(',', array_keys($photos)));

In this case, add_selected_prints_cart() can get the photo IDs using code similar to the following one.

function add_selected_prints_cart($photos) {
  $photo_ids = explode(',', $photos);

  // Load the photos from the database.
}

If you need to pass the array to the menu callback, I would add the array to the session variables. In this way the code would for defining the menu callback would be similar to the following one.

function mymodule_menu() {
  $items['mymodule_add_selected_prints_to_cart'] = array(
    'page callback' => 'add_selected_prints_cart',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

function mymodule_add_selected_prints_to_cart() {
  $photos = $_SESSION['mymodule_selected_photos'];
  // ...
}

(If you use 'access callback' => TRUE, the access arguments are not used.)

Otherwise, the code to convert an array to a string is similar to the following one.

$string = strtr(base64_encode(serialize($array)), array('+' => '-', '/' => '_', '=' => ''));

The code to obtain the array back from $string is the following one.

$array = unserialize(base64_decode(strtr($string, array('-' => '+', '_' => '/'))));

Bear in mind there is a limit for the URL length accepted from browsers.


custom field in product type not showing in line item drupal ive created custom fields in my product type.

then i have this code under my custom module

global $user;
$order = commerce_cart_order_load($user->uid);
if($order) {
     $line_item_list = $order->commerce_line_items["und"];
     foreach ($line_item_list as $key => $value) {
         $line_item = commerce_line_item_load($value["line_item_id"]);
         drupal_set_message('<pre>' . print_r($line_item, TRUE) . '</pre>');
     }
}

i tried to print per line item to, but i cant see my custom field in the print...

anyone experienced this?

You added the fields to the commerce product entity (commerce_product), not the line item entity (commerce_line_item).

That is why the fields don't show on your line item entity.

The line item entity contains a product reference field (commerce_product) referencing the associated product, you will need to inspect that to get the fields from the product.

e.g:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Get product field value from line item
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  // If line item is a commerce product type
  if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
    // Fetch duration value on product.
    $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->value();
    // Get raw values
    // $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->raw();
    drupal_set_message($duration);
  }
}


How to import a CSV with list field labels using Feeds? I have a content type "Car". The fields are "Title", "Body" and "Gearbox". The "field type" of the field "Gearbox" is "List (integer)", and the "Allowed values list" for this field (in the "key|label" format) are:

1|manual
2|automatic
3|semiautomatic

I want to import content from a CSV file using a standard node import with Feeds. My CSV is as follows

GUID,Title,Body,Gearbox
1,Lexus NX,blabla,automatic
2,Porsche Cayenne,bloblo,manual

On importing this CSV file, the value for "Gearbox" is not copied over. Instead, it appears as empty in the content. If I replace the values for "Gearbox" by their keys, as in this modified CSV file

GUID,Title,Body,Gearbox
1,Lexus NX,blabla,2
2,Porsche Cayenne,bloblo,1

then it works correctly.

Nevertheless, I'm not the end user and I need to leave the CSV file in its more human-friendly form that uses the "labels" instead of the "keys" (as in the original CSV above).

How can I do this? I.e. how can I have the import recognize the labels "manual", "automatic", etc instead of their corresponding keys?

It seems that this is a known issue. There is a patch at https://www.drupal.org/node/2006810


Adding a Space Context Condition I want to add a condition of what type of space is currently active on the site. Does anyone know of a module that supports this?

I notice that spaces is setting a context for us, but I cannot find the relevant plugin or set the condition up in Context UI.

function spaces_set_space($space = NULL) {
  static $active_space;
  if (isset($space)) {
    $active_space = $space;
    if (module_exists('context') &&
        $plugin = context_get_plugin('condition','spaces_type')
        ) {
        $plugin->execute($space);
    }
  }
  return isset($active_space) ? $active_space : FALSE;
}

If you can figure out the name of the contexts made available from spaces, you can use the condition that is triggered by other active contexts.  I personally have not heard of spaces creating context on their own however.  You may also consider writing your own plugin/module as this is relatively simple to do.  I myself used the path condition files to create the context keywords module(http://drupal.org/project/context_keywords).  You could honestly probably reuse 90% of the code from mine, and just change the part that returns true or false.


Can I store custom data in $node->data? What is the purpose of $node->data? the Node object reference has $node->date, which used for

  Long date, including timezone data, of when the node was created.

May I use $node->data to store my own temporary variables?

According to this page $node->data was used about Drupal 5 and is left there for legacy purposes only. It appears it's only purpose is to prevent "call to undefined property" errors. Do not use it.


Fatal Error - Fatal error: Unsupported operand types in public_html/includes/common.inc on line 2999 The page of my work is not loading anymore!
And Im not used to deal with drupal!
What I have to do to the page load properly! I even cant login as user or see any page of the site!
PLZ im really desesperated!

this error show when i try to enter in the page:
Fatal error: Unsupported operand types in /home/storage/2/58/58/xxxxx/public_html/includes/common.inc on line 2999
the page i wanna to work is that: www.meddco.com.br!

You need to access the installation's database.

Find the 'block_custom' table. This contains all custom blocks.
Browse the records and locate the one which creates the problem.
Clear the field 'body' which should contain your custom PHP code.


Modular content and syndication I am trying to sketch out a Drupal 8 based solution by which content is authored in a modular way, with an arbitrary number of different modular blocks of content,  that would also allow nodes to be pushed (or pulled) to other separate Drupal 8 installs. (The essential idea being that a set of editors have access to a set of simple modular blocks to build content which is likely to be duplicated across different separate sites and another set of editors have access to a more complicated set of blocks to build content that is not necessarily meant to be duplicated.)

So far I can't seem to find any obvious solutions, most seem to require knowledge of the content configuration beforehand. Is there an obvious solution I'm overlooking or just ignorant of?

A combination of Paragraphs and Deploy module have been suggested to me. I'm still evaluating their combination to determine if it's suitable but any additional suggestions would be very helpful!

It looks like this is currently not possible for Drupal 8, using community maintained modules. The Feeds Extensible Parsers module is not ready, which means the services+feeds method is not feasible, and the Deploy module is not ready. (Though methods may become available in the future for this particular workflow.)


Slide show inside of Body Content There are no shortages of options for slide shows in Drupal: views, modules, themes, etc. However, I need an option for inside the Body Field. I'm dreaming of an option that

Content editors can assemble without manually entering Javascript or CSS in the body or Code Per Node field
Accessible to screen readers (Jaws, Voiceover, Orca) by having Aria roles and landmarks in place
Is a module which, perhaps, employs an input filter.

Does such a solution exist? Is this a time to begin exploring Polymer more deeply?

In all my searches, I've seen blocks and views, but nothing that can be dropped into the Body Field.

that's a hard point that i'm also dealing with.

Actually i imagine 2 differents ways to solve this :

i install the module paragraph
It is pretty anwsome by changing the way a user contribute. But it doesn't allow to add a slideshow in a Body field.
Creating a plugins for CKEditor that create (a new button) that will add the slideshow HTML in the Body Field.
This button will be like "Create a table" button, you will decide how many images is needed and you will just add the  to it.
The HTML is quite simple, for bxSlider (http://bxslider.com/) for Exemple you will need to add this :

And for SlidesJS it's :

I didn't start this plugins yet because i finally decide to use Paragraph but i think this plugins for CKEditor can be a good tool in the futur.


How to add class to teaser P? In Drupal 8, how can I add a class to teaser p html tag. I want to style the paragraph in teaser only, not when whole content is shown.

We can style that with simple css,

.node--view-mode-teaser .node__content p {
  /* write you style */
}

I think, you don't need to add separate class in P tag for that. and it would also affect only the teaser mode content :)


How to map multiple existing term IDs to an entity I'm trying to map multiple existing terms using their target_id values to an entity (Commerce Product) and I can only get the first value to map.

My yml file looks like this:

  'field_prod_category/target_id':
    plugin: explode
    source: tid
    delimiter: ','

And, for now, I'm hard coding two existing term ID values in through the source plugin like so:

$row->setSourceProperty('tid', '806,635');

But no matter what I try only the first term is referenced. And, yes, the term field is set to unlimited.

Any ideas?

You need to use plugin sub_process. File yml have soure like this:

  field_prod_category:
    plugin: sub_process
    source: tids
    process:
      target_id: tid

and soure plugin need to prepare:

$tids = [
      'tid' => 806,
      'tid' => 635
    ];
$row->setSourceProperty('tids', $tids);


Git push to drupal.org always returns "Everything up-to-date" This same question was asked many times, but for now I didn't find any help in the responses.

I have a project in a sandbox which I frequently pushed to the DrupalGit repository without any issue during review process.

Then after successfully getting permission, I first wanted to simply promote my sandbox to a full project according to these instructions, but for some reason editing my sandbox page never showed me the "Promote" tab.

So I decided to create a full project from scratch, then I followed its "Version control" tab documentation to create and populate the corresponding repository: compared to the sandbox's one, you can see that it only contains the myModule.info file.
(this file is not the "true" myModule's info file: it was created in the earlier steps prescribed by the above doc).

Once successfully pushed this and added a "7.x-1.0" tag as also prescribed, I locally copied all my real files from sandbox to full-project directory, git-added them and git-committed them.

Then from now on, any git push origin 7.x-1.0 simply returns "Everything up-to-date", and obviously nothing is updated in the DrupalGit repository.

I looked at many posts and docs, in the Drupal community and elsewhere, tried a lot of more or less serious methods.
I even dropped all files but myModule.info from my local repository: pushing this committed situation also returns "Everything up-to-date", and indeed the same after bringing them again.

I could observed something weird when clicking the myModule.info file to display its contents:

in the sandbox repository it appears formatted with line numbers, as expected, and clicking "plain" displays its raw content
but in the full project repository it displays in hexdump mode, And clicking "plain" causes its download to be proposed!

This clearly means that the file in a somewhat strange state, and midht be significative... but not for me at the moment :-)

This not a real "answer" to the question I asked, but only the method I finally found to get out of my blocking situation.

Since it seemed not possible to make the remote repository to accept push attempts from its associated local repository, I took the problem from the opposite end.

After all it appears as a quite simple solution:

I renamed my local repository, say to myModule.old
I cloned the remote repository with
git clone --branch 7.x-1.x [myName]@git.drupal.org:project/myModule.git,
so getting a new myModule local repository
then I pasted whole contents from myModule.old into myModule, added and committed them
and finally used a simple git push origin (NOTE: without tag mentioned), with success

BTW, it's interesting to notice that trying with the tag mention again returned the "Everything up-to-date" message.
In the other hand, once pushed new contents, the myModule.info file displays normally rather than with the previous weird fashion.

Hope this helps somebody.


Is it good practice to style the panel layout? I have a panel layout. I was wondering if its okay to apply additional css ids / classes to this or to style elsewhere? I am using panels everywhere and I have moved the layout into my theme.

It's perfectly acceptable to add CSS ids and classes to panel layouts.


Send Email After User has confirmed email address using Rules I my drupal site, I have checked Require Email Confirmation to enable email confirmation. In this case it is sending an email with link to confirm email to set password for account.

Now when user has confirmed email address and set password for account, I want to send email to the user informing of confirmed email.

I have looked Rules Module for this, but there is no any such even present.

Any suggestion how can I implement this using Rules module.

-- Many thanks for your time

I did something like this on a site not long ago, and at the time I couldn't find a solution that would work without some extra code because of the way registration was set up, but for your case you should be able to use a rule to check when the user's access timestamp is first set, reacting to the "after updating an existing user account" event.

So you need to check the account-unchanged:last-access is 0 and the account:last-access is not 0, then fire your rule. I haven't tested that this will work, and you might need to add some extra conditions for your particular circumstances.


How to use select2 in form API drupal 7? Hei please help me using select2 in drupal 7
I'trying to make custom module and form type is select using form API drupal 7

can anyone give an example using select2 module in custom form API

From what I recall, the select2 javascript needs to be #attached to a render node or otherwise included on the page, then the dom content loaded callback used to locate the HTML select items that should be modified. Something like:

function () {
  $('select').select2();
}

See https://select2.github.io/ for examples. Within Drupal, you should really use the Drupal 'behaviours' framework, so that the right thing happens when AJAX and other dynamic loading happens.

There is also the project https://www.drupal.org/project/select2 which may help!