Custom Theming Bootsrap Carousel with Paragraph Type Background Info:
I tried to create a custom theme for my carousel section and I am unable to get it to work. I have tried using the default carousel that Drupal comes with. I have tried using slide show views. Also I already know about Jim Bir's Custom Bootstrap Carousel and Slick Carousel but I am unable to use them since these extensions are still in Beta.
Problem Statement:
The main avenue that I want to try to do is create a paragraph type called Carousel Section that has a reference to another paragraph type called `Caraousel Slide'.
I wanted to use this design so that way I can organize the slides individually on my pages.
Within the Carousel Slide paragraph type it would have the following fields:

Slide Image
Slide Title
Slide Description
Slide Link(which is the location of where the slide will take you if you click on it.)

I would like to use a preprocessor hook do get grab these values from Drupal and display them in my twigg file.
Question:
How can I achieve my problem statement? The bare minimal knowledge that I need is to how to at least get these fields to present themselves on my twig file and from there I can use HTML and CSS to make the carousel.

Unless you need some very specific logic, I wouldn't use preprocessing, but use Drupal's template suggestions and Twig instead.

I always use Slick over CDN, adjust for your own needs if necessary. All filenames are relative to the base directory of your theme or module. Replace UPPERCASE_WORDS with corresponding machine names.

Create a library for your carousel:

MYTHEME.libaries.yml

carousel:
  version: 1.0.0
  js:
    https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js: {type: external, minified: true, defer: true, async: true}
    js/my_carousel.js: {}
  css:
    layout:
      https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.min.css: {type: external, minified: true}
      css/my_carousel.css: {}

js/my_carousel.js

behaviors are the drupalesque counterpart to jQuery's .ready() handler (e.g. even if your carousel is loaded inside a view with ajaxified paging, it will still trigger .slick() after every paging).

(function ($, Drupal) {
  Drupal.behaviors.myCarousel = {
    attach: function (context, settings) {
      $('[data-slick]', context).once('myCarousel').slick();
    }
  };
}(jQuery, Drupal));

templates/paragraph--CAROUSELCONTAINER.twig.html

The container template would be the place where you alter your slick options, e.g. if you have a integer field "Autoplay speed" on your container paragraph, you could add to my_carousel_options using paragraph.field_autoplay_speed.0.value

{% set my_carousel_options = '"autoplay": true' %}
{{ attach_library('MYTHEME/carousel') }}

  {{ content.FIELD_CONTAINING_SLIDES }}

templates/paragraph--CAROUSELSLIDE.twig.html

Here you can decide what to render on each individual slide

{# maybe you also need an additional wrapper
 around each invidiual slide #}

  {{ content.MY_IMAGE_FIELD }}
  {{ content.MY_TITLE_FIELD }}
  {{ content.MY_DESCRIPTION_FIELD }}

If necessary you can further adjust the HTML markup of your slide subfields using something like templates/field--paragraph--MY-DESCRIPTION-FIELD.html.twig

Optional:
If you want to get rid of some container
s around fields automatically rendered by Drupal, create a wrapper-less field template. E.g. I wanted to remove ALL
s and field labels rendered by any paragraph host field:
(this is global for every paragraph host field, change it to a template suggestion matching only your carousel if you don't want this)

field--entity-reference-revisions.html.twig

{% for item in items %}
  {{ item.content }}
{% endfor %}

Finally create your own CSS styles for your carousel in css/my_carousel.css and rebuild the cache so Drupal discovers your new template files.

This basically is how I'm creating carousels on every of my projects. Not tested with Bootstrap theme though, this is some sort of general purpose tutorial.


Drupal 7 trim user input and other checks to prevent security issues What is the recommended way in Drupal to perform trim and other checks before accepting user input to avoid sql injections and other similar security issues?

Thanks.

I recommend reading this article :
https://www.drupal.org/writing-secure-code
Really a lot of good tips


Where is the $email_text variable set on ubercart? With Ubercart, where is the $email_text variable set, the variable that determines whether the "do not reply to this email" should be displayed in the email received by a customer after they place an order.

It's set in template_preprocess_uc_order(&variables) in the order module ($variables['email_text']).

If you're looking to override this variable for your site it can be overridden by defining a function MYTHEME_preprocess_uc_order(&variables) in your theme's template.php


Creating an alternative login page other than /user/login I have managed to do this in Drupal 7 with the following code:

function my_special_paths_menu() {

    $items['authenticate'] = array(
        'title' => 'Log in',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_login'),
        'access callback' => 'user_is_anonymous',
      );
     return $items;
    }

My question, is this code complete or is it missing some configuration in the menu item array? Is the code safe the way it is?

Yes, your code is complete, and is as safe as the default login form.

However, do bear in mind that if you want to replace the /user/login form, you will need to think about all scenarios in which users might end up there (e.g. [site:login-url] token, other modules, etc.) and handle them appropriately via redirects or access denied response (e.g. if you will be the only registered user on the site).

Here are the basics:

Redirecting

If you want to redirect users from /user/login to /authenticate for whatever reason, you will either need to use the Redirect module, or implement hook_menu_alter() in your custom module:

function YOUR_MODULE_menu_alter(&$items) {
  $items['user/login']['page callback'] = 'drupal_goto';
  $items['user/login']['page arguments'] = 'authenticate';
}

Replacing

If you want to make /user/login inaccessible to all other users, you can simply disable that path by again implementing the hook_menu_alter() in your custom module:

function YOUR_MODULE_menu_alter(&$items) {
  $items['user/login']['access callback'] = FALSE;
}

However, do bear in mind that you will have to test everything thoroughly and make sure that you have no modules that depend on the system /user/login, as well as that there are no workflows that will be affected (e.g. [site:login-url] tokens).

Hope this helps.


html formatted email using form api I have created my contact us module using form api, email is successfully generated and send to my specified email address, but I need body of the email to b html formatted, for this I have created another file mymodule.install in my module folder and add the below code:

function mymoduleenable() {
 $current = variable_get('mail_system', array('default-system' =>    'DefaultMailSystem'));
 $addition = array('mymodule' => 'mymoduleMailSystem');
 variable_set('mail_system', array_merge($current, $addition));
}

function mymoduledisable() {
 $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
 unset($mail_system['mymodule']);
 variable_set('mail_system', $mail_system);
}

and in my mymodule.module

 class mymoduleMailSystem extends DefaultMailSystem {
 public function format(array $message) {
 $message['body'] = implode("\n\n", $message['body']);
 $message['body'] = drupal_wrap_mail($message['body']);
 return $message;
 }
}

but due to above all piece of code I am unable to receive email, kindly suggest any solution.

Same thing i do in my module may be it is set to you requirement

    global $content;
    $content .= '<button class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">Apply</button>';
    $content .= '
';
    $content .= '
';
    $content .= '
';
    $content .= drupal_render($form);
    $content .= '
';
    $content .= '
';
    $content .= '
';
    return $content;


Required field set via hook_form_alter not fully working in Commerce Checkout form I created a hook function to make a field required and visible. The targeted form is the Checkout Billing Form at: example.com/en/checkout/35

I have to mention that the site is build with the Commerce Kickstart distribution.

        <?php
    function MyModule_form_alter(&$form, &$form_state, $form_id) {
            if ($form_id == 'commerce_checkout_form_checkout') {
                    $form['customer_profile_billing']['field_cif_nif_id']['#states'] = array(
                      // This #states rule says that the "field_cif_nif_id" fieldset should only
                      // be VISIBLE and REQUIRED if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
                              'visible' => array(
                                    '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('CIF/NIF/ID')),
                            ),'required' => array(
                                    '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('CIF/NIF/ID')),
                            ),
                    );

                   $form_state['rebuild'] = TRUE; //THIS LINE IS NOT WORKING
      }
    }
    ?>

The function seems to work fine since the fied is marked with the red asterisk *, but it is not really working since the form is sent and saved even if the required field is empty.

I think the problem is not in the function but in its relation with the Commerce Checkout form provided by Drupal Commerce or Commerce Kickstart.

Using required along with #states will add the required indicator to the element, But there will be no client or server side validation involved. So to make the field as required you would have to add the custom validation to the form and there you can validate the field something like below:

/**
 * Implements hook_form_alter().
 */
function MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is commerce checkout form.
  if ($form_id == 'commerce_checkout_form_checkout') {
    // Add the custom validation function to the form.
    $form['buttons']['continue']['#validate'][] = 'mymodule_custom_validate_required_field';
  }
}

/**
 * Callback handling the custom validation.
 */
function mymodule_custom_validate_required_field($form, &$form_state) {
  // Check if the field you want to validate exists in the form.
  // replace 'field_dispongo_de_' with the name of field you want to validate.
  if ((isset($form_state['values']['field_dispongo_de_'])) && (empty($form_state['values']['field_dispongo_de_']))) {
    form_set_error('field_dispongo_de_', 'Field cannot be left blank');
  }
}

Alternate way:

Since its a commerce checkout form so we can add the custom validation using hook_commerce_checkout_pane_info and commerce_checkout_form_validate as discussed here: Adding validation to commerce pane form


How to Make File Description Field Required? Use case: Users who are authorized to use the edit page are required

To upload at least one file
Must have an associated description with the file.

Plus: How can I edit "Description" to display "Alternative File Name" ?

depending on your needs, this could be accomplished using Field Collection, adding an image field and a description field (which can be made required) to the collection:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.


Theming/Aligning Multiple Views Blocks on Homepage I have an article content type which has a category field that is an entity reference field type linked to a taxonomy group of terms I created.

The website has 6 different pages which are just a taxonomy view based on the 6 different article categories listing the articles that are associated with that category. These are the settings of the taxonomy view used for each of the pages:

What I'm trying to do is create 6 block views on the homepage in a grid where each block view is a different category title showing the 4 most recent article titles and a more button to take you to the listing page of said category view. Each background would be a different image based on my CSS. This is what I'd like it to look like:

I'm using Boostrap so what I'd like is each row to be put within a
 and then each block to have a
.

What I want the final code for each block to look like is the following:

{{ category.title }}

Article Title 1

Article Title 2

Article Title 3

Article Title 4

        More

I know I could create a different block view in views for each of these (would that be the best practice?) and then place them in the content region only on the homepage but then how would I theme the template files so that I could have them work the way I've shown above?

Is there a better approach to this than what I'm suggesting above? Any help/suggestions is greatly appreciated. Also, if something exactly like this has been asked/answered before, a link to that would be helpful as I've tried searching on here and haven' been able to find anything exactly like my issue.

Please comment below if I have misunderstood anything and I can modify my answer.

First, I will clarify that I understand what is happening.

To the user, there appear to be 6 different pages on the site but in actuality, they are looking at the View Page that you posted above with contextual filters (each containing a different taxonomy term).

On the homepage, in a grid, you would like to display 6 Block Views that display the 4 most recent posts for their respective Taxonomy Term.

You would want Views to print out in a Bootstrap-like format so that they utilize the Bootstrap responsive grid.

This is what I recommend:

First we are going to create the first New Block.
Create a Block View called "Front Page News Blocks" (Or something along those lines) that lists Nodes of the Article type
Limit the View to only display 4 nodes
Ensure that it is sorted via post date (Ascending)
Add a "Custom text" field to the view and put the "More" link (with the btn and btn-primary classes) in the value
All of the above settings are "Applied to All Displays"
Now, you want to create some Block Views within this View. Have a total of 6 different Block Views
Within these, you can add categories Filters (but apply them only to the respective displays)
Also, override the URL in the "More" link in each view (Once again, don't forget to only apply it to the current display)
Create a template based on views-view.html.twig but name it after your View to override the default theme file
Within your custom TWIG file, you can add the "col-md-4" grid classes
You would also need to override the Homepage template so that you can add a div with the "row" class to the region where these blocks will be.
Now your CSS classes should be in the markup and you should be able to style your site as planned.

What I laid out was pretty generalized and high level. Definitely comment below if you need clarification on anything and I can edit this answer.

Hope this helps get you on the right track!


Add classes to form select option item How can I add classes to a form option tag without JS?  At the moment in Form API I can pass a keyed array like this

array(
  '0' => 'option 0',
  '1' => 'option 1',
)

and I'll get html like this

<option value="0">option 0</option>
<option value="1">option 1</option>

Is there a way to do something like this:

array(
  array(
    'value' => 0,
    'text' => 'option 0',
    'class' => 'bob 0',
  ),
  array(
    'value' => 1,
    'text' => 'option 1',
    'class' => 'bob 1',
  ),
)

and then get this

<option value="0" class="bob 0">option 0</option>
<option value="1" class="bob 1">option 1</option>

Unfortunately this isn't very easy using the Form API currently.

There's an issue open to add this functionality (it goes all the way back to 2008) that would theoretically allow you to do something like this:

$form['optiontest'] = array(
  '#type' => 'select',
  '#title' => t('Option test'),
  '#options' => array(
    array(
      '#return_value' => 0,
      '#value' => t('First option'),
      '#attributes' => array('class' => 'first', 'title' => t('First option')),
    ),
    array(
      '#value' => t('Option group'),
      '#attributes' => array('class' => 'group', 'title' => t('This is an optgroup')),
      '#options' => array(
        array('#return_value' => 2, '#value' => t('1st sub-option')),
        array('#return_value' => 4, '#value' => t('2nd sub-option')),
      ),
    ),
  ),
);

But unfortunately there are nothing but failed patches attached to the issue at the moment.

The only way I can think of to do it at the moment would be to add a #process function to the select element, and add the class(es) to each option when they're broken down individually.


Adding logic to a page I am new to Drupal, and I am trying to add some behavior to an existing page within Drupal.

Using the admin UI, I created an model with 2 numbers (num1, num2). I then rendered it into a form.

Now I would like to add a third field, and compute using the client the sum of num1 and num2 into this new field. This needs to be done as you type the numbers.

I wanted to use Javascript to do this, but I really don't know where to start. Is there an example on how to simply add some logic into an exiting screen that is generated by the admin tools?

This is more information.

Then, I just add these to fields into a page like so:

Again, at this point I would like to just add the sum of both numbers into a 3ed field that is not there yet (of course my project is much more complex, but this is a simple example). So I was going to add field_number3 into my Content type, and I wanted to do some simple Javascript to calculate the field.

I could really use some step by step examples, to just to know where to place a module, and what code to type in  the module to only add this behavior to my content.

I am very new to Drupal, and I am using Drupal 8.

Attaching custom JS to form

Adding css and javascript to a drupal 8 module

Here's an example of using hook_form_FORM_ID_alter. For this you'll need to make a custom module (conveniently named custommodule in the example below).

Module directory:

custommodule/
|- js/
   |-- custommodule.js
|-- custommodule.info.yml
|-- custommodule.libraries.yml
|-- custommodule.module

File contents:

custommodule.info.yml

type: module
name: Custommodule
description: 'Custom stuff'
package: Custom
core: '8.x'

custommodule.libraries.yml

custommodule:
  version: 1.x
  js:
    js/custommodule.js: {}
  dependencies:
    - core/jquery

custommodule.module

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custommodule_form_node_article_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#attached']['library'][] = 'custommodule/custommodule';
}

custommodule.js

(function($) {

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

      var num1 = $("#edit-field-num-1-0-value").value;
      var num2 = $("#edit-field-num-2-0-value").value;
      var result = (Number(num1)+Number(num2));
      $("#edit-field-num-3-0-value").value = result;
    }
  };

})(jQuery);

The example uses the default article node type, with 3 integer fields (field_num_1, field_num_2, field_num_3), and works on the article edit form (form id -> node_article_edit_form). The js part is also very basic so all it does is set the third field value once the page loads. Drupal_add_js is deprecated, so we use the $form['#attached']['library'] array to attach a library (defined in the custommodule.libraries.yml file) that contains the JS file (a single libraries.yml file can define more libraries, which can include more js/css files).


How can I theme the Captcha/ReCaptcha error message? I'd like to change how the error message is when a user fails the recpatcha.

Currently it is just plain text on top of my form but I would rather have it be a modal or at least be in red.

I looked into the templates folder in both the Captcha module and ReCaptcha but did not see anything for the error message.

Is there a way to theme the error message?

Believe I found a solution.

Since I am using the captcha with Webforms I inserted the below JS to the form and it seems to be working without any drawbacks.

(function ($, Drupal) {
Drupal.behaviors.myModuleBehavior = {
attach: function (context, settings) {
$( "[role=alert]" ).dialog();
}
};
})(jQuery, Drupal);


Individually place menu items How can I position each menu item individually in Drupal 7?
I've created a quick visualisation how I want it to look like:

The problem is that I still want to have hover effects and highlight the page I'm currently on.
The menu don't need to be dynamic because the menu items won't change.

Any Ideas?

Try theme_links

Like

<?php
print theme('links', array('links' => menu_navigation_links('menu-site-menu'),
'attributes' => array('class'=> array('links', 'site-menu')) ));
?>


login_destination module and link with anchor I want to to use login_destination module to have a link to login screen in comment-wrapper.tpl.php, so after the login, the user came back to write the comment.

I have installed and configured login_destination and modified comment-wrapper.tpl.php.

The login_destination documentation say that if I use my own links to the login screen, i have to use GET to supply "current" parameter.

So in my theme I've added to comment-wrapper.tpl.php:

$destino = drupal_get_destination();
$destino = $destino['destination'];

And changed the text to add the link to the login screen:

<?php if ($comment_form): ?>

<?php print t('Login or anonymous comment:', array('@login' => url('user', array('query' => array('current' => $destino), 'fragment' => 'comments')))) ?>

<?php print $comment_form; ?>

Now, when I click on "Login" link, opens an url like:

SITE.com/user?current=node/3#comments

But after finish the login, I'm redirected to node/3 alias, without the anchor #comments.

If I type on the browser the url:

SITE.com/node/3#comments

It' works ok, it goes to the #comments anchor.

Any help or suggerence?

Thanks!

Try this.

<?php if ($comment_form): ?>

<?php l('Login or anonymous comment', user, array('query' => 'current=node/3#comments')); ?>

<?php print $comment_form; ?>


How do I use hook_nodeapi()? I found an example on the Internet: Transform CCK field to body content.

function riddle_nodeapi(&$node, $op, $teaser, $page) {
  if ($node->type == "historia") {
    switch ($op) {
      case 'view':
        if ($node->field_svar[0]['value'] != "" AND $page == 1) {
          $svar = '<form><fieldset class="collapsible collapsed">
            <legend>Svar</legend>
            <div>'.$node->field_svar[0]['value'].'</div>
            </fieldset></form>';

          $node->content['riddle'] = array(
            '#value' => $svar,
            '#weight' => 0,
          );

          if (is_array($node->content['field_svar'])) {
            unset($node->content['field_svar']);
          }
        }

        break;
    }
  }
}

I don't know what the purpose of the following code is. Why should I use it?

 if (is_array($node->content['field_svar'])) {
   unset($node->content['field_svar']);
 }

What's the use of the hook_nodeapi() arguments $a3 and a4?
If in the case of a view operation, I set the $a3 to true or 1, will the body only effect on the node teaser? Am I right?

The following code is used because the module is already rendering the CCK field, and wants to avoid that Drupal renders the content of that field.

if (is_array($node->content['field_svar'])) {
  unset($node->content['field_svar']);
}

Without using that code, the field content will appear twice: once inside a field set, and once outside that field set.

The last parameters used for hook_nodeapi() are described from the documentation as:

  $a3

  For "view", passes in the $teaser parameter from node_view().
  For "validate", passes in the $form parameter from node_validate().

  $a4

  For "view", passes in the $page parameter from node_view().

It means that, when the operation is "view," $a3 is TRUE when Drupal is displaying the teaser (and FALSE when Drupal is displaying the full node content), and $a4 is TRUE when the node is being displayed alone in a page (and FALSE when the node is being displayed together other nodes in the same page).
To understand the meaning of the different values given to $a4, $a4 is TRUE when Drupal is displaying, for example, the page http://example.com/node/1 (where the same page displays only a node); its value is FALSE when Drupal is visualizing the front page and there are more than one node promoted to the front page.


Services 3 - updating a custom field in a user account I'm using Postman in Chrome to test my services. I'm sucessfully able to create user accounts using the following:

Headers:

Content-Type /application/x-www-form-urlencoded
X-CSRF-Token 84t_NqiZcxiK42Obcy4aIpT7oxhar4DJvf7hIvRSxJE

x-www-form-urlencoded data

Name = testname1
mail = testmail1@localhost.com
pass = pass

This works, but to update a custom field, nothing seems to work. My field is a text field with the machine name field_test_text, I've tried adding the value

field_test_text[und][0][value] = TEST

But this doesn't work, however the user is still created.

Switch between different content types and test, for example, application/json works perfectly for me. You need to do the following steps:

Request CSRF token /services/session/token (sample request below)

request.get({url:'https://serveraddress/services/session/token'}, function(error, response, body) {
if(!error && response.statusCode == 200) {
  console.log('CSRF Token obtained : ' + body);
} else {
  console.log('Failed to retrieve CSRF token.');
}
Make use of the obtained CSRF token to perform authentication (if needed), sample below

// Set the headers
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token' : token
};

// Configure the request
var options = {
  url: 'https://serveraddress/servicesendpoint/user/login.json',
  method: 'POST',
  headers: headers,
  body: 'username=yourusername&password=yourpassword'
};``

// Start the request
request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
      var jsonBody = JSON.parse(body);
      console.log('Authentication succeeded, cookie value is : ' + body);
      console.log('SESSID : ' + jsonBody.sessid);
      console.log('SESSION_NAME : ' + jsonBody.session_name);
      console.log('Token : ' + jsonBody.token);
    } else {
      console.log('Authentication failed. Error is : ' + error);
      console.log('Authentication failed. Body is  : ' + body);
      console.log('Authentication failed. Response is : ' + JSON.stringify(response));
    }
});

Now that you have SESSION NAME & SESSION ID, you can proceed with updating a node. See sample below.

//set headers
  var headers = {
              'X-CSRF-Token' : authResult.token,
              'Content-Type': 'application/json',
              'Cookie' : authResult.session_name + '=' + authResult.sessid
            };

  // Configure the request
              var options = {
                  url: 'https://serveraddress/serviceendpoint/node/' + user.result.nid,
                  method: 'PUT',
                  headers: headers,
                  json: data
              };

  request(options, function (error, response, body) {
            if(!error) {
                console.log('Drupal node is updated successfully!');
                console.log(body);
            } else {
              console.log('Updating Drupal node failed! Error status : ' + response.statusCode);
              console.log('Updating Drupal node failed! Error body : ' + JSON.stringify(body));
            }
          });

If you notice above, I am console logging all the errors that is returned from the Services, so that I have something to Google and figure out.

For those who wish to know how to upload a file and associate them to a node. Assuming that Service Endpoint is configured to accept file uploads. You will need a sample request as below:

     //data
     var data = {
       "uid":"1",
       "filesize":fileSizeInBytes,
       "filename":user.firstName + '_' + user.lastName,
       "file": base64Image
     };

 var options = {
       url: 'https://serveraddress/servicesendpoint/file',
       method: 'POST',
       headers: headers,
       json: data
     };
request(options, function(error, response, body) {
       if(!error) {
         //photo is uploaded, returning fid
         console.log('Publishing Image to Drpual succeeded. FID is : ' + body.fid);
       } else {
         console.log('Publishing Image to Drpual failed. Response is : ' + JSON.stringify(response));
         console.log('Publishing Image to Drpual failed. Body is : ' + JSON.stringify(body));
       }
     });

Attach the returned FID to the request that is supposed to update the node.

Sample JSON to update a field of a content type would look like this:

data = {
      "body": {
          "und": [
              {
                  "value": user.profile,
                  "format": "full_html"
              }
          ]
      },
      "field_member_position": {
          "und": [
              {
                  "value": user.title
              }
          ]
      },
      "field_member_photo" : {
        "und" : [
          {
            "fid" : fid
          }
        ]
      }
    };
  }

Hope above help those struggling with using Services 3. The code is written in Express JS 4 and I have used the request NPM module.

A simple checklist for Services 3 would be:

Configure the module (request content type, as well as allow CRUD on nodes/files as per your need)
Make sure you are hitting the correct URL to get token, authenticate and update node, upload file
Watch for famous errors such as Not Acceptable Content type, Trying to Authenticate as anonymous user, A particular field is required (username/password), others

When trying to update a custom field, it is more useful to SEE that particular node's structure via DEVEL and then accordingly structure your JSON data.


Setting an order as Completed In code I am trying to mark an order as completed. I am doing this in hook_commerce_payment_order_paid_in_full

function my_module_commerce_payment_order_paid_in_full($transaction) {
  $orderid = $transaction->order_number;
  $order = commerce_order_load($orderid);
  commerce_order_status_update($order, 'completed');
}

However this does not seem to work. The state the call is at when going into this is processing

I also have the following 2 rules

{ "commerce_checkout_order_status_update" : {
    "LABEL" : "Update the order status on checkout completion",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "commerce_order", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce-order" ], "order_state" : "pending" } }
    ]
  }
}

And

{ "rules_update_the_order_status_on_checkout_completion_if_payment_" : {
    "LABEL" : "Update the order status on checkout completion (if payment complete)",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "1",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "commerce_payment", "commerce_order", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "IF" : [
      { "commerce_payment_order_balance_comparison" : { "commerce_order" : [ "commerce_order" ], "value" : "0" } }
    ],
    "DO" : [
      { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "completed" } }
    ]
  }
}

In short as soon as the balance is 0 I want the order to be complete.

If the problem is simply that orders are being marked "paid in full" while still in checkout and then having their statuses overridden when the checkout completion rules run, why don't you just add a condition to the default checkout completion rules to not change the order status if it's already completed?


Has drupal abandoned drush? I've been away from drupal for 2-3 years. I just came back around and installed drush via composer (like the drush site recommends) and now every time I try to use drush I get a message telling me that I should be using composer:

~/sites/d7 $ drush version
 Drush version : 9.0-dev-gd4a3872
~/sites/d7 $ drush dl drupal-7.x
 [notice] dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/[project-name]. Use https://www.drupal.org/project/composer_generate to build a composer.json which represents the the enabled modules on your site.

I downloaded drupal 8 following these instructions for installing drupal via composer, but when I try to use drush in that project I get this message:

~/sites/cfbtv/web $ drush dl devel
This codebase is assembled with Composer instead of Drush. Use `composer update` and `composer require` instead of `drush pm-updatecode` and `drush pm-download`. You may override this error by [error]
using the --pm-force option.

Is there something wrong with my local env, or is drush a thing of the past now?

You have installed the development master branch of Drush. To continue using commands such as drush dl, drush pm-update and so on, you should install the 8.x branch of Drush.

However, your basic supposition is correct. The Drupal community is moving towards Composer and away from drush make and the drush pm-* commands. The reason for this is that more and more Drupal modules are depending on code that is distributed via Composer libraries. When using modules with Composer dependencies, the most convenient way to manage your Drupal site is through Composer. See drupal-composer/drupal-project for an example of this.

All of the other Drush commands are still relevant and remain useful.


Problem when visiting users profiles In my website, users can connect, see their profiles, update their profiles and visit other users profiles

So for each users, I created a profile page user-profile.tpl.php

But I've some troubles when I'm visiting other users account.

For example in my account profile page, there is a link who's redirecting me to the edit page.

I wrote this code for showing the edit link :

<?php
  global $user;
  print l(t('Update my profile'), "user/{$GLOBALS['user']->uid}/edit");
?>

When I'm visiting a random user page, this link appears. But I want it to appear only on my profile page

And it's the same for my profile picture, when I'm visiting a random user page, my picture is always showing.

<?php
    $user_item = user_load_by_name($user->name); // or user_load( $user->uid )
    print theme('user_picture', array('account' =>$user_item));
?>

I have no idea how to fix theses problems, that's why I need your help (I'm new to Drupal btw)

(I'm using Profile2)

Thanks

You can get the user id from url using arg() function. for the first part you can do something like this.

global $user;
$user_id = arg(1);
if($user->uid == $user_id) {
// means it is logged in user profile - so show edit link

}

For the second part you are loading profile of logged in user, that is why it is always showing your picture you need to do the following instead.

$user_item = user_load($user_id); // user id we got from arg()
print theme('user_picture', array('account' =>$user_item));


Two forms on the same page - both submit the same I have two forms on the same page, both called with drupal_get_form('some_form_name', $product_id);. The $product_id variable is used to fill in a hidden input. (The code is in a foreach, the $product_id variable is different for every form.)

In the generated HTML, the forms are correctly built. Both have different IDs, and both hidden fields have the correct value.

However, in the submit function of this forms, with the following code:

function some_form_name_submit($form, &$form_state) {
    dsm($form_state['values']['product_id']);
}

The product id is always the same. The first generated form's product id.

After some research, I found out that the hidden input form_id is the same in both forms. Looking into that.

Is there a way to solve this?

Found the solution. The problem was that the forms had the same form_id -- some_form_name, the string passed to drupal_get_form().

I generated the string with something like drupal_get_form('some_form_name_' . $product_id); instead of passing as second argument.

However, that means I would have to define a function for each product id. To avoid this, I implemented hook_forms(), so that each form id starting with some_form_name_ would use the same callback to generate the form:

function mymodule_forms($form_id) {
    if (preg_match('/^some_form_name_\d+$/', $form_id)) {
        return array(
            $form_id => array(
                'callback' => 'some_form_name',
            ),
        );
    }
}

This way, even though each form has a different form_id, they all use the some_form_name function to generate the form.

And no problem left.


Redirect a Users Name (Link) to a User Homepage in Panels Using Rules How does one create the said Redirect a Users Name (Link) to a User Homepage in Panels Using Rules.

Here is my scenerio:

I have a Panels set which will show a subject posted content page in the left panel and the right panel will show a Dynamic list of users in a View, ultimately related to the subject page (ie by ZIP/Postcode, but thats for later).

I wish the View of usernames to then allow the reader to click the said users name (maybe pulled from Profile2 field name link) and take it to a Users (from the said Views) 'about' Homepage. I have pre-designed as a Content (custom) Node template page in the backend Structure for displaying the Users 'homepage'. (the said user will have priviledges to edit/amend via their DB, but that's for later). I'm thinking that this can be done via Views and presumed that a custom Rules Component needs to be created, but I'm stumbling at the next stage hurdle as to "what/where". I'm not sure if I would need to create a dedicated 'node' or whether it can simply be done via a View and if the Relationship elements come into for it to show dynamically to the end browsing user.
Later, the Views will also incorporate Location map nodes (ala Google M), but for now I'm happy with an end result showing a static homepage which would have the normal 'about us' text, photo image, 'Contact Us' etc, ala the old Myspace type page.

I have viewed many of Johan Falks' tutorials at http://vimeo.com/nodeone but am still stumped about my approach or whether I'm missing a further module component?

I'm sure this is very basic stuff, but any clarificiation on this process for a learning novice is appreciated. Thanks.

So, you want to make the username link to a different page?

You can do that by overriding theme_username e.g, in template.php

You could also use hook_preprocess_username for the theme preprocess function and also change the entity_uri for the user entity, though the first option is probably simplest.


How to list nodes that share one or more of the same entity references as the current node I have three content types Projects, Campaigns and Blog Posts. Campaigns and Blog Posts share an entity reference field that allows for selection of one or more related Projects.

I currently have a View with block that is displayed on the individual Project nodes and lists Blog Posts that are related to that Project. There is a contextual filter to compare the array of related (Project) nodes within the Blog Posts with the ID of the current Project node. I want to add the same type of list to the individual Campaign nodes.

The Campaign nodes will have one or more referenced Projects and the Blog Posts must be compared to see if they share any of the referenced Projects in common.

For example Campaign 1 with references to:

(Project 1, Project 2, Project 3)

should show related Blog Posts with either:

(Project 1)
(Project 2)
(Project 3)
(Project 2, Project 3)
(Project 1, Project 3)
(Project 1, Project 2)
(Project 1, Project 2, Project 3)

I have read and tried a couple of possible solutions to configure the contextual filters and relationships, but nothing is working; the results are blank. I know for a fact that there is a Blog Post and a Campaign that share at least one common Project reference. So the results should show at least that one Blog Post.

Any ideas? Clearly defined configuration options would be appreciated.

You could get the blog posts related to projects refernced by the campaign displayed
through:

1- create a view  to get project id for projects have relation with that campaign.

2- create a new view listing blog posts that have relationships with projects taking project id as a contexctual filter.

3- create a .tpl file displaying the output of the view that gets projects from theme information

In that file embed blog posts view using views_embed_view() function giving the projects ids as a parameter for the view but you will need to

Configure views to accept multiple parameters you should set this option: View → Advanced → Your Contextual Filter → More → Allow Multiple Values

you will loop through fields to extract and form the ids array and pass it as the code sample below

$array = array('32+50+32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();

By that you will be able to get blog posts from another separated view


Make autocomplete window appear above accordion pane I have created a node add form using the field group module to put the form in a jQuery accordion.

I have a auto-complete field that is at the bottom of one pane so the div that appears that lets users choose from the auto-complete options is behind the pane below it as it has overflow: hidden. Here is an image of the problem:

I've fixed this behavior by changing 2 lines in autocomplete.js in the populatePopup function:

//var position = $input.position();
// changes to:
var position = $input.offset();

// and

//$input.before(this.popup);
// changes to:
$('body').append(this.popup);

As the auto-complete div is now appended to the body it appears above everything else.

This is great but the problem is I don't want to start hacking Drupal core js files.

I could copy the whole autocomplete.js to a new file and then replace the whole thing, but really I just want to override the populatePopup function.

Is it possible to do this?

(I've tried copying the populatePopup function into my own js file but I get the error Drupal.jsAC is undefined.)

Doh - I was so close.

The answer is to simply copy the function you want to override to your own custom JS file but make sure to wrap it in a document ready function!


Image grid from view with randomly inserted colored squares I've got a creative challenge here.  I've got a view that creates a grid of images linking to their respective content, but my designer threw in a bit of a twist.  He wants me to randomly insert colored squares between every 2-3 images.  I was looking into creating a custom template for this view to do the inserting, but he'd also like these colors to be editable through the admin.  While there are many ways to accomplish this I'm curious to hear your solutions.  I could create a "Grid Color" content type, but I'm not sure I want to clutter my content types with such an obscure type.

My solution was fairly simple.  I created a new content type called "Homepage Grid Spacer" and used auto_nodetitle to suppress the title.  I created a single field of the jQuery Colorpicker type and deleted the body.  Now the admin can insert these decorative squares between actual flagged content by creating and flagging them in the same fashion.

I updated my view to select the color code and suppress the image field of the actual content and I used the rewrite to add a div with the color in a data field.  I couldn't add the field in a style because Drupal doesn't allow this.  Then I added a couple lines of JavaScript to take the data color and make that the CSS background color.


Working on Drupal and Drush with teammates I'm currently working on a website using Drupal 8, with 3 other members in my team.

We use git as a versioning system, and we very often work at the same time on different branches.

Here is the problem :

If we all use local databases, then it's a mess when we have to merge our code, because we have to isolate the parts of the database that have changed, and create a patch, or re-create the changes ourselves a second time.
For example if I have created many static pages, I have to create them again, or export the part of the database containing them.
If we choose to share a database to avoid that problem, then every time someone runs the drush cr command, everyone's website gets synched to their last changes, erasing every other changes from other teammate, which can be very confusing and annoying.

What is the right solution here?

Checkout configuration management in Drupal 8. Though there are many modules that can help you out but most of them are in active development and not stable for production use yet.

Two most promising modules are Configuration Update module and Features module.

Checkout What are the alternatives to Features module in Drupal 8 for further notes.


Views date exposed filter by year in checkboxes I have date field. In views I want to add the a date exposed filter.

This filter will only display year and we can select multiple years.

Just like this

I have checked the better exposed filter module, date view and I did not find any option to display them in checkboxes nor I find any option to select multiple dates like in the picture we can select multiple years.

With the date views and better exposed filter, I can display year only in select list.

Is it achievable? Any suggestion?

You can construct the Exposed Year filter yourself using the Grouped filters option:

Add your Date field Filter and Expose it
Select Grouped filters under Filter type to expose
Tick Allow multiple selections
Select Radios under Widget type
Adjust the Label and Description if you need to
In the items table change all Operators to Is between and configure each year like so:

 2019   Is between   2019-01-01
                     2020-01-01

 2018   Is between   2018-01-01
                     2019-01-01

 2017   Is between   2017-01-01
                     2018-01-01

 ...

and so on for all the years. The times are assumed to be 00:00:00.

You don't have to use the Better exposed filters, they may interfere with the display of the grouped options.

BTW this issue may be relevant: Grouped exposed filter with "Allow multiple selections" ignores widget setting


Problem with a query On Drupal 8, I have this line inside my form (my_module/src/Form/MyCustomForm.php).

$users = db_query('SELECT * FROM {users}');

var_dump($users) shows an object (of my query) and not the list of all users.

object(Drupal\Core\Database\Statement)[322] public 'dbh' => object(Drupal\Core\Database\Driver\mysql\Connection)[20] protected 'needsCleanup' => boolean false protected 'target' => string 'default' (length=7) protected 'key' => string 'default' (length=7) protected 'logger' => null protected 'transactionLayers' => array (size=0) empty protected 'driverClasses' => array (size=0) empty protected 'statementClass' => string 'Drupal\Core\Database\Statement' (length=30) protected 'transactionSupport' => boolean true protected 'transactionalDDLSupport' => boolean false protected 'temporaryNameIndex' => int 0 protected 'connection' => object(PDO)[15] protected 'connectionOptions' => array (size=10) 'database' => string 'theming' (length=7) 'username' => string 'root' (length=4) 'password' => string 'private' (length=8) 'prefix' => array (size=1) ... 'host' => string 'localhost' (length=9) 'port' => string '3306' (length=4) 'namespace' => string 'Drupal\Core\Database\Driver\mysql' (length=33) 'driver' => string 'mysql' (length=5) 'pdo' => array (size=4) ... 'init_commands' => array (size=1) ... protected 'schema' => null protected 'prefixes' => array (size=1) 'default' => string '' (length=0) protected 'prefixSearch' => array (size=2) 0 => string '{' (length=1) 1 => string '}' (length=1) protected 'prefixReplace' => array (size=2) 0 => string '' (length=0) 1 => string '' (length=0) public '_serviceId' => string 'database' (length=8) public 'allowRowCount' => boolean false public 'queryString' => string 'SELECT * FROM users' (length=19)

Why?

There's nothing different from 7.x with db_query(), it returns a result set where you can fetch results from or loop over it. Refer to the database API documentation.

However, there are even less reasons for doing a direct database query in 8.x than in 7.x, and doing the query by hand is very likely going to be more complicated because of the data tables.

Use entity query instead:

<?php
$uids = \Drupal::entityQuery('user')
  ->execute();
?>

Executing an entity query always returns entity IDs which can then be loaded:

<?php
$users = \Drupal::entityManager()->getStorage('user')->loadMultiple($uids);
// Shorthand if you know that you have users:
$users = \Drupal\user\Entity\User::loadMultiple($uids);
?>


Disabling user/register I want to disable the user/register page in Drupal 7 but I still want registrations possible, but only through other links. I've tried altering the access to it through a module like so:

my_module_menu_alter(&$items) {
     $items['user/register']['access callback'] = FALSE;
}

but it does not seem to work. I know I can alter the form permission and set it to false but I need the form for other modules I have installed. Is there any way to do this with a already existing module or programmatically?

Your implementation is most probably correct, I use the following code to customize access to the register page in some projects:

function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = 'MYMODULE_user_register_access';
  unset($items['user/register']['access arguments']);
  $items['user/register']['type'] = MENU_CALLBACK;
}

Make sure that the custom module is enabled, make sure that the module name is spelled correctly, also make sure that there really is an & prepended to the $items parameter. It happened to me in the past that I forgot the reference operator on hook_X_alter implementations. Also flush caches after adding new hook implementation functions.


Combine several field as a new field say my custom content type has 3 different fields: max, min, mean. What I want to achieve is group them into a new field say statistics so the new statistics field will have all the values in fields max, min, mean.

In terms of display, I now have several walk around solutions.

in node--examplecontent.html.twig template:

statistics:{{ node.field_max }}/{{ node.field_min }}/{{
node.field_min }}

but the problems with this is that "statistics" is hard code so it
can't benefit from the translation module if I want to build a
multi-lang site.
or I could define a dummy field "statistics", and hide it in the
form display so user wont need to enter the value of "statistics"
when create new content of the content type. then in
node--examplecontent.html.twig template:

{{ node.field_statistics.fieldDefinition.label }}:{{ node.field_max
}}/{{ node.field_min }}/{{ node.field_min }}

this will allow me to translate to label of field statistics to have
it dispaly as a different language.

I wonder if there are some better ways to achieve it, thank you.

I think there are several ways to go about this, but with your current field setup and familiarity with template you can use the trans functionality in Twig (see https://www.drupal.org/node/2047135).

{% trans %}
  statistics: {{ node.field_max }}/{{ node.field_min }}/{{
node.field_min }}
{% endtrans %}

Other ways of doing things:

hook_entity_extra_field_info()
Display data via views (see nizz0k's answer)
Translate in PHP in the template preprocess function
Create a new field type that stores, min, max, and computes statistics via a Typed Data method.
Similarly to the above, add a typed data data type plugin to calculate statistics.


How to build an Isolated Drupal instance for testing In order to run DrupalWebTests on travis-ci, I need to build a new Drupal instance where these tests are ran.

Typically, one runs these tests with drush -l http://localhost.example test-run SomeTest

This, however, assumes Drupal installed, being served on http://localhost.example (a webserver) and it being connected to a database as set in settings.php, having simpletest enabled.

Typically, this means installing MySQL, Apache and installing and configuring Drupal. Those are heavy depedencies and doing so for each test-case or even just every build, will require a lot of overhead; a build server like Travis will need to install these servers for each test-run.

Drush has drush run-server to run a lightweight server. Drupal can run off a sqlite database, which would be extremely usefull for these tests.

Moreover: as far as I can make out, the actual web-tests are not ran from that Drupal-instance at http://localhost.example, but get a clean build and isolated database (as should be, when testing). It appears that the Fully-functional Drupal at http://localhost.example is merely used as bootstrap for the web-tests.

Can I circumvent that bootstrap in some way?

And if not, what is a quick and easy way to get a Drupal installed and serving with as little dependencies (like Apache/Nginx, MySQL etc) as possible?

Also note that I am running Travis already for tagadelic, but so far, only for the phpunit tests. I want to extend this to run the DrupalWebTests there as well.

You could just use different git branches to isolate your code tests.

git checkout -b iss_tst1
<make changes>
git add <changes>
git commit -m "my new changes" <changes>

git checkout -b iss_tst2
<make changes>
git add <changes>
git commit -m "other new independent changes" <changes>

Then you should be able to run independent tests on each branch.


Title changed programmatically is not put into breadcrumbs I have 2 functions in template.php: The first attaches current page title to breadcrumbs; the second sets the title to 'Completion' when the user opens /scores/completion.

function lwt_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    if (!empty($breadcrumb)) {
        // Adding the title of the current page to the breadcrumb.
        $breadcrumb[] = drupal_get_title();

        // Provide a navigational heading to give context for breadcrumb links to
        // screen-reader users. Make the heading invisible with .element-invisible.
        $output = '
' . t('You are here') . '
';

        $output .= '
' . implode(' » ', $breadcrumb) . '
';
        return $output;
    }
}

function lwt_preprocess_page(&$vars) {
      $path = drupal_get_path_alias();
      if ($path == 'scores/completion') {
            $vars['title'] = 'Completion';
      }
}

The breadcrumb is still scores. How do I fix it?

drupal_get_title() gets the title from a PHP static variable, which is different from the variable $variables['title'] passed to the template files.

Your template hook would work if it uses the following code.

function lwt_preprocess_page(&$vars) {
  $path = drupal_get_path_alias();
  if ($path == 'scores/completion') {
    // -1-
    $vars['title'] = t('Completion');
    drupal_set_title($vars['title']);
    // -1-
  }
}

What happens is the following:

lwt_preprocess_page() is invoked, and (through drupal_set_title()) sets the static variable containing the value returned from drupal_get_title().
template_process_page() is invoked, and it calls the theme function for the breadcrumbs; in your case that theme function is lwt_breadcrumb(), which calls drupal_get_title(), obtaining the same value you set in lwt_preprocess_page().

In lwt_preprocess_page() you could also replace the code between // -1- with the following one.

    unset($vars['title']);
    drupal_set_title(t('Completion'));

The reason also this code works is that template_process_page() first checks if $variables['title'] is set; if it is not set, it calls drupal_get_title().

  if (!isset($variables['title'])) {
    $variables['title'] = drupal_get_title();
  }

References

theme(), for the order in which theme template hooks are executed
drupal_static(), for understanding how the page title is stored in a static variable accessible to any function


Show highest and lowest price in a view from a node reference I have a content type called Cars, and a content type called Prices.  They are node referenced.  The Prices content type has a decimal cck field for the price called field_price.    So you can create a new Prices node that will have the price for the car.  There are multiple Prices nodes for each Car node.  In views, how would I be able to show the lowest and highest prices for the car.  For instance, it would say, Prices for this car range from $10,568 to $18,259.

There may be a more fancy-pants way to do this, but I would take the view template, extract the car type, and do a manual MIN() MAX() query to fetch these values.


How to change the order of attributes in the Ubertcart cart page In the screenshot, you can see that the attributes for this product are listed in seemingly random order.  Actually, it seems to be ordered by the attribute ID.  Is there a way to change this order?  Each attribute has a "List position" property but this only seems to be for the product page, it doesn't affect the cart.

By looking at ubdercart's theme_uc_attribute_add_to_cart function and how it is themeing the output including attributes, it appears that you can achieve what you want by implementing hook_form_alter. I would start by finding the form_id, perhaps by adding a debug statement in the function. Then I would implement hook_form_alter and would alter the way the attributes are ordered to my desired order.
If this does do what you want, try and follow the logic to see where the attributes are being themed and/or built. Then hook into that mechanism (form_alter or a preprocess function) and  I am confident you will achieve what you want.
Hope this helps.


How to convert Content Type Title into Term reference? I would like to make a content type node title into a Term of reference. The titles need to be limited by some taxonomies.

How to convert Content Type Title into Term reference?

Title Field UI might work for you. I haven't used this module, but apprently it allows you to modify title fields. Not sure if it will allow you the change the type from text to term reference. Although, you can always disable titles and use another term ref field as your title.


vote for users on drupal7 I need the functionality to be able to have a vote widget on a profile page.  So users can be voted for and the user with the most votes wins.

(the users profile page is done with panels & views)

Ive played around with the flag module and it somewhat works for what I want, also the vote module, but it seems to only work on nodes and comments and doesnt work on user pages...

Any advice is greatly appreciated

You can try to add fivestars module to your website, but then your users will be voted with stars instead of flags.

If you dont mind that you have to:

install fivestar module
add a field on your user profile of type "Fivestar Rating"
add a rule so people cant vote on themselves using rules module.

hope this helps


Create a block with contextual filter that show related nodes based on field value, not with taxonomy I'm no newbie to Views or Argument/Contextual Filters, but I'm having trouble getting my head around a (simple) view.

I've created a Content-type "Event".
Which contains an 'Addressfield', which I use to store an Address and Geocode it to an value which I store in Geofield.

What I'm trying to accomplish is a 'related nodes' block, similar to an 'related articles' based on taxonomy. In that case you make a relationship, and use the NID in de URL.

I've created a View:
- a block style.
- added a 'contextual filter #1':
- When Filter value is not available: 'provide default value', content id from URL.
- Extra: exclude. This filter excludes the current node.

I'm having trouble getting to the next step: I only want to show the nodes which have the same country as the current node. How do I accomplish that?

So if I'm visiting a node from 'France', I only want to show related nodes from France.

You can try using PHP code in the contextual filter. You will be able to load the Node using arg(1) - node ID and provide the field value based on the node. Refer screenshot.


Lots of 500.shtml page not found errors in logs I've been getting lots of page not found errors for  500.shtml in my logs. A lot of them seem to be originating from search spider and ho I might be able to fix these, I'm curious to why 500.shtml is even being sought out in the first place and how these are being generated at such a furious pace:

   type: page not found
   location:http://www.example.com/test.html
  referrer:
 message: 500.shtml
 severity: warning
  hostname:

500.shtml entries in the Drupal logs. In many cases, these are generated by search engines (determined by doing reverse lookups on the IP's), sometimes from users (but in very few cases). How can I fix it?

The 500 error page is show when the server has an internal error.

Your server is looking for a file named 500.shtml because a directive set that as the page that must be shown when the server has an internal error. The .htaccess file used by Drupal set the page for the "page not found" error to /index.php with the directive ErrorDocument, but it doesn't set any error page for any 500 codes, which is the set by the server using a different file; for Apache, this means the access.conf file, or any files included by that file.

For what can cause an internal error, it could be a server directive, or a wrong argument passed to such directives. Other causes could be:

directory permissions
file permissions
a wrong transfer mode used when transferring the Drupal PHP files to the remote server when using FTP
the line endings of the files that don't match the one used from the Operating System that is hosting the server


How to disable a language while still being able to create content for it I have a website with already 2 languages. I want to add a 3 one, but I obviously don't want it to be accessible until it is finished. If I disable to language, I can't create content in it anymore.

Anyone has a suggestion?

Thank

You could try to use the Hidden Language module.

  This module allows site admins to hide languages from end-users. As opposed to disabling language content editors still can translate content to that language. It's useful if you don't have entire website translated.


How do I hide the body field in a node using hide()? I'm using the following code, and it simply does not work:

 <?php hide($content['body']);
 print render($page['content']); ?>

I would like to hide the body field to show it elsewehere.

You're rendering the wrong thing: you need to render $content:

hide($content['body']);
print render($content);

See core's implementation of node.tpl.php for more information.


Should I create a new Form or use form alter? I'm very new to Drupal. I've been handed over a Drupal 7 project. In the project, there's a form to create a new record into database. However it's using hook_form_alter instead of creating from scratch. The form is called as node/add/<something> as a page. Similar to first few steps of this tutorial.

I'm not sure however if this is the correct Drupal way, or should I just rewrite it into a block, as I want to have it shown on .... at least two pages?

Any suggestions?

The distinction is simple:

If you need to add some fields to an existing form, and keep all of it's original functionality (or at least most of it), use hook_form_alter.
If you need to create a totally new experience, put it under different path and create form from scratch, like shown in Examples for developers
If you feel you need totally new form under already occupied path, think again as it might cripple existing functionality.Feel free to ask more specific question then.

Then, if you want a form at 2 pages, you have 2 choices:

If form will be the only significant element on these pages, make it a page (or pages) with hook_menu
If there are supposed to be other forms, submitted independently, wrap it into a block.


IMCE module button not showing for Editor role? I have given the Editor role literally every single permission, yet the button still only shows for admins. Am I missing a setting somewhere?

I was indeed missing a setting somewhere. You have to assign a user profile to the role before they see the button in site configuration -> IMCE.


How to migrate custom user fields to Drupal 7? I would like to migrate custom user fields from an external USER database table to the custom tables of Drupal 7.

I created custom fields for my users (First Name, Last Name, ...) under administration/configuration/account settings and I can confirm that these fields are created if I go to administration/people/ and click "edit" next to each user.

I also know that for each individual custom field that I have created, D7 created a new table of the form "field_data_field_[FIELD_NAME]" (ie. field_data_field_first_name, field_data_field_last_name, ...)

The specific commands I would like to find more information about are:

MigrateDestinationUser::getKeySchema();
$this->destination = new MigrateDestinationUser();

I understand the above command is the default used to import users to the default "users" database.

How can I migrate my content to another D7 table? Such as migrating the First Name from the external table to field_data_field_first_name?

An example migration is here (not my own) and there are some followup comments in that GIST:
https://gist.github.com/893241

What you are talking about is mapping old fields of data to new fields of data in drupal.

You do this by calling addFieldMapping() in your Migration class constructor. The migration __constructor() function typically has 3 big pieces.

Where is the data from. Your $this->source() SQL query.
What fields map from what to where -- per field.
Is there any default values or further cleanup needed of data. By using addField('new_drupal_field', 'old_value')->default('is_published', TRUE); or for instance addField('new_drupal_field', 'old_value')->seperator(',') for more than 1 entry per row.

See documentation on these pages:

MAPPINGS
Examples of Field Mappings
Advanced Field Mappings

The whole migration class, and more importantly its constructor, is basically a recipe of what drupal does per-row of the migration.

So after you have your source $query (basically a SELECT field1, field2, field3 from OLD_TABLE) you call the following:

// this is like saying field_first_name = old_field1
$this->addFieldMapping('field_first_name', 'old_field1');


How to show an alert when user navigates to another page without filling the form? I have a form created by a custom module. Now I want to show an alert like ("Please fil the complete form before navigating otherwise lost all the data") if the user navigate to another page without filling all required fields.

How can I do so?

Below are a few modules to consider (quotes included are from the project pages of these modules), sorted by "my recommended one first". It'll depend on your specific requirements which one would fit best for you.

Node Edit Protection (either for D6 or D7).

  A very simple JavaScript based protection that will alert a user if they are navigating away from a modified Node Edit form without saving. It uses a standard JavaScript confirm dialog that allows the user to either continue what they were doing, or cancel the move allowing them the opportunity to save. It marks the form as dirty by using the blur event of the node fields.

SaveGuard (either for D6 or D7).

  ... adds javascript which detects if a form had been modified, and if it has, uses the onBeforeUnload event to pop up a warning to the user if they attempt to navigate away from the page without saving their changes. This works for Firefox, IE, and Safari, but not Opera.

Dirty Forms (only an official release for D6, though for D7 there seems to be a trustworthy patch available also).

  ... provides a javascript behavior that checks forms before users leave the page, warning them if they are about to loose changes and providing an option to remain on the page.

  ... The module provides a configuration form that allows setting up a list of forms that should be excluded from the dirtyForms behavior.


Changing upload_max_filesize inb Drupal 7 Is there any way to change php's upload_max_filesize setting from settings.php in Drupal 7? This used to work for me in Druapl 6 but no longer seems to. I don't like the idea of doing it in .htaccess, because that's a core file that will get overwritten on an upgrade.

Personally I would change it in the /etc/php.ini file as it won't be overwritten. You will need to restart apache to see the changes


How to create a rule to assign roles to users based on some checkbox items in their profile? I am pretty new to Drupal. I am using Profile2 so that the user can select there own user role. So say I have a profile page with some checkbox items like

Automotive
Computer
Garden
etc

How would I add a condition or data comparison in Rules to say, If Automotive is selected/checked, set user role to that role? I also need to be able to select multiple checkboxes to get multiple roles.

Any suggestions?

Part 1 - Make it work for a single selection and related role

Create a rule which looks like so:

Rules Event: After saving user profile.
Rules Conditions (both conditions must be satisfied):

entity has field (with the field corresponding to (eg) "Automotive".
data comparison to check if "Automotive is selected/checked".

Rules Action: : Assign role to user (for the role related to "Automotive").

You could create a similar rule for each possible combination of checkboxes and roles to be assigned. Or continue as detailed in Part 2 to further enhance your rule from Part 1 so that you end up with a single rule for all possible combinations.

Part 2 - Make it work for other possible combinations

To also make it work for other possible combinations, and because of the fact that a Rules action cannot contain "conditions", you basically have 2 possible approaches:

Create a similar rule (as in Part 1) for each possible combination.
Use the Conditional Rules module to enhance the Rules Action in the above rule to alter the flow, using either Conditional (if/else) of Switch logic. Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).


token_replace : operate on two different 'user' entities? I've got an e-mail message with the following contents:

Dear [receiver:name],

[sender:name] would like to recommend the following link [node:url].

Now, I could certainly implement hook_tokens() and make sure that all 'receiver' and 'sender' tokens are replaced, but these entities are plain old 'user' objects. It would be great if I could just use the functionality already available, but as far as I can see, that requires me to specify replacement patterns in the format [user:name]. However, that doesn't work as it would mix up the sender and receiver.

Any idea if this is doable withouth having to reimplement the 'user' replacement logic?

I don't think you can do what you require as the data fed to [user:name] belongs to the currently logged in user. Sender and receiver would be different objects in your database.


Small site, multiple layouts So I've been fighting with this for a little bit, and I've been unable to get help from Google, so it's time to ask some experts!

I'm setting up a small business website; we're aiming to create something that's very simple now, and easy to grow as the business grows. Drupal fits the bill nicely, but it's fairly new to us. I'm trying to set up three simple layouts: a basic page (Header, Main Content, Side Bar Menu, Footer), a splash page (Header, Side Bar Content), and a product page (Header, Side Bar Content, and Footer). Nothing overly ambitious, but also not supported by Drupal  7 out of the box (as far as I can see, at least).

I tried experimenting with themes and subthemes, and played around with the Zen theme for a bit to limited success, but no variable layouts. After some digging, I think CTools + Panels is what makes the most sense, and I can get the layouts I want, but I can't figure out how to get the panels to display any actual content.

Is there an easy way to execute this plan with Panels, or should I be investigating a different option?

Panels is definitely the easiest way to create different layouts.

What you have to do is go to Panel Content and on the edge of each panel there is a little gear icon or arrow (if i recall correctly) that opens a drop down menu with many options. one of them is "add content", it will open a modal dialog with options to select from blocks the content you want to display, you can also add custom fields if you want!


How to create translations programmatically? I have a batch in which i'm importing nodes from REST webservices.
My application has two languages, FR and EN (default is FR).
So, I'm creating the node in FR, then, I loop through all other languages (just EN for now) and try to do as following :

$languages = \Drupal::languageManager()->getLanguages();
unset($languages['fr']);

foreach ($languages AS $langcode => $language) {
  if ($node->hasTranslation($langcode)) {
    $node_translation = $node->getTranslation($langcode);
  } else {
    $node_translation = $node->addTranslation($langcode, $node->toArray());
  }

  $node_translation->status = 1;
  $node_translation->title = 'title en';
  $node_translation->subtitle = 'subtitle en';
  $node_translation->save();
}

And it crashes with a 500 error, reporting :

 - Drupal\Core\Entity\EntityStorageException : Invalid translation language (und) specified. dans Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (ligne 805 de /.../web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
 - InvalidArgumentException : Invalid translation language (und) specified. dans Drupal\Core\Entity\ContentEntityBase->getTranslation() (ligne 783 de /.../web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

I'm pulling my hair out on this issue for days and can not understand why the error message tells me $langcode equals 'und' whereas a var_dump of it just before this line returns me 'en'.

Edit :
I tried to hardcode and remove the foreach. So just after the $node->save() :

$node_translation = $node->addTranslation('en', $node->toArray());
$node_translation->set('title', 'title en');
$node_translation->set('field_sub_title', 'subtitle en');
$node_translation->save();

This time, the error is the following :

InvalidArgumentException : Invalid translation language (en) specified.
dans Drupal\Core\Entity\ContentEntityBase->addTranslation() (ligne 863
de /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

After several days, I finally found the solution. Obviously, there is a bug with Drupal (here 8.4.0).

The hasTranslation() method don't work properly. Instead, you should use  EntityManager::getTranslationFromContext() (will be deprecated in Drupal 9 though).

You can also write a new method like this one to replace it:

/**
 * Check if a node as a translation for the given language.
 *
 * @param object $node
 *   The node object.
 * @param string $langcode
 *   The langcode.
 *
 * @return bool
 *   True (exists) or false (does not exist).
 */
function has_translation($node, $langcode) {
  $existing_translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, $langcode);
  return ($existing_translation->langcode->value === $langcode) ? TRUE : FALSE;
}

So, my corrected code is the following:

if (has_translation($node, $langcode)) {
  $node_translation = $node->getTranslation($langcode);
  $node_translation->title = 'title en';
  $node_translation->field_sub_title = 'subtitle en';
  $node_translation->status = NodeInterface::PUBLISHED;
}
else {
  $node->addTranslation($langcode, $values);
}

$node->save();


Define custom view page template with theme_hook_suggestions I would like to define 'theme_hook_suggestions' for a custom views-view.tpl.php file.

To achieve this, I wrote the following code into my template.php file:

/**
 * Implements hook_preprocess_views_view().
 */
function MYTHEME_preprocess_views_view(&$variables) {
  // Some logic to decide if the hook_suggestions should set or not
  // ...
  $variables['theme_hook_suggestions'][] = 'foo';
}

After that, I created a copy of views-view.tpl.php in the templates folder named foo.tpl.php.

Sadly, my template file is ignored by Drupal and the default views-view.tpl.php file is rendered on the page.

What's the matter? I debugged the theme_registry and the template path should be correct (points to my theme).

Update
The target is that I can switch between two template files which are defined in my preprocess function (see above). Because in some cases, my layout markup is significant different as in other cases.

I don't want to use the same template file for both cases; when I do this, the file is full of tousands of if() just for adjusting the markup for some cases.

Your approach is fine. The only problem is with the name of the hook suggestion and the equivelant tpl.php file.

Since you are preprocessing views_view the hook suggestion should be named something that starts with views_view ex: views_view__[anything]. Note that all the undersores will be replaced with dashes for the filename. So it should be something like views-view--[anything].tpl.php

For example:

/**
 * Implements hook_preprocess_views_view().
 */
function MYTHEME_preprocess_views_view(&$variables) {
  // Some logic to decide if the hook_suggestions should set or not
  // ...
  $variables['theme_hook_suggestions'][] = 'views_view__foo';
}

And the filename will be views-view--foo.tpl.php


maintain password value after failed login attempt I'm working on a custom login page for users. I have some special elements on the page, which might cause authentication to fail even though a user enters a valid username and password combination.

After a failed authentication attempt, the username field still keeps the username they entered, but the password field is blank. I would like the password field to keep its value, like the username field does.

I'm starting the form with user_login(). I added a check to add in the password:

if (isset($form_state['input']['pass']) ) {
// user has submitted the login form once.

 // maintain their entered password
  $form['pass']['#default_value'] = $form_state['input']['pass'];
}

Yet it doesn't survive.

How can I re-populate the password field after a failed login?

The password field doesn't use the "#default_value" property. This means that is not possible to pre fill the field with a default value as it is possible with a textfield field. As it is not possible to set a default value for the field, a password field is always shown empty.

It is what I would expect, especially when a validation handler returns an error for the entered password. If the password is wrong, I don't see any reason to pre fill the field with what previously entered, considering that what the user sees is something similar to "•••••" (or a group of asterisks).


Finding entity/webform fields in the database A bunch of user accounts were deleted and recreated with new UIDs, and so any webform submissions or entities that have fields pointing to the old UID are now broken/wrong. I already updated some UID columns to the new UID, but now I need to find other tables/fields that still point to the old UIDs (and the columns aren't called "UID").

Given the ID of an entityform or webform submission, how can I find which tables/columns in the database correspond to the fields that make up that entityform or submission?

As an example, say I have an entityform with entityform_id = 123 and type = 'my_report'. If I view the entity using the Drupal interface, I see a user field that is blank, because it points to a user's old UID. How do I find where that field is located in the database? Is there a mapping from type 'my_report' to a list of fields or tables?

Also of note is that I need to do this for a decent amount of types of entityforms and webforms, so it'd be nice if I could query for them all, rather than looking at each field of each form using the interface or something.

I used a query similar to this to help me find a list of tables and columns I needed to update:

SELECT DISTINCT
    table_name,
    column_name
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    column_name LIKE '%user%_target_id'
    AND (table_name LIKE 'field_data_field%'
    OR table_name LIKE 'field_revision_field%')

It's not ideal, and it still missed a couple tables.

I put the resulting list of tables and columns into a Python script and generated the SQL update statements I needed to run.

There is probably a better way to do it.


Drupal views override stopped working for no reason I have a normal website, where I override the views templates for one view. When I go into the views UI, and check Other->Theme , it clearly indicates it is using the custom templates. But when I check the website, the templates are not used.

I think this happened when activating cache. (Yes, I cleared it already, and many times).

I saw that suddenly, altough the theme still worked, it got deactivated. So I reactivated it, but still the views templates are not used in frontend.

Can anyone please shed a light on this?

It is only one template file that doesn't work anymore.

I have not experienced this, but have a theory.  The default views that come with the module can be restored to their original condition so your problem may relate to the "special' nature of these views.  Try cloning the view and making your modifications to the clone.


Form API submit handler does not get called I am using FAPI with dynamic fields. The code I am using is:

function email_action($form, &$form_state) {

$result = db_query('Select * from my_action_plan_settings ORDER BY action_type');
$records = array();
foreach ($result as  $record) {
  $records[] = $record->poa;
}

for ($i = 0; $i < count($records) ; $i++) {

  $form['action'] = array(
    '#type' => 'fieldset',
    '#title' => t('Action #@num', array('@num' => $i)),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['action'][$i]['poa'] = array(
    '#type' => 'textfield',
    '#title' => t('Point of Action'),
    '#default_value' => $point_of_actions[$i],
    '#description' => t("Enter first name."),
    '#required' => FALSE,
  );
  $form['action'][$i]['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email Address'),
    '#required' => FALSE,
  );

}

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

return $form;

}

function email_action_submit($form, &$form_state) {
  dsm($form_state);
}

The submit handler never gets called, I used a custom submit handler also, it does not get called. If I limit the count of loop to 20, the submit handler gets called and everything works fine but without breaking the for loop, the submit handler never get called, is there a limit to number of fields? Or am I doing something wrong. Not sure what the issue is.

You can try the following :

 function email_action($form, &$form_state) {

    $form['#submit'][] = 'email_action_submit';

    }

    //submit function for the form

    function email_action_submit($form, &$form_state) {

    // write your submit code here
    }


How to alter view query I am just looking for altering select query, created by any view just before its execute. For e.g. I want to add some manual filter which I can't add from Views' UI.

You are likely looking to use hook_view_query_alter, additionally you might want to look into some related questions on Drupal answers How do I use hook_views_query_alter()?.


How can I accurately determine when a customer is on the "Review" step in Commerce? I've created a custom checkout pane by extending Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase and added it to the "Order information" step in a checkout flow.  This accepts customer data.

The customer then progresses to the "Review" stage to confirm everything is correct. The customer can "Edit" their information if required, going back to the "Order information" step.

Within the custom pane I'm wanting to determine whether it's being displayed in the "Order information" step or the "Review" step.

getStepId() always returns what's in the config for the pane. In this case, "Order information".

$this->order->checkout_step seems to always return "Review", or maybe it's just reporting the highest step reached in the order thus far.

Is there a Commerce native way of determining the exact step being viewed? Or will I need to check the URL directly?

Edit: I've tried checking the route name, but both /checkout/[id]/order_information and /checkout/[id]/review return commerce_checkout.form.

A good place to look for example code related to the checkout form is CheckoutController.php. Its formPage() function ensures the form for the correct checkout page is built by comparing the checkout step requested in the URL to the checkout step the order last advanced to, ensuring the customer isn't trying to directly navigate to a later step than it's entitled to.

You can see that it uses the a route matcher to get the named 'step' parameter from the URL, and you can do the same thing in your own code. Typically you'd inject the route matcher into the checkout pane class, but a quick and dirty solution to fetch the current route matcher from the container is:

$container = \Drupal::getContainer();
$route_matcher = $container->get('current_route_match');
$step_id = $route_matcher->getParameter('step');

This will functionally do what you've done by looking at the URL directly, to be honest, but it's a bit more structured way of doing so.


How do I control the number of cols in a textarea? According to the Form API, you control the number of columns in a textarea with the #cols attribute.  However, setting this seems to have no effect when I use it inside a $form array (the companion #rows attribute works as expected).

This may just be a bug (and I understand that bug-reports are off-topic on SE DrupalAnswers). But I have searched the issue queues and haven't found any bug reports about this, which makes me suspect that there is something rather basic that I've misunderstood.

So: What is the correct way to control the number of  cols in a textarea?

Environment: Drupal 7 fresh install, Bartik theme with no customization.

Thanks David Thomas - CSS did it!

Since your comment is rather terse, I take the liberty of answering my own question where I describe how to use CSS in more detail.

To attach a CSS file, add the following to the form:

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

Then look at the HTML generated to find the class of the textarea:

<textarea id="edit-mymodule-data" name="mymodule_data" cols="40" rows="2"
  class="form-textarea">
Please fill in some data.
</textarea>

(Just for the record, notice that the values for cols and rows are picked up from the $form array, but unfortunately the value set for cols have no effect.)

The class of textarea is form-textarea, so placing the following in mymodule.css makes the textarea 100 pixels wide:

textarea.form-textarea { width: 100px; }


"What links here" for Beans I'm using an Entity Reference field (unlimited entries) and a View to include desired Beans on node pages. How can I create a view similar to node/%/backlinks which allows me to see all the nodes that reference a particular block?

So far, I have a View of Content. It includes a relationship to the Referenced Entity (Block) and a Contextual Filter on Block ID. I want to include this View as a menu item on the Block itself, but blocks aren't displayed with their BID, they use a transliterated version of the label as an alias.

I need to find a way to access the Block ID from the alias, or somehow expose a transliterated version of the Label through Views.

I think your problem is that you are focusing on the label. You need to use a contextual filter of 'Block: Block Delta'. Then you can add a menu tab to views using this path:

block/%/back-links


Canonical URLs per node I'm trying to find out how to set a canonical url on certen pages/articles on a drupal 8 installation.
Metatag module, have the option for setting the canonical URL but is a general setting not specific for every page/article.
Does anybody know how to solve this?
Thank you!

If you want to set a specific canonical URL for a given node, just edit your node and uncheck "Generate automatic URL alias" in the URL alias section and you'll be able to write your own URL.
You might need Path module to be enabled to do that.
If you want to have specific automatic patterns for your URL alias depending on the type of node, then you will need the module Pathauto (https://www.drupal.org/project/pathauto) ; just enable it and configure your patterns for each type of node


Trouble saving canvas as image to the public file directory I've created a canvas via jQuery and need to save it back to the public file directory as an image, so I can access it like any other image.

I can create the file and save it, into the same file location as my save.php script, but unable to save it to the public file directory...

var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL("image/png");

$.ajax({
  type: "POST",
  url:  Drupal.settings.basePath + "mypath/save.php",
  data: {
     imgBase64: dataURL
  }
})

Then the following php as called in save.php:

$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'public://' . uniqid() . 'myCanvas.png';
file_put_contents($fileName, $fileData);

excluding 'public://' . will happily save to the location specified in Drupal.settings.basePath + "mypath/...", but I'm unable to tell it to save to the public directory or even any directory structure...

You need to create a module, and define a menu path in it using hook_menu(), and the page callback for that script will be your upload script.

function hook_menu()
{
  $menu['mymodule/upload'] = array
  (
    'title' => 'upload',
    'page callback' => 'mymodule_upload_callback',
    'access callback' => TRUE
  );

  return $menu;
}

Note that you'll need to name your hook in line with Drupal hook naming conventions: https://www.drupal.org/docs/7/creating-custom-modules/understanding-the-hook-system-for-drupal-modules

Then your upload callback:

function mymodule_upload_callback()
{
  // Handle your upload here. You will have
  // access to public:// and the rest of the Drupal API.

  // call drupal_exit at the end() to prevent your
  // script from going past this point.
  drupal_exit();
}


How to expose non Drupal tables in Views? I wonder what is the best way to allow the Views module to access external tables not in Drupal?

I tried the Data module, but it doesn't allow for a datetime datatype.

The data module is a good start.

You can skip the data module and create your own views type with hook_views_data()
Angie has an example here.

Date times can be tricky, if you post another question with your specific problem with date times there may be a solution.

You don't specify if the DB is the same. You would need to define a second database in your settings.php if you need to connect to a different DB.


Unable to upload video files in drupal 7 with the video module I am trying to make a simple video uploading site with Drupal. I am using the Video module. Let me tell you what I have done:

1) Just made a fresh installation of Drupal 7.7

2) Installed the Video module

3) Enabled the following

Video
Video UI

Now when I go to configuration tab I see the following error:

  Exception: You must have the cURL extension enabled to use this
  library. in require_once()  (line 22 of
  C:\wamp\www\freshdrupal\sites\all\modules\video\libraries\zencoder-php\Zencoder.php).

However I can still create a new content type and add field of video type. In that case when I add a content and upload video it gaves the same exception error as shown above.

Please help. If there is any substitute module for doing the same please tell me so. I need it urgently.

According to your error, you need to have CURL installed.

If you're running a mac:
http://www.davidonzo.com/lng/en/post/986/php-mac-os-x-how-to-install-the-curl-library/

If you're running linux:
type in the command line - "apt-get install curl"

If you're running WAMP on Windows:
click the WAMP icon in task tray, then go to PHP > PHP Extensions > php_curl. Then restart apache.


Prevent a "default value" checkbox being created with entity? I have a boolean field associated with my custom entity. The field itself is hidden in the entity form however when an instance of my entity is created a field record is generated with the default value. This is not the case for a text field i have, where if the field is hidden the field record is not created.

Basically this creation of a default boolean field is messing up my views further down the line.

How can i prevent a default value boolean field being autogenerated when hidden?

Thanks
Mathew

I am sure there are other (better )ways but the way i got around this issue, which fundamentally was about not having the default turn up in my views further down the line, was to implement a hook on hook_views_pre_view and show/hide the fields as i wanted:

function mymod_views_pre_view(ViewExecutable $view, $display_id, array &$args)
{
  ...
  $fields[$field_name]['exclude'] = TRUE;
}

worked for me hope it helps someone else.


How to convert a stdClass object to a SimpleXMLElement object I have a JSON file from a web service and want to use this data with a Drupal module. However, this module expects XML data. So I have the idea of overwriting the module. To do this, I need to convert the JSON file in XML, and ensure the file changes from JSON to PHP array.

Does any method or library exist to do this or convert .json file to .xml directly?

Now I have an array that is like the following one:

Array(
  [0] => stdClass Object(
    [sponsor] => stdClass Object(
      [created_at] =>
    )
  )
)

I need to convert this array in:

SimpleXMLElement Object(
  [@attributes] => Array(
    [type] => Array(
      [sponsor] => Array(
        [0] => SimpleXMLElement Object(
          [created-at] =>
        )
      )
    )
  )
)

Using the XML Serializer package, you can use the following code to make the conversion, as reported in this answer on Stack Overflow.

function json_to_xml($json) {
  $serializer = new XML_Serializer();
  $obj = json_decode($json);

  if ($serializer->serialize($obj)) {
    return $serializer->getSerializedData();
  }
  else {
    return NULL;
  }
}

Alternatively, you can use the following code give in this answer for the same question.

require_once 'XML/Serializer.php';

$data = json_decode($json, true)

// An array of serializer options.
$serializer_options = array (
  'addDecl' => TRUE,
  'encoding' => 'ISO-8859-1',
  'indent' => '  ',
  'rootName' => 'json',
  'mode' => 'simplexml'
);

$Serializer = &new XML_Serializer($serializer_options);
$status = $Serializer->serialize($data);

if (PEAR::isError($status)) {
  die($status->getMessage());
}

echo '<pre>';
echo htmlspecialchars($Serializer->getSerializedData());
echo '</pre>';


Attach a submit handler on an ajax-y form (hook_media_format_form_prepare_alter) I'm working with media 7.x-2.0-unstable7.

I am attempting to adjust the behavior of the media module's wysiwyg embedded image attribute editor modal dialog (c.f. http://drupal.org/node/835516).  It was pretty easy to adjust the contents of this dialog with hook_media_format_form_prepare_alter (see: http://drupal.org/node/835516#comment-7075374), and I expected that it would be easy to add a submit handler, and Drupal would jump through the hoops for me to insure that it was called at the right time. If this service is offered, I can't seem to figure out how to make it work.

The only other place I can find that uses hook_media_format_form_prepare_alter is media_crop, and it includes its own ajax POST to send its data back to the server.  It's not clear to me how the standard media_format_form saves its data.  It looks like ctools handles calling the submit handler for similar form, media_file_edit_modal (called for editing image metadata fields for media image files that are entity fields).  Is there something similar for hook_media_format_form_prepare_alter, or do I have to write my own Javascript and my own data-receive menu, like media_crop does?

media.api.php did not help clarify.

It always pays to test your assumptions.  The media_format_form only saves metadata edits into the embedded media tag in the edit text contents; the alt and title information attached to the file object are not adjusted.  There is an advantage to this, in that different instances of the same picture embedded in different locations can also have different alt and title text.  Unfortunately, though, it also means that if an image is uploaded via the embedded media image tool in a wysiwyg editor, then the alt and title fields will be empty the next time that image is used, whether it is used as an embedded image or attached to a media image file field.

It would be helpful if media_format_form would save metadata changes back to the file object, just as media_file_edit_modal does.  However, it appears that at the moment, that capability is not present in the code.