AJAX error: node form + list field with multiple options + image field I'm trying to add an AJAX callback to a list field with multiple selection enabled. This works properly on its own, but if I add an image field, the form will throw errors when 2 or more fields are selected.

Here's my setup:

Blank installation of Drupal 7 + image + list modules.
Create a "Sample" (machine name: sample) content type.
Add an image field ("Image").
Add a list field with possibility to select unlimited values ("List").
Enable the custom module below.
Try creating a new node and select 2 options in the "List" field. This will throw the following AJAX validation error:
"An illegal choice has been detected. Please contact the site administrator."

Code:

//
// File: sample.module
//
function sample_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'sample_node_form':
      $form['#id'] = $form_id;
      $form['field_list'][LANGUAGE_NONE]['#ajax'] = array(
        'method' => 'replaceWith',
        'wrapper' => $form_id,
        'callback' => 'sample_form_alter_ajax',
      );
      break;
  }
}
function sample_form_alter_ajax($form, $form_state) {
  // Of course, my logic will be added here.
  return $form;
}

//
// File: sample.info
//
name = Sample
description = Sample
package = Sample
core = 7.x
version = 7.x-1.0

Am I doing something wrong or is this a bug in image.module?
Is there anything I need to change in the way I set up my AJAX callback?

Thanks!

Update 1

The problem can be further narrowed to any file upload field. Here's a sample module that can be used standalone to replicate the issue. No need for creating content types.

sample.module file content:

function sample_menu() {
  $items['sample'] = array(
    'title' => 'Sample page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sample_page_form'),
    'access callback' => TRUE,
  );

  return $items;
}

function sample_page_form($form, &$form_state) {
  $form['#id'] = 'sample-page-form';
  $form['list'] = array(
    '#type' => 'select',
    '#title' => t('Select something'),
    '#options' => array(
      'option1' => t('Option 1'),
      'option2' => t('Option 2'),
      'option3' => t('Option 3'),
    ),
    '#multiple' => TRUE,
    '#ajax' => array(
      'method' => 'replaceWith',
      'wrapper' => $form['#id'],
      'callback' => 'sample_page_form_ajax',
    ),
  );
  $form['image'] = array(
    '#type' => 'file',
    '#title' => t('Test fileupload field'),
  );

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

  return $form;
}

function sample_page_form_ajax($form, $form_state) {
  return $form;
}

Update 2

This seems to work properly if the field type is changed to checkboxes instead. Not a real solution though, just a workaround.

After additional testing, this seems to be a bug in Drupal core that affects only the select form elements.

Workaround is to change the field type to checkboxes. Everything else can stay the same. Values are then passed properly and everything works OK even with multiple file upload fields added to the same form.

Also the validation and submit handlers work as expected in this case.

I created a ticket for Drupal core here.


expose age range in views but DOB field is date I want to expose an age range in a view (select registered users of age between 25-50) . I tried birthday module and also tried adding a Date of Birth field to user profile using Profile2 Module .

And I think Views Contextual Range Filter works with ranges (25--100) not with dates .

any ideas ?
thanks

Try using the Computed Field module (in beta in 7). You would simply add a new field, of say age, and of Computed type, (follow a walkthrough here) and then use a Filter in the View to select the range of ages that you require.

Hope this helps!


Add body class to Node Display (to distinguish it from Node/Edit or Node/add view) I want to add a body class that will only appear on the actual node display (e.g. mysite.com/node/1). I don't want this body class to appear on the node/edit page (e.g. (mysite.com/node/1/edit) or the node/add page.

The reason for this is that I am making custom node form templates. At the moment, the css gets wrongly applied to the node Display.

I know I could just add a wrapper DIV to my templates, but I would rather use the body class, as it will be more efficient for my theming work flow.

I have successfully applied body classes to the edit and add displays with the following code in template.php

function MYTHEME_preprocess_html(&$variables) {
  if ((arg(0)=='node' && arg(2)=='edit') || (arg(0) == 'node') && (arg(1) == 'add')) {
    $variables['classes_array'][] = 'node-edit-page';
  }
}

Is there something similar I could use to target the actual node display? I tried doing a KPR dump of the page, node and HTML hooks with theme_devel, but I could not find anything useful.

arg(2) will return NULL on node pages (like node/1).

  if (arg(0)=='node' && is_numeric(arg(1)) && !arg(2)) {
    $variables['classes_array'][] = 'node-view-page';
  }


Theming views data export XLS button I have a view that I have attached a data export view to. I want to change the default orange icon that shows XLS at the bottom of the view, to another button with text "Download View". How can I achieve this?

This image is set in function views_data_export_views_plugins(), in views_data_export.views

Implement your own hook_views_plugins() and override ['style']['views_data_export_xls']['export feed icon'] with your own value. Just make sure your module fires after Views Data Export.


How to add Checkbox Fields to User Accounts? Is it possible to add multi-choice checkbox fields to a Content Type or the fields of a User Type? Hoping it is possible to create the following when a User is registering for an account. They should be able to choose multiple check boxes when registering.

Desired output in user registration form:

<input type="checkbox" id="checkbox1" name="checkbox1" value="first-choice">
First Choice

<input type="checkbox" id="checkbox2" name="checkbox2" value="second-choice">
Second Choice

<input type="checkbox" id="checkbox3" name="checkbox3" value="third-choice">
Thrid Choice

You can add checkbox list from Account Settings

Go to  Configuration >> People >> Account settings - http://example.com/admin/config/people/accounts/fields

Add Field >> Add a new field of List(text)

Add options and select options as unlimited (for multiple select)

Save and go to Manage Form display (/admin/config/people/accounts/form-display) change the checkbox widget to checkboxes/radio buttons.

That's it you can see the check boxes in user account form like this


Views: Access CCK image delta for each image link I have a view that for each row, outputs the first 3 images of a CCK image field.

I would like to be able to Output a different link for each image in the format node/[nid]?image=[delta]

I don't mind writing a token for this purpose, although I'm not sure how I'd access the delta number in the first place, other that some convoluted loop that just increments and resets a static variable, and even then, would that even work or is there some sort of token caching that would break even that approach?

Depending on the views version you use, you have different options to render a multiple values field and the fields themselves.

The easiest thing in this case would be to create a special field formatter for the images. Field formatters are almost exactly same for both Drupal 6 and 7 and is what you could call a theme function for fields. In that theme function you would be able to handle the different deltas, as you will have that variable accessible.

This  post explains a bit about field formatters.
This post explains how to create a field formatter (D6).


Convert two existing sites to multisite I have two sites running from separate installations. I would like to move them to a multisite configuration. I am currently developing in a localhost environment.

I am starting by moving the first site into a multisite config within its own installation. I have given it its own unique folder in the sites directory, set up the sites.php file and given the site its own settings.php in its directory. When I navigate to the location specified in the sites.php configuration I get a not found error, and when I go to the drupal install directory, Drupal would like to do a fresh install.

Do I need to set up a .conf file in the sites-enabled folder of apache2?

Any help is greatly appreciated.

Yes. Configure an apache virtual host for each site. They look something like this:

<VirtualHost *:80>
    DocumentRoot "/path/to/drupal/install"
    ServerName mysite.example.com
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/path/to/drupal/install"
    ServerName myothersite.example.com
</VirtualHost>

Every virtual host in the multisite must be configured with the same DocumentRoot. The ServerName directive should match what you have used as the respective site's key in sites.php. Note that in this case *:80 signifies this virtual host listens on every IP of this server.


UI.selectmenu from jQuery is not imported! I have this function to add libraries from jQuery UI, but the selectmen, and tooltip seems to be missing! anyone know how to import them in Drupal 7.4?

function kalender_init() {
    $lib= array(
        'drupal.ajax', 'drupal.form',
        'drupal.autocomplete',
        'jquery', 'ui','ui.selectable',
        'ui.droppable','ui.draggable',
        'ui.sortable','ui.resizable',
        'ui.tabs','ui.dialog',
        'ui.datepicker','ui.autocomplete',
        'ui.button', 'ui.buttonset',
        'ui.selectmenu', 'ui.tooltip',
        'form'
    );
    foreach($lib as $l){
        drupal_add_library('system', $l);
    }
}

I need for the form over here:

foreach($result as $color){
    array_push($colors, $color->name);
}
foreach($colors as $color => $id){
    array_push($attr, array('class' => array('colors-list'), 'data-color' => $color) );
}
$form['gruppen']['checkbox'][$group->id]['color'] = array(
    '#type' => 'select',
    '#suffix' => '

',
    '#default_value' => 0,
    '#options' => $colors,
    '#options_attributes' => $attr,
);

Selectmenu Widget is added in jQuery UI 1.11, which is not supported by core and also jquery_update module. There is an issue on Drupal.org.

Tabs Widget is added since jQuery UI 1.9, you can have it if you installed latest version of jquery_update module with proper configuration.


Change the name of uploaded file based on content type and entity id Consider this pattern :

  [content type]-[entity ID].[file:ffp-extension-original]

is there any hook so I can change the uploaded file name based on content type and node ID in drupal 8?

PS:

I used File(field) paths module but I couldn't find proper tokens to get it work right

You might be able to do this with hook_ENTITY_TYPE_update().  Take a look at the D8 version of the upload_replace module code for an example of changing filenames.


Indexing all pages of a website in Google I use Google CSE on my website, which contains upwards of 5000 stories. Naturally, I would like all of this content to be indexed in Google. Many of these stories will not be linked elsewhere on the site... can they still find their way into Google's search index?

Thanks!

The XML sitemap module will generate a file which can be submitted to google, and other search engines to tell them about all of your content.


Can I store media files in the private directory? The normal behavior, described also in Give access to private files to certain role? seem to be the following.

  Once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.

Does it work for media type fields?
How can it be configured?

I would like the files to be accessible only from users who authenticate themselves using CAS.

You can use the private file system with media entities. Users who have permission to view the entity they are attached to will be able to access the files. So if your file is attached to a media entity that is attached to a publicly visible node, the node is public, so the file will be open to anyone. If you add some sort of viewing permissions to the node through a contributed module or something, then the files will only be visible to those users.
It is however possible to do custom permissions, using hook_file_download().


How to get value from field added in user settings I am writing a module that performs a redirect based on what value was in a custom field called "field_account_type" that was added in user settings. How do I store this value in a variable within hook_user_login()?

You can access global $user custom field values in the hook that suits you like this :

function your_hook() {
  global $user;
  $current_user = user_load($user->uid);
  $vars['account_type'] = $current_user->field_account_type[LANGUAGE_NONE][0]['value'];
}


drush variable-set for permission table I want to enable access comments, post comments, and post comments without approval for anonymous using drush.

Fresh install, the table entry look like this:

INSERT INTO `permission` VALUES (2,2,'access comments, access content, post comments, post comments without approval',0);

After access comments, post comments, and post comments without approval enabled for anonymous, it looks like this:

INSERT INTO `permission` VALUES (3,1,'access comments, post comments, post comments without approval, access content',0);
INSERT INTO `permission` VALUES (4,2,'access comments, post comments, post comments without approval, access content',0);

I can use drush variable-set error_level "0" to change error reporting level. But how about above case? It looks more difficult to understand

There is currently no explicit command to run in order to grant a role a certain permission. The documentation is very helpful here - http://www.drush.org/help/5

However, you can use drush to execute native SQL in order to solve the issue

e.g.

drush sql-query "INSERT INTO permission VALUES (4,2,'access comments, post comments, post comments without approval, access content',0)"

If this is something you will be doing on a regular basis after a site install, consider creating your own custom install profile (which will contain the required SQL, or features), or creating your own custom module (e.g. created using features). I imagine having to run this script over CLI is not the most maintainable solution ;)


Migration via phpmyadmin We are moving to a Drupal distribution. From all the research we have done, there is no easy path to do Drupal 8 to Drupal 8 migration.

We are looking to copy some content via phpmyadmin.

Data we need to move are:

Taxonomy
Nodes
Comments

Which tables do we need to copy from one database to the new?

We did copy the users successfully.

Now wondering if we can do the content as well.

if migration sounds too hard ...

install and config
https://www.drupal.org/project/default_content_deploy

then

"drush default-content-deploy:entity-list"

to see a list then:

"drush default-content-deploy:export taxonomy_term"
"drush default-content-deploy:export node"
"drush default-content-deploy:exportcomment"

copy the exported files to your next site, make sure the nodes taxonomy_terms and comments have same field structure (can do this by exporting / importing config or look at features module)

after that import your content.

   "default-content-deploy:import"

again make backups of your "new" database before this though !

extra bonus use version control on the exported content .. that way developers / live sites can share the content easily.


How can I translate the title of taxonomy term pages when using i18n? On the page of translated taxonomy term "Site Development" there is Russian source Term name in the title tag and in the page title (h1). You can see the problem at http://tlito.ru/en/categories/site-development

I often use the i18n module, but what kind of error/problem could be causing this?

Yet another interesting multi lingual challenge, this one related to taxonomies. The reason for your issue might be because of one reasons explained below.

Use a recent i18n version

Make sure you're using that the version of the i18n module is at least version 7.x-1.8, because it might be because of a bug in the 7.x-1.7 version of it.

Use the correct translation mode

You also want to check the "translation mode" that you've specified within admin/structure/taxonomy/categories/edit (whereas "categories" is the name of your specific category): by default that is set to "Localize", though it should be set to "translate". Attention: after changing this value, be aware that you then also have to:

enter a translated value for each of the tags and
revisit any of the existing nodes that are already using the specific taxonomy, so that they use the (translated) term that corresponds to the language of the node.

Obvious, if you have other taxonomies with the same issue (like "categories" in your case), you should repeat this for those others also.

Consider the Title module

Possibly related to this issue is that titles that do not get translated in a site using the i18n module, is most often because of the Title module that has not been enabled. From the module's project page (bold markup added here):

  After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.

FYI: I have not yet run into any situation where I had to install/enable this module to get multi language site to work as I want.


How do I configure the recurring node checkout payment? In the past years, I use commerce node checkout to published a node when the user checkout completed. Now I want to automatically, charge user when their node published expired.

How can I link the node to the recurring product, so the recurring payment happen when the node expire every month?

I got it working.  I've read the file "README.txt" and found that any product type can be a recurring product.

Now I configured my existing product type to add the fields, required by recurring payment.  So, now when I checkout, it does create a recurring entities for this order.  Hope it will help someone.


how to create file programmatically only login users download it I want to create file programmatically ,I want only authenticated user can download it and direct access return  403 to them.
I search and saw How Can I Make File Downloads Available Only to Authenticated Users? but my files not field files(not record in file table) and programmatically I created them with:

    $temp1=variable_get('file_public_path').'/export';
      if(!file_prepare_directory($temp1,FILE_CREATE_DIRECTORY)){
          drupal_set_message(t('Problem in write file in directory'),'error');
          return;
      }
    $filename='Export-giftcard-'.time().'.csv';
        $filepath=$temp1.'/'.$filename;
    //    $filepath='sites\\defauls\\files\\Export-giftcard-.csv';
        $df = fopen($filepath, 'w');
        if(!$df){
            drupal_set_message(t('Can not write file in').$filepath,'error');
            return;
        }
        fputcsv($df,array('code','credit'));
   fclose($df);
    $path = file_create_url($filepath);
    drupal_set_message(t('Export done. ') . '' . t('Download export file') . '');

after rooby answer I update my question

I set private file system to system/files/export and  in my code use it
$temp1 = variable_get('file_private_path');
also I implement hook_file_download

function mymodule_file_download($uri) {
  // Check if the file is controlled by the current module.
  if (!file_prepare_directory($uri)) {
    $uri = FALSE;
  }
// I will put my conditions later
      $info = image_get_info($uri);
      return array('Content-Type' => $info['mime_type']);
}

but when I try to click on link to download file return Forbidden to me.I think mymodule_file_download not run when I try to access system/files/export/myfile.csv

Create a private file field as you would if they were regular private files.

Hook in to the file download function: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_file_download/7

Let Drupal handle permissions,  create your file dynamically.


Views display settings are in the database but don't show up in views UI I'm trying to create a copy of a live site and use it as a test site, but am having trouble with views. There's a view whose settings are in the database but don't show up correctly in the views UI.

I copied the site by (1) installing Drupal, (2) installing the required modules, including some custom features, and (3) exporting the database from the live site and importing to the test site.

The view in question is defined in a feature, and also exists in the views_view and views_display tables in the database. I have not reverted the feature, so I believe the feature code should be ignored in favor of whatever is in the database.

In any case, both in the database and in the feature, the view has an added display with some settings that override the default display. For example, the added display has Header: PHP Code, which overrides the default display's Header: None. In the views UI, the added display exists, but, except for Name, all of its overridden settings, relationships, arguments, fields, and filters are gone. That's also the case for some of the other displays on the view. One display lost its relationships, arguments, and sort criteria, but not its fields and filters.

I've tried clearing all caches (drush cc all), clearing the views cache (Admin > Site Building > Views > Tools), and deleting all rows from the views_object_cache table. Didn't help.

FWIW - you might want to install drush and use the drush archive-dump command which will extract your entire site (database, drupal instance and files) into a single tarball file.  You can then use drush archive-restore to import that site into a different site on the same or different machine.

There are other ways, of course, but this seems to be one of the easiest as there is nothing to remember or think about other than doing it.

Good luck - B


Add html5 input types using drupal form api I want to add HTML5 number type textfield in the form programmatically. I am building the form using hook_form().
I tried adding the code:-

$form['field_price']['#attributes']['type'] = 'number';

But it isnt working.

Is there any other work around for the same?

Try Element module. it adds advance html5 elements to your form.

Similar question is asked here


Ajax returned values do not update when field value changes I have an ajax form element, age, that I'm passing to a query within an ajax callback. The callback generates some product information and returns it as a part of the form array.

The problem is this: if I update the age field, the callback is fired, the query is re-run, and the wrapper is refreshed, however it isn't updating the wrapper div with the new information, it's reloading the initial information.

The code lives here: http://pastebin.com/vUrCMX7c

Any help is greatly appreciated.

Check for any errors in Firebug's console.
In Firebug's net tab, what is the value coming back from the XHR callback?

If the value coming back from the XHR is the old value, then your problem is on the server side. If the value coming back from the XHR is the new one, then your problem is on the client side (like JQuery not being able to find it's target element). Hope that helps.


How do you load a node inside of another node? A node has several text links or thumbnails loaded from a view. For the purpose of this question, lets suppose they're thumbnails and the area with the thumbnails lets call it the "head" of the node.

Those thumbnails link to other nodes. To be able to understand the scenario am trying place here. Lets call the nodes that the thumbnails link to "Subnodes". The Area under the thumbnails, is a area where you want to load a "subnode" from the thumbnail clicked. Lets call this area the "footer".

The goal here is keep the original node with the thumbnails or text links ("Header") at the top of the page AND load the subnode in the "footer". The ideal method would involve some AJAX to keep the page load away from the end user. Although this is not required because a solution with a page load is acceptable.

Extra consideration to anyone who purposes a solution using AJAX.

Take a look at the Peekaboo; Ajax field formatter module.

  Provides the ability to load the contents of a field via Ajax.

  Use cases

  Field output that is heavy on resources
  Some fields, such as the *reference fields, can contain a tremendous amount of overhead when formatting the output for the field. This module allows the page output to load without calculating the formatted output of the field, and the field contents can be subsequently loaded into the page with Ajax.
  Field output that takes up too much space
  Peekaboo can be used to initially hide certain fields that take up a lot of space, like maps or images, only to be revealed later at the user's request.
  Fields that reveal more information
  Peekaboo can also be used purely for the Ajax functionality as a gimmick to reveal more information.


How to include media documents in search Is there any way to include documents I created with the media core module into the search form of the page? I only found the categories "users" and "nodes".

As I understand, you want to search by Media entities/records.

If you use the standard Search module from Core, then it impossible.

But you can install the Search API module, configure the search server (search server can use current drupal Database or Apache Solr, or smth other).

In the Search API you can create indexes and include the documents into the index.

To display a page with search results you can use a Views module (using content from Search API index) or you can try to use the Search API Pages module


Need to hide a field for the node author For a particular content type education i need a field to be hidden for the node author. It works in the template file but not with preprocess. This is my code

 function aapka_preprocess_node(&$variables){
     $node = $variables['node'];
     if ($node->type == 'education'){
     if ($node->uid == $user->uid && $user->uid != 1) {
 unset($variables['content']['field_college']);}
  }

What am i doing wrong??

You are referencing $user without bringing it into scope.

e.g using your current approach you could do this:

function aapka_preprocess_node(&$variables){
  // Bring global user object into scope
  global $user;
  // Assign by reference
  $node =& $variables['node'];
  if ($node->type == 'education'){
    if ($node->uid == $user->uid && $user->uid != 1) {
      unset($variables['content']['field_college']);
    }
  }
}

Keep in mind that won't work if the node is cached and the cache doesn't vary between the author and other regular registered users.


Custom menu as admin menu Is there a module that take a custom menu and show it like Admin menu?

I want to create my custom menu and then display it like admin menu (only for some roles).

I've tried some modules but:

Admin menu does not allow to select which menu should be displayed, and however I want to display default menu for Administrator and a custom menu for "editors" and other custom roles
Superfish or Nice menus does not allow to place the menu in top of page, like Admin menu does

Another solution could be a module that place a block in top of page, fixed, so I could use a "simple" superfish menu, but I have not find something like this.

The main question is that I can't use the "default" management menu, but a custom menu.

You want Admin menu source. It allows you to configure each role with a menu as the source for admin_menu.


How can I get more than 10 search results on one page in Drupal 7? By default search page shows only 10 results. How can I change it to display unlimited number of results?

I recommend using views for this. Views comes with a search view included (disabled by default). Use an exposed search term filter to provide the search functionality, and customize other aspects of the view as needed.


Can I include nodes in a view's results only at URLs specified in the nodes? Is it possible to conditionally include nodes in a view based on the paths specified in a field on that node? The idea is to essentially mimic the default property of blocks, making their display allowed or disallowed at specified paths. My view (technically a view block) is being used to show sponsor images as a slideshow, and I'd like to be able to define which pages each specific sponsors' graphics should display.

I'd imagine it would include the use of a contextual filter on the field containing the paths, but I can't figure out how it would work. Possibly via some implementation of Views Argument Substitutions, although that seems to base its results off of specified path arguments and not the whole path.
In the meantime, I'm implementing Nodeblock as a partial substitute, but I'd prefer to leverage views if possible.

EDIT: Thanks to mchar's answer below, I was able to get a working snippet for this functionality. It could probably be optimized, but that's for another thread.

function MYMODULE_views_pre_render(&$view) {
    if($view->name=='sponsors') {
        $current_path = drupal_lookup_path('alias',current_path());
        foreach($view->result as $row_num => $row) {
            foreach($row->field_field_urls_to_show_up_on as $urlNum => $url) {
                $this_path = $url['rendered']['#markup'];

                // If the path contains an asterisk
                // Asterisks should only appear at the end of a path at the time of writing
                if (strpos($haystack = $this_path, $needle = '*') !== false) {
                    $this_path = str_replace('/*', '', $this_path);
                    if (strpos($haystack = $current_path, $needle = $this_path) === false) {
                        unset($view->result[$row_num]);
                    }
                }

                // if current_path is not the same as the provided path (no *)
                elseif ($current_path != $this_path) {
                    unset($view->result[$row_num]);
                }
            }
        }
    }
}

Hook views_pre_render should meet your needs.

Here is a sample code of what you are describing:

$string_pos = strpos($haystack = current_path(), $needle = 'chickens'); // or you may use drupal_get_path_alias()
  if ($view->name == 'view_name' && $view->current_display == 'view_display') {
    foreach($view->result as $row_num => $row) {
      if ($string_pos && strpos($haystack = $row->node_path, $needle = 'chickens')) {
        unset($view->result[$row_num]);
      }
    }
  }

It can be optimized but I guess you got the idea.

Hope that helps!


using Feeds Xpath Parser to import RSS feeds I am trying to import a Wordpress feed with images (e.g. http://blog.objet.com/feed/) into Drupal 7. I've installed the Feeds XPath Parser module and read the documentation but I am still having the following issues:

The document is XML, but firefox shows it as XHTML. Whic parser to use? XML Parser or HTML Parser?
What is the selector (context) of the root element? I've tried 'xhtml', '/xhtml', 'xhtml:meta',  '/xhtml:meta', 'item', '/item' (with both XML and XHTML parsers) but no elements are getting imported (the feed was imported correctly before I've installed the 'Feeds XPath Parser' module).

Updates:

I was also trying to add "//item" as a selector, this time I got one item, with one image, while no other items being imported.

You have to fully understand the XPath queries logic to use the parser. It's very powerful once you get it, but it needs a bit of practice.

Here is a good starting page : http://www.w3schools.com/xpath/

Note that you have two parts in the UI for the queries :

One to set the context, which is the element all further queries will be run from
One for each field

The context element depends on your document and the logic of the data inside. Usually, you set the context each 'entity' or node is saved in, and then query fields or attributes for the different fields.

For example, if you have a 'Thing' entity like this :

<Thing>
<id>1</id>
<name>Name One</name>
</Thing>
<Thing>
<id>2</id>
<name>Name Two</name>
</Thing>

... you would set the context to /Thing and then each field query to name and id. You also have a syntax to query attributes.

Also, be aware Feeds is only compatible with XPath 1.0 syntax.


Create content type with fields that are content types I am trying to do something similar to this

I have a catalog content type.  I want to be able to add one or more books related to the catalog topic to this content type. These books would be of a custom content type. Each book would only be tied to a single catalog but a catalog may have many books.

I want to create a page for each catalog topic that has the fields of the catalog content type (like description etc) and then a list of all the books related to the catalog topic.

I want authenticated users to be able to add new books ("add book" link) to the catalog and also to be able to create new catalogs for the topics they choose. When a new catalog is created, it should have an "add book" link.

How would do this?

A think you could be interested in Field Collection


How can I create Rules condition for event when 404 error generated? I've assigned page for 404 error handling (example.com/404).
I've created Rules condition: Data to compare: [site:current-page:url], Data value: 404.
And I've created some Rules action for this case.

But when I open nonexistent page (example.com/wrong) - there is no corresponding Rules action.
It is because I see 'example.com/wrong' address instead of 'example.com/404'

But how can I create Rules condition for event when 404 error generated?

Navigate to this path admin/config/system/site-information, which will look like www.example.com/admin/config/system/site-information.

Enter the page URL(your page for 404) in the 'Default 404 (not found) page', where you want to navigate your user when 404 happens.

Note - I don't think you can detect 404 from rules. May be somebody can answer about that but not me. Though I have experience with rules but never seen this kind of thing.


How to deal with deleted posts: Returning 410 status and preventing path re-use For my jobs site, I want to return 410 status for those jobs which expire or are removed permanently. How can I do it so that 410 instead of 404 is returned for say job related node types( they'll be unpublished first and later deleted permanently I guess I should return 404 for unpublished then 410 when deleted)?

Secondly in case it really works out to use 410 for such pages but later new job pages may be published by Path Auto which could assign the very same url's based on title name for which 410 was returned once. I understand if a url comes back after 410 it will be permanently ignore by Google. So I guess I'd need that Path Auto always generate a non-duplicated (deleted) url. So solve this I'd need to tag an always increasing number with the url or adds jobs in url directories based on dates like xyz.com/oct/job1.... So I'd need to take care of this too if I'm able to return 410 for such page.

Pathauto will not duplicate paths. If your Pathauto URL pattern results in the path 'oct/job1' and that path already exists, Pathauto will add an integer to the end of the alias, incrementing it for every new 'identical' path. IE, you'll end up with these paths:

oct/job1
oct/job1-0
oct/job1-1
oct/job1-2
oct/job1-3

... etc.

So what you need to do is:

Implement hook_menu() to create a custom page callback that will map to a function which will return the 410 HTTP code.
Create the callback function for the path you created in hook_menu()
Implement hook_node_delete() and look at the type of the node being deleted; if the type matches the content type you're working with, run a query to update the url_alias database table, changing the 'source' of the records relating to your node from the 'node/##' value to the menu callback you created in step 1. This will prevent Pathauto from deleting the aliases, and will instead map them to your function which will return the 410 HTTP code.

One thing to keep in mind is that the module in which you implement this custom functionality needs to fire before Pathauto, so you may need to alter your module's 'weight' value in the system database table.


browscap.ini is not configured in php.ini In my status report I'm still getting this error:

Browscap data   /   browscap.ini is not configured in php.ini.

When I searched on the internet I found this topic that suggested this:

[browscap]
; http://php.net/browscap
browscap = "C:\xampp\php\extras\browscap.ini"

I've download full_php_browscap.ini file on browscap.org and placed it in the root where my php.ini is also located (also changed the name to browscap.ini).

Then I've placed this in my php.ini file:

[browscap]
browscap = "/domains/mydomain.be/public_html/staging/browscap.ini"

But I'm still getting the error ... . My php.ini file is located in the same directory as the browscap.ini file.


How to add a block to the main page region? I want to add a simple blocks in the main page region. Instead of basic page or article I just want to add 4 blocks on that page. So, it looks like, Home page(Have blocks) >> sub-Home(have blocks) >> All Basic page(content). This looks simple but there is no way in the add block options where we can display as block and have a path.

Go to YOUR_SITE/admin/structure/block and find the Content region

then go to Configure

Then configure the Visibility settings, in this case this block only will be showed in the front page.


How to customize the display of a block? I'm new to drupal, I'm using Finder module, I was able to hide some buttons and clean the presentation a little bit, but I also want to be able to customize the search fields display, I'm not sure if I will have to develop a module and implement a certain hook or this should be done in the template.

here's how the block looks like :

I'm trying to inline those input fields and add some style to them and my question is how can I achieve this.

You can customize the display of a block by using Block Class module.

  Block Class allows users to add classes to any block through the
  block's configuration interface. By adding a very short snippet of PHP
  to a theme's block.tpl.php file, classes can be added to the parent
   element of a block. Hooray for more powerful
  block theming!

In this case, first look at the CSS selector and then add a single line to theme's CSS file such as:

.label { display: inline }

It's about CSS.


How to reset node id to a lower number - Drupal 7 I have loaded thousand of nodes in different tests. How can I safely delete all the extra nodes and obly the database table to increment the node nid after the next valid (not deleted) nid? I.e., now I have 50 valid nodes, and the index starts at 250.000. How can I force it to start at nid = 51 without making the whole database crash ?

A secure way, please. Not low level, but with a module or something that respects referential integrity of the whole database.

The node id is the primary key of the {node} database table. You need to reset the "auto_increment" property of that table to 1 (or 51 in your case). You can do that with PHPMyAdmin, or other MySQL client.


how to assign first img linked on a node to image field What I have: a D7 site with around 2k nodes on it, many of these nodes have images <img> in the html of the body but those images are not assigned to the image field. (It is an old drupal site that was upgraded to D7).

I would like to parse all the nodes so that the first image in the body content is assigned programatically to the image field of the node. Manually editing is not an option, as there are over 2.000 nodes on that site.

Is there a way to do that programatically? I guess field api may help (and so my tag) but I dont really know.

Thanks.

I would write a module that read the field_data_body table in database. This table contains a field called body_value where the values are stored. If the module find a  mark, you can get the "src" attributte.

You don't forget to make a comparison in field_revision_body table to avoid problems.

Once you have the path of the file, you must save it as managed file in database. For this, take a look to "file.inc".

Here a little summary for last changes in D7.

I think it's important that you understand the difference between managed files and unmanaged files. Once you have saved the file, you could load the node, and assign to the field_image field, then node_save().


Creating 2 forms to work together on the same page for the same query I'm facing trouble coming up with the following approach:

I will have 3 separate forms acting on the same query from third party API's.

On the front page there is a shorter quick-form that would lead to the page of the other 2 forms. In some cases the information from the first form is sufficient to query the information and the information will be queried.

In other cases additional input from the second form is required to make the query. The third form is for fine-tuning an existing query.

The first form isn't an issue, it's a separate block on the front page that will store the information internally for the second form to see with multiform functionalities and on submit redirect to the second forms page, where the form can process the information and see if a query can be made or will give results and go ahead with it, if not, then ask for further input.

The second and third form are on the same page, where the second form has necessary input fields for the query, which can also be changed to change the results, and the third form is just for fine-tuning this query like a filter or so.

Right now I'm stuck with the second 2 forms working together on the same page, being separate forms but altering the same query/information. And would appreciate all and any help with this approach that would be "the Drupal way".

Better visualization:

Imagine a flight booking site: first form is your departure airport that takes you to the second 2 forms, where already a lot of flights from your airport can be displayed, second form takes in a destination, dates and passengers; the third form would let you fine-tune travel class, meals, airlines to avoid airlines preferred, how many layovers, how long layovers and so on..

All the information with each form is queried from different airline API's and will have to be redone on every change.

From your question... you are saying you have 3 forms...

The first form (on its own page) leads to the other 2 forms (which are on a different page, but both forms are on that single page)... it's not completely clear what the problem is - only that both forms are supposed to alter a query, but this is not happening?

Perhaps you could place the fields for both forms in a single form and assign different actions to each of the submit buttons... technically there will only be one form, but visually through styling you can make it appear as two separate forms through CSS - for example using tabs where the fields for the first form is on the first tab... and the fields for the second form is on the second tab... the first tab would have a submit button defined like this:

        $form['submit1']=array(
        '#type' => 'submit',
        '#value' => t('Submit form 1'),
        '#submit' => array('::processForm1'),
        );

and on the second tab you can define another submit button:

        $form['submit2']=array(
        '#type' => 'submit',
        '#value' => t('Submit form 2'),
        '#submit' => array('::processForm2'),
        );

Enough to say in the form object, you will need to define both the processForm1 function and the processForm2 function... in order to decipher which button triggered the submit in the formValidation and formSubmit functions you will use a line such as:

      $trigger=$form_state->getValue('op');

where $trigger will hold the label of the triggering button.

Hope that helps and makes sense.


Can I hide date field if older than a certian time using Rules? I want to know if I can hide the values of a date field if the values are older than a certain time. The website is built with Drupal 7, and Display Suite.

Use the Conditional Fields  module.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


How to create a relationship between a table in a database and content type in views d7? A table table_A is present in database with a abc_nid and abc_code columns.
I have  a node having abc_nid as node_nid
How can I link a abc_code (from the table_A) in a view using relationship(non programmatically) or any other way ?

You can certainly implement this functionality by creating a views plugin:

In your <module_name>.module file implement hook_views_api().
In your <module_name>.views.inc, implement hook_views_data(). Something roughly like this:

/** This hook should be placed in MODULENAME.views.inc and it will be
 * auto-loaded. MODULENAME.views.inc must be in the directory specified by the
 * 'path' key returned by MODULENAME_views_api(), or the same directory as the
 * .module file, if 'path' is unspecified.
 */
function MODULENAME_views_views_data() {
  $data = array();

  // Select/Create a category.
  $data['table_A']['table']['group'] = t('Your category');

  // Define the join with your table.
  $data['table_A']['table']['join'] = array(
      'node' => array(
      'left_field' => 'abc_nid',
      'field' => 'nid',
    ),
  );

  $data['table_A']['abc_code'] = array(
    'title' => t('ABC Code title'),
    'help' => t('Some help text.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
  return $data;
}

You can choose the appropriate handlers:

Views field handlers
Views sort handlers
Views filter handlers

If required you can add you own handlers by extending the handlers. But, adding a handler is required.
This will provide you a field, a filter and a sort criteria in your view of nodes which will display/filter/sort the fields on the basis of the value of abc_code for that particular field.


Drupal 7 Omega - js file not working Okay so I have a headache trying to figure this one out. I am working in Drupal 7 with the Omega theme. Trying to get a js file to work.

I have a js file that is set up through the .info file and is showing in view source. The file contents are below. I can get this to work when I place in the wysiwyg on the page however it won't work when I set it up properly as a .js file.

 (function ($) {
// All your code here
  $('#block-menu-menu ul.menu').removeClass('menu').addClass('sub-menu');

// Create the dropdown base
  $("<select />").appendTo(".menu");

  // Create default option "Go to..."
  $("<option />", {
     "selected": "selected",
     "value"   : "",
     "text"    : "Go to..."
  }).appendTo(".menu select");

  // Populate dropdown with  items
  $(".menu a").each(function() {
   var el = $(this);
   $("<option />", {
       "value"   : el.attr("href"),
       "text"    : el.text()
   }).appendTo(".menu select");
  });

  $(".menu select").change(function() {
    window.location = $(this).find("option:selected").val();
  });

})(jQuery);

My issue is it works when placed in the page, but when I place in the .js file and call it through .info it won't work. Again the file shows up in the view source so it is there. I have to be missing something. NOTE * I am not a developer.

Any thoughts?
Thank you!

You need to wrap your javascript in a Drupal Behaviors handler. You can read the Javascript Documentation for more information (scroll down and look for the heading "Behaviors").

Basically, your code will end up looking something like this:

    (function ($) {

      Drupal.behaviors.exampleBehavior = {
        attach: function (context, settings) {
         // All your code here
       }
     };

   })(jQuery);

If this does not solve your issue, you use check your site for any javascript error messages and update your original post to include them. The way I recommend to do this is to install the Web Developer plugin for Firefox and open up the Error Console (tools -> web developer -> error console) and look for messages highlighted in red.


How can I add a log entry to watchdog every time form_set_error() is triggered on user_account_form_validate()? I'm not much of a coder so I'm having a real hard time figuring this out.

I have a custom module and I'm trying to override user_account_form_validate() (from user.module) so that I can add a watchdog entry every time a specific instance of form_set_error() is called:

elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
  form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
}

I need to do this because sometimes the Email registration module causes this error to fire and I want to make sure that this doesn't occur; so, to ensure users aren't seeing this error, I want to log it in watchdog if it occurs.

I know I can hack core and add the following line just after form_set_error:

watchdog('mymodule', 'Registration error: %name was already registered.', array('%name' => $form_state['values']['name']), WATCHDOG_ALERT);

But how I can I do this without hacking core?  I tried various permutations of function

  function mytheme_user_register_form_validate (&$form, &$form_state) {}

in a custom module but I couldn't successfully get Drupal to use my function instead of the core one.

To add a new validation handler to a form, you need to implement hook_form_alter(). In your case, I would use the following code, which adds an extra validation handler that is executed before the other ones added by the User module.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  array_unshift($form['#validate'], 'mymodule_user_register_validate');
}

function mymodule_user_register_validate($form, &$form_state) {
  $account = $form['#user'];

  if (isset($form_state['values']['name'])) {
    if ($error = user_validate_name($form_state['values']['name'])) {
      // This is intentionally empty.
    }
    elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
      // Log the error with watchdog().
    }
  }
}


Drush dl with dependencies on a multisite environment When downloading a project using drush dl <project> in a site specific folder on a multisite environment, the module is being downloaded to /modules. However, the dependencies are being downloaded to /sites/all/modules. Is there a way to force Drush to download the dependencies to the site specific module folder using Drush 5?

Nope; Drush doesn't pass --destination to the command used to download the dependencies.  The code is in drush_pm_enable_validate; patches welcome.

The issue is at http://drupal.org/node/1632578


How to use "IS NULL" and "IS NOT NULL" Operators in JSON API Collections? I am creating an API with Conditions and Operators. For '=' and '<>' operators its working fine. But for "IS NULL" and "IS NOT NULL" operators the response is 400: Bad Request.

{{URL}}/jsonapi/node/CONTENT_TYPE?filter[filter1][condition][path]=TAXONOMY_FIELD.drupal_internal__tid&filter[filter1][condition][value]={{TID}}&filter[filter1][condition][operator]=IS NULL

Request:

Response:
The error says: Filters using the 'IS NULL' operator should not provide a value.

Should the operators be encoded ? If yes, then which encoding should be used and what is the encoded string for these operators ?

You don't need this line, because value is supposed to be null
&filter[filter1][condition][value]={{TID}}


Create a node when the user is activated Drupal Version: 8.92
Part 1. I am trying to create a node when the user is activated by the administrator for the first time. However, I am not able to find the right event/hook to execute the code. I tried "user_activated" but it is not working.
function my_module_user_activated(\Drupal\user\UserInterface $user) {
  \Drupal\node\Entity\Node::create([
    'type' => 'my_node',
    'title' => $user->getDisplayName(),
    'uid' => $user->id(),
  ])->save();
}

Any pointers?
PS: I don't want to create the node using hook_user_insert().
Part 2. If I need to delay the node creation to user validating the email by clicking a URL, what hook should I try?
Thank You!
Uri

Modified code based on the pointers from No Sssweat. The working code is below for any future references.
function <MY-MODULE>_user_presave(\Drupal\user\UserInterface $user) {
  if (($user->isActive()) and ($user->getLastAccessedTime() == 0 ) and ( $user->hasRole('role_name'))){
  \Drupal\node\Entity\Node::create([
    'type' => 'my_content_type',
    'title' => $user->getDisplayName(),
    'uid' => $user->id(),
  ])->save();
  }

}


Is there a module that lets one person do a bulk publish/update? On my site I need the ability to let multiple people edit and add content, but I need that content to be only able to be published at one time by one person.

Is there a module out there that lets a user of a certain role publish all of the new and updated content at the same time?

This should be possible using the Views Bulk Operations module (=VBO) ... Quote from its project page:

  ... augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

So create a view that lists all "content waiting to be published", whereas you might want to limit the access to such view to only that "one person" (the content approver?).

Then have the content approver use VBO to select "all" content to then apply "bulk operation" = "publish".

Should you want to do so, you could further enhance/refine this content approval process with modules Flag and Rules modules also. Refer to these questions to get an idea of the possibilities:

How can I allow anonymous visitors to submit content?.
How to implement a nomination process for nodes?


Server side Drupal install as git local repo I have a Drupal install on a shared server and would like to do some version control on it, namely git.

I'm a beginner at Drupal and only just starting with git so I've become a bit overwhelmed with any instructions on the web for doing this, as they assume you're proficient with one or the other.

What I want my setup to be is

The hosted Drupal install is my git's "local" repo.
Make changes, commit
Push to github

The problem is that as it is a shared server, I don't think I can install git. So, firstly, is this workflow possible without installing git on the server? And, if so, secondly, could somebody please point me in the right direction for setting this up.

As always, if somebody has a better way of doing it, please say!

Fair warning, I don't know Drupal, so it's possible you're describing a common workflow. All the same I know a thing or two about git, and what you describe is a bit backwards. The problem is here:

  The hosted Drupal install is my git's "local" repo.
  Make changes, commit
  Push to github

By treating your production environment, the hosted Drupal install, as your local repository, you basically circumvent the benefits of versioned deployment. If you break that local, you break the site. If you want to work on a test feature branch (maybe new content you're still creating), you have to expose it to the world. A more canonical approach might be:

Commit to the site locally (on your computer) as well as a clone on your hosted site. Use github to push and pull between them. The Drupal docs have a solid example of this.
Commit to the site locally (on your computer), and use a post-receive hook to deploy the Drupal site, if your hosting provider supports git installation. This is a common setup in web application deployment.

In either case, note that you want a truly local copy, some place to experiment around, rather than the live website.


How to print Json data from Facebook in a block? I would like to print the amount of Facebook likes for a url into a block.
The Facebook API returns JSON like so:  https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27https://drupal.stackexchange.com/%27&format=json

What is the Drupal 8 way to print this data in an block?

Normally I would look for a contributed module that might already be written, but at this time none of Drupal for FaceBook, FaceBook Like Button, Views FaceBook Like, FaceBook Social, or Social Media Links have Drupal 8 releases. It would be a good idea to look at contributing to the above projects.

In order to accomplish this, you will need to create a Block plugin in a custom module. There are a few of options. Code examples are sort of pseudo-codeish.

Contribute and port one of the modules above to Drupal 8.
In PHP, you may use Guzzle in the build method in the block plugin. The advantage here is that the block will be cached and save performance on subsequent loads.

```

$client = \Drupal::service('http_client');
$options = [
  'query' => [
    'query' => "select like_count from link_state where url = 'http://drupal.stackexchange.com/'",
    'format' => 'json'
];
$response = $client->request('https://api.facebook.com/method/fql.query', $options);
// the "serializer" service could also be used if deserializing into a known Drupal typed data type.
$data = json_decode($response->getBody());

```

You may also add a JavaScript asset to the render array of the block, and then code some JavaScript that makes a request. The advantage here is that this is that this is done after Drupal render, but it will make an additional http request on each page load.

```

(function($, Drupal) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $.ajax('https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27http://drupal.stackexchange.com/%27&format=json', {
        dataType: 'json'
      }).done(function(data) {

      });
    }
  };
})(jQuery, Drupal);

```


Save pdf files in folder using TCPDF I have installed Print module and also TCPDF library to generate PDF files. However, Print module can just create PDF files to download, but not to save in server folder. I have tried to change method _print_pdf_tcpdf in Print module, so files can be saved in server folder. I have changed _print_pdf_tcpdf function  as follows:

I have changed line

$pdf->Output($filename, $output_dest);

to this line:

$pdf->Output($filename, 'F');

But this code throws error:

TCPDF ERROR: Unable to create output file: https://mywebsite/sites/default/files/aaa.pdf

I have set permissions for sites folder to write. Another modules can write into this folder, so I dont think the problem is in permissions.
Can anybody help
where can be problem?

I've made a couple of TCPDF implementations myself in Drupal. As Clive suggested, you shouldn't use URIs in TCPDF's output() method, instead you'll want to provide absolute filepaths.

This code has always worked for me:

// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$path = drupal_realpath('public://folder/folder2/folder3');

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

EDIT: As Clive mentioned in the comment, drupal_realpath() is deprecated. Here's an alternative:

// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$uri = 'public://folder/folder2/folder3';
$stream = file_stream_wrapper_get_instance_by_uri($uri);
$path = DRUPAL_ROOT . '/' . $stream->getDirectoryPath() . '/' . file_uri_target($uri);

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

Just make sure you're always providing an absolute path for TCPDF.


Cannot Find CSS Class For A Custom Block Hello due to much help from here in the past im starting to theme whatever part of my drupal site that i like. Its great. Ive ran into a a strange one though. I have created a custom block (block 130). You can see it on top of my site

BBC Live Olympics | Add Olympic Comment | Football Livescore | OLB Olympics
http://onlinebanter.com/latest

For some reason it doesnt have any div class Im trying to change the p bit.

Ive tried various things but still cant seem to find this blovk. Does anyine have any suggestions?

Thanks

You don't have a class, but you do have an ID so you can use:

#primary p {color:red;}

Note: there is also a nice module call block class (http://drupal.org/project/block_class) that you can use


2 servers with 2 local memcached: flush both I have servers and 1 memcached server linked by the network. When I add 2 memcached on the 2 servers, locally, it's drastically faste !

So I've configured Drupal to use memcached on 127.0.0.1, except for sessions.
The sessions are the only data hosted on the network server (MC 3).

DRUPAL 1    DRUPAL 2
 MC 1         MC 2
   \            /
    \          /
     \        /
        MC 3
      Sessions

It's fine, except for the cache flush because when I do a drush cc all, Drupal 1 will only flush MC1, and Drupal2 only MC2, but not both.

The idea is to force Drupal to clear all the memcached, but to use only the localhost + MC3.

What is your advice, add a hook to clear both servers?

I suggest you to use Drush aliases.

Here is the quote from the documentation http://drush.org/en/master/usage/#site-aliases

  Drush lets you run commands on a remote server, or even on a set of remote servers. Once defined, aliases can be references with the @ nomenclature

Also from here https://raw.githubusercontent.com/drush-ops/drush/master/examples/example.aliases.drushrc.php

  Alias groups (aliases stored together in files called GROUPNAME.aliases.drushrc.php, as mentioned above) also create an implicit namespace that is named after the group name.

Finally, these are few simple steps to achieve what you want:

Create production.aliases.drushrc.php file
Put in this file aliases for both Drupal 1 and 2
Then you can clear cache on all site at once with drush @production cc all


Error after transfering process to a new host I transfered my website to a new host and I am seeing this error:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'teise1_katalogas.system' doesn't exist: SELECT name, filename
  FROM {system} WHERE status = 1 AND bootstrap = 1 AND type = 'module'
  ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 136 of
  /home1/teise1/public_html/imoniukatalogai.lt/includes/module.inc).

Anybody who knows how to resolve this error?

These kinds of problems (after transfer to a new host) might be caused by some type of permission problems. At least if we may assume that the table in the error message does actually exist (if not that needs to be addressed of course).

So I'd verify that the userid specified in the settings.php file, has the appropriate access to the Drupal database (also specified in settings.php).

Another option is to verify the various items mentioned in https://www.drupal.org/node/1308308


Add state permissions and allow state changes I'm using Workflow module. I want to give permission to a specific role to edit the content moderation state. I found these on permissions page but it's not working. After I update the role permission, he got "Access Denied"

As far as I'm aware, there's no way to give permission to manage a specific state, nor workflow for that matter.

The only permission to cover these is administer workflows and it covers all workflows.

You can see this by looking the content_moderation.routing.yml

content_moderation.workflow_type_edit_form:
path: '/admin/config/workflow/workflows/manage/{workflow}/type/{entity_type_id}'
defaults:
  _form: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm'
  _title_callback: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm::getTitle'
requirements:
  _permission: 'administer workflows'

EDIT
That is with the default permissions.


How do you remove the "user login" block? I know this is a simple question, but I've searched for way too long.

I just want to remove the user login box so that all accesses to the site, apart administrator access, will be anonymous. We don't want users to create accounts on the system.

You may disable block on admin/structure/block page, but users can create new accounts from /user page. It's best practice disable creating new accounts by visitors.

For drupal 7 go to configuration -> people -> account settings -> registration and cancellation and set "Who can register accounts?" -> "Administrators only".
For drupal 6 go to administer --> user management --> user settings and set "Public registrations" --> "Only site administrators can create new user accounts."


Show subterms in a page I have two categories and each one has subcategories. I put the parent categories in a menu. What I need is: when I click a parent category its subcategories should be shown in a new page.

How I should that? I'm using Drupal 7.

Taxonomy VTN provide new pages for taxonomy terms, as described in its page it provide what you want by Terms of a parent: taxonomy_vtn/voc/xxx/xxx option

in Drupal 7 you can use views to show child terms in page when you click on parent term:

create new views for taxonomy terms (you should select taxonomy terms in creation form)
create page display
select taxonomy/term/% as path
use argument


What settings are there for sending an email to the users who create accounts? How can I send an email to users after registration, confirming they have been registered?

From user/register, when users enter the required data (name, username, email) as administrator I receive the account information, but the users don't get any message.

In configuration > people > account settings or going to config/people/accounts you can set who gets what and even modify the text

Register without admin approval

Check this setting

Who can register accounts? : visitors

and the user that registers will receive Welcome (no approval required) email which will include a one time link to complete registration.  Upon clicking on the link and following the instructions he is a registered user.

Register with admin approval

check the following setting

Who can register accounts? : Visitors, but administrator approval is required

The user will get Admin (user awaiting approval) email upon registering and if enabled on Account activation the setting Notify user when account is activated is enabled the user will get a 2nd email upon admin approval.


How can I run a query with php before entering a view Is there any way to specify that a certain query has to run before entering a view?  in a module with php .

I used hook_views_pre_execute
and was able to run what I wanted before the view is created


Webforms - '[+] Add more fields' (up to 5) button to file upload form control I managed to add fields to submit attachments in a webform.
Now all I need is to restyle them to only allow one upload per charge plus a 'add more button'. I need to restyle the 1 into 2.

How can this easily achieved?

Have you checked this Webform Add module ?

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields.


How can I check whether a username is in use? On creating a "course" content, i am creating a dummy user as its "instructor". Here is the related question.

I wasn't able to add a condition to the rule that creates the user, that checks whether a user with that name already exists. If it does, then the action (create new user) will not fire.

How can I do that?

I am using rules module with drupal 7.

You need add the condition for if the user exists or doesn't exist and then you are able to create two actions, depending on the user exists or not.

The problem is that this is not possible to do with Rules out of the box. It's not hard to add a condition like this, but it required custom code in a custom module. If this is not an option, what you are asking for is impossible AFAIK, as it doesn't exist.


zero distance in views geofield proximity problem I am having trouble getting it views to calculate the distance. I want a current user to see the distance to other users however the only result I have gotten is 0 between users.

I tried to follow this and still got no result:

  Looks pretty straightforward using geofield 7.x-2.0-alpha2:

  I assume you have geofield and geophp enabled and assume you have
  added a geofield to your users that get the location from an
  addressfield.

  create a view of type users add "[name of your geofield] - proximity"
  field select "source of origin", I tried "exposed geofield proximity
  filter", check the "round" box add "[name of your geofield] -
  proximity" exposed filter and select a "source of origin point" as
  well. For example, add a "geocoded location" (fancy word for address)
  add that same field to your sort options to sort by proximity as well.
  In your example you would probably change the "source of origin point"
  to "current user".

I have checked the users address and they create points. Do anyone have an idea how to get it to work?

I just posted a new documentation page for geofield that shows how to setup a basic proximity search: http://drupal.org/node/1944648


How to send an email using Rules when a node's boolean field is changed? I managed to setup email notification via the Rules module when the content is updated.

But I want to limit this only when the value changes in a specific field that is boolean "Yes", "No".

Update:
This is the part where i am stuck. I am not sure what to pick at Data selector, while at bottom (Field: Value) i found the field i need.
I tried to save with "node" to try 2nd condition but also did not find an option: "Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different."

Here are some details about how to make this work (using Rules):

Rules Event: Before saving content.
Rules Condition (1st): "Entity has field", whereas you should specify these values:

"node" (saved content) for the "data selector" of entity.
the machine name of your boolean field (for field).

Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.

So part of the "clue" to make this rule work is the condition Entity has field. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Update (to further clarify the new questions in the "update" part of your question, with the quoted text copied from the update in the question):

  I am not sure what to pick at Data selector, while at bottom (Field: Value) i found the field I need.

You should select node (saved content), because you want to check if a "node" has the field you're looking for.

  ... but also did not find an option: "Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different."

For this you add an additional Rules Condition which is a Data comparison. And the actual data to be compared are:

original value of the field, which you should be able to find/select by first using as data selector the node-unchanged:...(unchanged content), followed by selecting the field name of your field from the additional list that is shown after you selected that node-unchanged:...(unchanged content).
updated value of the field, which you should be able to find/select by first using as data selector the node:...(saved content), followed by selecting the field name of your field from the additional list that is shown after you selected that node:...(saved content).


How do you change what a function in a core module does? I am trying to change certain Drupal behavior. I have traced this behavior back to a function in RDF core module, and would like to change what it does. The function in question is rdf_preprocess_node().

Getting what I want would seem as simple as removing one or two blocks of code from this function. So that's exactly what I tried doing: I copied the function into my theme's template.php, made the changes, renamed the function from rdf_preprocess_node to THEMENAME_rdf_preprocess_node. This did not work, Devel Themer did not list my THEMENAME_rdf_preprocess_node among the preprocess functions used.

I do not understand why this didn't work. Only other option that I know is to try and dig through what the function affected and undo it, which sounds horrible.

What's a practical way to change what a function from another module does?

This is actually pretty easy.

All you have to do is implement your own template_preprocess_node().  Then inside, it update the $variables that the RDF module made.  If you want to update the header additions that it did, then implement a hook_html_head_alter(), and update those elements.

If you do this from your theme, then these will run after the RDF module.  If you do it from a module, then you need to set the weight to be higher than the RDF module.


What's the difference between "Contexts" in CTools/Panels and in Context module? I've been wondering this for a while and always assumed they were different things, but the fact that the Context module uses CTools for its Plugin API kinda confuses me even more...

Can someone please break it down for me please? Thanks!

This is essentially a duplicate of Panels or Context module?. However, Lullabot has a pretty good breakdown on the differences, and at the end of the day, it comes down to a matter of preference (I personally tend to go with Context).


Schema.org itemprop="url" inside anchor object (link) I'm trying to use the preprocess function to change the default outpot of links  to include Schema.org's itemprop="url" inside the anchor object, as well as adding a  to the title of the link. For example:

Example Title

*Just to clarify: I want to do this for any link, not just menu or breadcrumb links.

I have managed to do something similar with images using the following code inside my template.php file, but had no luck with adapting it to links:

function THEME_preprocess_image(&$vars)
{
$vars["attributes"]["itemprop"] = "image";
}

Source can be found here.

I know that Microdata module might be able to handle that with a few modifications, however, I'd rather do everything manually instead.

I have spent hours searching for solutions but couldn't find any..
Any help would be greatly appreciated, thanks!

So after spending some more time on the matter, I finally found the solution and I am posting it here in case anyone is interested.

Simply put the following code in your template.php file, inside your theme folder:

function YOUR-THEME_link($variables) {
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

Hope that helps..
Remember to change 'YOUR-THEME' to your theme's name, and don't forget to clear the cache.


How do I redirect from an existing file? I have the Redirect module installed, but when I add a redirect from an existing file to a new file, the redirect doesn't activate.

I did some digging and found a post suggesting that Drupal can't redirect a file if it already exists, it can only redirect from 404 or pages. Is this true? Is there really no way to redirect from an existing file?

And if it is true, how do I delete the file? There doesn't seem to be a way to delete a file once it is uploaded. The file was originally attached to a content item but that content has since been deleted.

The redirect rules in .htaccess that cause Drupal to be fired up only happen if/when an actual file doesn't exist. For example, if I have a file in my webroot named file.txt, and I go to example.com/file.txt, Drupal will not start, as the file exists. If that file does not exist, Drupal will be fired up, and show a 404 page (unless you have an alias in Drupal for the path /file.txt). You have said the file exists on your system, which means Drupal is not being started up when someone accesses that file, and therefore the redirect module will not work.

As for how to delete the file, you say the content item has been deleted. This should also result in the file being deleted, though it does not appear that it was. I'd do a search through the {file_managed} table in the database to make sure it's not still in there for some reason - maybe the file is still attached to a different piece of content or something. If you're absolutely sure the file does not exist in Drupal anymore, then you can log into your server (ftp, ssh etc) and manually delete the file.


How can I change the display of government field in drupal commerce shipping address? I need to change the display of the order/shipping address of drupal commerce to render the city in a select list instead of writing the city, I need to upload in the database the list of the cites relevant to the governments of Egypt.

Are there a module may help to achieve this? as I don't have a PHP developing experience.

There is not currently a way to do this with the Address Field module. One of the Address Field maintainers has addressed that this in the works for 2.x release. In the meantime, the only way to do this is with a custom module. Someone has already written up an example of how to do this, specifically using Egypt as an example.


Theme Entity Reference output I have a content type called SimpleNewsletter which has an Entity Reference field called field_newsletter_content. Multiple articles are linked with one SimpleNewsletter node.   Under Manage Display of SimpleNewsletter, I can manage which fields to display.

But I have a situation where I only need to display certain fields not all the fields (ex: "Node Title")

In order to theme field_newsletter_content field I have created a new file called field--field_newsletter_content.tpl.php

Is it possible only to display certain fields?

Maybe you could use the teaser for displaying your entityreference nodes. Under Manage display under format for the entity reference field, choose Rendered entity, choose settings and use teaser instead of full mode.

Go the the display settings for the content type that is being referenced and apply your display settings for the teaser display.


How do I avoid mydomain.com/node/1 or mydomain.com/node/4 is used? I am using the Pathauto module for creating user-friendly and SEO-friendly URLs.
Therefore, I do not want and there is no need that the "old URL" like mydomain.com/node/1 or mydomain.com/node/4 is any longer public. So, how do I hide this and make only the path aliases public?

You need to create patterns for pathauto and go back to those nodes and save them, ensuring “generate new alias” is checked off on the node form.


Allowed column type names and element type names for creating custom Field Types I'm creating new Field Types in Drupal 8.
I recently asked which are the type names allowed for the DataDefinition::create() method, receiving a good answer.

Now I figured out that I need at least other two type names:

A column type name to use inside the method schema(...) from the FieldItemBase class.
Another type name to create elements inside the method formElement(...) from the class WidgetBase.

For example this is a snippet of code used to create a new Field Type, defining the schema() method:

public static function schema(FieldStorageDefinitionInterface $fd) {

  $columns = array(

    //

    // Here the column type name is 'varchar'
    'password' => array(
      'description' => 'A plain text password.',
      'type' => 'varchar',
    ),

    //

  );

  $schema = array(
    'columns' => $columns,
    'indexes' => array(),
    'foreign keys' => array(),
  );

  return $schema;
}

In the above code the column type name is 'varchar'.

And this is another snippet, defining the formElement method (always used defining the Field Type):

public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

  //

  // Here the element type name is 'password'
  $element['passwordlist'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Select a password for the user'),
  );

  //

  return $element;
}

In the above code the element type name is 'password'.

What can I use for 'type' in the first case and '#type' in the second case?

All available schema types are listed in the following table:
https://www.drupal.org/node/159605

Here is a list of available types of render elements (first column of the table corresponds to the #type property of the element)
https://api.drupal.org/api/drupal/elements


Capture search term? Is there a function that captures search parameters? Specifically I just need the search term as a variable to compare against certain node taxonomies to add a custom filter on the search template.

I want to capture the search term without going through any Solr API. Is this possible?

Typically searching with the default search box results in a url that looks like this:

/search/node/[search term]

So you can capture that search term (in your custom module presumably) with a line like this:

$path = explode('/', $_GET['q'], 3);

// Make sure the path you got has three components and begins with 'search'
if(count($path) == 3 && $path[0]=="search") {
   // Get component #3 (index starts at 0)
   drupal_set_message("Here are my search terms: " . $path[2]);
}


Use mobile phone number as account ID so users dont have to register? Im making a mobile first site. Is there a way of using a user's mobile phone number so they dont have to register for an account?

Or, if a user creates an account the normal way on a desktop and enters their phone number, is it possible to detect when the visit the site with a phone from that number and log them in?

Thanks

If I get you right you want detect that a user is recuring user? Generaly this can be done with a cookie.

Tecnicaly there is no reason to use a phone number. As far as I know there's no possibility for a web application to get the phonenumber automatically. A solution could be an app as frontend which delegates to the website.


What is the relationship between the node and the node revision table in Drupal 7? I am trying to optimise the code in a Drupal 7 website by replacing node_load functions to retrieve only the title with custom SQL queries.

So far, I have been successful in retrieving the same values. However I just cant seem to get the gist of getting the title from the latest revision of a node or retrieve any other value from the associated fields.

Can anyone point me out regarding the concept of revisions from a table point of view?

I believe this is what you're looking for:

function MYMODULE_get_node_title($nid) {
  // Using Drupal's DB API.
  $query = db_select('node_revision', 'r')
    ->fields('r', array('title'))
    ->addTag('node_access');
  $query->leftJoin('node', 'n', 'n.vid = r.vid');
  $query->condition('n.nid', $nid);
  $title = $query
    ->execute()
    ->fetchField();

  // Using a custom query. This might help you understand better what's the
  // exact relationship. This approach is a bit faster as well.
  $title = db_query("SELECT r.title
                     FROM
                      {node} n,
                      {node_revision} r
                     WHERE
                      n.nid = :nid AND
                      n.vid = r.vid", array(':nid' => $nid))->fetchField();

  return $title;
}

To understand the relationship look at the second approach, using a custom raw query.
vid stands for version ID and if you look at the node table you will see that there is a column named vid.
This is the active version of that node and is the ID you should use to get all field values and other attributes of that piece of content.

Hope this helps.


How to check entity is already created? I have the code that create entity named "Victory" in entity type, my problem is how to prevent user creates the entity with the same name again.

function commerce_services_store_create($data, $flatten_fields) {
  $storeName = $data['store_name'];
  $status = 1;

  $entityType = "fruit_store";       //entity type name Fruit Store
  $entity = entity_create($entityType, array('type' => "store")); //bundle store
  $entityWrapper= entity_metadata_wrapper($entityType,$entity);  // create entity named "Victory"
  $entityWrapper->title->set($storeName);
  $entityWrapper->save();

  $store_id = $entityWrapper->id-> value();
  if($store_id != null){
    $reply= (array('status' => $status,'result' =>"Your store name ". $storeName. " Store id is ". $store_id));
  }else{
    $status = 0;
    $result = "Can't create store.";
    $reply = $reply= array('status' => $status,'result' => $result);
  }

  return $reply;

}

Just like validating the user email in any system you check if its already exists or not, in your case we need to check that we have no entity with the same attribute value exists:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'Fruit_Store')
  ->entityCondition('bundle', 'store')
  // this is a condition for the entity field values
  ->fieldCondition('field_title', 'value', 'spotlight', '=');

$result = $query->execute();

if (!empty($result['Fruit_Store'])) {
  // entity already exsits.
}
else{
  // add new entity
}

you can find more information about EntityFieldQuery in this page:

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


Act on date field value I have a CT with a  Date (Unix timestamp) field implemented. It represents the start date of an event.

One simply question: Is there a way to compare somehow, this value with the current date() and when it matches (equal) the current date() to trigger an action? It must be equal, other way will trigger an action many times.

Up until now I've tried in hook_node_view to implement the whole logic, no luck.

This hook offers no accuracy on what someone wants to do.

Cron job's aren't suitable, cron isn't running every minute or second.

The other thing I've tried was Rules, but things become complicated, thought is the best way to follow!?
Any suggestions?

Step 1 - Use VBO and Rules

You could process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list of nodes that you want to be processed (ie those for which the date field matches your criteria).
Add a loop to perform a Rules Action, for each node contained in your Views results.

For any node related data you may need in your Rules Actions, make sure that they are contained in the Views result.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

Step 2 - Trigger the rule

Use the "Rules Once per Day" module to actually get your rule triggered. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt the rule from Step 1 to run ... once a day, on any day.


How to add an Ajax call to an element that already has callback set? I want to add an ajax callback to a form element inside a form_alter, but it already has 2 callbacks assigned to it.
When I review:
$form['payment_information']['payment_method']['#ajax']['callback']

it has 2 callbacks already assigned to it.
If I do this:
$form['payment_information']['payment_method']['#ajax'] = [
  'callback' => '_sia_general_get_fee',
  'event' => 'click',
];

My callback is hit on click; but of course, the other 2 callbacks are wiped out and do not work.
If I add something like this:
$form['payment_information']['payment_method']['#ajax']['callback'][] = '_sia_general_get_fee';

then the other callbacks are called; but mine is not - I suspect since I no longer of an event defined.
I am also not sure how the other ajax calls work when they have no events defined for them.
Is there any way to do this?

I doubt that the array you've found really assigns 2 callbacks. It's rather an array defining a class and a method for a single callback:
'callback' => ['Drupal\foo\BarClass', 'ajaxCallback']

In fact, you can only set one callback in an #ajax element. If you want to override a callback you have to include the overridden callback in your code:
Drupal\foo\BarClass::ajaxCallback($form, $form_state)

and add your ajax commands to the returned ajax response (or in case the original method returns a render array you can either add your own content to the array or transform the render array into an ajax command which you return with your own commands in an ajax response).
Caveat: This only works if the overridden callback is static. If it runs in an instantiated object you have to override the class method itself.


Fixed number of digits from Token module random number I want to use the Token module random number generator, but it says use [random:number] to generate "A random number from 0 to 2147483647".

How can I change this and get fixed number of digits? For example, I need a 4 digits in each generated number (1000 to 9999). Or only 3 digits in each number (from 001 to 100).

You could use modular arithmetic.

$token_random; // This is the value returned from the Token module
$my_random = ($token_random % 9999);

Or if you need the 3 digit value:

$my_random = ($token_random % 100);


Search has disappeared on Drupal Commerce Kickstart site When I first installed Drupal Commerce Kickstart it had a search enabled in the 'User Bar First' region. Now for some reason it has disappeared and I can't find it anywhere. I have tried searching the blocks and checking the search settings. What has happened to it?

The block that you need is actually called 'Exposed form: display_products-page'. Since it isn't immediately obvious what this is for I must have changed the block position to 'none'. Since it doesn't have search in the block name I didn't realize it was connected to search. Simply looking at the blocks on a new Kickstart Commerce install made it obvious what I was needed. Just change the position of the 'Exposed form: display_products-page' block to 'User Bar First'.


When sending a Drupal database to a developer, how can I remove users' personal info (e-mail addresses, passwords)? How can I remove users' e-mail addresses and passwords when sending a database to a developer (for investigating a bug, etc.)?  The e-mail addresses and passwords are irrelevant for the bug and, although I have not consulted with a lawyer, this seems to be a general safe practice.

Drush supports an sql-sanitize function:

    $ drush help sql-sanitize Run sanitization operations on the current database.

    Options:

    --db-url=<mysql://root:pass@127.0.0.1/db  A Drupal 6 style database URL.
    Only required for initial install - not re-install.

    --sanitize-email        The pattern for test email addresses
                        in the sanitization operation, or
                        "no" to keep email addresses
                        unchanged.  May contain replacement
                        patterns %uid, %mail or %name.
                        Default is "user+%uid@localhost".

--sanitize-password     The password to assign to all
                        accounts in the sanitization
                        operation, or "no" to keep passwords
                        unchanged.  Default is "password".

    Aliases: sqlsan

You could always setup a clone of your live site using drush archive-dump or drush sql-sync then run sql-sanitize on that cloned sites db and get everything cleaned. I believe sql-sanitize provides a hook so you can sanitize custom drupal data you deem sensitive beyond the scope of the default username and password.


Problem using tokens when mailing to site owner after an order I'm new to drupal

What I want to do:

After a user places an order I want to send an email to the site owner with information of the order. These 2 tokens (that are standard) are working:

[current-user:name]
[message:message-commerce-order:order-number]

I navigate to structure > messages > (here I made a new message) commerce order: order confirmation to admin > edit

path = admin/structure/messages/manage/commerce_order_order_confirmation_to_admin

@ the end of this page I can select tokens

My problem:

When I select a token at the bottom of the edit page and I paste it in my email body, and I actually receive the email, the variable of the token isn't shown. It only gives me the token itself.

For example the token for price doesn't work

[message:message-commerce-line-item:commerce-product:commerce_price]

What am I doing wrong, am I missing some steps?

Do I need to add a rule to the fields of the checkout order steps? But when I choose for shipment it's with radio buttons, so not exactly a field.

I encountered similar issues in the Rules email body. Standard input filters were being applied to the field. You may need to install the Token Filter module and configure input formats accordingly.


Importing Bootstrap CDN-mediated styles into the Sub-theme's Style.css I've opened a fresh Bootstrap sub-theme. This sub-theme is empty of any styles. What is the right way to import the CDN-mediated style sheets into the (now-empty) Style.css of the sub-theme?

It's a long story why I don't want to use the Bootstrap CDN in that particular case but I really just want everything to be local.

How could I import the basic Bootstrap Stylesheets into my Sub-theme's Style.css file and finally use everything local?

Thanks,

You can use Bootstrap Library module to do that. quoting from the project page:

  This module is fully compatible with the Bootstrap Theme. If you wish,
  use it as an alterative to the CDN loading.


get path of an uploaded file This is my form to upload a photo

 $form['Background_image'] = array(
 '#type' => 'managed_file',
 '#title' => t('Choose a background image'),
 '#description' => t('Click "Browse..." to select an image to upload.'),
 '#required' => TRUE,
 '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
'#upload_location' => 'public://backgroundimage/',
 '#default_value' => $this->options['Background_image'],

);

I tried this function that get the current uploaded image and return its path, but still not working: what is missing:

function image_path()
  {
   $f = file_load($this->options['Background_image']);
  //this too is not working:
  //$f = file_load($form_state['values']['Background_image']);
   $url_image = file_create_url($f->uri);
   print_r($url_image);
   return ($url_image);
  }

In your submit handler of your form, you should be able to retrieve the fid of the uploaded file / image. By using this fid, you can load the file and work with that object.

function YOUR_MODULE_FORM_NAME_submit($form, &$form_state)
{
    $fid = $form_state['values']['Background_image'];

    if ($fid !== 0) {
        // Retrieve image URL
        $image_url = YOUR_MODULE_get_file_url(file_load($fid));
    }
}

function YOUR_MODULE_get_file_url($file)
{
    if (!$file) {
        // File not found
        return false;
    }

    // Return URL from a give file URI
    return file_create_url($file->uri);
}


Is there a way to check user permissions in javascript? Is there a way to check user permissions in javascript? I have a segment of code that I only want visible if the user has the proper permissions, and I think it would be easiest way to check the permissions, and then just set the segment to display: none; if the user doesn't have the right permissions.

It is not secure to only rely on Javacript. It is better to separate that .js function which needs permission to execute from other codes then put in a file and load that .js file from your hook_preprocess_page if the user has permission (or some role). I implement this idea with user roles, you may use another strategy for checking the permission.

function THEME_preprocess_page(&$var){
      global $user;
      if(in_array("SOME_ROLE_NAME_WITH_ACCESS_TO_JS_FUNCTION",$user->roles))
            drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/Your_js.js');

}

in your theme directory, I supposed you placed your .js files in /js directory. So you should create Your_js.js file in that directory and put that function inside it. If the user has appropriate role, that file with that function in it will be loaded and you can use it later, otherwise it won't.