Drupal Import Commerce Product Display Multiple Images With Feed? So... I have been attempting to import a list of products from a D6 site into Commerce Kickstart 2.6 and at every turn it's fraught.

My latest attempt has been to
a) Use Node Export to get a CSV of products from old site. Good.

b) Import using Commerce Product Feeds, first to get the Product and then again to get the Display (nodes). Three problems:

How does one map the 'images' field in the CSV? The CSV I'm importing has a path to the JPG file for each product in the folder where the images can be found. Eg.

  /sites/default/products/myproduct.jpg

Two issues:

This works for -one- image, but not if the product has multiple images. I tried mapping the CSV columns for each image path to the 'Images' field in the importer multiple times but this did not work. Again, only the 1st image imported
I can't figure out how to add the ALT tag to each product.

So: should each image be simple strings or is there some other data format (eg. array)?

When using Feeds & Commerce Product Processor you might want to to install Feeds Tamper as well. If the field that you are importing has multiple values you will typically have a delimiter (comma). I'd suggest using the explode function from Tamper to break the field into an array of values to import.  It might also help if you do a replace on the values you exploded to use the public file URI syntax (public://products/myproduct.jpg).


How do I set BCC in the email I am sending? I am using Drupal 8. How can I add the BCC field in the mail function.

Using below code Bcc not working

$params['body'] = 'test body';
$params['subject'] = 'test subject';
$params['Bcc'] = 'test@gmail.com';
$message =  \Drupal::service('plugin.manager.mail')->mail('test', 'test_email_form', $to, $langcode, $params, $from);

hook_mail function code:

function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'test_email_form':
      $message['headers']['Bcc'] = $params['Bcc'];
      break;
  }
}

Your hook_mail implementation needs to set the subject/body for the email to send; $params is just passed for context.

Given your first snippet, this should work:

function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'test_email_form':
      $message['headers']['Bcc'] = $params['Bcc'];
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}


How can I track statistics regarding the number of sign-ups vs. account deletions? I'm working on a social networking site in Drupal 7 that I haven't launched yet.  However, once I've launched I would like some basic metrics to track how I'm doing, particularly the number of sign-ups per week (or some other arbitrary interval) and the number of users who have cancelled/deleted their accounts.

Is there a way to track this from within Drupal?

Views is your friend. You can build a view that shows the total number of registrations per week, for example. You can use an exposed filter to change the date ranges.

You can use user stats to keep track of last login time and then built a similar view.

If you user userpoints you can get stats based on activity (or the lack thereof).


How to relate nodes in Drupal 7 How can I relate content in Drupal 7?

I have three content types:

Product Group ( With detail page )
Product ( With detail page )
Application ( With detail page )

A product belongs to a product group.

An application belongs to a product group.

How can I do this kind of relationship?

The best way is to use the Entity Reference Module.

Install the module
At the Product add a field My Product Group and Field Type: Entity Reference. If you have many Products use the autocomplete widget.
On the next page chose Target type: Node and then the as Target bundles the Product Group.

Now when you add a ‘Product’ you can assign the parent ‘Product Group’.

Do the same for Application and Product.

The final structure will be:

- Product Group
- (have) Product
-- (have) Application

To display the results is another story. You can go to ‘Manage display’ of the content type and Render the entity. Or you can use views if you like something more complex.


Media Module: How to enable SVG files I can currently upload with an Image field for SVG.   I am using the SVG image module.

I just installed the Media module so I can use the Media library functionality.   However when I add a new Image using Add Media.   I am getting the error message I was having problems with before.

Only files with the following extensions are allowed: png gif jpg jpeg.

Not sure where to resolve this.   Please advise thanks.

You can use SVG Image Field module with Drupal 8 and the new core Media module.

Enable Media module and the experimental Media Library module both of which are found in Drupal >=8.7 core.
Download and enable SVG Image Field and apply to it the patch from Issue #3053011.
Go to /admin/structure/media  and click the "Add Media Type" button.
For the Media Type Name specify 'SVG'.
For the Media source select SVG from the dropdown.
In the field mappings map Name to Name (the only option in the dropdown).
Click save. Then proceed to configure the Form Display and the Display for the Default and Media Library view mode at /admin/structure/media/manage/svg/form-display and /admin/structure/media/manage/svg/display respectively. You'll most likely want to just enable the "SVG" field, and disable the rest of the fields. The default display you can choose to use an inline SVG option.
Add a Media reference (Entity reference) field to your node types and configure it to allow the SVG bundle type.  Optionally, enable other bundle types as well, like Image if you want to allow both images and SVGs in the same slot).
Go create a node,  and click the "Add media" link.
Notice that the Media Library loads with a vertical tab for each kind of media type bundle you enabled in step 7 on your node configuration screen.

If you're still on the fence about how to choose the right SVG media module from Drupal 8 contrib, you may find my comparison of the 3 modules helpful to guide your decision making:

https://drupal.stackexchange.com/a/280837/3167


Caching pages for anonymous users prevents other cache logic? I'm looking to confirm my suspicions as anything but, if I enable caching for anonymous users then any cache logic I've implemented in custom modules, views and blocks is thrown out, is this correct?  What I mean is, if I have a block showing some weather information that has a 5 minute cache but I turn on anonymous page caching, the cache logic of my block is never considered.

Is there a way around this?

The page cache just takes whatever is generated by the current page, stuffs it into a large string and stores it into the cache. As long as that cache entry is then valid, it is returned and no other code is invoked.

Once the page cache is expired, the page will be regenerated completely and any other element will either be loaded from a specific cache or rebuilt.

If it's important that certain information is kept up to date, all you need to do is make sure that the cache expiration time of the page cache is the same or lower as the one of the relevant block/page/whatever.

There is a concept, called ESI, that basically allows to define placeholders in a page cache string that can be replaced with separate request. However, Drupal 7 doesn't really allow that yet (Drupal 8 will hopefully improve this) but this is for things that actually are different based on the user, for example if you have a site that is the same for all users except a single block that is user-specific. Not for something like a weather block that is the same for all users and valid for 5 minutes.


What module should I use to save a module settings in a feature? I am needing some additional power for my Features.  I have several modules that have their own settings (like css injector... yeah, I know) which do not appear in teh list of items that can be saved within a feature.  I have been told that Strongarm offers a good way to include additional configuration within a feature (above and beyond what Features can normally store.)  I have also heard talk of another module that is (commonly?) used with Features which improves its ability to store and transfer configurations.  I can not remember the name of this other module.  Could someone point me in the right direction?

Many modules store their settings in variables, that's what Strongarm is good for : it can help you export those variables with features.

My usual way of finding out which variable to export (and exporting it) :

see the source HTML of the form where you set the values
in the "name" attribute you will most often find the name of the variable
use drush vget *that_variable* to check if it exists

drush vget is useful because it searches all variables that have a name similar to the string you provide, so sometimes you can do some testing to see other variables that could be useful

if you confirm the name of the variable, put it into the feature's info file

features[variable][] = that_variable

run drush fu your_feature

this will export the variable's value

The other module you heard off might have been Features Extra. Me personally i don't find it that useful anymore.

There is a free video on drupalize.me about features. And an article on d.o.


how to use hook_user_login to catch username and password I am trying to catch the username and password which are entered on the user login form. This is my code:

function impak_integration_user_login(&$edit, $account) {
  drupal_set_message("Welcome User!" . print_r($edit). print_r($account));
  global $user;
  drupal_set_message(print_r($user));
  }

The hook does work, as It does print out the Welcome message after login. However, I can't figure out how to get any of the user information, specifically the entered username and password.

The information send in the login form is in the $edit array. You can get this information as follows:

function YOURMODULE_user_login(&$edit, $account) {
  $username = $edit['input']['name'];
  $password = $edit['input']['pass'];
  drupal_set_message("Welcome $username your password is $password");
}


Clean Deleted Field from Database I have created fields deleted them. Tables for the fields are gone upon deletion, but they are still in field_config and field_config_instance

Is there anyway to clean them?

Thanks

using drush:

$ drush eval "field_purge_batch(500)"

you might have to run a few times, or increase the $batch_size
then there might still be field_deleted and field_deleted_revision tables, even after running cron

query

SELECT * FROM `field_config` WHERE `deleted` = 1
SELECT * FROM `field_config_instance` WHERE `deleted` = 1

if you come up empty, you can safely delete those leftover tables


Custom Module to remove User Menu Tabs I'm hoping someone can take pity on me because I just can't seem to figure out how to make a simple module to remove, or hide some tabs in my user pages.
I read the docs on making custom modules, questions about removing tabs, and thought I figured it out. I made a custom module called 'TabEdit' with this structure, just to test it out:
/tabedit
    tabedit.info.yml
    tabedit.module

tabedit.info.yml
name: TabEdit
description: Edit tabs shown in user pages.
type: module
package: custom
core: 8.x
core_version_requirement: ^8 || ^9

tabedit.module
<?php
/**
 * Implements hook_menu_local_tasks_alter()
 */
function tabedit_menu_local_tasks_alter(&$data, $route_name) {
  unset($data['tabs'][0]['simplenews.newsletter_subscriptions_user']);
}

It didn't work, so I obviously still don't get the fundamentals on how to make a module. What I want to do is remove the Shortcuts, Simplenews Subscriptions, Activity, and Submissions from the user menu tabs.

Hooks need to be written in . module file not in controller. Move your code to .module file and also it should be tabedit_menu_local_tasks_alter
tabedit.module
<?php

/**
 * Implements hook_menu_local_tasks_alter()
 */
function tabedit_menu_local_tasks_alter(&$data, $route_name) {
  unset($data['tabs'][0]['simplenews.newsletter_subscriptions_user']);
}

Clear flush all caches so hook gets pickedup.


How do I programmatically change the user ID in a order? I programmatically created a user using the following code.

use Drupal\user\Entity\User;

/**
 * Helper function to create a new user.
 */
function create_new_user() {
  $user = User::create();
  $user->setPassword('<password>');
  $user->enforceIsNew();
  $user->setEmail('<email>');
  $user->setUsername('<username>');
  $user->save();
  drupal_set_message("User with uid " . $user->id() . " saved!\n");
}

Now I need to set the ID of the created user into an order.

I've loaded the order using the following code.

$ord_id = 10;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);

I want to update the user ID of this order. How can I achieve this?

It should be as simple as:

$order->setCustomer($user)->save();

Or if you only have the user ID and don't want to load the account object:

$order->set('uid', $uid);
$order->save();


Unique field value per multivalued field collection Field collection Config (multi value)

Field1---Name -Autocomplete (single value) (Entity Reference)
Field2---Score - Computed field.

Example Values for field collections

Field collection [0]
------Bill (1112)- where 1112 is nid
------Score - some value will be generated depends on 1112

Field collection [1]
------Roger (1345)- where 1345 is nid
------Score - some value will be generated depends on 1345

Field collection [2]
------Roger (1467)- where 1467 is nid
------Score - some value will be generated depends on 1467
..
..
Field collection [n]
------Maddy (1652)- where 1652 is nid
------Score - some value will be generated depends on 1652

From above config how to make field Name's value should not hold the duplicate value for field collection ie Bill should not be applied again.
There is a module called https://drupal.org/project/unique_field which forces field's value to be unique per content type or per all node, but not per field.
In above case somehow(that what is required) if we make per field then also it could only applied to Name field which is inside field collection rather than field collection itself. Right?

I had to do this the other day and found it easiest with a custom validation function.

Using hook_form_alter add a new validation function:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //drupal_set_message("Form ID is : " . $form_id);
  switch($form_id) {
    case 'YOUR_FORM_ID':
      //dpm($form);
      $form['#validate'][] = 'validate_unique_field_collection_names';
      break;
  }
}

And then in your new validation function:

function validate_unique_field_collection_names($form, &$form_state) {
  $used_ids = array();
  foreach($form_state['values']['field_people_collection'][LANGUAGE_NONE] as $k => $item) {
    if($k === 'add_more') continue; // skip loop if key is add_more
    $user_target_id = $item['field_name'][LANGUAGE_NONE][0]['target_id'];
    if(in_array($user_target_id, $used_ids)) { // check if UID is in used array
      form_set_error('field_people_collection]['.LANGUAGE_NONE.']['.$k.'][field_name', t('Names must be unique.')); // if it is set an error
    } else {
      $used_ids[] = $user_target_id; // else add it into the used array
    }
  }
}


7 - Add CSS to a LIST items in a block I'm trying to display a block on a left side bar with few links. I've created a block and it shows up with the links but NO CSS applied:

            Home

            Site Info

            Career

            About Us

When I check the elements in UI, it doesn't show the vertical-tabs class being applied.

I'm not looking for any custom form. I need to know how the CSS should be applied in this case.

Thanks.

There's a template hook for this: template_preprocess_block

Use $variables['classes_array'] to add classes to the block.


How to determine which element has called (triggered) the AJAX callback function? For example:

/** FIRST FIELDSET **/

$form['fieldset_1']['enabled'] = array(
  '#type'        => 'radios',
  '#options'     => array(1 => t('Enable'),
                          0 => t('Desable'),
                          ),
  '#ajax'    => array('callback' => 'my_ajax_callback',
                      'wrapper'  => 'my_wrapper_1',
                     ),
);

$form['fieldset_1']['myChangebleField'] = array(
  '#type'   => 'whatever',
  '#prefix' => '
',
  '#suffix' => '
',
);

/** SECOND FIELDSET **/

$form['fieldset_2']['enabled'] = array(
  '#type'        => 'radios',
  '#options'     => array(1 => t('Enable'),
                          0 => t('Desable'),
                          ),
  // Now I am calling the same callback function but assigning a different wrapper
  '#ajax'    => array('callback' => 'my_ajax_callback',
                      'wrapper'  => 'my_wrapper_2',
                     ),
);

$form['fieldset_2']['myChangebleField'] = array(
  '#type'   => 'whatever',
  '#prefix' => '
',
  '#suffix' => '
',
);

function my_ajax_callback($form, $form_state) {

/**
 *  How do I figure out which of the element "enabled" was the caller?
 *
 *  In that way I could do something like:
 **/
   switch($caller){
     case 'fieldset_1':
       // do stuff...
       break;
     case 'fieldset_2':
       // do stuff...
       break;
     // ...
   }

   return $form[$fieldset]['myChangebleField']
}

As seen in the example above, how do I figure out which of the element "enabled" was the caller?

Having two callback functions is not an option as the form elements will be constructed in a dynamic way and I won't actually use a switch statement in the callback function as shown in the example.

Cheers,

Got it!!! This guy here $form_state['triggering_element'] does the trick.


Convert vertical (portrait) picture to horizontal (landscape), filling empty space around with blurred background How can I do this in Drupal 7?

Note: Original question was here.

I have created custom module called "Blurred". It can be described as "post scale blurred background effect for images".


How can I add some style to title of side bar block? I want to add some style to my drupal 8 Sidebar menu, I want to create something like below image with Font awesome and css:

First add position: relative as a style to the containing element (most likely the nav element.
Add a pseudo element after the h2 element, which you probably want to have your specificity include the class of the nav element.
Style the pseudo element with position: absolute; right: 0;
Tweak the styles of the h2 and h2:after blocks to suit your needs.


db_affected_rows gives fatal error in drupal 7 How can i get the number of affected rows in drupal 7? db_affected_rows which i was used in d6 is not working in d7. It shows an error

 $bool = db_query("SELECT * FROM {template_config} WHERE user_role = ':d'",array(':d'=> $id));
        $num = db_affected_rows();
        if ($num != 0) {
            $result = db_fetch_array($bool);
            $custom_theme = $result['theme_name'];
        }

i want to check if there is any affected rows.db_num_rows also is not working in d7
How can i do this in d7?

There is no db_affected_rows() in Drupal 7 I'm afraid. Also you don't need include the quotes in your variable placeholder. Your code might look a little more like this:

$results = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchAll();

if (count($results) > 0) {
  $first_result = $results[0];

  $custom_theme = $first_result->theme_name;
}

It could be even simpler though:

if ($result = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchObject()) {
  $custom_theme = $result->theme_name;
}


Using preprocess node variable in page.tpl.php I've set up a couple of variables in my template_preprocess_node(). How can I access them within a page template? I can access the $node variable, but it doesn't seem to have been preprocessed.

How can I force preprocessing?

The node variable for page templates is set in template_preprocess_page
http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess_page/6
You should override that function in your theme


Drupal multi-site subdomain and subpath going to same site Is it possible for Drupal to handle both subdomain and subpath for a single site in a Drupal multi-site environment?

For example:

foo.example.com ---> 'foo'

example.com/foo ---> 'foo'

Is this possible? Would I run into any issues?

You can configure your desired structure/aliasing by creating the sites.php file in the sites directory. See the example.sites.php file in the same directory for extensive documentation on this topic.

So, for your use case:

$sites['foo.example.com'] = 'foo';
$sites['example.com.foo'] = 'foo';

When visiting foo.example.com or example.com/foo, Drupal will return the "website" located at sites/foo. (However, instead of foo usually the name of the (sub)direcotry is one of these aliases).

About running into any issues, the one thing that comes into my mind is that search engines seem to appreciate unique content. It is considered bad practice if your (public) content can be accessed by multiple web addresses (therefore generally it is recommended to set up 301 redirects, however, not sure if this is the right place to discuss this topic since it is not specific to Drupal).


Updating all existing user's custom field I am fairly new to Drupal development and ran into a problem when trying to create a cron to update the value on a custom field for all the existing users.

Here is the code, when I click run cron it does nothing. I do no see my value in the custom field I created on any of the users.

/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    $user->field_my_field = 'test';
    user_save($user);
  }
}

Found out why it was not working (Which also explains why none of my debugging was displaying.) I had to skip over the the user with UID of 0 and modify how I set the field value or else the user_save function would break the code (For anyone that is interested.)

/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    if($user->uid == 0)
    {
      continue;
    }

    $edit = array(
      'field_my_field' => array(
        'und' => array(
          0 => array(
            'value' => 'test'
            )
          )
        )
      );
    user_save($user, $edit);
  }
}


Create Entity bundles programmatically The Paragraphs module seems great, but it does not provide any API (I looked at the source). So I think that will be enough to use Drupal API and/or Entity API.

About this module: it provides a new entity type 'Paragraph' and field with same name. User can create via UI 'Paragraph types' (bundles) with fields and view display settings like node entity.

My question: What's the right way to define bundle type for this entity type with custom fields in a custom module?

I think I must create fields first, using field_create_field() and field_create_instance() in hook_enable(). But what's next?

I must create bundle for paragraphs entity and attach created field, but I don't know how and any searches always send me to documentation about how programmatically create entity itself.

There is more easy way to do this: Use the module functions.

paragraphs.module contain these functions:

paragraphs_bundle_save()  to create and update bundles
paragraphs_bundle_delete() to remove bundles
paragraphs_bundle_load() to get the list of bundles or load a bundle

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Create new Bundle.
  $bundle = new stdClass();
  $bundle->name = 'Test Bundle'; // user friendly label
  $bundle->bundle = 'paragraphy_test'; // machine name
  $bundle->locked = 0;
  $status = paragraphs_bundle_save($bundle);
}


Is there a way to serve a specific node for certain paths? I'm using Pantheon and there doesn't seem to be a way to update nginx/apache config.

One of my templates is actually a single page app, and I'd like to tell Drupal to serve /node/1 for a couple of URIs.

Get the current path alias or path? shows how I am able to get the current path in the .theme file.

Is there a way to serve a specific node for certain paths?

Core has URL aliasing built in, and having multiple aliases for a single path is supported.

You can manage these at /admin/config/search/path (assuming you have the core Path module enabled).


Link to create a node, save it, and then go to the edit page I want to enable users to click a link to create a node of a specific content type. However, instead of going to /node/add/contenttype, which is the standard Drupal flow, I want the node of the relevant content type to automatically be created and saved, and then redirect the user to the newly created node's edit page.

In other words, when a user clicks "add a node," I want to create the node for the user and send the user to the edit page.

I want to do this because I have a very long, complicated form and I want to use the Autosave Form module to automatically save the form; however, this module can only save a node/entity that has already been saved once (entities with an entity ID).

What's the simplest way to implement this?

I'm thinking that I will need to define a custom route that checks permission, runs code to create the node, and then redirects to the node.

EDIT: Overriding the NodeController

As suggested by 4k4, I overrode the NodeController as follows.  However, the problem is that when I go to /node/add/contenttype, the node is created and the form is shown, but it's an old form; when I try to save it, I get this error: "The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved."

class MymoduleNodeController extends NodeController {
  public function add(NodeTypeInterface $node_type) {
    $content_type = $node_type->id();
    if ($content_type == 'MYTYPE') {
      $node = $this->entityManager()->getStorage('node')->create([
        'type' => $node_type->id(),
      ]);
      $node->save();
      $form = $this->entityFormBuilder()->getForm($node);

      return $form;
    }
    else { // Default node creation behavior

I think the simplest way is to save the node right after you've created it in a custom version of NodeController::add():

  public function add(NodeTypeInterface $node_type) {
    $node = $this->entityManager()->getStorage('node')->create([
      'type' => $node_type->id(),
    ]);

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
  }

Edit:

Because building the form directly with the saved node doesn't work, return a redirect response for the node edit form:

    $node->save();
    return $this->redirect('entity.node.edit_form', ['node' => $node->id()]);


Is it possible to turn off Ajax load for Commerce Coupon Module? I am getting a bunch of issues with the Commerce Coupon module 7.x-2.0-rc3. Mainly there are inconsistencies with the forms updating and also intermittent timeouts. I'm assuming it's an Ajax load issue.

Is there a way to turn off the Ajax load when a coupon is applied, and just get a regular page load?

Maybe you run into this bug https://www.drupal.org/node/2412549.

Apply the two patches mentioned in comment #9

  If you really want to turn of AJAX, you need to hook all the
  corresponding forms and unset #ajax.

i would not suggest this thoe !


Unlimited Values Weight Currently I have a field that allows unlimited values, and it's displayed as a video player, using user-input URL from that field. Now I would like to do some custom coding or whatever it takes to somehow pick the first URL (the one at the very top), so I can have the video player play only one URL. Any ideas?

In a multi-value text field, and assuming D7, the values are something like this:

// if set, this is the first value...
$node->FIELD_NAME[$node->language][0]['value']
// if at least one set, this is the last value...
$node->FIELD_NAME[$node->language][count($node->FIELD_NAME[$node->language])-1]['value']

so depending on what you mean by 'on top,' one of these values is most probably what you are looking for.  (If D6, just take out the [$node->language] part)


User Management - with different levels We are working on a site building using drupal. We have 3 different user profiles / roles.

Site Administrator (manage client admin and content)
Client Administrator (manage department admins)
Department Administrator (manage his own content)

Project Flow: Site admin, will manage client administrator. Whereas client admin will manage department administrator.

Since we are at the beginner level in Drupal, I wanted to know which module will suit the above user management.

For each role you can grant access control with permissions, so each user with specific role can manage any content or users you want to.

Managing access control with permissions and user roles
User: access and management settings


Default image is not displayed while creating a node I have created a content type and added a Preview Image field. Its type is file and its widget type is image. For Default Image, I have uploaded an image that should be displayed at the time of creating one new node.

My problem is that it is not displaying on the node creation form.

Here is the screen shot for  field type. The drupal version i am using is Drupal 7 .


How to use galleria to create slideshow of Images in a Node Can http://drupal.org/project/views_galleria be used to create a slideshow of images in an image field on the node display page (i.e. /node/*)?

When I go to "Manage Display" for the content type, I do not see "..Galleria.." as one of the display options for the image field that can take multiple images?

I am able to use http://drupal.org/project/views_slideshow but it is not as nice.

Any recommendations of other decent looking slideshow modules is also welcome

Quick solutions eva module , with this you can set up a view of images with contextual filter (nid) , then attach it to the content type , then it will be available under manage display


Facebook OAuth (FBOAuth) fails to login I've installed the Facebook OAuth module which is an essential part of the website I am building. Unfortunately, the connection fails:

  "The Facebook login could not be completed due to an error. Please create an account or contact us directly. Details about this error have already been recorded to the error log."

The module seems to perform just fine in the beginning. Once I click on the FConnect button, I am redirected to facebook website, asked to login and grant access to precisely that information which I asked for when configuring the module.

(Also, when I misconfigure the facebook app, for instance by entering the wrong site domain, I am blocked much further in the process.)

The problem occurs when I am sent back from facebook to my website. Then instead of being connected, I receive the error message I mentioned.

I have had a valuable exchange with the maintainer of the module that can be found on http://drupal.org/node/1994900#comment-7419898. Unfortunately, he could not figure out the problem.

I have spent two days on it, trying many different things, but I could not find a solution. You can find a complete record of my different attempts on http://drupal.org/node/1994900#comment-7419898, but to summarize I have:

checked solutions proposed in related issues, http://drupal.org/node/1441978, http://drupal.org/node/1466598,
http://drupal.org/node/1974488.
Tried with and without clean url's
Tried to disable absolutely all the modules except for fb oauth to check whether it was a module compatibility issue (also tried a clear install of drupal with only Facebook Oauth module)
Checked that http requests were enables on my server.
Tried the alternative Fbconnect module, but I could not configure it either (I got unsolvable errors message before I could even try a connection).

Now I am short of ideas... Anything to propose?

I must say that I am a beginner, so I do not get most technical details. My sepcs are:

Drupal 7.22
Facebook OAuth 7.x-1.6
Hosted by Host1Free.

For its functionality you need to follow these steps:

Make an Application on Facebook.
Visit https://developers.facebook.com/apps/ and create a new application.
While making the application on Facebook don't forget to disable the Sandbox Mode.
Add a Website domain name on which you want to use the fboauth login button.
From there copy the  App. ID and App Secret to /admin/config/people/fboauth

That would work for you.


hide a view field content for anonymous only? How can I hide a field for the anonymous user in a view?

Logged in users should still be able to see the field.

(Drupal 8.3.0)

This might be overkill for just one field, but you could take a look at the Field Permissions module: https://www.drupal.org/project/field_permissions. This module allows you to set permissions on a per-field basis, so you can just remove all permissions for anonymous users for this field.


Some trouble autopath I have some trouble with user path aliases. I want that every user has a small page under /member/username. To enforce that I build in the settings (/admin/config/search/path/patterns) under user path the plattern: member/[user:name].

This seems to work fine but if I look at the contact link I get the link /user/1/contact I expect the link http://example.com/member/username/contact.

I have the same problem for some other links like editing any node. E.g. I have a link in my menu called Updates which is aviable under /updates but when I try to edit this one I see the url /node/123/edit.

I know that there is a module called Extended Path Aliases but this one breaks one of my own modules.

The problem there is that I use taxonomy to build paths for topics e.g. photography and sports. Normal posted news are then aviable under /photography/a-great-day or /sports/scores that will work with Extended Path Aliases, but it compleatly breaks my module with this pathes sports/event/%date (notation from menu_hook). That one seems to be routed to /sports.

I got the solution via IRC. Simply install and activate Sub-pathauto.


How can I change the number of items in a view only for the first page? I'm trying to build a view with a different number of items for the first page (2 items) than the others (3 items). How can I build it to avoid skipping items ?
I made tests using hook_views_pre_build() but the result isn't conclusive as the second page will miss one item (item C):

Here is my current code:

function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'my_view' && empty($_GET['page']) {
    //The view normally has 3 items per page, put 2 for the first page.
    $view->items_per_page = 2;
  }
}

And here is the result I obtain:

  First page:

  item A
  item B

  Second page:

  item D
  item E
  item F

As you can see, item C is missing because setting the number of items per page to 3 imply that the first page also has 3 items.

Is there another way to get this working ?

This is how I got it working, use two hooks. Assuming we have a view called my_view and the display is page_1.
Pre-build: Set the items per page to 10 for the first page.
Pre-render: Add an additional CSS class to the view.
/**
 * Implements hook_views_pre_build().
 */
function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1') {
    // Page is zero indexed: first page is NULL or 0.
    if (!$view->getRequest()->query->get('page')) {
      // Default is 9, we set it to 10.
      $view->setItemsPerPage(10);
    }
    else {
      // Set the offset on subsequent pages, because we have one more on the first page.
      $view->setOffset(1);
    }
  }
}

/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1' && !$view->getCurrentPage()) {
    // Add CSS class for first page.
    $view->display_handler->setOption(
      'css_class',
      $view->display_handler->getOption('css_class') . ' is-first-page'
    );

    // To attach a library, use:
    // $view->element['#attached']['library'][] = 'my_module/view-first-page';
  }
}


Accessing the in-place editor with a keyboard hotkey ? (cross-platrofm Drupal question) Quite hardcore, cross-platform programming question:

Can a logged admin user reach a state when clicking some button on the keyboard on a Drupal node opens its quick-edit widget to quickly edit the node?

Something that will work for all common systems (Ubuntu, Windows10, Mac).

Accessing the quick-edit widget in the current way tens if not hundred+ times a day can be a bit annoying in this could make the Drupal edit experience much better.

You can use my module, Instant Transmission.

  Why waste time moving the mouse cursor 7000 pixels or navigating drop
  downs or scrolling down the page to hit the save button, when you can
  use ... Instant Transmission.

  Instant Transmission allows you to quickly edit or configure nodes/blocks
  much faster than ever before.


Varnish causes page load time to increase I am running Drupal 6 with pressflow on Ubuntu 11.04.
I installed Varnish http accelerator and Varnish Drupal module. The Varnish is running and the Varnish page at admin/settings/varnish confirms this.

I measured the Time per request before and after installing Varnish with apache bench like this:

ab -n 10 http://my-site.local/

Installing varnish actually increases the Time per request from about 1 second to 1.3 seconds so there must be something wrong in my configuration of Varnish http accelerator.

In php.ini I have set a memory_limit of 512M.

While configuring Varnish to talk with Drupal I followed these instructions given in http://groups.drupal.org/node/25425.

Here is the contents of my /etc/default/varnish

 # Configuration file for varnish
    #
    # /etc/init.d/varnish expects the variables $DAEMON_OPTS, $NFILES and $MEMLOCK
    # to be set from this shell script fragment.
    #

    # Should we start varnishd at boot?  Set to "yes" to enable.
    START=yes

# Maximum number of open files (for ulimit -n)
NFILES=131072

# Maximum locked memory size (for ulimit -l)
# Used for locking the shared memory log in memory.  If you increase log size,
# you need to increase this number as well
MEMLOCK=82000

# Default varnish instance name is the local nodename.  Can be overridden with
# the -n switch, to have more instances on a single server.
INSTANCE=pressflow

# This file contains 4 alternatives, please use only one.

## Alternative 2, Configuration with VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# one content server selected by the vcl file, based on the request.  Use a 1GB
# fixed-size cache file.
#

DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -u varnish -g varnish \
             -S /etc/varnish/secret \
             -s malloc,256M"

And here is the statistics Varnish module gives after running apache bench few times:

      41  Client connections accepted
      41  Client requests received
      29  Cache hits for pass
      12  Cache misses
      41  Backend conn. success
      12  Backend conn. was closed
      12  Backend conn. recycles
       1  Fetch with Length
      11  Fetch chunked
      29  Fetch wanted close
      11  N struct sess_mem
       2  N struct object
       4  N struct objectcore
       4  N struct objecthead
      10  N worker threads
      10  N worker threads created
       1  N backends
      10  N expired objects
      40  Objects sent with write
      41  Total Sessions
      41  Total Requests
      29  Total pass
      41  Total fetch
   16495  Total header bytes
  645600  Total body bytes
      41  Session Closed
       1  Session Linger
    3776  SHM records
     899  SHM writes
      53  SMA allocator requests
       4  SMA outstanding allocations
   19984  SMA outstanding bytes
 5254284  SMA bytes allocated
 5234300  SMA bytes free
      41  Backend requests made
       1  N vcl total
       1  N vcl available
       1  N total active purges
       1  N new purges added
      41  HCB Lookups without lock
       3  HCB Lookups with lock
       3  HCB Inserts
     922  Client uptime

I cannot comment yet as a new user so here goes my response.

For starters 1 second to 1.3 seconds is not all that much of a difference, and you dont seem to have an overabundance of misses so its doing its thing. Run some tests that simulate a lot of page requests on the same content and watch the hits/misses.  Also did you test again without Varnish on the same site?

One other thing is to be sure you've properly sized the Varnish storage to match your servers available resources.  This being off too much can drag the system for obvious reasons.

Any reason your not using Drupal 7?  Pressflow 7 is available now too.

There is also the option to use Boost + Varnish.
http://www.trellon.com/content/blog/boosted-varnish-high-performance-caching-made-easy


Multiple Fields For Node Data I am creating a content type for events.  One of the parts of data I want to have is for speakers.  With the speakers I want to have their name, image, company, and bio.  I want to be able to more than one speaker similar to a multivalue text field where you can simply click add another item.

Can this be done in Drupal 7, and if so how?

You can use the Field collection module which lets you the possibility the regroup multiple fields (name, image, company, bio) into one collection (speaker). On that collection, you can put the number of values to unlimited.


Using 3rd party libraries I'm trying to load https://github.com/PHPOffice/PHPExcel in a custom module.  I've successfully added the library dependency to the composer.json file and Composer correctly downloads it into the 'vendor' folder.

The PHPExcel library doesn't use namespaces.  How do I access the library?  The following line

PHPExcel_IOFactory::load($excel_filepath);

results in

Fatal error: Class 'Drupal\mymodule\Form\PHPExcel_IOFactory' not found in /home/me/webs/client/myhomedir/modules/custom/mymodule/src/Form/ImportProductsForm.php on line 60

If possible, I'd prefer not to use the Libraries module.

You are in your own namespace, that means PHP by default tries to load the class from your current namespace.

To load a non-namespaced class, you need to explicitly refer to the global namespace with a :

\PHPExcel_IOFactory::load($excel_filepath);


Custom Line Item Loses commerce_unit_price and commerce_total I'm working on commerce_layaway and running into an issue with my custom line_items. I've been using the commerce_shipping module as a base to work from.

I've added a new checkout page and pane. The current sequence of events is - Review cart, Shipping/Billing Information, Select Layaway option, Select Shipping option, Credit card information, Review, submit transaction.

When I select the layaway option I want to use, the commerce_line_item of type 'layaway' is created and has the commerce_unit_price and commerce_total price. At this point the line_item has been saved (which is why we have the commerce_total price on the line item). Moving on to the next step.

During the submission of the shipping pane form the following error occurs.

EntityMetadataWrapperException: Unable to get the data property currency_code
as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue()
(line 442 of /var/aegir/platforms/commerce-7.x-1.3/profiles/worxco/modules/
secondary/entity/includes/entity.wrapper.inc).

This occurs because when the commerce_order_calculate_total($order) function is called it loads up the order_wrapper and loops through each line item. It gets the pricing of the commerce_total and for some reason when it gets to my custom commerce_line_item of type 'layaway' the commerce_total and commerce_unit_price and no longer there. So the error from above is thrown because the currency_code can not be retrieved from the non-existing commerce_total.

Is there something special I'm supposed to do in order to retrieve my commerce_unit_price and commerce_total for my line_item? I've debugged the code and don't see where the shipping is loading extra data and yet it still has it's commerce_unit_price and commerce_total.

The implementation of hook_commerce_line_item_type_info() fixes this issue. Each custom line_item needs to be created via this hook. This will add the two fields commerce_unit_price and commerce_total to the line_item.


Node as block: Is there a module? Is there any module for Drupal 8 that will do same functionality as nodeblock does, or do we have to programmatically render it?

NodeBlock has been replaced by EntityBlock in Drupal 8.


Change the height of the ckeditor text window If I try to change the height and style of the ckeditor text window with css then I find there are numerous layers to the css which makes it difficult to style. Is there a width and height setting in the settings which I can modify?

You should give this a go...

/**
 * Set a class on the iframe body element for WYSIWYG editors.
 * This only works for the WYSIWYG module: http://drupal.org/project/wysiwyg
 */
function adaptivetheme_wysiwyg_editor_settings_alter(&$settings, &$context) {
  $settings['bodyClass'] = 'wysiwygeditor';
}


Getting the values and url of an entity reference field using entity query then store it inside a variable I'm trying to figure out how I can output the values and url of the entity reference field values and display them inside the twig. Here is a sample of the code that I have constructed. I can't seem to find out what else is missing

        // Entity Query for Academic Experience Entity Reference Field
        $academicExperience = $query->get('node')
                                    ->condition('status', 1, '=')
                                    ->condition('type','programs')
                                    ->sort('created')
                                    ->execute();

        foreach ($academicExperience as $key => $academic_menu) {

             $academicNode = _nodeLoad($academic_menu);

             //Entity Reference Field
             $variables['academic_menu'][$key]['menu'] = $academicNode->get('field_academic_experience_ref')->value;
        }

                {% for academic in academic_menu %}

                    <span>{{ academic['menu'] }}</span>

                {% endfor %}

Getting the values and url

Sounds like you want to link to the referenced node, so I will assume that you want to do that.

No need to use entity query at all.

You can do it like this, assuming your content type is Article:

function mytheme_preprocess_node(&$variables) {

  $node = $variables['node']; // gets current node object

  if ($node->getType() == 'article') { // checks if content type is article

    $reference_links = array(); // creates empty array
    foreach ($node->field_academic_experience_ref as $item) { // loop through ref field
      if ($item->entity) { // gets referenced node object
        $reference_links[] = $item->entity->toLink(); // gets ref node link, adds to array
      }
    }

    $variables['academic_menu'] = $reference_links; // creates variable

  }

}

Then in twig

{% for reference_link in academic_menu %}
   {{ reference_link }}
{% endfor %}


Configuring Fail2ban for the r4032login module Recently, I installed fail2ban on my server to help prevent bots from abusing the site.

I have the r4032login module installed and it is writing to the log, but it is using HTTP status 302 for the redirect to the login page.

I'm wondering what would be the easiest way to have fail2ban work alongside the r4032login.

Here is a sample log entry:

ddd.ddd.ddd.ddd - - [12/May/2019:14:46:26 -0400] "GET /node/1/edit HTTP/1.1" 302 4305 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"

https://www.fail2ban.org/wiki/index.php/Main_Page

https://www.drupal.org/project/r4032login

For Fail2Ban v0.10.2, I edited two files in the /etc/fail2ban directory.

I added the following entry to jail.local:

[apache-forbidden]
enabled = true
port = http,https
filter = apache-forbidden
logpath = %(apache_access_log)s
maxretry = 3
findtime = 600
bantime  = 600

For filter.d/apache-forbidden.conf I have the following:

[INCLUDES]

before = common.conf

[Definition]

failregex = <HOST> - - .*HTTP/[0-9]+(.[0-9]+)?" 302

The 302 at the end is to reflect the redirect code for r4032login module.

NOTE: 302 redirects by other modules and Apache might also trigger a ban. Please see the comment below to mitigate this effect.


Personal Contact Form Link I am using Drupal panopoly. For a node type, I am able to display the content of the node and some profile information about the author. I used Contexts for this.
However now, I want to display the link to author's personal contact form. The link to the personal contact form shows up on the View profile page. I need to add a direct link to the Contact Form from the node display page. How do I do this?

You can use the Drupal core Contact module to do exactly that.

EDIT: In conjuction with Menu Tokens, you will be able to add a menu entry that pulls in the current user id. Add this to your path when creating a menu link:

user/[user:uid]/contact

You'll need to enable "Use tokens" and select "User from context" in the Methods for Users dropdown. See screenshot:


"This theme is missing a 'content' region".? while creating my custom theme i am getting a error "This theme is missing a 'content' region.".please have a look on screen attached(designed by manoj kumar).any help would be appricated.

Looks like you need to indent your region names 2 spaces. See https://www.drupal.org/node/2349827 for more information on defining a theme with an .info.yml file.

Also the link in your description is missing a closing  tag.

You should also be quoting some of your strings.  There is a link on the page above to read the quick introduction to the YAML file format that takes you to http://symfony.com/doc/current/components/yaml/yaml_format.html . That page provides good information on quoting strings.


Migrate d2d UI Comment Fields Running Drupal-to-Drupal 7.x-2.1.  I am attempting to migrate d6 comment attachments to d7 using the UI.  In d6, I used the Comment Upload module for comment attachments.  d7 does not have such a module, but you can attach files to comments by adding a file field to the comment structure.

I created migration code which provides the source file field information I need (from the d6 comment_upload table).  I created a file field in the d7 destination content type comment structure.

However, when I run the Drupal import option in the d2d UI and navigate to the destination map for the content type comment in question, I do not see the file field I created.

Is this normal?  A bug?

I have seen a 'solution' to migrating files attached to comments from d6 to d7 advertised here, but after following 3 links, it only provides a vague explanation with examples of core node file migration.  There is no example, or logic, provided to show how to actually map a d6 file field to a d7 comment file field.

My hope was to be able to do this through the d2d ui, but it does not appear to display comment file fields.

Any help on this?

Thanks!

There is no bug.  I ran the import the first time, then discovered that I was migrating nodes to the wrong content type, so ran it again with the correct content type.

Thing is, if you don't configure your destination content type as allowing comments, then comment migration will be skipped for all sources mapped to that destination.

So, I thought d2d ui wasn't working correctly when all the time it was my configuration.  Oops!


Passing dates or date ranges into a view as arguments Drupal 7, Views and Date modules installed.

I have a view on a content type with a date field (timestamp, but I can change it if necessary)

When I use it in filter criteria, I have no problem to use criteria like Mydate greater than, less than, between, not between etc.
But if I try to do the same thing using contextual filters I have only the "equal" criteria. I need to do this, so i can call the view from code passing arguments to it.

I found some pages about Drupal 6 where is written that i can pass parameter to the filter in format: 2008-11-12--2010-11-12, but when i try to make it and hit 'update preview', i obtain: (field_data_field_test_date.field_test_date_value = '2008-01-01--2010-12-31') in the query.

I need to:

use criteria greater than, less than, between
pass date range to the view

Does anybody have some suggestion on how I can do it?

Please refer below URL and check the answer given by @Dmitriy

How to implement less than / greater than in views contextual filters

This may help you.


Should a site be in maintenance mode when running the Drush Up command? I'm not asking if I can update my website with Drush. I'm not asking if Drush can make it in maintenance mode.

My question is ... if I'm using the command drush up to update my Drupal core or a module is the best practice to put my website on maintenance mode or does not matter?

In the past, I update all my modules without putting my website in maintenance mode, and so far I have not any problems, but I'm looking for the best practice.

BTW, I already test my Drupal core update in a Dev environment, and everything is working fine.

The first bit of advice here is to always run drush up on a dev or staging site first, before running it on a production site.  Sometimes, due to bugs or incompatibilities, upgrades can break a previously-working site.  It is therefore always best to test your upgrade before bringing it live.  After testing, it is also best if you move the exact files that you tested from dev to live rather than run drush up again.  You never know, someone might publish a new release while you are testing!

When you run drush up on your test site, you will notice at the end that Drush will report either "No database updates", or it will run an updatedb, and you will see a report on the database changes that you made.

If there are no database updates required, then generally speaking, it is safe to update your code without putting your site in maintenance mode.  Note, however, that there is a small risk that a web request might be processed when only some of the files in your site have been upgraded.  Since it only takes a small amount of time to git pull or rsync your files, this is only likely to be a problem if your site gets a lot of traffic.  If you are concerned about this, you could put your site into maintenance mode, or better yet, put up an 'in progress' page by adjusting your web server's configuration.

If database updates are required, it is a good idea to put your site into maintenance mode before updating it.  After copying the files to your production system, run drush updatedb to run the database updates.  When database updates are required, it is common for them to do operations such as add new columns or tables to your database.  The new code in core or your contrib modules may assume these schema changes have been made, and may crash if run prior to the completion of the database update.  drush updatedb can take a little while to run, so it is more likely that you might serve a web request before it finishes.

Note that if there ever is a problem, it would only be observed by a small number of clients, and would be fixed with a simple page refresh in the browser.  Since you are probably watching your updatedb run, you would probably never see these failures yourself.  It is best to keep your site clean from transient failures, though, so maintenance mode is the safer option.

It is a good idea to script the update operation, so that it will run smoothly and easily every time.  See drush_deploy  and upgradepath for two example projects that do this.


Converting JSON to select list options I have an array that I have JSON decoded from a JSON object. Below is my array I am using for select options. The problem is each select options has a option group with a number (0-11). How can I convert this array to one that does not have these numbers in front of it?

Here is my array:

    array(21) { [0]=> array(1) { [198413]=> string(23) "option1" } [1]=> array(1) { [247598]=> string(24) "option2" } [2]=> array(1) { [195666]=> string(17) "option3" } [3]=> array(1) { [195632]=> string(22) "option..." } [4]=> array(1) { [243763]=> string(24) "option..." } [5]=> array(1) { [196600]=> string(13) "option..." } [6]=> array(1) { [196597]=> string(11) "option..." } [7]=> array(1) { [196592]=> string(16) "option..." } [8]=> array(1) { [196549]=> string(17) "option..." } [9]=> array(1) { [251324]=> string(10) "option..." } [10]=> array(1) { [195564]=> string(50) "option..." } }

Here is my code:

      $result = drupal_http_request('https://'.$key.'@'.$company.'.example.com/example.json');
    $feed_array = json_decode($result->data, TRUE);
    $projects = array();
    foreach ($feed_array['todo-lists'] as $project) {
    $projects[] = array(
    $project['id'] => $project['name']
    );
    }

The easiest way to do it would be to iterate through the array

$options = array();
foreach($project as $option_group)
{
   $options[key($option_group)] = next($option_group);
}

Or, if you can't count on there being only one element in each option group, do:

$options = array();
foreach($project as $option_group)
{
   $options = array_merge($options, $option_group);
}


How to save custom value in DB from custom .module I have inherited a custom module, which groups together some field of an custom ContentType and sends it by email.

In the module there are 3 functions.

Email check preg match:

function __autoload($class_name) {
  require_once($class_name . '.lib.php');
}
require_once('vumclass.lib.php');

This function gets triggered when the node is saved or updated. Right?

function vumveranstaltungsmailer_action_info() {
  return array(
    'vumveranstaltungsmailer_action' => array(
      'type' => 'node',
      'label' => 'vumveranstaltungsmailer_action',
      'configurable' => FALSE,
      'triggers' => array('node_insert', 'node_update'),
    ),
  );
}

Do stuff, send email:

function vumveranstaltungsmailer_action($object, $context) {
//do Stuff, sends email. Not shown here.

//I want to set this field to empty/clear it
$object->field_email_mailer_01['und']['0']['value']->set(NULL);

}

Bare with me, I am pretty a beginner/noob. I am a bit overwhelmed where and how to do it. Please give me a simple solution, so I understand it. Quick and dirty is fine for me ;-)

Once you get your nid of the node you can use the code below to change the field value

  $node = node_load($nid);

   unset($node->field_example['und'][0]['value']);
    //similarly for other fields you can change the value
    node_save($node);


When should the second drupal_bootstrap() parameter be used? The parameters accepted from drupal_bootstrap() are two; the second is defined as follows:

  $new_phase: A boolean, set to FALSE if calling drupal_bootstrap() from inside a function called from drupal_bootstrap() (recursion).

I am not clear what that means, considering that statistics_exit() calls drupal_bootstrap() using just one argument, thus using the default value (TRUE) for the second one.
hook_exit() is invoked from _drupal_bootstrap_page_cache(), and statistics_exit() should be considered a function called from drupal_bootstrap() that calls drupal_bootstrap().

Yet, statistics_exit() is not using FALSE as second argument of drupal_bootstrap().

The only functions I found that use FALSE as second parameter are module_hook_info(), and _drupal_bootstrap_page_cache(), which contain the following code.

  // module_hook_info()
  // This function is indirectly invoked from bootstrap_invoke_all(), in which
  // case common.inc, subsystems, and modules are not loaded yet, so it does not
  // make sense to support hook groups resp. lazy-loaded include files prior to
  // full bootstrap.
  if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
    return array();
  }

  // _drupal_bootstrap_page_cache()
  // Check for a cache mode force from settings.php.
  if (variable_get('page_cache_without_database')) {
    $cache_enabled = TRUE;
  }
  else {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
    $cache_enabled = variable_get('cache');
  }

From the code of the first function I could understand I should use FALSE when I need to get the current bootstrap phase, and in that case I would use NULL as first argument.
From the code of the second function, I could understand that the second parameter is an internal parameter, I should not pass in my functions, as the only case a function of mine is being called from drupal_bootstrap() (also indirectly, through a function that is called from drupal_bootstrap()) is when I implement hook_boot(), or hook_exit().

Did I misunderstand what said in the drupal_bootstrap() documentation? If it so, when exactly should a call to drupal_bootstrap() use a value for the second parameter that is different from its default value?

Without looking more closely, I can't say why statistics_exit() doesn't use the second parameter, but to answer your question...

The drupal_bootstrap() function only ever needs to be called with $new_phase = FALSE to prevent an infinite loop inside the core bootstrap code. Unless you're modifying core, you'll always want to leave the second parameter at its default value (TRUE).

The key is in this part of drupal_bootstrap():

// When not recursing, store the phase name so it's not forgotten while
// recursing.
if ($new_phase) {
  $final_phase = $phase;
}

Calls to drupal_bootstrap() outside the bootstrap process always specify the final phase to bootstrap to (or only get the current phase, in which case, the second parameter doesn't matter). When you call drupal_boostrap(), you'll be initiating the bootstrap process and setting the static $final_phase variable, so you'll need $new_phase = TRUE.


How to use file_save to store pictures into a folder on server? what i want to perform (globally) is to import a csv file that contains data such as book_title, author, and the cover image of the books. The csv file is loaded, book_title and author are stored in their respective tables but for pictures, what i want is to put them manually (ftp for example) on a folder (doesn't matter if it's my default public folder or a new one) and store data in tables like : file_managed and field_data_field_cover_picture etc
In my csv file, and for pictures column i just write filenames of every picture.

At the moment, i'm confused and this is my actual code :

$filename_cover = $get_filename.'.jpg'; <===from csv

        $add_cover_file = db_insert('file_managed')
        // ->key(array('fid' => rand()))
        ->fields(array(
            'uid' => $user->uid,
            'filename' => $filename_cover ,
            'uri' => 'public://couvertures/'.$filename_couv,<==my file
            'filemime' => 'application/octet-stream',
            'status' => 1,
            'timestamp' => time()
        ))
        ->execute();

Now adding on the pictures covers table : (how to put the fid ?)

  $add_couverture = db_merge('field_data_field_photo_de_couverture')
        ->key(array('entity_id' => $newNode->nid, 'field_photo_de_couverture_fid'=>$add_couv_file->fid ))
        ->fields(array(
            'field_photo_de_couverture_fid'=>$get_fid ,
            'entity_id' => $newNode->nid,
            'delta' => 0,
            'bundle' => 'livre',
            'entity_type' => 'node'
        ))
        ->execute();

Try this:

$file = file_save((object)array(
    'filename' => $file_name,
    'uri' => $destination_uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($destination_uri),
  ));
//at that point you can use the $file->fid
//do the magic on your custom table field_data_field_photo_de_couverture


How to extend a module hook from another module? I want to be able to clone/replicate a node from one language to another on click of a button using a custom module. Basically we have a view which displays all nodes in the system and under the "operations" column, we have Edit, Delete, Clone.

On click of the Clone button, I want to replicate the node (keeping the same exact data values as is except for the language field) to other languages.

I have installed the node_clone and replicate modules to help me, but I am struggling to see how I can create a custom module that can call the hooks in those contrib modules in such a way that I can save the node in different languages automatically instead of click on the "Translate" tab and manually doing it one by one.

I have tried calling the clone_node_save from the Node clone module from my custom module, but that does not work.

How can I extend a module hook in a custom module?

You can use the following code to solve your problem:

//clone the node
$new = clone $node;
//set the node to new
$new->is_new = true;
//unset the nid and the vid
unset($new->nid);
unset($new->vid);
//setting the new language
$new->language = 'fr';
//save the new node
node_save($new);

Reference: Programmatically create a new node from an existing NID


How to wrap Drupal "$messages" in a div? How can I wrap $messages in a div using template.php file?

This is my code:

function THEME_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
      $output .= '
' . $message . "
\n";
    }
    $output .= "
\n";
    }
    else {
      $output .= reset($messages);
    }
    $output .= "
\n";
    }
    return $output;
}

I need to wrap so the result it's this:

I'm not interested to in doing it in page.tpl.php like this because it will leave an empty div if there's no messages:

<?php print render($page['messages']); ?>

So far I wasn't able to output the #messages div, every time I try something I break everything or nothing happens.

Thank you.

Change this:

return $output;

To this:

return '
' . $output . '
';


Appropriate theme function for alter specific field for a view I have used a view in my drupal.

In this view, I have used an "add to cart button" field.

In my theme, I am searching for a theme function in order to alter this field.
For example  want to remove css classes from this button and add another attributes to it.

what is the suitable theme_function in order to achieve this goal?

Fences should be the answer of your problem:
https://drupal.org/project/fences

Or you could create a template for this view-field:
https://drupal.org/node/352970


How to programmatically determine whether a node is a og group type node? Drupal 7, OG

How to programmatically determine whether a node is an og group type node?

I found a way to do this using og_get_group_ids() :

og_get_group_ids('node', array($nid));

If the result is not empty then the node is an og group type node.


Views: Only show 3 largest values and their sum per user I am creating a scoreboard website for fisherman that shows the sum of their top catches for the day.  A custom content type allows the anglers to upload a photograph, fish type, and fish length numerical value (DONE).  Anglers may upload as many catches per day (DONE) as they want.  I have Views showing me all fish caught (DONE).  I have Views_Calc showing me data about "all fish caught" per day (DONE).

However, I only want to calculate, display, and store in the database the SUM of the X longest fish an angler has caught that day.

So, I'm trying to build:

1) A View ranking anglers by the sum of their, say, 5 longest fish caught per day.

Consider that some anglers may have a tough day fishing and only be able to upload, say, 3 fish per day.  Conversely (and this is the situation I am having trouble rendering) an angler may submit, say, 14 fish caught that day but I only want to display the sum of the 5 longest.

I would like the SUM to be a database entry so it is accessible via Views for other purposes.

The rendering may look like:

RANK   |  ANGLER NAME  |  5 LONGEST FISH
  1    |  John Smith   |   49.75 inches
  2    |  Joe Blow     |   47.25 inches
  3    |  Kevin Jones  |   42.50 inches
  4    |  Dave Craig   |   37.75 inches
...

Any pointers?  Thanks in advance!

If you don't want to build a custom module I would think Rules is your best bet. Also install Conditional Rules as what you will be doing will requires logic a bit difficult to accomplish with Rules alone.

I will create a Result content type that will hold the aggregated result for the day per angler, as well as entity references to the fish content type. Then, after the angler uploaded a new entry, the rule will cycle through the related fish types and do the Maths and store the result in the result field.


How to show how many hits has got one page I'm trying to get something like this "viewed: 123 times." on every single node a part from the static pages like about us or contact etc..

Is there a module for it or is better to create a flag for this?

Thanks in advance.

check the Statistics module. Its already there in drupal, just need to enable it


Panels in-place editor won't show in panels even after setting renderer My relevant specs are: Drupal 7, Jquery update 2.5.7 (set to 1.7), Ctools 1.7.7, and Panels 3.5.7.

The problem:

I've enabled "Panels in-place editor" to ease panels editing. I've set the renderer at Paenls>Settings` from "Standart" to "Panels in-place editor" and cleared cache - and yet, when standing at the Panel node I don't see it. reasons?

notes:

The site has only 1 user, me, the Admin so it's not a permissions
issue (also checked permissions).
My layout was taken from "Panels extra layouts" module, if it makes
any difference...

Solved!

It seems to me that there are two types of renderes for panels:

The first is the global renderer that indeed I've changed to "Panels in-place editor". The second is each Panel's own or Specific renderer.

My problem occurred because for some reason, My Panel's own renderer wasn't affected from the global one, and stayed "Standart". I have no idea why that happen (might be a bug)...

Anyways, to change your Panel's own renderer just go to it's Panel.page\Panel.node and click on the tab "Edit" located on it's top. Thus when you edit the Panel itself you could choose it's own renderer and Problem should be solved by then.

All luck, Ben.


Trying to submit a node add form via AJAX but failing I'm simply trying to submit a node add form via AJAX:

function input_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'page_node_form':
      $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'wrapper' => 'apple-node-form',
            'callback' => 'node_add_callback',
            'method' => 'replace',
            'effect' => 'fade'
        )
      );
      break;
  }
  return;
}

function node_add_callback(){
  $node = new stdClass();
  $node->type = 'page';
  return drupal_get_form('node_form', $node);
}

input_form_alter() DOES get called. And when I click the submit button, I even see the standard ajax gif and "Please wait" message. The gif and wait message then disappear, as expected. However, no new node has actually been created.

Solved it. The problem was this code:

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
        'wrapper' => 'apple-node-form',
        'callback' => 'node_add_callback',
        'method' => 'replace',
        'effect' => 'fade'
    )
  );

This overwrites the $form['actions']['submit'] array that already existed, recreating it with the values I specified. Since all I wanted to do was add an AJAX submission, the following code should replace the above:

    $form['actions']['submit']['#ajax'] = array(
        'wrapper' => 'apple-node-form',
        'callback' => 'node_add_callback',
        'method' => 'replace',
        'effect' => 'fade'
    );

In other words, we're just adding an #ajax item to the already created $form['actions']['submit'] array.


Determine Array Key For Field Type Programatically Different fields have different keys for the actual 'value' of the field. For example a regular text field has:

$node->field_my_text_field[$node->language]['value']

Whereas if I have a field using the email module, it looks like this:

$node->field_my_email_field[$node->language]['email']

I'm working on a function that saves a whole bunch of fields, and I want it to be as flexible as possible, it has a loop that looks like this:

foreach($person_details as $k=>$detail) {
    $node->{'field_'.$k}[$node->language][0]['value'] = $detail;
}

This is no good at the moment since 'value' is hard coded, and I have some fields in there that use 'email' and a few others from various modules.

Is there any way to know in advance what the key should be?

My solution ended up being this:

$field_structure = field_info_field($field_name);
$keys = array_keys($field_structure['storage']['details']['sql']['FIELD_LOAD_CURRENT']['field_data_'.$field_name]);

This gives an array of all the posible data columns for $field_name, where $field_name is something like 'field_my_field'.


Preprocess Field: CSS Style per page Trying to set up a preprocess_field_hook() to send a different css style depending on the node that is loaded for simpler theming. Will not work and been beating my head.

Have this set inside my template.phpand have my tpl pages named correctly (exam: node--node_page_one.tpl.php), which is loading fine with other functions already working. I feel like I need to have it point to the actual element somehow? Or should I be doing this somewhere else like in the preprocess_node_hook()?

Sorry for my noobness.

 function mytheme_preprocess_field(&$variables, $hook) {
      $variables['fieldclass'] = '';
      switch ($variables) {
        case 'node_page_one':
          $variables['fieldclass'] = 'tiny-blue';
          break;
        case 'node_page_two':
          $variables['fieldclass'] = 'large-green';
          break;
        default:
          $variables['fieldclass'] = 'black';
          break;
      }

Rather than $variables['fieldclass'] use $variables['classes_array']

Based on the docs


Operations in find content page not working I am using Drupal 7 and I don't see any options listed down in the operations drop down in the find content page. The options are listed in content's tab, but when I move to files tab, the drop down is not shown.

Do you have the options to operate(delete, unpublish) files as we do to nodes? Any help would be appreciated.

Thank you

Did you try selecting some files before (tick checkbox)?
Some filters only appears when contents are selected (in the Media tab for example in my website)


how to make an automatic download button? I have a Content type with a file field. I want to add another field (download button) which when users click on that, they would be able to download the file (uploaded in file field), and show file field as a simple preview image or even hidden it.
Is there any module to do this(1:create a button with custom css through cck and 2: automatically link the file path to download button), or any other ways?

The generic file output of the file field is pretty close to what you are asking. It creates a link with a icon showing the file type and links to the file (download, unless the browser understands the file, like an image would be displayed in the browser instead of being downloaded)

You could with theming/css alter the appearance if you so please.

If you want force download, you have to modify the headers sent to the browser. You can use the File Force Download if this is your goal (Thanks for the tip @nicoz). It seems to be using field formatters, which functions much like the generic file display possible with file fields.


Altering comment data on publishing I have a boolean field ( field_rejected ) in my custom comment implementation ,I need to set this field to false if this comment is published

I tried hook_comment_update and hook_comment_insert, This didn't work as it says in the documentation :

  "Note that hook implementations may not alter the stored entity data."

Then I tried doing this using hook_entity_presave but this also didn't work as it results in an infinite loading or error code 500.

This is the code I used:

function custom_comments_notification_comment_presave($comment) {
  if ($comment->isPublished() && !$comment->original->isPublished()) {
    $comment->set('field_rejected', 0, $notify = true);
    $comment->save();
  }
}

Note that this is implemented in custom module's .module file.

How can I solve this? How can change the boolean 'field_rejected' after publishing a comment?

Remove that $comment->save(); Because you are already in the save process and you will trigger it over and over again with this.


How can I display a block only when a node meets a particular condition? I have a block that allows a site visitor to query an external calendar, but it will only work for certain nodes.

How can I set it up so that I can i) indicate whether or not a node has calendar data available for the node and ii) if it has calendar data available, display the block and if it hasn't got calendar data available, the block is not displayed?

Someone suggested to me that I use Workflow to do this, but I've not been able to figure out how Workflow would help me set this up.

I would use the PHP visibility settings to display the block on a node's page if a cck value in that node has some value, assuming that this cck field's value is an indication of that node containing calendar data. Once you've created the block that you want to display (or not display) add the following code to the "Page specific visibility settings" in the block configuration menu:

<?php
$node = node_load( arg(1) );

if ($node && $node->type =="[your_content_type]" && $node->field_has_cal_data[0]['value'] =='Yes'){
return TRUE;
}

return FALSE;

?>

This is assuming that the url is built like "content/name-or-id-of-node".


related products in blog post I'm building my first drupal commerce with commerce-kickstart 2 on drupal7.
My client asked my to add a feature that associate products and blog posts.

At first I thought the best way was to add "product-reference" to the blog-post content type, this way the non-technical user could easily select 0 to n products to the post as "suggested" or "correlated" products, but when I added the product-reference field the whole blog-post content-type became a "product display" and the template file for the view was the wrong one.

Then I though of creating a block with a query for the products but I don't want the client to have to deal with this level of complexity.

I thought about writing the logic inside the product display template file but it doesn't feel like a good practice.

I searched for modules but I didn't find what I was looking for (maybe because I'm noobie to drupal I don't know yet how the search efficiently)

Are there any modules that can help with this?

thx

So this is an important question for Drupal Commerce: What is the best practice way of creating a related products block per content type?

Fortunately, there's a simple answer. Just add an entity reference field that references the product displays:

Add an entity reference field called "Related Products" on your blog content type.
Configure this field to only show the product displays (not product entities).
Hide this field on the "Manage Display" tab.
Create a view block that targets your blog content type.

Edit the view and add a contextual filter for "Node ID" and provide the default value to come from the URL. This will allow the block to bring in the node you are viewing if you are viewing your blog post.
Add a relationship on the "Related Products" field you added to your blog content type and rename it "Related Products" and require that relationship.
Add a field, it should be your product reference field for your product display. For me, it's called "Product" but it could be called something different depending on your setup. NOTE Make sure you set it up to use your new relationship.
Modify the title to use your new relationship.
Set the View Block to display in a sidebar or some region that is available on blog posts.

And BAM! there you have it! A step-by-step to show off related projects in a block on your blog posts.


CKEditor custom plugin to add richcombo select list I am building a CKEditor plugin for Drupal 8. I've done plugins that show a button in the editor toolbar, but this one should render a select list. The list is not showing up in the configuration page (admin/config/content/formats/manage/basic_html), so I cannot add it to the toolbar. I can't see what I am missing.

This code works fine on a standalone CKEditor setup (outside of Drupal):

'use strict';

CKEDITOR.plugins.add( 'widgets', {
  requires : ['richcombo'],

  init: function( editor ) {
    console.log('In CKEDITOR.plugins init()');
    var config = editor.config;

    editor.ui.addRichCombo('widgets', {
      label : "Widgets", // label displayed in toolbar
      title : 'Insert Widget', // tooltip text when hovering over the dropdown
      multiSelect : false,

      // use the same style as the font/style dropdowns
      panel : {
        css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat( config.contentsCss ),
      },

      init : function() {
        // dropdown options:
        // this.add( VALUE, HTML, TEXT );
        // VALUE - The value we get when the row is clicked
        // HTML - html/plain text that should be displayed in the dropdown
        // TEXT - displayed in popup when hovered over the row.
        this.add( "
Widget 1
", "Widget 1", "Widget 1" );
        this.add( "
Widget 2
", "Widget 2", "Widget 2" );
      },

      // this function is called when a row is clicked
      onClick: function(value) {
        editor.insertHtml(value);
        console.log(value);
      },
    });
  }
});

The above code was placed in /modules/custom_widgets/js/plugins/widgets/plugin.js

Besides, /modules/custom_widgets/custom_widgets.module is empty, /modules/custom_widgets/custom_widgets.info.yml sets "ckeditor" as a module dependency, and this is the code of my D8 plugin, in /modules/custom_widgets/src/Plugin/CKEditorPlugin/Widgets.php:

<?php

/**
 * @file
 * Definition of \Drupal\custom_widgets\Plugin\CKEditorPlugin\Widgets.
 */

namespace Drupal\custom_widgets\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Widgets" plugin.
 *
 * @CKEditorPlugin(
 *   id = "widgets",
 *   label = @Translation("Widgets")
 * )
 */
class Widgets extends PluginBase implements CKEditorPluginInterface {

  /**
   * {@inheritdoc}
   */
  function getDependencies(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function getLibraries(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function isInternal() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  function getFile() {
    return drupal_get_path('module', 'custom_widgets') . '/js/plugins/widgets/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return [];
  }
}

Any help is greatly appreciated, as all examples I could find were about adding a custom button or a custom contextual menu entry, but nothing about combo lists.

You should really be extending CKEditorPluginBase and implement getButtons method. This is likely why you don't see it in the administrative interface, but in a vanilla CKEditor test, you do.

https://api.drupal.org/api/drupal/core!modules!ckeditor!src!CKEditorPluginButtonsInterface.php/function/CKEditorPluginButtonsInterface%3A%3AgetButtons/8.2.x


Handling dynamic URLs through my custom module I have written a custom module and have defined a menu inside the module as test. This menu uses a function named mymodule_test() to render contents. The code written for this menu is working perfectly OK and I am getting expected output on /test page.

Now, I want to define some more menus that use the same mymodule_test(). I understand that I can define more menu items in the mymodule_menu() as below.

$items['test-1'] = array(
  'title' => 'Test',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mymodule_test'),
  'access arguments' => array('administer mymodule'),
  'type' => MENU_NORMAL_ITEM,
);

However, I am planing to use more than 100 such menu and believe this is not the best way to achieve this. Please guide me in the right direction to achieve the same.

This is to note that these menus will be dynamic in nature so I cannot hard code it in the module file.

I am using Drupal 6.

Firstly, you should not define a callback as ['/test-1'], instead just use ['test-1'], without the slash - '/'.
Check here - http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_menu/6

If you want to create 100 menus, go ahead, this is the way you can do this.
If just the path is changing and nothing else, I would recommend to create an array, and then loop it, defining the value of the array item in the menu-path.
something like this -

$arr = array('test-1', 'test-2', 'test-3', 'test-4', 'test-5');
foreach ($arr as $a) {
  $items[$a] = array(
  'title' => 'Test',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mymodule_test'),
  'access arguments' => array('administer mymodule'),
  'type' => MENU_NORMAL_ITEM,
  );
}

This will be less code and quick.


Views PHP: how to get the `end-date` value within `Global(PHP)`? I am rewriting the output a view block with a Global(PHP) field from the module Views PHP, and one of the fields I am rewriting is a Date field.

The value for the field is : 2015 - 08:30 to 09:30

I am looping through the fields and simply printing them to see the output:

foreach ($data->field_field_item_timespot as $timeEntry) {
  $time = $timeEntry['raw']['value'];
  print $time;
}

This is the output: 2015-01-01 08:30:00

The issue that I am having is that it is only printing the start-date of the field, when I need both start-date & end-date. I am specifying the Date field to display start and end date values, and it does in the view, but not inside the Global(PHP).

Any ideas how to get the end-date value within Global(PHP)?

$time = $timeEntry['raw']['value'] == Start Date

$time = $timeEntry['raw']['value2']== End Date


Programatically render a node in a specific language I want to render a node display programmatically for sending it to a search engine. It works ok but is ignoring the language and renders the field labels in the source language (which is English).

I use the following code for creating the teaser markup.

 $render_array_teaser = $view_builder->view($entity, 'compact_teaser', 'de');
 $rendered_teaser = $renderer->renderPlain($render_array_teaser);

The result gives me a teaser that includes a field named "field_sku" that has the label "SKU number". If I output the teaser in the browser the label gets correctly translated to German = "Artikelnummer" if the current language is "German".

If I render the teaser with the above code the label stays English even if I set the langcode parameter to 'de'.

How to get the teaser with German lables?

The field labels are used from the config translation system. You also need to set the config override language. See user_mail() in core.

  // Temporarily alter the language manager.
  $language_manager = \Drupal::languageManager();
  $langcode = $message['langcode'];
  $variables = array('user' => $params['account']);

  $language = \Drupal::languageManager()->getLanguage($params['account']->getPreferredLangcode());
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
  $mail_config = \Drupal::config('user.mail');

  // Restore the language manager.
  $language_manager->setConfigOverrideLanguage($original_language);


Views-based search analytics I have a search: search terms field setup in a view in drupal 7. It's exposed to users so they can search nodes.

I know my users are using the search but google analytics isn't capturing that information.

I also looked at reports > top search phrases and it shows nothing...even though I believe views uses the basic search module.

My question is: is there a way to see statistics on what terms users are using to search with this view?

Looks like I found a possible answer. Use Google Analytics module and make sure to track internal search. Then setup your Google Analytics account like so.


REST API POST returning 400 Syntax error I wrote a REST plugin for posting data to my Drupal site, When I send JSON data from browser it is returning the error {readyState: 4, responseText: "{"error":"Syntax error"}", responseJSON: Object, status: 400, statusText: "Bad Request"} but it is working fine in Postman. What might be the issue?

The data I am send is  {"name" : "user", "pass" : "userpass"}

I am also adding the following headers in request.

"Content-Type", 'application/json'
"Accept", 'application/json'

You can use Postman to generate your code

Click here to change code language


What MySQL privileges would a read-only drupal db user need I am in the process of configuring a server that will be on the front end and will be the read-only installation.  Can anyone give me some guidance on what to look for for in regards to what tables the mysql user will need write access for... such as like access log, etc.

I am just looking for a starting point. It doesn't need to be specific.

Looking through the core tables of a fairly lean install, these will probably need to be writeable:

access
batch
cache and cache_*
flood
history
node_access
queue
sessions
semaphore
users (for last login date)
watchdog

These I'm not too sure about, worth testing:

registry
registry_file
file_usage
blocked_ips

Contrib modules are different matter, you'll need to look at those one-by-one as it will depend on which ones you use (e.g. ctools has ctools_css_cache and ctools_object_cache)


Can I run Drush in a situation where the database is on one server and the remainder of the Drupal installation is on another? I have a setup (out of necessity not choice) where my drupal installation is on server a, and the database on which it relies is on server b.  The site is working fine, however when I run most Drush commands I get the good old:

Drush was not able to start (bootstrap) the Drupal database.

On the server where everything except the database is stored, there is no mysql.  If drush isn't an option for me that's perfectly fine but I've been tearing my hair out on this one.

Many thanks in advance for any ideas.

I've never run a Drupal site like this, but Drush should take your database settings from your settings.php file; if the database is remote for Drupal, then it should be remote for Drush as well.  Note that most Drush commands (with the notable exception of the sql-* commands, which you will not be able to use without a local mysql installation) just call through to the corresponding Drupal code, after first bootstrapping.  If your bootstrapping is failing, check to see if there is anything in your settings.php that depends on the site's URI to select the database.  If so, make sure that you use the --uri= flag, or set the 'uri' element in your Drush site alias when using Drush.  If that doesn't get you going, post the output of a failing Drush command with the --debug flag specified.


How to add a custom variable that can be accessed on bootstrap's menu--account.html.twig? I have a custom theme (subtheme of drupal bootstrap theme).  We are overriding menu--account.html.twig.  So I copied menu--account.html.twig from the bootstrap theme template folder into my theme's template folder, and I verified this template is being used because static text changes I added show up on screen.

Now I'm trying to add a variable that the menu--account.html.twig template can read.

How do I do that?  My variable's name is 'nickname'.  I tried this:

 function mymodule_preprocess_menu__account(&$variables)
 {
     $variables['nickname'] = 'Jeff';
 }

The variable is added to the array, and I can see it if I use dpm, but when I reference {{nickname}} in the template it's always null.

I also read I had to define the variable like this:

 function candidate_poral_theme_registry_alter(&$theme_registry)
 {
   $theme_registry['menu__account']['variables']['nickname'] = 'default';
 }

But that also doesn't work.

Any assistance would be welcome.

I have done this for a theme on past projects. Be sure to pass it in through the content item:

Example

use Drupal\Core\Render\Markup;

function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu__account']['variables']['nickname'] = 'default';
}

function mytheme_preprocess_menu__account(&$variables) {
  // code...

  $variables['content']['#nickname'] = [
    .. renderable properties
  ];

  // or also...

  $variables['content']['#nickname'] = Markup::create('Jeff');
}

Then, in the twig template:

{{ custom_var }}


Override registration page problem I'm trying to customize the user registration page in a zen subtheme.
The template candidates files suggested by themer devel are page-user.tpl.php and page-user-register.tpl.php, but when I try to create them, page.tpl.php (placed in the subtheme as well) is not overridden.
All other pages are working fine.
I've clean theme registry and checked all file permissions, I still can't get this.
What did I miss?

If you're using D7, you'll need two dashes between page-user, not one.

Some examples


Advance Search form $form is not the same when invoked a second time? I Want the users to have an expanded advance search form if no results are returned from a search. The advance search form on the search page always defaults to collapsed.

I found that I can check whether I have results in two different ways: theme or module, depending on the hook I want to use, I chose module because it fires earlier than the theme's.

I also can effect the advanced search form's attributes (whether it's collapsed, or maybe display other data inside of the advanced search form, etc) with drupal's hook_FORMID_form_alter() with MYTHEME_form_search_form_alter's first call. The issue I have is MYTHEME_form_search_form_alter() gets called before results are returned.

So I can alter the advance search form first, then I can check if we returned any results from the search... which doesn't help me, because I need it to be vice versa - If I know I have no results then I know to expand the advanced search form's collapsible form.

My quick solution was to invoke drupal_get_form() with drupal_get_form("search_form", "no_results"); inside of my module's preprocess search hook MYMODULE_search_preprocess_search_results(&$variables) and just pass in the variable "no_results". This (as most of you probably know) will invoke hook_form_search_form_alter again, where I can edit the advance search form now and I will alter the advance search form only if my variable "no_results" comes through.

Here is my crux though! Even though I am invoking that theme hook again and checking for the variable, when I go to edit the $form's "advanced" entry... its gone now. So it's clearly there when theme's hook is called, and I can indeed effect the arrays, but if I try to effect the advanced array when I invoke the theme's hook (inside of my module's hook) it's not there. Where would I invoke this theme's hook if not on the module layer? Hell, the theme's preprocess hook is fired AFTER the module's and has proven to be the same circumstance, seems in either of the two ways of checking my results I cannot invoke the form_alter hook and get the exact same form back.

This is before I check results when THEME's alter hook is first being called:

This is after I check results in my module's hook and invoke the THEME's alter hook once more:

You can see my new variable denoting that we have no result (in this case it's LarryU) under the action key, but there is no advanced key. I tried just remaking it but it doesn't to the form.

As I understood from your question you need to add additional style when no results found.

The file search-block-form.tpl.php in search module folder is responsible about displaying the form you could copy it to your theme folder and alter the markup as you need (You have to clear cache in order to flush theme registry).

Also take a look at the two files search-result.tpl.php and search-results.tpl.php the same could be done depending on your needs and use case.

For more clarification about theme suggestions read


How to programmatically replace a field label and content before rendering? I expected to be able to do it with THEME_preprocess_field, but the data at that point seems to have only the content's markup and not the label. I would need an instance where I can change both, because there's some mutual conditioning between them.
I also tried with THEME_node_view to no effect.
Note: I want to do this in a theme, not a custom module.

I expected to be able to do it with THEME_preprocess_field, but the
data at that point seems to have only the content's markup

There are more template variables:
field.html.twig:
{#
/**
 * @file
 * Default theme implementation for a field.
 *
 * ...
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 *
 * @ingroup themeable
 */
#}

So you can change for example label:
mytheme.theme:
/**
 * Implements hook_preprocess_HOOK() for field.html.twig.
 */
function mytheme_preprocess_field(&$variables) {
  $variables['label'] = 'foo';
}