Login programmatically using ajax I have a button in my custom module

  function sign_up_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['captcha']['#suffix'] ='<input type="button" id="test" name="test" value="OK">';

    $form['#attached']['js'][] = array
      (
       'type' => 'file',
       'data' => drupal_get_path('module', 'sign_up') . '/js/sign_up.js',
    );

         $form['actions']['submit'] = array("#type" => "submit", "#value" => "Create Account",
        "#ajax" => array(
        "wrapper" => "formwrapper", "effect" => "fade", "method" => "replace",));
   }

Note: Ive removed the callback key of #ajax inorder to avoid page refresh.

In my sign_up.js I made an ajax call when this button is clicked.

  $(function() {

      $("#test").click(function(){

         $.ajax({url:"/path/to/normalphp/page/userLogin.php",success:function(response){

          alert(response);

      }});
    });
  });

The onclick is working and the ajax call is also successful.

In my userLogin.php (not a module file.Normal php file) I just hardcode the uid and call user_login_submit() .

<?php

 chdir($_SERVER['DOCUMENT_ROOT'].'/');
 define('DRUPAL_ROOT', getcwd());
 //Load Drupal
 require_once './includes/bootstrap.inc';
 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $account = array('uid' => 49); //existing uid
  user_login_submit(array(), $account);

The result which I expect is to automatically redirect the user to welcome screen.But this is not happening.When I try to login with this user from the drupal login page its successful.
This is just a test as I wanted to customize my registration screen (make ajax calls,jquery validations etc) and then automatically redirects to welcome screen when the validation is success.
Note: I have already done the settings in drupal where email notification is not needed.
Can someone help me out in this?

Instead of using jQuery AJAX, you can achieve this by Drupal Form API AJAX.

You can hide the Actual submit button in the hook_form_alter using hide() and add a custom button with AJAX callback.

Or if you still want to practice this using jQuery AJAX, Drupal's way of handling AJAX calls is little different. You may have to first understand the hook_menu in Drupal. Once you have a clear understanding of this system, you have to create pages using this hook. In drupal, it is not advisable to create custom php files for handling AJAX callbacks. Instead you can create a page using hook_menu and handle the server callback there. For the JS part, the Drupal way is to use Drupal Behaviors

This is a small example of how it would look like.

Your custom module to handle AJAX login (sign_up.module)

<?php
function sign_up_menu {
    $items = array();
    $items['custom/user-login'] = array(
        'page callback' => 'custom_user_login_callback',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE
    );
    return $items;
}
function custom_user_login_callback(){
    /**
     *  You can validate the User credentials here and provide error message for invalid credentials or send him to welcome page using drupal_goto() for valid credentials
    **/
}

-

The custom JS file (sign_up.js)

Drupal.behaviors.customSignUp = {
    attach: function(context, settings) {
        $("#test", context).once(function(){
            $(this).click(function(){
                $.ajax({
                      url: Drupal.settings.basePath + 'custom/user-login',
                      type: 'POST',
                      data: {
                        username: /** Pass the User Name **/
                        password: /** Pass the Password **/
                      },
                      success: function(response) {
                        $('#ajax-response-wrapper').html(response);
                        Drupal.attachBehaviors();
                      }
                });
            });
        });
    }
};


How can I override the fivestar title attribute without hacking the module? It's line 4 of this part of fivestar.module:

$options = array('-' => t('Select rating'));
for ($i = 1; $i <= $element['#stars']; $i++) {
$this_value = ceil($i * 100/$element['#stars']);
$options[$this_value] = t('Give @title @star/@count', array('@title' => $title, '@star' => $i, '@count' => $element['#stars']));}

It creates a verbose title on every star. I tried this javascript

var elements = document.getElementsByTagName('a');

for (var i = 0, len = elements.length; i < len; i++)
{
  elements[i].removeAttribute('title');
}

but it doesn't affect these links. I even tried doing it inline at the bottom of html.tpl. Is there a function I can use in template.php? Full file if it helps.

The reason your javascript didn't work is simple. If you disable Javascript and load the page with the fivestar widget, it's just a simple <select> list. It's turned into a clickable star widget using Javascript as well. So your js was most probably being overridden by fivestar.

You can do this without hacking the module and without using javascript by creating another custom module, but there's a small issue explained at the end. Lets call the module myfivestar for example.

You would then need to implement hook_element_info_alter() to change the fivestar element's process callback to your own custom one:

function myfivestar_element_info_alter(&$type) {
  // Change the process callback of fivestar to myfivestar_expand
  if (isset($type ['fivestar']['#process'])) {
    $type ['fivestar']['#process'] = array('myfivestar_expand');
  }
}

Now you just need to copy the function fivestar_expand from the fivestar.module to your own module, rename it to myfivestar_expand, and change the line:

$options[$this_value] = t('Give @title @star/@count', array('@title' => $title, '@star' => $i, '@count' => $element['#stars']));

to:

$options[$this_value] = ''

which will effectively make the <select> list useless for visitors browsing with Javascript off as it removes the option labels which are then turned into the title attribute using fivestar's javascript.


How to get content with their taxonomy term name and id? Hello I have created content type product. I also add Taxonomy with name "category". I add field in with term reference in product content type.
Now I want to get all content with taxonomy name and id which have  content type named "product" using query in Drupal 8 .

Make a dynamic query like this:

$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->condition('nfd.type', 'product');
$query->leftJoin('node__field_category', 'ft', 'ft.entity_id = nfd.nid');
$query->leftJoin('taxonomy_term_field_data', 'fd', 'fd.tid = ft.field_category_target_id');
$query->fields('fd', ['tid', 'name']);
$query->fields('nfd', ['nid']);
$results = $query->execute()->fetchAll();

Suppose the reference field taxonomy machine name is "node__field_category".
The result of the query will be node id , term name and term id.


Embed controls 8 #table element? I'm using the Drupal 8 #table element to populate a table on my form, and it's working great for displaying static data.

foreach ($entries = getData() as $entry) {
  $row = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $entry);
  $rows[] = $row;
}
$form['table'] = array(
  '#type' => 'table',
  '#header' => $headers,
  '#rows' => $rows,
  '#attributes' => array('id' => 'my-module-list'),
  '#empty' => t('No entries available.'),
);

However, I would like to embed a control in each row of the table, for example:

foreach ($entries = getData() as $entry) {
  $row = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $entry);
  $row["field_name"] = array(
    '#type' => 'textbox',
  );
  $rows[] = $row;
}
//dpm($rows);
$form['table'] = array(
  '#type' => 'table',
  '#header' => $headers,
  '#rows' => $rows,
  '#attributes' => array('id' => 'my-module-list'),
  '#empty' => t('No entries available.'),
);

However, the #textbox field is currently being ignored, and an empty cell is shown in its place.

Is there a way I can embed fields in a Drupal generated table, or do I need to build my own table from scratch?

It is no problem to put form elements in a table. See the example in core/lib/Drupal/Core/Render/Element/Table.php:

$form['contacts'] = array(
    '#type' => 'table',
    '#title' => 'Sample Table',
    '#header' => array('Name', 'Phone'),
  );

  for ($i=1; $i<=4; $i++) {
    $form['contacts'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#title_display' => 'invisible',
    );

    $form['contacts'][$i]['phone'] = array(
      '#type' => 'tel',
      '#title' => t('Phone'),
      '#title_display' => 'invisible',
    );
  }

Maybe you should start from here and then put step by step your code in this example and see when it breaks.


How can we create configurable product in ubercart? I am creating an e-commerce website using ubercart and Drupal 7. I have created attribute size and color for the product from the  "Administration » Store » Products" and assigned to product.

I have also used search api and facet api module to generate facet search. I have created a views page to display product listing of search index product and showing facet block in that page.

Now, the problem is that I want to display product attribute as filter in the above product listing page. I have searched on google but did not find any solution for that.

Can any one suggest me?

Thanks in advance for your help.

If I had this problem,

I would have created taxonomy terms corresponding to the attributes
The taxonomy terms can be used as search filters, rather than hacking the uc_attributes.

or

If views is used to display the products, then add filters in the views as product attributes.
The taxonomy terms can also be used in views to filter the products.


Drilling down into an Entity Reference Field in Rules Actions I have the following setup where I have 2 content types called BRIEFS and IDEAS. On BRIEFS, I have a list of users selected in a field called brief_recipients which is a user reference field.

IDEAS has a entity reference field (associated_brief) that references a BRIEF.

Currently when I create an IDEA, it will email the author of the referenced BRIEF. This works using the following rules setup:

Now I'm trying to add in a LOOP to access the entityfield associated_brief's > brief_recipients field and email them too.

But the problem seems to be that Rules cannot drill down into an entityfield's fields as I can only get to body and author only as seen here:

Now the question is how do you drill down into an entity field's fields? Or is there another suggested way of doing this?

Which hook would I need to tap into if I had to write this custom?

In my scattered experience with rules, a limitation on what data you can access is usually a safeguard because the data has not been confirmed to exist yet.  In the Rules conditions, create "entity has field" condition twice.

1) Rule Conditions > Entity has field
Data selector: node
Field: field-associated-brief

This is your entity reference field, and gives Rules the comfort of knowing the reference field is usable. Once you have the above conditions, rules will load up the referenced fields from your node

2) Rule Conditions > Entity has field
Data selector: node:field-associated-brief
Field: field-breif-recipients

3) Now the action is able to use the field confirmed in the conditions

Even if you do not think the conditions should be required, it is good practice to confirm you have the data before you try to use it.  Here is another person who had a very similar issue


Change texts according to other language in template.php I have multilangual website ancak my site's footer is in template.php.

Like this:

function _site_footer(){
    global $language;

    $output = '

                   this is a lorem ipsum

    return $output;
}

I want, when I turn my site to other language, get this footer:

function _site_footer(){
    global $language;

    $output = '

                   TESTTESTTESTTEST

    return $output;
}

How can I change it in template.php? Thank you.

Global $language variable returns current language object, you can get current language code by $language->language property. Example:

global $language;
$output = '

                   this is a lorem ipsum

';
if($language->language == 'en') {
    $output = '

                   this is a lorem ipsum in english

';
}

return $output;

But better way would be using Render Arrays

2-Solution: is to wrap the text with t() function. And translate the text by admin/config/regional/translate link.

function _site_footer(){
    $output = '

                   ' . t('this is a lorem ipsum') .
                '

'
    return $output;
}


Print Entity Reference Value from Entity Meta Wrapper I have this code to get entity meta wrapper and print text fields. But I can't see how to print entity reference values.

$wrapper = entity_metadata_wrapper('my_entity', $entity);
print $wrapper->field_my_field->value();

You can access entity reference values by calling entity metadata wrapper API on the reference field.

For instance, if you have a node with a field which references a profile2 entity,

$wrapper = entity_metadata_wrapper('node', node_load(1));
$profile_wrapper = entity_metadata_wrapper('profile2', $wrapper->field_profile->value());
print $profile_wrapper->field_about->value();

or if you prefer rendering the entity,

print render($profile_wrapper->view());


How to alter query of services module I am using service module 7.x-3.12. The index call by node resource provides provides node related data but only from node table. I can't fetch the value from custom fields of a node. So I want to alter the query in index call build by services_resource_build_index_query() function. But I can't find any way to alter the query.

You can use rules for this to add custom field or you can use "hook_services_request_postprocess_alter" to add new array with custom field.

Using rule you can set in event "Content is viewed of type .." and in action you need to custom php that returns $node->custom_field = val;


How do I add another field after saving entity metadata wrapper? I'm trying to do something like this:

function create_content($type,$content){
  $node = entity_create('node', array('type' => $type));
  $emw_node = entity_metadata_wrapper('node', $node);
  $fields = field_info_instances("node",$type);
  foreach ($content as $field => $value){
    if (array_key_exists($field,$fields)){
      $type=field_info_field_by_id($fields[$field]['field_id'])['type'];
      if ($type=='link_field') {
        $emw_node->$field->url = $value;
      }
      else {
        $emw_node->$field = $value;
      }
    }
  }
  $emw_node->save();
  $id = $emw_node->getIdentifier();
  $emw_node->other_field = $id;
  $emw_node->save();
}

With the idea of copying the node id to another field. However, I get an error:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at node(9999)->field_other_field: 9999. in EntityMetadataWrapper->set() (line 122 of /sites/all/modules/entity/includes/entity.wrapper.inc).

How do I do this properly, preferably while still using an entity metadata wrapper?

The problem can be with your field format. If your field other_field is a text field check what text format is set for it in admin/structure/types/manage/your_content_type/fields. EG:

If it is different from the plain text format you have to assign an array as a value to your field. EG:

$emw_node->other_field = array('value' => $id, 'format' => 'filtered_html');

or just

$emw_node->other_field = array('value' => $id);


Is it possible to add style plugins? I would like to allow users to choose a style for each pane and choose options such as margin and font size. It is clear how to do this in Drupal 7. But I can't seem to figure out whether it's possible in Drupal 8.

Note:
It could be an issue where the stylizer module isn't running properly. I see that the styles plugin is in the directory under the panels module. But even though panels are enabled I don't see any style options on the panes when I attempt to configure them.

It appears that the functionality does not yet exist for Drupal 8

https://www.drupal.org/node/2296437


Default value for Price field I'd like to know if there's a way to assign a default value in the Price field in Drupal Commerce. Currently, there are no field settings available.

It is not possible for the default price field, because Drupal locks down the field / widget settings for "locked" fields. This is a general Drupal issue, but you could work around it by using an alternate price field that you add custom to your product type paired with a product pricing rule that swaps that price in at the start of the pricing process. You'd have to do a form alter or something to hide the default price field from your product forms.


how to Create some nodes of a content type when created a node of another content type? I would like to create an editable task table with slickgrid view, where each row is a node (of content type 2) that will be created automatically by a different content type (the 1st content type) or a webform.

Content type 1 - The 1st content type have 4 fields (this node will create automatically some nodes of the second content type)

1st - "Days" - is a Date field type - with unlimited (1 to 10) values

2nd - "City's" - is a Reference to a Term - with unlimited (1 to 10) values

3th - "Type of operation" is a Reference to a Term - with an unique value

4th - "Number of person by city" is a Integer field type - with an unique value

Content type 2 - the 2nd content type have those fields

1st - "Day" - is a Date field type - with an unique value

2nd - "City" - is a Reference to a Term - with an unique value

3th - "Type of operation" is a Reference to a Term - with an unique value

4th - "Name of a person" is a text field - with an unique value

Now for example if i create a node of Content type 1 with 5 values for the date field and 5 for the City's and the number "2" for the integer field, it will create automatically 5*5*2= 50 nodes of Content type 2, the "name of a person" field will be created empty of course.

I think i must create a module or perhaps with rules it's possible ? is it possible to replace the content type 1 by a webform? I'm newbie in drupal module developement. Thanks.

Custom module is the best way to go. With rules it's really complex. You need to use below hook in your custom module to solve above problem.

hook_node_insert to hook into above node creation. Hook Responds to creation of a new node.
In above hook implementation you need to create new nodes using code. Please find article which explains same.


What does 'Rebuild Permissions' actually do? I've been working with a lot of custom content types lately, and I keep getting a message to rebuild my permissions.

It seems like it happens everytime I create a new content type. Is this normal behavior? And what exactly is happening when I do this?

Drupal core uses database tables to control some aspects of content viewing/editing permissions. These tables are used by contrib modules like Domain Access or Taxonomy Access Control to store information about which roles/users can see which nodes. Because it is not easily determinable which configuration changes will result in actual permission changes Drupal marks these tables as needing updating for a broad set of configuration changes.


Rabbit hole: what's the recommended setting for content that should not be directly accessible? I have one content type, as well as several vocabularies (taxonomy) that are only shown on the site through views and therefore should not be accessible on their own. I'm using the rabbit hole module to prevent that from happening.

My question is this: from an SEO point of view, is it better to use a 301 redirect (to the front page), or a "page not found" response?

Maybe I should point out that the site isn't online yet, so it hasn't been crawled by search engines.

It's really up to you what you want to do but the way I see it, if a user goes to a random non-existing path on your site they will get a 404 error, so if the rabbit hole page is a page the user should never be able to get to then it should also be a 404 error because as far as that user is concerned it is not a valid page.

Now if you redirect all 404 errors to your home page or search page or something then these pages should have the same behavior.

If the page is something that anonymous users cannot see but a paying member can (or some similar scenario), then it may make more sense to set rabbit hole to a 403 error, because it is a page that they can't currently see but could see if they log in.


Printer, email and PDF - can I use this module to print Views? I have installed Printer, email and PDF and I am happy with the way it renders nodes.  I was wondering if there was a way for it to print views too.

It should be the same idea, but instead of using nid in the URL use Views page path.

Examples:

print view page: http://www.example.com/print/view-path
pdf view page: http://www.example.com/printpdf/view-path
email view page: http://www.example.com/printmail/view-path


How do I prevent rewritten views field output from having ":" stripped out of the  sizes attribute? I'm working on advanced responsive images in a Drupal 8 view, designed to suggest showing different images at various screen sizes around the Bootstrap theme.

Is there a way I can prevent everything up to the ":" from being stripped/filtered out in my views field output sizes attribute?

My views field rewrite looks like this:

It renders for the most part. However, the resulting html looks like this:

<img src="/sites/default/files/styles/product_listing_lg/public/products/2017-01/IMG_0196.JPG?itok=pUdgY8n9"
srcset="/sites/default/files/styles/product_listing_lg/public/products/2017-01/IMG_0196.JPG?itok=pUdgY8n9 1w,/sites/default/files/styles/product_listing_md/public/products/2017-01/IMG_0196.JPG?itok=t7jNSmMk 769w,/sites/default/files/styles/product_listing_sm/public/products/2017-01/IMG_0196.JPG?itok=NH8p7qki 993w,/sites/default/files/styles/product_listing_xs/public/products/2017-01/IMG_0196.JPG?itok=feCEjmRl 1201w"
alt="black and gold variegated infinity scarf (wrapped, front)"
sizes=" 993px) 25vw"
class="img-responsive">

sizes attribute in rewrite:

sizes="(min-width: 0px) 100vw, (min-width: 769px) 50vw, (min-width: 993px) 25vw"

sizes attribute output:

sizes=" 993px) 25vw"

I seem to have the same challenge whether I'm rewriting an image field or specifying replacement patterns in a global text area.

I haven't explored any preprocess or twig template options yet. Is this something I need to resolve outside of views UI to prevent the filtering? What's the best way to proceed?

Based on No Sssweat's comment suggestion, I was able to work out a views field template in my custom theme to resolve this question. As I used the twig tweak module to help apply multiple image styles in node templates, I also used it in my views field template in a similar way.

In views-view-field--[view id]--[display id]--[field id].html.twig
(or views-view-field--products--page-1--nothing-2.html.twig in my case):

{#
/**
 * @file
 * Default theme implementation for a single field in a view.
 *
 * Available variables:
 * - view: The view that the field belongs to.
 * - field: The field handler that can process the input.
 * - row: The raw result of the database query that generated this field.
 * - output: The processed output that will normally be used.
 *
 * When fetching output from the row this construct should be used:
 * data = row[field.field_alias]
 *
 * The above will guarantee that you'll always get the correct data, regardless
 * of any changes in the aliasing that might happen if the view is modified.
 *
 * @see template_preprocess_views_view_field()
 *
 * @ingroup themeable
 */
#}
{% set href = path('entity.node.canonical', {'node': row._entity.id}) %}
{% set image = row._entity.field_product_images[0] %}
{% set product_listing_xs = image.entity.uri.value|image_style('product_listing_xs') %} {# requires twig tweak module #}
{% set product_listing_sm = image.entity.uri.value|image_style('product_listing_sm') %} {# requires twig tweak module #}
{% set product_listing_md = image.entity.uri.value|image_style('product_listing_md') %} {# requires twig tweak module #}
{% set product_listing_lg = image.entity.uri.value|image_style('product_listing_lg') %} {# requires twig tweak module #}

No ":" or other items were stripped from the final output.

As a result of the field template, I was also able to remove six hidden field items in the views settings that were used in the rewrite this template now handles.


Query result to display in Views i have created a custom view. its just showing nodes of a particular type. Now i want to do something with it. I am writing a SQL query:

global $user;
$query = db_select('challenges','c');
$query->join('node','n','n.nid = c.cid');
$query->join('field_data_body','f','n.nid = f.entity_id');
$query->join('field_data_field_challenge_pic', 'fp','n.nid = fp.entity_id');
$query->join('file_managed','fm','fp.field_challenge_pic_fid = fm.fid');
$query->fields('n',array('nid','title','created'))
      ->field('f',array('f','body_value'))
      ->field('fp',array('fm','uri'))
      ->condition('c.cid','$user->uid','=');
$result = $query->execute();

Where should i place this query in my custom module and how can i get my view to display this? I tried writing this code in a tpl file for the view and then did print_r and render() but no effect. I think it should be done through views.

write code in your module like this way.

Declaring the block

function mymodule_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current posts'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}

Retrieving data

    function mymodule_contents(){
      $query = db_select('challenges','c')
$query = db_select('challenges','c');
$query->join('node','n','n.nid = c.cid');
$query->join('field_data_body','f','n.nid = f.entity_id');
$query->join('field_data_field_challenge_pic', 'fp','n.nid = fp.entity_id');
$query->join('file_managed','fm','fp.field_challenge_pic_fid = fm.fid');
$query->fields('n',array('nid','title','created'))
      ->field('f',array('f','body_value'))
      ->field('fp',array('fm','uri'))
      ->condition('c.cid','$user->uid','=')
        ->execute();
      return $query;
    }

Generating block content

function mymodule_block_view($delta = '') {
  switch($delta){
    case 'current_posts':
      $block['subject'] = t('Posts');
      if(user_access('access content')){
        //Use our custom function to retrieve data.
        $result = mymodule_contents();
        //Array to contain items for the block to render.
        $items = array();
        //Iterate over the resultset and format as links.
        foreach ($result as $post){
          print $post;
        }

        if (empty($items)) { //No content in the last week.
          $block['content'] = t('No posts available.');
        }
        else {
          //Pass data through theme function.
          $block['content'] = theme('item_list', array(
            'items' => $items));
        }
      }
    return $block;
  }

}


On Imported content I am getting the error Text format field is required I imported some content to a content type on a csv which imported fine but when I went to edit and same the content I get the error Text format field is required. Is there any known way to fix this? Thanks

You need to add default value for text format when you migrate content. Example body field

'body/format':
  plugin: default_value
  default_value: basic_html
'body/value': body

After update config migration you need update migration with command

drush mim MIGRATATION_ID --update


path to node edit page I am using js injector to add script to my drupal website. But the script is also loading on the admin pages and node edit pages.

I have selected the option

Add tracking to specific pages  Every page except the listed pages

and defined admin/* which removes the script from admin pages but what path should I define to exclude the script from the node edit pages

To specify the path match for node/[nid]/edit pages, you can use

node/*/edit

as the page match string there.


create a datetime field with data module I have installed the data module in order to create some data tables, but I have noticed that there is no datetime type given in the user interface, so how can I add some datatime fields to my data tables with the use od data module?

To get date and time data types in the Drupal that can be used in fields, etc., install the Date module in addition to the Data module.


Cloning nodes between multisite instances with separate databases I'm working on a Drupal 8.6 multisite and my client wants to be able to duplicate content between many of these sites. The codebase of the websites is the same, but each of them uses a different database. For that, I made a module with some hooks that gets the node serialized and posts it to another site. code below:

function a8_replicate_node_insert(Node $node) {
  $type = $node->getType();

  if($type == 'event')
  {
    $portals = $node->get('field_duplicate_to_portal')->getValue();
    $serializer = \Drupal::service('serializer');
    $data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);
    $data = json_decode($data); // make it array again

    foreach ($portals as $url) {
      try{
        a8_replicate_post_to_other_site($url['value'], $data, 'insert');
      }
      catch (\Exception $e){
        die($e->getMessage());
      }
    }

  }
}

The a8_replicate_post_to_other_site function just uses curl to post the data as json to the other website. Then I made another module to receive the content, with the following function:

  public function receive() {
    $ip = \Drupal::request()->getClientIp();
    // to make sure it's the machine posting to itself
    if($ip == '127.0.0.1') {
      $data = json_decode(file_get_contents('php://input'), true);

      if($data['action']=='insert') {

        $node = Node::create($data['node']);
        $node->save();// <<<< error happens here
      }
    }
  }

It's my first Drupal development and I'm I don't know pretty well what I'm doing.

Is this the right way to create a node? Is there a better and safer way to do it?

I wouldn't use the approach you used. Here is my recommendation.

First, define your database connection to each multisite on the default setting.php with different name, check the example below:

#Default site

$databases['default']['default'] = array (
  'database' => 'dbname',
  'username' => 'uname',
  'password' => 'password',
  'prefix' => '',
  'host' => 'host',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

#Site 1
$databases['site1']['default'] = array (
  'database' => 'dbname',
  'username' => 'uname',
  'password' => 'password',
  'prefix' => '',
  'host' => 'host',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

#Site 2
$databases['site2']['default'] = array (
  'database' => 'dbname',
  'username' => 'uname',
  'password' => 'password',
  'prefix' => '',
  'host' => 'host',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Now, on hook_node_insert you can save the node object to multiple databases by changing the database each time, refer the code below as an example:

// Switch to site 1 database
\Drupal\Core\Database\Database::setActiveConnection('site1');
//$node will have all fields you need
$site1Node = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$site1Node->save();
// Switch to site 2 database
\Drupal\Core\Database\Database::setActiveConnection('site2');

$site2Node = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$site2Node->save();

// finnally make sure to swich back to default datyabase
\Drupal\Core\Database\Database::setActiveConnection();


Migrate Drupal 8 install from one server to another I've been using Drupal since 4.6 and it's always been easy to copy a site from one server to the other. Make up a tarball, do a database dump, go to the new machine, unpack the tarball and load in the data and you're good to go.

I'm not finding this to be the case at all in D8. Every time I try to move between servers, I end up with fatal errors.

I find that I have to end up doing an install from scratch and then loading the database into the new install. That works, but then my /sites/default/files/config_[hash] are different, so the sites are out of sync.

What am I missing? In theory, the Configuration Initiative was supposed to make this easier, but so far for me that has not been the case.

BTW
 - instructions on "rebuild" - https://drupal.org/documentation/rebuild
 - managing config: https://drupal.org/documentation/administer/config

I recommend using Drush as version 8.x-6.x is compatible with Drupal 8. You can then use drush archive-dump and drush archive-restore to move a .tar.gz file of your database and site files around as-needed.


How to add a custom block on Print module? I'm using the Print module. I wonder if there is a way to print a custom block on the print.tpl.php. Because I want to print a node but that node has its own custom blocks that is rendered on its .tpl. I want the PDF of the Print module to also get all those blocks on the display.

Any help would be greatly appriciated.

You can do this by using Display Suite module. It allows you to add the block as a field in the "Manage display" tab of your content type. You can then place it wherever you want on your node page.

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. A predefined list of layouts (D7
  only) is available for even more drag and drop fun!


Using custom token in node body I am trying to minimize my workload in the future by putting recycled content into tokens, so that I only have to update the token as opposed to updating each individual node that uses the same content. I have little experience with tokens, so my question is very basic.

Example of what I want.. say I have the following on dozens of different nodes:

Item 1: $29.99

Rather than having to update each node when 'Item 1' gets a price change, I'd rather have each node just using a token for 'Item 1', so that I only have to update the token instead of all the nodes. I've installed the Custom Tokens module, but don't understand how to display my custom token in the node's content body. If I set the custom token name as "token-1", how would I display the token in the actual content? ie. [token-1], [custom:token-1] etc don't work.

Any help would be greatly appreciated!

You'll want to have the Token filter module installed and configured in your text formats to use tokens in the node body.


Search page summary customization using views I can figure out how to create a search results page using views in Drupal 7. What I cannot solve is how to format it the same way as a search results page with two lines of summary text and the keyword(s) in bold. Do I have to use the "fields" display?

Yes you need to use fields. One for the title, one for the teaser and any additional fields you want to add in. You can configure the amount of text that appears in the teaser so you can get your two lines of text.


Can the Devel Generate module generate content for all possible permutations and combinations? I love the Devel Generate module as it helps me to create test content very quickly. Random content that the module generates is sufficient most of the times.

But at times I would like to have content for all the permutations and combinations. For example let us say that a content type has three optional fields. So in total I would like to have 8 nodes of that type created that cover all the permutations.

Is this something that can be achieved with the Devel module?

To my knowledge there is no such feature in the Devel Generate module.

Therefor, as an alternative, I recommend to use a (rather basic) custom module for creating such nodes (so without using Devel Generate).

The article about How to programmatically create nodes, comments and taxonomies in Drupal 7 contains great example of how to do so. Here is a summary of that article (about how to programmatically create a node):

  Initialize a node object
  Add body field
  Add custom fields
  Add file / image field
  Add a term to a node
  Save a node

You probably don't need the "add file" and "add term", and simply have to repeat the "add custom fields" a few times (for each of your 3 fields), and then "you" are in full control of which permutations/combinations you actually want.


Is there a significant performance difference between the Computed Field module and writing code? When I got started using Drupal 7, I added several fields to my site using the Computed Field module (to calculate age, zodiac sign, and so on).

Now that I have been using Drupal 7 for a few years, I realize that it is generally not a great practice to write PHP code in the UI, as the Computed Field module requires.  But, the code I am using has worked for the past few years, so that is no longer an issue.

However, I am wondering if there is a significant performance difference between using the Computed Field module (saving the result in the DB) vs. running the PHP in hook_node_presave() or in a similar fashion somewhere in a custom module.

Would removing my computed fields (and uninstalling the Computed Field module) and replacing them with fields in a custom module significantly increase performance?

"Significant" really depends on too many things - how often such nodes are created, how many users (anon/auth) does your website have, which other modules you have installed, what's your workflow setup (e.g. Rules, moderation modules, etc.) and so on.

While doing this through your code is definitely going to be faster, I doubt you will really notice performance improvements. Doing things in code will in most cases have lower overhead than installing a module to do the same.
If you're really wondering about exact performance differences, you will have to benchmark it with Devel and xdebug for example.

However, you already mentioned another important point - it's generally not a good practice to have raw PHP code entered anywhere in admin. Sometimes it's faster to do it (e.g. in Rules, Views or other contrib modules), but over time you should look to migrate those changes to code. Not to mention that you will reduce the number of modules on your website, which is generally a good thing.


How to turn on block or panel from old site to the new one I'm fairly new to Drupal. I have an old version of site with a "block" or "panel" or whatever it's called, that displays on a page, and the new version doesn't have it, and I for god's love can't figure out how to turn it on. It would require looking at it directly, because it's just something I can't see in that beautiful user friendly admin dashboard of Drupal.

EDIT: Upon closer examination, it looks like a view with "content" data that is on the old site, but the "content" is missing on new one. Anyone knowing how to deal with that, I would appriciate that a lot.

Views out of the box support export / import functionality . You can export any view from any instance to any instance using below steps.. Make sure both the instances are in same Major Drupal version..

Login as administrator
Go to the view you want to export "admin/structure/views"
Edit View
Click on export link in the drop down

Copy content
Go to new site and navigate to "admin/structure/views/import"
Paste copied content and click on Import


How to remove the Themekey module after its Installation failed? I installed the module ThemeKey, but the installation failed with a WSOD. Now every page gives me the same 'The website encountered an unexpected error'.

So I need to remove themekey, but how can I do so? The watchdog table doesn't include any message relating to this problem, so is no help. Can I disable/remove it via the database, or am I stuck with rebuilding the whole system?

Use Drush drush pm-uninstall themekey or Drupal Console drupal module:uninstall themekey to disable themekey from the command line.


How can i have a SimpleNews signup form as modal/lightbox Is it possible to have the Simplenews sign up form block as a modal - I'd like to present people to the signup a bit more visible than a static block.
Would i be possible to present the modal when eg. 3 pages have been viewed. Assuming that visitors with 1-2 page views would not be interessted in a newsletter.

It's certainly possible, however, modals aren't as simple as clickkng a few things together (at least not before drupal 8 :p).

One way to do it would be to add a counter to user's Session. Increase the counter every time a new page is viewed and once it reaches 3, trigger the display of a modal, for instance by using ctools modal generation api.


Show or hide fields in view based on a user relationships I have a table on my site made with views. I have the User Relationships module installed so users can connect with each other.
I want most of the fields to be visible for all users but there is one field that must only be showed if the author of the content and the logged in user have a relation with each other.

Is this even possible? I have tried different settings.
It is possible with a filter criteria to hide the complete node if the users aren't related. But that is not what I want. It is just one field of that node type that must be hidden if the users aren't related.

The Views Conditional module works for me! Thank you J. Reynolds!
I have the price field set to be hidden, and created a conditional field that shows the price field (with the token), if the relationship field (also hidden),   haves the value of "the name of the relationship". If it has not that value it shows "----".
I am going to fine tune some things around the relationships module but this is exactly what I needed. Thanks again!


How can I design a relationship between two types of users? I have two types of users in drupal-7: children users and parents users. How can I design a relationship between these types of users?

Also How can I maintain this relationship in the code? i.e. getting the parent of the child or vice versa.

You can use the User Relationships module for that.

  Administrators are able create relationship types (friend, coworker, etc). Relationship types can be setup to be one-way or mutual. If a relationship type is one-way (subscriber) only the requester is shown as relating to the requestee. Relationship types can also be set as needing or not needing approval.

I've used this module for one of my project. It works great!


How can I filter a view by "has translation"? Filter a view by "Current user language" creates an empty div when missing translation. This is problematic because it breaks my layout. See the below image for my criteria.

This is not tested but you could probably add the filter "Node translation: Child translation" to your view. Together with the current user language fiter this could work. Description is: "Content that is a translation of a source translation."


Drupal 8, Commerce 2 custom products, variations and order items I'm trying to create custom products with Commerce 2. More specifically I'm trying to have custom ui for customers to build their purchasable products.

I thought that I would be able to create single Product and it's variation and then make some adjustments for price and some other fields. It seems that I'm able to programmatically create custom OrderItem, set all custom fields as needed and then add item to cart. Apparently this works as expected.

But I'm having issues getting custom price set for the OrderItem. Seems that I have to create separate ProductVariation for each ordered item, even if it's the same in all practical purposes. Only differing data is price. I tried using instructions here(http://docs.drupalcommerce.org/v2/recipes/orders.html).

$order_item = \Drupal\commerce_order\Entity\OrderItem::create([
  'type' => 'custom_order_item_type',
  'purchased_entity' => $variation_red_medium,
  'quantity' => 2,
  'unit_price' => $variation_red_medium->getPrice(),
]);
$order_item->save();

If I leave unit_price empty, to be set later, I get TypeError: Argument 1 passed to Drupal\commerce_order\Entity\OrderItem::setUnitPrice() must be an instance of Drupal\commerce_price\Price, null given, called in /var/www/drupalvm/web/modules/contrib/commerce/modules/order/src/OrderRefresh.php on line 143

I'm trying to do this:

// You can also set the price with setUnitPrice.
$unit_price = new \Drupal\commerce_price\Price('9.99', 'USD');
$order_item->setUnitPrice($unit_price);
$order_item->save();

Only way I got this to work was setting ProductVariation price separately, but this then updates the basic price on the Product page, which really isn't what I'm looking for..

On the documentation it says this:

 * adjustments [OPTIONAL] - [Array(Drupal\commerce_order\Adjustment)]
 *   Array of any price adjustments.

but I can't get this far because OrderItem creation fails because of the missing price. If I set price, it just get's overridden from the initial ProductVariation.

I suppose that I can get around this by creating those ProductVariations on the fly, but I'd rather not since I don't need those for anything else than this single purchase.

So I guess I'm looking for some instructions on how to do dynamic products. Tried PurchasableEntity initially, but couldn't get that working at all and wasn't able to reverse engineer my needs from ProductBundle or similar.

Or any info how to set OrderItem price independently from ProductVariation.

Cheers,

Janne

When setting the unit price, you must set the override parameter to true as so:

$unit_price = new \Drupal\commerce_price\Price('9.99', 'USD');
$order_item->setUnitPrice($unit_price, TRUE);
$order_item->save();


what's Taxed line items in the ubercart tax module? does anyone know what is referring to the fields :
Taxed line items : Shipping,Empty line,Tax in the tax configuration?
i couldn't find an explanation

Line items are the items in an order. They can include products, shipping, and tax. The taxed line items are the line items you apply the tax rate to. Generally that would just be the products.


How to get "empty line items" in Commerce, similar to Ubercart? In Ubercart, there is a little feature for adding "empty line items" to an admin created order. This allowed an admin to manually enter a custom title for the line item and a custom amount. Essentially allowing you to add line items without going through the process of creating a product first, then attaching it to the order. Very helpful for creating invoices for custom services. Is there any way I can get this feature in Drupal Commerce?

This is how it looks and works in Ubercart:

In Drupal Commerce, we made the decision to add line item type dependent callbacks to the line item API. A product line item will function differently from a shipping line item will function ... etc. As a side effect, this means there is no such thing as a "generic" line item, just like there is no such thing as a typeless node.

What needs to happen, if it doesn't already exist, is a small contrib module could be made that adds a basic line item type whose "line item add form" in the order edit page lets you specify all the information needed to manage and display that line item. Where it's gonna break down are things like pricing rules - should these line items have taxes? Should other discounts apply? Or display rules - should these show up on customer order pages?

There is no such feature in core (as you can see, it'd be a small contrib, but it wouldn't be trivial to make), but if it were tested and proved as a concept in contrib, I don't see why we couldn't consider it for inclusion in Commerce 2.x.


Display different time from one field value I have field to display event start date and time. This field uses date module's widget. I need display time of event start for different time zones. For example:

Eventname - starttime for Tallin: 05.07.2015 01:54

Eventname - starttime for Boston: 05.07.2015 09:54 (+8 Hours)

How can I add +8 hours to date field value and display result on node?

Well you are better off writing a custom module or using a function that can swap out a timezone variable instead of manually calculating by adding 8 hours...
But if that's what you want here is one way of achieving this..

Create a node template for that content type or specific node (whichever suits your scenario).

In the template file you can use:

 <?php
    // Your date field. note the appended 'field_' at the start of the machine name.
    $date = new DateTime($content['field_YOUR_FIELD_MACHINE_NAME']['#items'][0]['value']);

    // Boston date field
    $boston_date = $date;
    $boston_date ->modify("+8 hours");
    $boston_date ->format("d.m.Y H:i");

    //Outputs your date field with 8 hours added to it.
    print 'Eventname - starttime for Boston: ' . $boston_date;
 ?>


Different sets of language icons per theme I'm using Language Icons and Language Switcher modules. The flag icons are added to the language switcher block, but the icons are stored in sites/all/modules/languageicons/flags. They are of fixed height of 12 pixels by default and they are used by every theme.

I want to use different sets of flag icons with different dimensions per theme, for example, Theme 1 will use the default icons of 12x12 pixels, but Theme 2 will use the icons of 19x19 pixels. I will have my custom flag icons in my custom module or in my custom themes.

I would do this by using hook_block_view_alter() to override the block output per theme, but I'm looking for a better and right way.

As mentioned in my question, I could not do this by using hook_block_view_alter() because I can only have the renderable HTML of the block content in that hook.

I found a theme function theme_languageicons_icon, which renders the icons, in the file sites/all/modules/ languageicons/languageicons.module. I copied the theme function into my custom module and implemented hook_theme_registry_alter() to override it.
Then, I updated the function as my need and flushed caches. It gave me exactly what I needed.

function MYMODULE_theme_registry_alter(&$theme_registry){
    if( isset($theme_registry['languageicons_icon']) ){
        $theme_registry['languageicons_icon']['function'] = 'theme_mymodule_languageicons_icon';
    }
}

function theme_mymodule_languageicons_icon($variables) {
  global $theme;
  $language = $variables['language'];
  $title    = $variables['title'];
  # define icons path for various themes
  $default_path = variable_get('languageicons_path', drupal_get_path('module', 'languageicons') . '/flags/*.png');
  $path_by_theme = array(
    'theme1' => drupal_get_path('theme', 'theme1') . '/flags/*.png'
    'theme2' => drupal_get_path('theme', 'theme2') . '/flags/*.png'
  );
  $path = (isset($path_by_theme[$theme]) && file_exists($path_by_theme[$theme])) ? $path_by_theme[$theme] : $default_path;
  # define dimension for various themes
  $default_size = check_plain(variable_get('languageicons_size', '16x12'));
  $size_by_theme = array(
    'theme1' => '19x19',
    'theme2' => '25x24',
  );
  $size = (isset($size_by_theme[$theme])) ? $size_by_theme[$theme] : $default_size;

  if ($path) {
    $title = $title ? $title : $language->native;
    // Build up $image for theme_image() consumption.
    $image = array(
      'path' => str_replace('*', $language->language, check_plain($path)),
      'alt' => $title,
      'title' => $title,
      'attributes' => array(
        'class' => 'language-icon',
      ),
    );
    if ($size) {
      list($width, $height) = explode('x', $size);
      $image += array('width' => $width, 'height' => $height);
    }
    return theme('image', $image);
  }
}

If you have a better solution, it is welcome.


clearfix to views-row What is the recommended way to add a "clearfix" class to a div.views-row?

Note that I dont want to add the clearfix to all views, just a specific view.

Is this best done with a template override, or is there a mystical alter hook that will let me add in what I need in my template.php without having to override and thus maintain an entire views template file, just to add a class.

Is this views 3? If so if you go to the Settings for the format you can add a Row class (the description says "The class to provide on each row") which should do what you want without templates etc.


Hide hybridauth tab from user page I want to hide hybridauth tab in user page. I have used  $items['user/%user/hybridauth']['access callback'] = FALSE; in hook_menu_alter() which gives the result, but hides for all user. In my case I Want hybridauth tab to hide for all user except admin.

Can you try this solution?

$items['user/%user/hybridauth']['access arguments'] = array('administer site configuration');


How to rewrite link to taxonomy term in Views when using Pathauto? The default language of my site is English.  Taxonomy terms are translated using Entity Translation.  I have created a view that uses aggregation to show Japanese terms (name provided by the Title module).

However, the Japanese terms do not have a path alias, so I need to rewrite the link provided by the view to point to the English term.  The URL aliases of the English terms are generated by Pathauto, which strips some words ("to" in "Things I like to do").

Example:

English term: Listening to Music
Pathauto alias: listening-music
Japanese term: 音楽鑑賞
Desired output: 音楽鑑賞 (link pointing to listening-music)

I tried rewriting the link to [name] (the English term) with conversion to lowercase and spaces converted to dashes, but this causes the link to be listening-to-music, not listening-music.  Ideally, I would like to keep pathauto settings as they are and somehow grab the URL of the term within views.  Is this possible?

To get path of taxonomy term in default language (in your case it is English) you can use url() function, example:

$term_url = url('taxonomy/term/'. $term->tid, array('language' => language_default()));


Equivalent of _phptemplate_variables() There is a function in Drupal 5 (_phptemplate_variables()) that has been deprecated in Drupal 6.
Is there a similar function in Drupal 6?

well, i'm not totally sure what you mean, but according to the title of the post, you want a redirect function ?

something like the drupal_goto(); function?

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_goto/6


How to modify a form field? i want to modify a Select option field of webform with hook_form_FORM_ID_alter(), but when I do something like:

$form['submitted']['dia'] = array(
'#type' => 'select',
'#title' => 'Dia',
'#options' => $options_first,
'#default_value' => $selected,
'#ajax' => array(
  'callback' => 'ajax_example_dependent_dropdown_callback',
  'wrapper' => 'dropdown-second-replace',
),
);

all the other values are replaced and also the weight.

I only need to add 'options', 'default_value', and 'ajax'. If I remove other properties like, 'type' the field is not displayed, and the other properties like weight is removed if I do what is in the code. How to modify these 3 attributes?

When you are using this syntax:

$form['submitted']['dia'] = array(

you create a whole new array, with only the values you provided. Old array that was there is simply discarded. If you only want to add or modify 'options', 'default_value', and 'ajax', you need to access them directly:

$form['submitted']['dia']['options'] = $options_first;
$form['submitted']['dia']['default_value'] = $selected;
$form['submitted']['dia']['ajax'] = array(
  'callback' => 'ajax_example_dependent_dropdown_callback',
  'wrapper' => 'dropdown-second-replace',
);


How can I write an if else statement in Twig based on commerce stock quantity? Building a D8 Commerce site and trying to hide the price if the product is out of stock.
I can access the stock value with this:
{{ product.variation_field_stock_level.0 }}

I've tried this:
{% if product.variation_field_stock_level.0 > 0 %}
 {{ product.variation_price }}
{% else %}

Sold

{% endif %}

...but it prints the price regardless of whether the stock value is 0 or 1 (or more).
I've also tried:
{% if product.variation_field_stock_level.0 == 0 %}

Sold

{% else %}
  {{ product.variation_price }}
{% endif %}

Regardless of what I try it just will not work.

This is very close - but it seems you are missing the actual stock level value from the object. Start by doing something like:
{{product.variation_field_stock_level.0|json_encode}}

Run it through a json cleaner to make it readable, like: JSON Cleaner
You will see this:
{"#type":"html_tag","#tag":"p","#value":0}

Now the conditional will be:
{% if product.variation_field_stock_level.0['#value'] > 0 %}
    {{ product.variation_price }}
{% else %}

Sold

{% endif %}


How would I get taxonomy info using the taxonomy term ID, in order to theme it? I need to be able to extract a taxonomy array and use it to create links.

taxonomy_term_load() looks promising.

  Return the term object matching a term ID.

  Parameters

  $tid A term's ID

  Return value

  A term object. Results are statically cached.


how to remove fieldset from date input I set up a site in drupal, and I need to show the fields of date type in the same way as other fields. the problem is that those fields are inside a fieldset.

I'm try the solution code karate, buts it only changes the fieldset to a label.

What I want is showing those fields outside a fieldset, stay equal to the remaining fields.

I am using the following code.

/**
 * Remove fieldset from date inputs
 */
function mytheme_date_combo($variables) {
    dd($variables);
    return theme('form_element', $variables);
}

I used a patch from an issue queue in drupal to sort me out on that one. I should say it works well for me. You can find it here


Disable shipping on checkout page How to disable shipping or delivery pane by rules on checkout page?
i am developing a sytem using ubercart in drupal 7.

You can hide it dynamically if no products in the order are
shippable. We are using ubercart 7.x-3.4 and on the Checkout
settings page /admin/store/settings/checkout (Home » Administration
» Store » Configuration » Checkout) there is an checkbox 'Hide
delivery information when carts have no shippable items.' Then, when
you edit each product, the Product information vertical tab contains
a checkbox 'Product is shippable.'
You can hide it completely on the Checkout settings page /admin/store/settings/checkout (Home » Administration » Store »
Configuration » Checkout) there is a list of the panes available on
the Checkout. If you uncheck 'Delivery information' and 'Delivery method' those panes will never appear.  If you are going to hide the Delivery information pane then the other option on the Checkout settings page 'Use the same address for billing and delivery by default.' would be useful too.


Different domain per node I wonder if it is possible to have different domains set for, for instance, per path basis, or view basis, or node id basis?

Domain Access is great module that allows you to different domains set for instance, per path basis, or view basis, or node id basis.

The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.


During updating translation: Fatal error: Maximum execution time of 240 seconds exceeded I've tried to install a second language to my Drupal7 site. It can be done either by automatically or manually translation. I tried both but I got into the following issue at halftime:

  Maximum execution time of 240 seconds exceeded.

I tried to set higher values in php.ini:

default_socket_timeout = 240 (it was 60)
max_input_time = 360;
max_execution_time = 360;

I using local WAMP and Drupal7 installation. Port 8888.

I need help with configuration or another way to install it.

Open sites/all/modules/l10n_update/l10n_update.locale.inc; at line 28, change the code to the following one:

drupal_set_time_limit(840);

It will increase the execution time and will work. The original code set the time limit to 240.


twig check if image style or view mode exists I have a site design the i need to implement.
in this design I have a grid and in the grid I can put any content (node/paragraph) that i choose.
the image of the content changes size and ratio in relation to its location in the grid.
I created display modes for the nodes and i use twig tweak to render it in the right display mode for example:

{{ drupal_entity('node', content['#node'].id , 'box_grid_1x2') }}

for the paragraphs I add my image style directly in the paragraph template:

{{ content.field_image.0 | merge({'#image_style': 'box_grid_1x2'}) }}

because its a little more dynamic than this and my 'box_grid_1x2' is actually a variable that can be set by the user I want to verify that my image styles of view modes do exist before printing them and if they dont I want to print a fallback display\image style.

how would you do it?
Thanks for your help.

You can check image style existence in a preprocess hooks like follows.

$variables['image_style_exists'] = (bool) ImageStyle::load($style_name);

Though it's better to validate user input instead.
Note that configuration entities like image styles or views can be selected through entity reference field which may perform such a validation for you.


Programatically created node type does not display title field I have created a new node type within a module (for Drupal 7). I have created fields for it programatically as well and they all display. The one problem I am experiencing is that the title field does not display. I am not sure how or where to look to fix this. The title field does display in the node type's manage fields display.

Here is the code for creating the node type in hook_install():

// define the node type
  $type = array(
    'type' => $machine_name,
    'name' => $t($parameters['name']),
    'base' => 'room_reservations',
    'module' => 'room_reservations',
    'description' => $t($parameters['description']),
    'has_title' => TRUE,
    'title_label' => $t($parameters['title_label']),
    'custom' => FALSE,
    'locked' => TRUE,
    'disabled' => FALSE,
  );

// set other node defaults not declared above
  $content_type = node_type_set_defaults($type);

// add the body field
  node_add_body_field($content_type, $t($parameters['body_label']));

// save the content type
  node_type_save($content_type);

Drupal does not display the title field in the manage display page by default.

You would have to use Display Suite Module and enable a layout for the page to get the title and other fields to display in the Manage Display page.


Add relationship to node view I recently installed the "simplenews" and "simplenews_scheduler" modules. The first module generates a view where you can see the newsletters.
My idea was to create a relationship in that view to gather the data from the "simplenews_scheduler" table to know if a newsletter has an active schedule.

I tried the "views_data" and "views_data_alter" hooks but I can't add the "activated" field of the "simplenews_scheduler" table. The base table of the view is "node_field_data"

Is it possible to do what I'm trying to do? And if so, can someone tell me what I should do?
Thank you very much.

To create a view from a database table instead of using hook_views_data you can use Views Custom Table module:

View custom table module provide you functionality to integrate your custom table data to views, and access all it's column in views. This module use hook_view_data to add custom tables in views.

it's easy just follow the 7 steps in How to use section in module page.


Count total number of values in a field of all nodes combined for a view I need to count the number of entries made to a field in all nodes combined together.

I tried toggling aggregation to 'yes' and aggregation type to 'COUNT as distinct'. But at that time I'm getting count for each node separately.
But What I really need is a single line output saying this much of entries made to this field for the whole nodes combined together.

The after that I will be able to filter it by 'id from logged in user' or 'date created'.

There is a module to assist with that: Views Field

  Allows field tables to be used as base tables with Views.

After you installed the module you need to visit the field setting on any content type that includes the field. Tick Expose as base table, then select all the columns to expose excluding revision_id.

Next create a view and at admin/structure/views/addat Show listbox you select the Field base table. This will now create a view on the field in question's base table.

Your view settings should have these settings:

Use aggregation: Yes
Fields: Entity Type (The entity type this data is attached to) with
Aggregation setting Count.

You can now add Relationship: Field tables: Field XXX => Node to get access to the nodes the fields are attached to and from there author etc.

ALTERNATIVE

Create a View of Content (ie nodes) showing fields. Set Aggregation to Yes. Remove sort Criteria, filter criteria and Pager. Add your field's delta (Delta - Appears in: node:xxx.) to the View fields with aggregation set to COUNT.


Shipping rules for group of countries (ex. UK or ITALY) I'm creating the shipping rates depending on country. I've got groups of countries with the same rate.

I've installed Shipping 2.0 and Flat Rate module.

I've limited the available countries through the customer profile and then I've created the flat rates for group of country (ITALY or BRAZIL) and some for a single country (UK).

In the components I did this

Condition:
Order address component comparision

Address : Shipping address

Address component : Country

VALUE : GB

(REMEMBER, THE VALUE IS THE TWO LETTER ABBREVIATION, ITALY WILL BE IT AND UNITED KINGDOM IS GB. YOU CAN FIND IT LOOKING A THE HTML OF THE SHIPPING FORM)

I've added one condition per each country of that group. I've implemented with OR but for some reason it does not work.

This is the result:
Condition 1 : IT

OR

Condition 2: FR

This does not work, so I tried:

Condition 1: IT

--OR

----Condition 2: FR

But nothing...

What Am I doing wrong? It's something related to the "OR"?

The flat rate with single country works, the one with complex rules doesn't.

I SOLVED IT: IT WAS THE CONDITIONS POSITIONS. THE RIGHT WAY TO USE "OR" IS THIS:

OR

--CONTITION 1

--CONTIDION 2

HERE YOU CAN FIN A REALLE NICE RULES TUTORIAL

The OR and AND-groups takes all conditions inside of them with the chosen operator.

Your:

Condition 1: IT
--OR
----Condition 2: FR

Will be converted into ([Condition 1] AND ([Condition 2])).

Try putting both Condition 1 and Condition 2 in the OR-group:

--OR
----Condition 1: IT
----Condition 2: FR

This should be converted into ([Condition 1] OR [Condition 2]).
If that's what you're after.

Edit: Just a couple of minutes too late :)


Comparison in twig templates I have a list field for a custom content type that looks like this:

Field Machine name is: field_app_os

key|label
Win|Windows
Android|Android

I can access the key in Twig template by using content.field_app_os or Twig Field Value and the output of both is Android:

  Twig Field Value allows Drupal 8 themers to get partial data from
  field render arrays. It gives them more control over the output
  without drilling deep into the render array or using preprocess
  functions.
  Filters:
  - field_label : Returns the field label value.
  - field_value : Returns the render array of the field value(s) without the field wrappers.

/* with use of Twig Field Value module */
{{ content.field_app_os|field_value }}  {# outputs 'Android' #}

 /* without use of Twig Field Value module */
{{ content.field_app_os }}  {# outputs 'Android' #}

However, if I do a simple comparison, the output of both is False.

{% set app_os = content.field_app_os|field_value %}
{{ kint(app_os == 'Android') }} {# outputs 'bool FALSE' #}

Or When I use:

{% set app_os = content.field_app_os %}
{{ kint(app_os == 'Android') }} {# outputs 'bool FALSE' #}

What's wrong in my code?

{{ content }} is a render array, where you find the label of the key/label pair probably here:

{{ content.field_app_os[0]['#markup'] }}

But this is not ideal for logic:

The position in the render array can change, for example if you
install a layout module.
The content of #markup depends on how the
field formatter is configured in the view mode.
The label is translatable, so the
logic breaks on a multilingual site.

So it's better to use the database value in:

{{ node.field_app_os.value }}

This is the first part of the key/label pair, which is untranslatable and you can access the value independent on how the field is configured in the view mode.


Is there any reason Backup & Migrate leaves all the .info files around? I just discovered that there are hundreds of .info files left lying around in the folder that the Backup & Migrate module uses for scheduled backups, while only 12 of these have a corresponding .gz file.

Is there a reason to keep these?  Do they have any real value?

There doesn't appear to be any value to keeping them.  To get rid of them, you can do something like this

cd /private/backup_migrate/scheduled  # where ever you keep this
for file in *.info; do gz_file=`echo "$file" | sed -e 's/.info//'`; if [[ ! -f "${gz_file}" ]]; then rm -f "${file}"; fi; done

This will preserve all *.info files that correspond to a *.gz file, and delete the rest.  It appears to be an oversight on the part of the Backup & Migrate module to leave all of these lying around.   (Apologies in advance to the module's maintainers if I'm mistaken on this:  I do not mean to be critical, and I appreciate your work!)

If you want to wrap all this up into a quick alias or function, you can put something like this into your ~/.bashrc or ~/.zshrc or whatever:

function cleanup_backups(){
  pushd /<youfillinthispart>/private/backup_migrate/scheduled
  for file in *.info; do
    gz_file=`echo "$file" | sed -e 's/.info//'`
    if [[ ! -f "${gz_file}" ]]; then
      rm -f "${file}"
    fi
  done
  pushd
}

(You'll have to make it a bit more complicated if you have subdirectories in your scheduled backups folder, but this should get you started.)


Print module theming address for user page I am using the print module to have print-friendly pages. I followed theme suggestions, I could not make the theming work for user pages. So far, I tried the following I would like to theme user pages for printing but I could not figure out how.

print--html--user.tpl.php
print--html--user--%.tpl.php
print--html--page--user.tpl.php

Example pages to view theme suggestions, here and here.

The print module that you try to use only works for nodes.
You can use the Entity Print module for Drupal 7.
You can read in the docs how to override the default template.

Overriding Templates
You can copy the entity-print.tpl.php template into your theme to take control of the global PDF template.
If you wish to have per entity type templates you can do so by implementing hook_theme() for different entity type keys, for example:
<?php
function MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'entity_print__commerce_order' => array(
      'base hook' => 'entity_print',
      'template' => 'entity-print--commerce-order',
    ),
  );
}
?>


hide published node's field? I want to hide one of a node's field when the node was published. I copied and renamed the node.tpl.php as node--app.tpl.php cause the node's content type's machine name is app.

I tested it by add the code at the beginning of the node--app.tpl.php file. yeah it works.

<?php print $node->field__iap_dl['und'][0]['url']; ?>

In order to hide the field I added one line in the existing code.

<div class="content clearfix"<?php print $content_attributes; ?>>

<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  hide($content['field__ipa_dl']);    // I added!
  print render($content);
?>
</div>

This time it didn't work. What's wrong? I am newbie to code the Drupal.

You did not tell it to hide $node->field__iap_dl['und'][0]['url'].

The field probably did not show up in the rendered content, but it will still appear if you tell the template to print the information directly from the node object.

The simplest way to hide a field is to go to /admin/structure/types and under manage fields for the content type, mark the field as hidden.

EDIT:

Is this a cut and paste of your code? If so the fields names are different. field__iap_dl is not the same as field__ipa_dl.


How can I theme a module in Drupal 7? I'm new to developing in Drupal and am trying to create my first module. I've got it all set up, but I don't know how to add the theme to it. Right now it just shows a blank page with only the text "Hello World".

   <?php
function news_main() {
    require_once('/global_applications/news/home.php');
}

function news_menu() {
    $items = array();

    $items['news'] = array(
        'page callback' => 'news_main',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
     );

    return $items;
}
?>

You are seeing a page containing just that string because the code you are using is printing the string, and then it exits. This means the theming system used by Drupal is not used to render the page, which will just contain the echoed text.

If you want to theme a page, the page callback needs to return HTML content, as in Drupal 6, or an array that contains the same elements used for the array passed to drupal_render().

As example of page callback, you can look at node_add_page():

function node_add_page() {
  $item = menu_get_item();
  $content = system_admin_menu_block($item);
  // Bypass the node/add listing if only one content type is available.
  if (count($content) == 1) {
    $item = array_shift($content);
    drupal_goto($item['href']);
  }
  return theme('node_add_list', array('content' => $content));
}

An example of page callback that returns an array is node_page_default(), which contains the following code:

function node_page_default() {
  $select = db_select('node', 'n')
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('promote', 1)
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->extend('PagerDefault')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access');

  $nids = $select->execute()->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build = node_view_multiple($nodes);

    // 'rss.xml' is a path, not a file, registered in node_menu().
    drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
    drupal_set_title('');
  }
  else {
    drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);

    $default_message = '
' . t('No front page content has been created yet.') . '
';

    $default_links = array();
    if (_node_add_access()) {
      $default_links[] = l(t('Add new content'), 'node/add');
    }
    if (!empty($default_links)) {
      $default_message .= theme('item_list', array('items' => $default_links));
    }

    $build['default_message'] = array(
      '#markup' => $default_message,
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }
  return $build;
}

You first task is then to incorporate the code there is in the /global_applications/news/home.php file into news_main(), and change it to either return HTML content, or an array as required by drupal_render(). The latter is preferred as it allows other modules to alter the output of the page callback.

Keep in mind that if you need to render a form, you should use the form API, which means that the page callback should be "drupal_get_form," in that case; the first argument passed in "page arguments" is the form ID for the form to render.


Compute 3 New Date Fields What is the best way to output 3 new dates relative to the first date? For instance, I have a date field called "medication_start" = 1/1/2010. I would like three new dates generated in 3 new fields in 6, 12, and 18 months from the start date.

Period 1 (6 months): 6/1/2010
Period 2 (12 months): 12/1/2010
Period 3 (18 months): 6/1/2011

You could use something like Computed Field for this or you can write your own custom module. You could hook into node save using hook_node_presave (since it acts on save and presave) and calculate the other 3 fields that you need to save. Either way should work pretty well. You would just use php date functions to calculate the new dates either way. There are a bunch of examples for computed field online and in their documentation you could use to draw inspiration from.


Custom links to switch language in Drupal 6 In my case, I wanted to print the language switch links directly in page.tpl.php, for example with:

English
Deutsch

How can I accomplish this without using the "Language switcher" block? I checked all the modules that comes with the Internationalization project, but I didn't see any hook_block() implementation that outputs the language switcher block.

UPDATED:
I wanted something like: This site is on russian, english and kazakh languages.
This cannot be done with language switcher block.

i've tried this way in page.tpl.php:

<?php
$way = drupal_is_front_page() ? '<front>' : $_GET['q'];
print ''. 'на ' . l('русском', $way). ', ' . l('казахском', 'kk/'.$way). ' и ' . l('английском', 'en/'.$way) .'';
?>

Default language is russian - mysite.com, when i switch to an english - mysite.com/en, as you see it adds prefix 'en'. But now if i want to switch on kazakh language - mysite.com/kk from english the link looks mysite.com/en/kk == it adds en to my URL. How to make this correctly?

What doesn't work for you with the language switcher ?
If you want to reproduce its behavior, have a look at its code and try to do something equal.

Here is some code:

$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$languages = language_list('enabled');
$links = array();
foreach ($languages[1] as $language) {
  $links[$language->language] = array(
    'href' => $path,
    'title' => $language->native,
    'language' => $language,
    'attributes' => array('class' => 'language-link'),
  );
}
drupal_alter('translation_link', $links, $path);
//dpm($links);

foreach ($links as $link) {
  echo t('Link for ') . l($link['title'], $link['href']) . '<br />';
}


Are there changes to Views functions? I am trying to update a old custom module written for Drupal 7 for Drupal 8. I have used a lot of view functions like views_include() and views_get_view(). Are they all dropped in Drupal 8?

function validate_email($email) {
    //pass the email to the filter
    views_include('view');
    $name = 'send_otp';
    $display = 'page_1';
    $alter = array('exposed' =>array('field_email_value' => $email));
    $view = views_get_view($name);
    $view->init_display($display);
    $view->preview=TRUE;
    $view->is_cacheable = FALSE;
    if(isset($alter['exposed'])) {
        foreach($alter['exposed'] as $key => $valor) {
            $view->exposed_input[$key] = $valor;
        }
    }
    $view->pre_execute();
    $output = $view->display_handler->preview();
    $view->post_execute();
    //if the result is empty
    if(empty($view->result)) {
        //return 0
        return 0;
    }
    else {
        //return node id
        return $view->result[0]->nid;
    }
}

  Fatal error:  Call to undefined function views_include() in /var/www/html/mdc-conference-backend/sites/all/modules/custom/rest/sendotp.php on line
  43

views_get_view became Views::getView, and several others are now static methods on the Views class in the views module.

I don't think views_include is necessary anymore.


How to make an OR statement in rules? I am using Rules with Rules Once Per a Day. Although Once Per a Day is not part of the default Rules, the general core of my question applies to default Rules.

I want Rules per Once a day to activate either on Monday or Thursday. To do this I am using an OR condition:

But it did not work. Is my OR statement set up correctly?

I’ve looked at several Drupal Rules tutorials about creating OR conditions, but they all seem to give different advice. Some say you need a separate OR grouping for each condition, others say all the conditions need to be in one OR group.

NB: My rule exists on the main rules screen and NOT under the components tab.

Both the conditions should be nested under the "OR" line like this:

+ OR
  + Current day of the week (is Monday)
  + Current day of the week (is Thursday)

What you have at the moment is a clause that says "if the current day of the week is a Monday and one of the following conditions is true: the day of the week is Thursday"


Modify the error message about the maximum upload file size I would like to modify the default error message for the maximum upload file size, but I can't find the configuration.
I looked at webform general settings, individual settings, and media file settings, but I found nothing about it. Forum issues only talk about configuration of the maximum file size, not about customization of the error message.

Can anyone help me?

As far as I know, there is not a way to add a validation handler for the file field type in general. You'll need to set a hook form alter and add a custom form validate handler for the edit forms, webforms, etc that you want to override.

Refer to: How do I add a custom validation handler to an existing form/field?

Alternatively, if your site is a multilingual site configured for internationalization, you can probably override the english version of the message in the. po file. I would advise against installing and enabling internationalization just for this use case, as it adds several pieces of functionality to the site and can bloat your database.


XML sitemap in Multilingual site How to configure xml sitemap for multi language site.For translation I am using i18n module and for xml sitemap. Now there are only one link show in NL site map and 26 in default language.

Run the cron manually it will update this.If you have more translations for NL it will get update there.

cheers!


Disabled messages still showing I'm trying to use the Disable Messages Module to hide some messages. For example the message Proposal has been updated. (because I'm using a wizard and updates every step).

These are my configuration settings of the disable messages module:

I've cleared my cache but the message is still showing. Am I doing something wrong?

It should be:

Proposal .* has been updated

and not

Proposal *. has been updated

What you want is

Proposal, space, any number of any characters, space, ...

But what you wrote is:

Proposal, any number of spaces, one of any character, space, ...


How to send form submitted data to paypal in Drupal? I have setup a form where user fill some fields and choose a user type & on submission I have to send him to paypal with the values which he filled up, so that on IPN callback I receive the data from them and do something(this is the procedure I have come to know from reading paypal integration with php), I am stuck at form point because at submission I have another function where I can get the selected value by form_state..

Here is the code --

<?php

//Hook_Menu for paypal callback function.
function user_type_registration_menu(){
  $items = array();
          $items['paypal/payment/ipn'] = array(
          'title' => t('Paypal Payment IPN'),
          'description' => t('Paypal Payment IPN'),
          'type' => MENU_CALLBACK,
        'file'  => 'paypal_payment.inc',
          'page callback' => 'paypal_payment_paypal_ipn_callback',
          'access callback' => TRUE,
        );
      return $items;
}

//Form alter for registration form.
function user_type_register_form_alter(&$form, &$form_state, $form_id){
  switch($form_id) {
      case 'user_register_form': // the value we stole from the rendered form
        $form['account']['user_type'] = array(
          '#type' => 'select',
          '#title' => t('Membership Type:'),
          '#options' => array(
            0 => t('General $50.00/Yr'),
            1 => t('Student $40.00/Yr'),
            2 => t('Government $60.00/Yr'),
            ),
           '#weight' => -11,
           '#description' => t('Select the membership type, which you want to have.'),
          );
        $form['account']['user_type_submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
          '#submit' => array('user_type_register_form_submit'),
          '#validate' => array('user_type_register_form_alter_validate'),
        );
        $form['account']['name']['#description'] = t('');
        $form['account']['mail']['#description'] = t('');
        unset ($form['actions']);// unset the default submit Button
        return $form;
      break;
    }
}

function user_type_register_form_submit($form, &$form_state){
  $username = $form_state['values']['name'];
  $user_email = $form_state['values']['mail'];
  $user_type = $form_state['values']['user_type'];
  $password = user_password(8);
  switch($user_type){

    case '0':
      dpm("General");
      $membership_price = 50;
      $fields = array(
        'name' => $username,
        'mail' => $user_email,
        'pass' => $password,
        'status' => 1,
        'init' => $user_email,
        'roles' => array(
          DRUPAL_AUTHENTICATED_RID => 'authenticated user',),
      );
      $account = user_save('', $fields);
      $account->password = $fields['password'];
      //--Here I have to send if to PAYPAL

      dpm("user registered");
      break;

    case '1':
      dpm("Student");
      $membership_price = 40;
      $fields = array(
        'name' => $username,
        'mail' => $user_email,
        'pass' => $password,
        'status' => 1,
        'init' => $user_email,
        'roles' => array(
          DRUPAL_AUTHENTICATED_RID => 'authenticated user',),
      );
      $account = user_save('', $fields);
      $account->password = $fields['password'];
      //--Here I have to send if to PAYPAL
      break;

    case '2':
      dpm("Government");
      $membership_price = 60;
      $fields = array(
        'name' => $username,
        'mail' => $user_email,
        'pass' => $password,
        'status' => 1,
        'init' => $user_email,
        'roles' => array(
          DRUPAL_AUTHENTICATED_RID => 'authenticated user',),
      );
      $account = user_save('', $fields);
      $account->password = $fields['password'];
      //--Here I have to send if to PAYPAL
      break;
  }
}

function user_type_register_form_alter_validate(){

}

I hope somebody can help...

I'm the maintainer of Drupal Commerce and of the Commerce PayPal module. I'm afraid your question is too broad to be answerable here, but for folks looking to solve the same issue, you should check out the code in my Commerce PayPal module. It provides a full integration of WPS, WPP, EC, and PPA / Payflow Link.

For general Drupal support, there are much better channels to pursue. I'd look into videos or books specifically focusing on the Forms API or just dive into module code like mine to learn through investigating working examples.


How do I convert a render array to plain HTML? I have a render array with a list of items.

$array = array(
  'list' => array(
    '#items' => $items,
    '#theme' => 'item_list'
  )
);

I tried to use it with ajax_command_html(), which works perfectly with a simple HTML string, but it doesn't work when it gets a render array.

Can I somehow convert this render array to an HTML string to use it with that function?

ajax_prepare_response() contains the following code.

$html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
$commands[] = ajax_command_insert(NULL, $html);
// Add the status messages inside the new content's wrapper element, so that
// on subsequent Ajax requests, it is treated as old content.
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));

So, to achieve the same (i.e. convert a render array into a HTML string), you can call drupal_render() passing the render array to the function.

 $render_array = array(
    '#items' => $items,
    '#theme' => 'item_list'
 );

 return ajax_command_html($elector, drupal_render($render_array));

Also theme() would return a HTML string, and you could as well use the following code.

 return ajax_command_html($elector, theme('item_list', array('items' => $items)));

Since Drupal 8 doesn't have the theme() function anymore, I would use drupal_render() just to make easier to convert Drupal 7 code to Drupal 8.

Keep in mind that drupal_render() is expecting an array; in the case you are calling it from a function that could receive a string as argument, you need to verify you are passing an array to drupal_render(), as the code I shown does.


How to create a statistics dashboard of my users using Views? I'm working on a Drupal website based on its users. They can login, pay their debts, set and update their personal and contact information, etc.

I would like to create a Dashboard showing statistics of these users, based on my user's fields, something like:

GENDER: Male 54% - 46% Female
ACTIVE USERS: 67%
AGES: 20% KIDS - 56% Young - 16% Old - 8% Other

I even have a design for it, I´m just trying to figure it out technically using the Views module. Any idea?

Use the Charts module and its integration with the Views module. A straight forward cloning of the delivered views example would do what you are asking for. Have a look at this online example to get a first impression.

Some more examples of the Charts integration with Views, using data contained in "nodes" (so not using any Views aggregation facilities):

Single chart, not attached to a table, and without aggregation.
Table with attached charts, and without aggregation.
Combination chart without aggregation.

Disclosure: I'm a (co-)maintainer of Charts.


Drupal Commerce 2 deployment I'm developing a store on Drupal 8 with Drupal Commerce 2.1. I'm doing it locally using docker4drupal Docker containers.

I just want to be sure that all my Commerce settings including categories, products and variations will be transferred to the external server during deployment.

Do I need special modules or methods for this except copying the files, database etc?

I don't think you need special modules or methods. Just copying the files and exporting/importing the database is enough. A module like Backup and Migrate can help you on that task but is not a must.

Anyway and as an extra information there are some optional but good practices (tools):

Drush: Apart that it can help you on some tasks (clearing cache, enabling modules, etc) it also can help you make a database dump using a command like drush sql-dump > file.sql, then you transfer the database to your server and you can import the database with a command like drush sql-cli < file.sql. If you are using Drupal 8.4.* just make sure to use drush 8.1.12 or higher. Drush can also help you syncronize the local dev site with the production site and even clone the site (more advanced).
Git repository: It will help you track custom files and even the configuration using a sync directory. The good thing about this is that you actually don't "transfer" the files, but commit/checkout, it can help you on your development workflow. Some people commit also the drupal or vendor files, other people (like me) just commit the custom files (modules and themes) and commit the composer files (see next).
Composer. The good thing about this is that you just transfer the composer.json and composer.lock file and then on the production server just run the command composer install --no-dev and it will download all the drupal/vendor files including contrib, modules, themes, libs, etc that you specified in the composer.json file (so you're actually not transfering the files). Specifically for commerce, the project base of drupal commerce can be a good starting point. Just customize it as you want.
Config Split module. It will helps on spliting your configuration so you can have modules that are enabled only locally on your dev environment but not enabled on the production server (like explained here), so in combination with composer you can have downloaded and enabled the devel module locally but not in the production server (as an example).

This answer is not intended to give you a how to on the tools mentioned, but to let you know some tools that exists and can help you in the process of developing drupal sites in general, if them sounds new to you and you are interested in any topics, please look their documentation sites and look around the internet as there are plenty of information, tutorials and videos that will help you consolidate your own workflow.


How to display the same nodes with two different themes? I have some content types normally displayed with the default theme of my site.

Now, I want to show such content types also in another section that is displayed with another theme and layout.

What is the best way to do it?

Yes simplest way to do it is using Themekey module. See the demo config for article type nodes.


How can I change my footer? I am trying to change the footer on a Drupal 7.2 site.

How can I achieve it?

It's ether in a block or in your template. First check the block admin page at admin/structure/block, and look in the section of footer (or something like that). If there is nothing there, it will be in your template. Most likely it will be located in page.tpl.php.


drupal and ndb cluster engines we have an application which was built with drupal connecting to a mysql db. upon go-live we found that the production db is a clustered one and requires us to change our db tables to NDB cluster engines.

Is drupal capable of working with clustered db's and how do we do this?

OBSERVATIONS

Default Drupal installations use MyISAM storage engine
Most plugins assume MyISAM storage engine for tables
Many have switched to InnoDB

What tables should or could be migrated to InnoDB, and which should remain MyISAM?
How do I convert a database from MyISAM to InnoDB?
FULLTEXT indexes not supported in InnoDB in MySQL 5.5
FULLTEXT indexes are supported in InnoDB in MySQL 5.6 (when it goes GA)

If is straightforwards to convert MyISAM to InnoDB, such as with the following:

ALTER TABLE node ENGINE=InnoDB;

Not so with NDB. For the table node, let's take the following approach:

mysqldump -u... -p... dbname --no-create-info node > node_data.sql

Then, load the table into the NDB Cluster

mysql -u... -p... -Ddbname -A < node_data.sql

and you let all the management nodes and SQL nodes determine where to store/shard the data.

If and only if you have the patience to

upgrade Drupal
avoid using FULLTEXT indexes (currently not supported by NDB)
apply plugins

drop FULLTEXT indexes
convert any MyISAM tables to NDB

migrate/reload data

then it is worth a shot.

Please post NDB Cluster questions in the DBA StackExchange.

DISCLAIMER : Not Drupal Expert, Not CMCDBA (not Cluster Certified), just CMDBA


Set default value to an image field form element using form_alter I am using this code, but the form doesn't get default image value:
The image is created and exists in the server:

$image = file_get_contents($url);
$destination = 'image.jpg';
$file = file_save_data($image, $destination, FILE_EXISTS_RENAME);

And $form is populated this way:

$form['field_user_picture']['und'][0]['value']['#default_value']['fid'] = $file->fid;

I think I am missing something, could anybody help?

Try it like this:

$form['field_user_picture']['und'][0]['#default_value']['fid'] = $file->fid;

(Remove ['value'] key.)