Importing Feeds into an entity? I am trying to create a store using Ubercart. like most other things on my site, I have a large amount of data stored on a csv file that I downloaded out of PHPmyAdmin from another site (the clients original site), which I need to upload into my new site. I am trying to upload them as products, but the problem is that things like the "List Price", the 'cost", the "sell price", and "SKU" number are entities, and those fields don't show up in the feeds importer. is there a way to import feeds into an entity as well as a field?

In Drupal 7 you can acheve this using the Commerce feeds module.
Also check this tutorial.

I couldn't find anything similar for Ubercart; maybe back-porting the Commerce feeds module is the only way to go.


Unable to loop through all nodes in a content type and load them without hitting memory limits I'm having an issue in Drupal 8 where I am unable to loop through a large amount of nodes without hitting memory limits. The products content type in the below example has ~6000 nodes. The memory limit is currently set to 512M and is not changeable.

I've tried unsetting the $node variable and clearing the entity cache  in the loop without any success.

$query = \Drupal::entityQuery('node')
         ->condition('type', 'product')
         ->execute();
$nids = array_keys($query);

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    print $node->title->value;
}

The goal is to be able to iterate through all nodes of a content type without hitting memory limits.

I was able to get this to work by using the following command pulled from the deprecated node_load() function.

\Drupal::entityManager()->getStorage('node')->resetCache(array('NID'));

The fixed script would be:

$query = \Drupal::entityQuery('node')
         ->condition('type', 'product')
         ->execute();
$nids = array_keys($query);

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    print $node->title->value;
    \Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
}


Entity Reference field in custom line item missing multiple field values I added an entity reference field to a line item within commerce.

Target is user, entity selection is done through a custom view. The view populates the values of a date field within the actual user entity. The preview works as desired, the field has 3 values and those 3 get shown in the views preview.

However looking at the add to cart form it always shows just the last value of this multiple value field. Why are not shown all 3 values in the add to cart form?

Line-item entity reference fields being displayed as views is most likely not supported, or not very well supported, because it's a very edge-case situation. Nothing appears to be in the issue queue regarding this limitation, so you might make a feature request and see where it goes.


Drupal Migration and 404 Errors I've set up a Drupal 7 site locally and have ftp'd the site over to my ISP's server which is a linux box running PHP and MySQL.

I've never successfully logged into the remote site before and I have locked myself out as I got the admin password wrong.  When I go http://www.example.com/?q=user and click on request New Password then I get this error:

Not Found

The requested URL /user/password was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

One thing I've been confused about and that is the .htaccess file.  I never had one locally on my Mac and I did not need it (I know it is hidden) - so I downloaded one and deployed it to the web site but then I got 500 errors, it made it worse.

I've since deleted that file and at least I get some content - but not very much - just the front page.  I overrode the themes name in settings.php as I have user access errors when using a new template, if I get passed this bit I can probably fix that.  I changed it back to one of the default themes and that allowed me to get some content and not the 'white screen of death'

Advice welcome!

To get site working properly:  It seems like .htaccess issue. You do need the .htaccess file. It should be in the document root folder and secured so that any host account can read it. Out of the box Drupal has this file.

To recover Drupal User=1 password: If you are lucky, your ISP may have drush installed globally on this server. SSH to the server and try "drush uli" command. If not, you can try installing drush on your local machine - the pain will be well worth it if you plan to continue working on Drupal. You can use "drush uli" command on your local machine, login with the on-time login link given and change the admin password. They upload the database back to your ISP.


Views accordion grouping on taxonomy I have a content type: products. This content type use its own taxonomy (type1, Type2, Type3).

My content has 2 fields: Title and baseline (and more, but I don't want to use them on this view).

What I want:

Display a page with my products listed by taxonomy

Type1
   [title Product 1] [baseline product 1]
   [title Product 2] [baseline product 2]
   [title Product 3] [baseline product 3]
Type2
   [title Product 4] [baseline product 4]
   [title Product 5] [baseline product 5]
Type3
   [title Product 6] [baseline product 6]

I can do this easily, But I want more: I want to use views accordion module to display that. And I want the types being the header tabs.

The problem is: whatever I try, I get the same problem:

the module makes each node a tab

Type1
<title Product 1 tab >
   [title Product 1] [baseline product 1]
<title Product 2 tab >
<title Product 3 tab >
Type2
<title Product 4 tab >
<title Product 5 tab >
Type3
<title Product 6 tab >

In screenshot: (Don't pay attention of the text, it's some creepy test content):

My objective:

From your question, I'm assuming that you've already created view and set everything.

You just need to do some Format settings for Views Accordion in your View.

Here are the steps to make your grouping field as the "header" or "trigger" of the accordion action.

Go to  Format: Views Accordion Settings and select Grouping field.
Check "Use the group header as the Accordion header"

I've tested it myself. It works as you expected.


Problems with notice I'm new in Drupal. I had to migrate a page from a client to another server. The page work well on a development test but not anymore.

I have these errors:

Notice: Undefined index: highlighted en include() (línea 126 de /home/portal/public_html/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_first en include() (línea 138 de /home/portal/public_html/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_second en include() (línea 144 de /home/portal/public_html/modules/system/page.tpl.php).
Notice: Undefined index: hotel en drupal_theme_initialize() (línea 100 de /home/portal/public_html/includes/theme.inc).
Notice: Trying to get property of non-object en _drupal_theme_initialize() (línea 146 de /home/portal/public_html/includes/theme.inc).
Notice: Trying to get property of non-object en _theme_load_registry() (línea 335 de /home/portal/public_html/includes/theme.inc).
Notice: Undefined index: hotel en theme_get_setting() (línea 1431 de /home/portal/public_html/includes/theme.inc).
Notice: Trying to get property of non-object en theme_get_setting() (línea 1478 de /home/portal/public_html/includes/theme.inc).

The link to the page is: http://www.portaldelcuadrado.com.ar/
What can i do?

Thanks

Is the theme on the test site and the live site the same theme with the same regions defined. The drupal theme() function is complaining that regions are not defined which the body (node) content is trying to be placed in.


How do I add classes to an img tag inside the node? I want to add classes to the image that is getting displayed only inside the node. I want to do it in the Drupal way.

Here is the img tag HTML.

I want to add the classes like the below

I just want to add "medium img-polaroid" like class to the img field.

you could preprocess the content in the template, but it would be a little difficult, or you could do it via attachBehaviors in jQuery.

If you mind the jQuery way you can add this script:

(function($) {
  Drupal.behaviors.classadd = {
    attach: function(){
      $('.node img').addClass('class1 class2 class3');
    }
  }
}

This way you can easily add classes to your node with .node class. even when you load content dinamicly via ajax. the attachBehavior is a useful Drupal technic to attach actions to your content, and it's widely implemented in all the Drupal framework.


positioning sticky field using hook_form_alter in drupal 7 I'm trying to remove the sticky option from the option bar and adding it to the user form.

function vacancies_form_vacature_node_form_alter(&$form, &$form_state, $form_id) {
// remove sticky field from default (option) location
unset($form['options']['sticky']);

//create new sticky field
$form['sticky'] = array (
    '#type' => 'checkbox',
    '#title' => 'Top vacature',
    '#default_value' => $form['#node']->sticky,
    '#weight' => -1,
);

dsm($form);

}

Weight of other elements go from 1 to 14 so -1 should put this form element on top.
But with the code above it shows up at the end of the form.

How do I put the sticky button in the middle of my form?

This code:

$form['sticky'] = array (
    '#type' => 'checkbox',
    '#title' => 'Top vacature',
    '#default_value' => $form['#node']->sticky,
    '#weight' => -100,
);

works for me just fine. I don't know what's happening in your node edit form, but for me title field had #weight equal to -5, so obviously this item with weight -1 wouldn't show up on top.


Dynamic view title from node title How to set a view title from page title dynamically, as if the page node title is About the Company I want the corresponding view title to be the same as node title.

any suggestions

Hope this will help  you.

In Drupal 7 you can use VIEWS CONTEXTUAL FILTER for your requirement

Steps

Add VIEWS contextual filter for node ID

 item
Contextual filter settings for node ID

Provide the default argument from the URL
Also override the TITLE and the BREADCRUMB

Open browser and type Base_url/view_path/NODE_ID you can see both the TITLE and the BREADCRUMB will be changed based on the NODE ID.


Set weight for JavaScript files loaded via theme.libraries.yml? Im loading a JavaScript file via my theme's libraries.yml file. How can I change the weight of this file?

I need the file to load before the core and module's JavaScript files. If I set header: true then this happens, but I still want to load the file at the bottom of the page.

You need to try this with in libraries.yml file

js:
    js/foo.js:
    js/bar.js: { weight: N }


How do I re-run updates (change module schema version)? I'm working on a module, and I changed a couple field types in the schema. I didn't take a backup before testing it and messed up the DB (it's just a dev site). Anyway, I reinstalled everything, and the schema version is set to that of the highest update. However, I actually do need to run the update; a View I have wouldn't install if I had the updated schema in the module code, so I figured this would be a good way to test that update.

How do I reset the schema version of my module to a particular version? In Drupal 7, I would have done this:

drush sqlq "UPDATE system SET schema_version=8102 WHERE name='flllpdf' AND type='module'"

While accessing state directly works, you can also just use the API: drupal_set_installed_schema_version(). Which actually exists unchanged at least since 4.7, as visible on the linked documentation page. Probably one of the few API functions that existed for so long ;)

To set it from drush:

drush ev "drupal_set_installed_schema_version('fillpdf', 8012)"

Note: In Drupal 7 you need to add extra include 'includes/install.inc';.


How to output content to a page I have a form on my page that is being submitted. I am implementing hook_form_submit and within that function I have a search algorithm that processes the entered data and returns a result. I would like to display that result on the page underneath the search box. For debugging purposes so far I've simply used drupal_set_message() but this is no permanent solution.
I am new to Drupal module development so I am unsure how to go about this.

Any help would be greatly appreciated!

I'm afraid I posted to quickly, my apologies.

After re-reading your post, I would advise you to work with an AJAX callback that returns te search results.

First of all you need to create a form api implementation that holds the ajax callback

$form['search']['client'] = array(
'#type' => 'textfield',
'#title' => t('Search Client'),
'#description' => t('Search for an existing client'),
'#autocomplete_path' => 'searchclient/autocomplete',
);

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

Then you need to make sure that 'searchclient/autocomplete' is registered as a valid menu path (hook_menu) like this for example:

/**
* @return array
* Implements hook_menu().
*/
function your_project_menu() {
$items = array();

$items['searchclient/autocomplete'] = array(
  'title' => t('AutoComp Menu'),
  'page callback' => 'your_project_search_client',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

  return $items;
}

After this you need to create your page callback function that will actually return the content to the page:

function your_project_search_client($string) {

  $matches = array();

  // do what you want here

  drupal_json_output($matches);
  exit;
}

As some extra info:

-> $string is the entered search text in the form element
-> $matches holds the data to be returned to the screen.

More information on ajax callbacks can be found here:

https://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7
https://www.drupal.org/node/2046693


Error consolidation/annotated-command Trying to install Drush using Composer, i get an error concerning consolidation/annotated-command. What does it mean "locked at 2.0.3" and "requires 2.8.1"?

This is the error:

Your requirements could not be resolved to an installable set of packages.

  Problem 1

- Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
- Conclusion: remove consolidation/annotated-command 2.0.3
- Conclusion: don't install consolidation/annotated-command 2.0.3
- drush/drush dev-master requires consolidation/annotated-command ^2.8.1 -> satisfiable by consolidation/annotated-command[2.8.1, 2.8.2].
- Can only install one of: consolidation/annotated-command[2.8.1, 2.0.3].
- Can only install one of: consolidation/annotated-command[2.8.2, 2.0.3].
- Installation request for consolidation/annotated-command (locked at 2.0.3) -> satisfiable by consolidation/annotated-command[2.0.3].

Installation failed, reverting ./composer.json to its original content.

I get this error after changing the minimum version of drush/drush to ~9.0 in my composer.json and running composer update drush/drush afterwards.

I solved it by just executing composer require drush/drush:~9.0 which lead to the error message drush/drush 9.5.x-dev requires symfony/config ^3.4, so I had to execute composer require symfony/config:^3.4 before composer require drush/drush:~9.0 could be finished successful.

Don't know if this is the only way or best practice to solve such a dependency conflict but in short this worked for me:

composer require symfony/config:^3.4
composer require drush/drush:~9.0


Enabling blocks in an install profile I'm creating an install profile and I just can't seem to get my blocks enabled.

When I check the database after using the code below in my install function it puts the records in the block table, but the status is set to 0 and the region detail isn't inserted.

I'm using code from other install profiles and I can't see why mine isn't working - works fine on things like the erecruiter profile, the omega profile, but whenever I try it never works! Anyone experienced similar?

// Enable some standard blocks.
$default_theme = 'mytheme';
$admin_theme = 'seven';
$values = array(
array(
  'module' => 'system',
  'delta' => 'main',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'content',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'node',
  'delta' => 'recent',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 10,
  'region' => 'dashboard_main',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'user',
  'delta' => 'login',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'sidebar_first',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'navigation',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'sidebar_first',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'powered-by',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 10,
  'region' => 'footer',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'help',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'help',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'main',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'content',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'help',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'help',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'user',
  'delta' => 'login',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 10,
  'region' => 'content',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'user',
  'delta' => 'new',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'dashboard_sidebar',
  'pages' => '',
  'cache' => -1,
 ),
);
$query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
foreach ($values as $record) {
  $query->values($record);
}
$query->execute();

Are you using the Profiler library to drive your installation profile? If so, there's a "feature" in the 7.x-2.0-beta1 release that causes this behavior. In short, there's some legacy code that disables all blocks in the database upon installation.

If you're using the Profiler module, upgrade to the latest development snapshot to get the fix.


How to setup module install (sub-folder) paths from the *very beginning* (contrib, custom, features etc) - i.e. not move them after the install I've seen plenty of guides saying why it's a good thing to organise modules in different folders... (and I'd agree) e.g.:

Where to put custom modules?
https://drupal.org/documentation/install/modules-themes/modules-7
http://befused.com/drupal/module-directory-structure (particularly like this guide, more folders and options to choose from)

...and how to move the modules to the new place(s) after installation

How to move installed modules from /sites/all/modules/* to /sites/all/contrib/modules/*
https://stackoverflow.com/questions/2654720/drupal-moving-module-folder
How to reorganize drupal sites/all/modules structure without symbolic links?

... but these haven't worked for me, perhaps I need to try again. My site broke, even after trying the registry rebuild and clear cache many times.

So my question is this: How can I run the installation of Drupal to set up the modules to be installed in different folders (e.g. like in examples http://befused.com/drupal/module-directory-structure )?

There doesn't seem to be anything out there if you want your module paths (sub-folders) structured in a certain way, right from the beginning. NOT after the fact.

I want the folders to be set up in the first place, right from the beginning. So example, whenever I use drush to download a contrib module, the module is placed in the contrib sub-folder: sites/all/modules/contrib for example.

Some other references:

Can Drupal be configured to find modules in other locations? - this suggests Drupal can just discover the location, I'm not so keen on this, I'd rather Drupal always know where the modules are rather than having to discover where they are.
Is it possible to change the path of modules/themes installed using an installation profile? - I just want to use the plain vanilla Drupal 7 core install. If I was going to use this option, what would be the minimum I would need to provide in a setup to have module sub-folders?

Actually it seems like all you need to do is just create a folder called contrib in /sites/all/modules

when I issued drush dl views (at the docroot/install top level root of my site), drush put the views module in the contrib folder

as for features - you specify where you want the module to go when you (re)create the Feature (in the Feature section of the Drupal config)

as for custom - I'm hoping that Drupal will discover custom modules here - but is discovering, rather than a setting determining the path, a good thing?

Thought I'd still ask the question even after I'd found an answer, didn't want to waste the effort in making the question - hope someone else finds it useful.

Please provide your own answer or comment to enhance what I found.


Show Block view of Restricted Content Type I have a content type of Events which i make restricted for anonymous users via content_access module. But on the home page there is a block view of most recent Events. I don't want that block view to be hidden from anonymous users. I have selected all roles in the view settings so that i should show but i think because of contect_access restrictions on Event Content Type its not displyaing the block.

How can i show that block ?

Thanks

In the Views UI there is a setting under 'Advanced' called 'Query Settings'. Click on 'Settings' next to it, then in the next popup make sure to select 'Disable SQL rewriting'.

  Disabling SQL rewriting will disable node_access checks as well as
  other modules that implement hook_query_alter().


How to abort the ajax request and redirect in the ajax callback of form element I want to redirect the page in the ajax callback function, and nothing (like "header", "drupal_goto" etc.) works for redirect in the ajax callback function.

If you've got ctools installed (nearly all Drupal sites do), you can make use of ctools_ajax_command_redirect() in your AJAX callback, e.g.

ctools_include('ajax');
$commands[] = ctools_ajax_command_redirect('path/to/redirect');
return array('#type' => 'ajax', '#commands' => $commands);


Mobile navigation works on desktop resize but not on mobile devices I'm using the mobile navigation module for a responsive menu, and it works perfect if I resize the browser window on my desktop, but it won't work on actual mobile devices (tested on iPhone and Galaxy Note 2).  I've used the module before and never had any issues, and I'm using the same configuration, as far as I can tell. I can't figure out why it's not working.

This is the site I'm working on, and here's a screenshot of the problem on the Note 2. I recently upgraded my server from PHP 5.2 to 5.3, but I don't think that could be causing this issue (plus I needed to upgrade for a different module).

Other than that I really have no clue, so I'd appreciate your help.

There is a jQuery error happening on your webpage.

You need to fix that either by trying var $ = jQuery.noconflit();
OR
Update the version of jQuery to 1.7, don't upgrade to version higher than 1.7 since jQuery 'on' function will not work.

Thank,
Vineeth


How reload form values with ajax So I'm trying to do something really simple but haven't manage to know how to do it with the Ajax API form from drupal 7. I have an administrative GUI with a select input type, I set the #ajax property with the callback but I don't want to replace anything just need to reload/refresh the values for specific inputs most of them textfield, when the selection change.

Any insight on how to do this? Can it be done with the Ajax Drupal 7 API?

Thanks....

You should put a wrapper around the fields of which you want to reload/refresh (basically replace) and in the call back return the either the form values in an array or the wrapper.

This basically means that on the event specified in the callback, eg change the whole wrapper div is swapped out and replaced with a new one built by the php in your form.


Where is a UI-configured Views display definition read from? General question: In Views 3, on Drupal 7, when a View display in configured using Views UI, what is the location where the configuration is 'read' and applied when...:

...creating a query to generate a page?
...loading its Views UI page (I believe this is the table views_display)?

Background / why asking: I've encountered a very strange problem where (despite repeatedly clearing all caches including Views cache and even disabling Views caching in Views advanced settings), the output a view generates in situ in a panel / block on the page doesn't match the rules shown for it on editting it in Views UI.

Edit: Actually, looks like they are both coming from the same place but the two displays got merged and became non-overridden in a strange way. I'll keep this open as I'd like to know for sure where these are stored in the DB for future reference anyway.

It's a dev environment with no memcache / memcached / boost etc - no additional layers of caching.

There's one existing question where someone finds Views UI somehow 'loses' the override settings for a views display, but it's not related to my case: there's nothing on my general question, the cause doesn't apply in my case, and none of the suggestions there help. There's also a question which includes my general question on drupal.org but none of the replies answer my question.

The table {views_view} has the list of views.  The more or less matches up with what is on admin/structure/views, except for views created by modules.

The table {views_display} has displays for each view, keyed to {views_view} with the vid column.  The id column is the machine name from admin/structure/views/view/foo/edit.  There is one row per display.  The display_options column has a serialized version settings from the edit form, and it more or less matches up with the display section when you export a view from admin/structure/views/view/foo/export.  I am also pretty sure that the actual query is essentially built up from the same column.

In my years of using a sledgehammer to make Drupal do what my clients need, I don't recall ever poking through the views tables for anything.  I will periodically look at an export to see what is going on with a view, and export/edit/import views to adjust things, though.


Unable to use Node::load Fatal error: Class 'EntityInterface' not found in /cptestd8/modules/custom/custom-autofill-reference/custom_autofill_reference.module on line 13

use Drupal\node\Entity\Node;
    function custom_autofill_reference_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

      drupal_set_message($form_id);

      if($form_id =='node_monitoring_report_form'){
        $field_school_information =  \Drupal::request()->query->get('field_school_information');
        $node_details = Node::load($field_school_information);
        $node = $node_details->field_FIELD_NAME->value;
        $form['field_school_information']['widget'][0]['target_id']['#default_value']=  $node;

      }
    }

While trying to load the node I get error as shown below:

  Fatal error: Class 'EntityInterface' not found in
  /modules/custom/custom-autofill-reference/custom_autofill_reference.module
  on line 13

And line 13 is:

$form['field_school_information']['widget'][0]['target_id']['#default_value'] = $node;

Drupal Version: 8.6.x

use Drupal\node\Entity\Node;

function custom_autofill_reference_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id =='node_monitoring_report_form'){
    $field_school_information =  \Drupal::request()->query->get('field_school_information');
    $node_details = \Drupal\node\Entity\Node::load($field_school_information);
    $form['field_school_information']['widget'][0]['target_id']['#default_value'] = $node_details;
  }

}

Above code worked finally and it was showing error as I did not clear the cache while trying to check it out.


Rebuild images from image style I have an image style in Drupal 7. I attached several images to a nodes and display the images based on this style. I then changed the effects on this image style but the existing images are not being recreated with the new image style effects. They show with the old image style effects.

If I attach new images, they use the new effects. Deleting an existing image and re-uploading causes the image to use the old effects.

The manual (incorrectly I assume) states that just saving an image style causes a rebuild:
http://drupal.org/documentation/modules/image

I have cleared the cached.

How do I force a rebuild?

Clearing cache, won't flush image styles: http://drupal.org/node/997332

You could:

delete them manually
use image_style_flush
use the command line: rm -rf sites/default/files/styles
use drush: drush image-flush


How can I prevent a custom block from rewriting HTML? I have a self-contained widget written by a third party that consists of HTML, JS, and CSS. I've dumped it into a custom block with Full HTML (and verified the Full HTML settings are loose enough that they shouldn't conflict with the markup). Also, I'm using CKEditor. When I save the custom block, it turns
 into
&nbsp;
 so that the widget doesn't even get an opportunity to render.
Is there a workaround for this? Is my only alternative to create a custom module?

Try going to Admin menu > Configuration > Content authoring > Text formats and editors then edit yours (E.g. "basic html")
Down towards the bottom you should see an option: Correct faulty and chopped off HTML - uncheck that option and save.
Not sure why a widget would expect an un-closed <div /> tag though.


Email filter in default admin users/people search form I would like an additional filter (email-text input) in the drupal7 default admin users/people search form. Is there any module as I can't find one for drupal7?
I found that another way is the use of views but I want the default search form with additional input filter.

Looks like this module achieve what you need.


How to attach Dropzone.js uploads to a form element I'm integrating dropzone.js into my form, but I have an issue regarding my file uploads.  I have my dropzone set up, and file uploads are in the $_FILES array.  I want to call file_save_upload to handle the file management, but per the code:

// Make sure there's an upload to process.
if (empty($_FILES['files']['name'][$form_field_name])) {
    return NULL;
}

it looks for the files under $_FILES['files']['name'].  The dropzone.js uploads my files to $_FILES['file']['file'].

I haven't seen an easy way to specify an input element for dropzone.js to upload to.  On the Form API side, I could just mimic the functionality of file_save_upload(), but all the code already exists and it does a lot, and I'd hate to duplicate it.

Maybe I can copy the $_FILES['file']['file'] array over to $_FILES['files'], then call file_save_upload()?  I'm trying to make sure there is a better way to do it before I start hacking.

I now have the files under $_FILES['files'].

My JS code:

(function ($) {

    Drupal.behaviors.dz = {
        attach: function (context, settings) {
            Dropzone.options.picsForm = {
                paramName: "files",
                autoProcessQueue: false,
                uploadMultiple: true,
                parallelUploads: 100,
                maxFiles: 100,

                init: function() {
                    var dz = this;
                    // #edit-next is the id of my submit button
                    this.element.querySelector("#edit-next").addEventListener("click", function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        dz.processQueue();
                    });

                }
            };

        }
      }

})(jQuery);

The '$form_field_name' parameter is a numeric index now, so I just get the count of the $_FILES['names'] array and call file_save_upload() for each one.


Is there a module or functionality to export/import roles and permissions? I have been searching for a module or functionality to export/import roles and permission from one installation to another, but could not find it. Is there such a functionality or module for Drupal 7?


Testing installation profile with custom tasks For a large project, we are using a code driven development workflow. We are using a custom installation profile to install and configure the contrib and custom modules used on the project. The ensure correctness of this profile, we need to test it like any other module.

Currently, we use a SimpleTest test case that looks like this which worked good so far.

class FooTestCase extends DrupalWebTestCase {

  protected $admin_user = null;

  public function getInfo() {
    return array(
      'name' => 'Foo Profile',
      'description' => 'Ensure that the Foo profile configure the site.',
      'group' => 'Foo',
    );
  }

  public function setUp() {
    $this->profile = 'foo';
    parent::setUp();
  }

  //Test methods ...
}

The site has to be multilingual, so in order to install and enable all the required language, I added a custom profile task using hook_install_tasks. The task works fine when executed from the browser. But it is not executed when DrupalWebTestCase::setUp` is run. So we are unable to test its effect to ensure they are not lost whatever the refactoring our profile will go through in the future.

Since languages installation require translations loading, the task itself use batch processing.

I'm looking for both a way to have this particular task executed in FooTestCase:setUp and more generally to have all the (non interactive tasks) in my profile executed.

For reference, here is the code for the task

function foo_install_tasks($install_state) {
  return array(on
    'foo_install_import_locales' => array(
      'display_name' => 'Install additional languages',
      'display' => TRUE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    )
  );
}

function foo_install_import_locales(&$install_state) {
  include_once DRUPAL_ROOT . '/includes/locale.inc';
  include_once DRUPAL_ROOT . '/includes/iso.inc';
  $batch = array();
  $predefined = _locale_get_predefined_list();
  foreach (array('nl', 'de') as $install_locale) {
    if (!isset($predefined[$install_locale])) {
      // Drupal does not know about this language, so we prefill its values with
      // our best guess. The user will be able to edit afterwards.
      locale_add_language($install_locale, $install_locale, $install_locale, LANGUAGE_LTR, '', '', TRUE, FALSE);
    }
    else {
      // A known predefined language, details will be filled in properly.
      locale_add_language($install_locale, NULL, NULL, NULL, '', '', TRUE, FALSE);
    }

    // Collect files to import for this language.
    $batch = array_merge($batch, locale_batch_by_language($install_locale, NULL));

  }
  if (!empty($batch)) {
      // Remember components we cover in this batch set.
      variable_set('foo_install_import_locales', $batch['#components']);
      return $batch;
  }
}

I typically find it best to leave your installation profile as bare bones as possible, and put tasks like this into hook_enable of a site specific module.  Similarly, any updates that need to be made should be put into hook_update_N functions in the same module, while updating the hook_enable implementation.

This makes it much simpler to test and has the added benefit of keeping all of your setup and updates in one place.


How to use Views Rules? I've looked here: https://www.drupal.org/project/views_rules but can't get past 2.2 Add a "Rules" display.

I don't know what that means. I've installed Views Rules but can't find any Rules option anywhere in my Views.

First of all: thanks for mentioning the Views Rules module. I didn't know it, but I'm sure it will be handy in the future.

It seems that you're not quite familiar with the Views module. While creating or editing your View, you should click the "add" button at the top, right underneath "Displays". When you select "Rules", a new display is added and there appears a little button with the text "Rules" in it. (I've already added one in the picture underneath.)

Afterwards, configure the Rules' settings by clicking "edit the field info" and choose the desired data types.

Finally, select the View you would like to use in your Rule. In my case, the View is called "Test".


Programmatically delete CCK field value I have content type with Photos ImageField. I need to create some moderation view to show all photos and "delete" link to delete appropriate photo. How can I programmatically delete value from CCK field (in general not only ImageField but any field type)?

You will need to check the ImageField array to see what needs to be changed but for D6 but it   should be something like the below:

$node = node_load($nid);
$node->field_photo[0]['value'] = NULL;
node_save($node);

Just change the field name to what you are using and change the $nid to the node id #.


Why is my theme table row array not being displayed? I have the below code and I know both the $headers and the $html have values stored in them as i can echo them out.
I can also set the 'header' => in the theme function to be either $header or $html and it will display the data.

However when I add in 'rows' =>, no data is displayed.

Can anyone see why?

function emnies_ad_hoc_query_exporter_get_html_formatted_ad_hoc_query_responses($obj_response) {
  $str_current_country = '';

  foreach ($obj_response as $response) {
    if ($str_current_country != $response->country) {
      $str_current_country = $response->country;
      $html = emnies_ad_hoc_query_exporter_get_country_row($str_current_country, $obj_response);
    }
  }
  $header = array('Country', 'Wider Dissemination', 'Responses');
  $output = theme('table', array(
    'header' => $header,
    'rows' => $html
  ));
  return $output;
}

function emnies_ad_hoc_query_exporter_get_country_row($str_current_country, $obj_response) {
  $rows = array();
  $i = 0;
  foreach ($obj_response as $response) {
    if ($str_current_country == $response->country) {
      if ($i == 0) {
        $rows[] = $str_current_country;
        $rows[] = $response->wider_dissemination;
      }
      $i = $i + 1;
      $rows[] = $response->response;
    }
  }
  return $rows;
}

Try looking at it this way.  From looking at your $header, you are looking for 3 columns?

foreach ($obj_response as $response) {
if ($str_current_country == $response->country) {
  $rows[] = array($str_current_country, $response->wider_dissemination, $response->response);
}

EDIT

// Test Output
$header = array(t('Country'), t('Wider Dissemination'), t('Responses'));
$rows = array();
$rows[] = array('US', 'Extremely Wide', 'Response');
print theme('table', array('header' => $header, 'rows' => $rows));

The test works for me.  Maybe something in your response value is messing with it?


Alter user_pass_reset for one time login D7 I don't like the one time login process; sending the users directly to their user edit page is not what I want. I want to force the users to insert a new password.

I have created a module that doesn't work; obviously I'm not affecting the submit action and is not taking the newly inserted username to the user object.

// Let's try to add a form in the user pass reset form for password requests.
function xxx_login_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_pass_reset') {
    $form['#account'] = $GLOBALS['user'];
    $form['loginsetup'] = array(
      '#title' => t('Login setup'),
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE
    );
    $form['loginsetup']['account']['name'] = array(
      '#type' => 'textfield',
      '#size' => 25,
      '#title' => t('Username'),
      '#required' => TRUE
    );

    $form['loginsetup']['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#title' => 'Please enter your new password',
      '#required' => TRUE,
    );

    $form['message']['#markup'] = FALSE;
    $form['help']['#markup'] = FALSE;
    $form['actions']['submit']['#value'] = 'Enter';
    //  $form['#validate'][] = 'xxx_login_user_pass_validate';
    $form['#submit'][] = 'xxx_login_user_pass_submit';
  }

  return $form;
}

// We'll check if the user did not leave a username.

// function xxx_login_user_pass_validate($form, &$form_state) {
//   if (empty($form_state['values']['name'])) {
//     form_set_error('name', t('You must select a username.'));
//   }
// }

// We should send the new values to the user object.

 function xxx_login_user_pass_submit($form, &$form_state) {
   // Set up the edit array to pass to user_save().
   $edit = array(
     'pass' => $form_state['values']['pass'],
     'name' => $form_state['values']['name']
   );

   // Save the account with the new password and name
   user_save($form['#account'], $edit);

   // Inform the user.
   drupal_set_message(t('Your login details have been stored. Welcome to example.com!'));
}

The validate function is now commented, but it does not affect the module; with or without it, it still does not work.

This is a bit of a SNAFU as user_password_reset doesn't have a hook associated with it. Why that is, I fail to see.

However, you can always use this little trick in hook_user_login to determine when users log in with a reset link by checking the emptiness of the $edit parameter as the only time it will be empty will be when the user didn't submit a form to log in = when they were automatically logged in.

function mymodule_user_login(&$edit, $account){
  if(!$edit){ // only for automatic pwd resets
    // do your thing, redirect to a password change form with drupal_goto or whatever you need.
  }
}

The implementation of forcing the user set a new password is another question altogether. We do it with a modal window that shows a simple custom form, but there are plenty of ways to do it. Unfortunately the easiest one is sending the user to their user edit form like the password reset functionality automatically does, but there's absolutely no reason why you couldn't just do whatever at that point as the user is logged in and good to go.


What are the options for an e-card wizard module? I am looking at creating an e-card wizard and would like to know if there are any modules that exist which would help with this.
A link should be added to a node and then the user should be able to create an e-card using information from this node. They need to be able to select a theme/image for the card, add a caption, add their email and the recipients email and then send it. Options to then share this with Facebook or Twitter etc should then be available.

Anyone done anything similar before?

Take a look at ecards module

As mentioned in the page, you can see a demo on http://www.mahlove.com/friendship-day/friendship-day-ecards/160


How do I make the title field in views as the title of the block? So how do I make the field "title" also show in the title of the block? Thanks.

Here is the image of the view: http://i.stack.imgur.com/jyUmo.png

Add a contextual filter of type 'Content: Nid'.
Set 'Provide default value' to 'Content ID from URL'

Under 'When the filter value IS available or a default is provided' set 'Override Title' to %1.

That should do the trick...


Views Slideshow constant cycle Is it possible to have a slideshow slide content constantly without stopping and no pause? That means it would always slide in fixed speed. I'd be using the scrollLeft effect or something like that.

It doesn't have to be Views Slideshow module, but it has to be Views displayed content which would scroll constantly from right to left.

Or should I just drop that and implement some custom javascript?

You can achieve that using the jCarousel module. I've used this module and works fine for me.

  This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.

Image from module page.

There is another module called  Owl Carousel

  This module integrates the wonderful Owl Carousel slider built by OwlFonk. The primary module is comprised of three sub modules providing a views style, field formatter & administration UI. The administration form leverages the variable module providing multilingual support out of the box.


Using a taxonomy select field as a contextual filter for an Entity Reference View powered select box I've got a parent child relationship between two content types: Properties and Parks. They are organized into a taxonomy we'll call Market. When creating a Park you select the Market it belongs to. Then creating a Property (which is child to a Park) you also select the Market and then select the Park it should be a child of. I need the select list of Parks (which is an Entity Reference) to filter based on what Market is selected to only show Parks from that Market. I have created an Entity Reference View properly and am able to see it filtering properly in the preview. But how can I use the data from the first select box for Market (a Term reference select list) to power the contextual filter of the second select box for Parks (an Entity Reference select list with the Entity selection set to filter by Entity Reference View).

I'm not sure if this is even possible, but have been stuck on it for a while.

I was able to find a workaround to this and display the market (taxonomy) and park (parent) in a select list from a view. Then wrote some javascript to disable the options that are irrelevant (parks from other markets) once the user selects the market of the property.


How to set the path for the public directory? I used to have a Drupal 7 installation on var/www, but I had to move it to var/www/drupal. The problems is that my files are still in var/www/sites/default/files and I am unable to move them.

I need to make Drupal use that directory as default file directory (just on level above). On admin/config/media/file-system, I tried to use absolute file path, without success. I tried to set ../sites/default/files too; it was almost successful, but now I am having problems with the image creation and caching. I have to manually load every single image style; otherwise, it does not find the file.

How can I set up a public file folder which is one folder above Drupal's root folder?

You can maybe create a symlink of /var/www/sites/default/files to /var/www/drupal/sites/default/files. Assuming you're inside /var/www/drupal, the command to do that is:

ln -s ../sites/default/files sites/default/files

So with this in the File System configuration page, you can just use the default path "sites/default/files".

But you can also just transfer /var/www/sites/default/files into it's new and final location though just to make things cleaner and organized, if you want.

Updated

Since you have noted also that "../sites/default/files" almost worked maybe you just need to update the permissions of the folder to maybe 775 and try to clear caches.

Hope everything works for you.


Changing the label of Change Password Form How to change the form label from Password to New Password and Confirm password to New Confirm password on THEME_form_user_form_alter(without changing any twig files)? I had tried kint($form['account']['pass']) to see any possible way, no clue...

Current Change Password Form

Current password

|||||||||||||||||

Password (to New Password)

|||||||||||||||||

Confirm password (to New Confirm password)

|||||||||||||||||

function THEME_form_user_form_alter(&$form, $form_state) {
  kint($form['account']);
}

There are no #title element on pass field.

You have to create a new module and use hook_element_info_alter
to alter title input like this:

function my_module_element_info_alter(array &$types) {
  if (isset($types['password_confirm'])) {
    $types['password_confirm']['#process'][] = '_mymodule_change_title';
  }
}

and process function

function _mymodule_change_title(&$element) {
  $element['pass1']['#title'] = t('New title 1');
  $element['pass2']['#title'] = t('New title 2');
  return $element;
}

and as a result


Is there an easy way to display Atlassian Gadgets within a Drupal node? We are looking into a way to display information from Jira in Drupal.

Using Drupal 6, is there an easy way to display Jira/Atlassian Gadgets within a Drupal node?

I have looked into a few things, and while it seems that the Dashboard module allows to include Gadgets, I don't want to have to use a Dashboard for this. I just wanted to embed a Gadget into a normal Drupal node.

Any hints or ideas?

Well, taking a look at the Jira/Atlassian web site, they are based in Java technology. Without going into too many details, because I'd have to learn how their proprietary environment works to advise you further, it is possible to embed Java applets in a Drupal page, in pretty much the same manner that one embeds a YouTube video on a Drupal page: just embed the markup in the same manner as you would any other web page, just make sure that the Drupal page's Input Filters are set to not strip out your embedding tags (such as using the 'Full HTML' Input Filter.)

However, this just gets one of their Java Applets on the page. It's not interacting with any information in your Drupal installation. In order to get your Java communicating with your Drupal installation's data, you need to install something like the Services Module into your Drupal installation hosting these Jira/Atlassian Java Applets, plus the Services REST server, and then create an API within the REST Services Framework that either mimics what the Java Applet expects for it's communications, or custom modify the Java Applets to communicate thru the API you created within Services.

So, no, there is no easy method if you want these Java Applets communicating with your Drupal installation's data. If you just want to display them, AND they support simple embedded like most Java Applets, just use the appropriate Input Filters when placing the Java Applet's embed script in the Drupal page.


Redirect on node form submit with custom module - hook_form_alter I have Druapl 6 with orgranic groups installed. I need a thing - when a group user creates "group" content after node form submission he must be redirected back on group homepage instead of node view page.

function heihachi_form_alter(&$form, $form_state, $form_id) {
  switch($form_id) {
        case 'group_wall_node_form':
        unset($form['buttons']['preview']);

        $redirect = 'node/' . $form['og_initial_groups']['#value'][0];
        $form_state['redirect'][0] = $redirect;
        //dpm($form);
        break;
  }
}

but that code doesn't redirect at all. Using simple $form['#redirect'] works, but it affects Node delete button aswell, so i can't delete my node because it redirects on a custom path. Thanks for all advices in advance.

My new code (not working also):

function heihachi_form_alter(&$form, $form_state, $form_id) {
  switch($form_id) {
        case 'group_wall_node_form':
        unset($form['buttons']['preview']);
        $form['#submit'][] = 'custom_redirect';
        //dpm($form);
        break;
  }
}

function custom_redirect($form, &$form_state) {

  //unset($_REQUEST['destination']);
  //unset($form['#redirect']);

  $form_state['rebuild'] = TRUE;

  $redirect = 'node/' . $form['og_initial_groups']['#value'][0];
  $form_state['redirect'] = $redirect;
}

This is what i see in $form variable:

0 (String, 21 characters ) menu_node_form_submit | (Callback) menu_node_form_submit();

1 (String, 31 characters ) auto_nodetitle_node_form_submit | (Callback) auto_nodetitle_node_form_submit();

2 (String, 15 characters ) custom_redirect | (Callback) custom_redirect();

I guess something wrong is there?

SOLVED!

used hook_nodeapi as one guy told me below:

function heihachi_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if ($node->type == 'group_wall') {
    if ($op == 'insert') {
      $_REQUEST['destination'] = 'xxx';
    }
  }

use hook_nodeapi with op insert or add another submit function in hook_form_alter.


Multisites with multicron Planning is like that:-

  We are going to manage multisites & each site having 3 cron jobs daily
  basis.

so my question is how can I analyze server performance there for multisites ?

Current scenario :

  10 sites having 3 cron jobs in each 10 minutes & each cron is updating
  contents in each sites(Number of updating contents maximum 3000 in
  each site with each cron job) but as I am seeing here cpu utilization
  & mysql is 100% occupied by first 5 sites.

I don't know resource is enough or not ?

Is this related to resource OR how can I improve performance there with cron jobs?

Right now I am using Elysia cron with each site.

Thanks in advance!

To analyze the performance of each multisite you will need to coorelate web server logs with performance logs or use an APM service like Newrelic where you can watch PHP at a very granular level as the cron jobs run.

Unfortunately, there is no easy fix for your problem. Multisites can only be used when the sites are not complex or demand a lot of processing. I believe you have a decision to make.

Keep using the multisite function of Drupal and deal with the performance issues you have in complicated and creative ways. Create ways would be using multiple servers and databases to offload the cron jobs to so it does not impact the websites.

OR

Break the sites up into different Drupal installations and use a code repository to manage the multiple sites.

You should read the articles written by Pantheon on Multisites. They had the same problem as you and realized the problems (performance) with multisites and devised another way to run complex multisites.


How to print YAML form in custom block under drupal 8 The accordion section was created in custom block under drupal 8. And I want to show yaml form in description of that accordion section. So, I would like to ask how to print YAML form in custom block.

Install the module insert Block

Enable and configure the insert block text format in 'admin/config/content/formats'

Make a new block with your form so that your form is available as a block.

In your accordion block you can call your form block with the special insert block tags [block:module=delta]. Make sure the 'insert block' text type is selected.


Content acces basing on a field value In Drupal 8, how do I give access to some nodes to users with specific roles, depending on a field value or a taxonomy value?

this is how i did it ( simplified for demo purpose )

function my_module_node_access(NodeInterface $node, $op, AccountInterface $account) {

global $user;
$user = \Drupal\user\Entity\User::load($account->id());

  if ($node->bundle() == 'my_content_type') {
    if ($op == 'view') {
        $visibility=$node->field_visibilite->getString();
        $target=$node->field_target->getString();

        if ($visibility ==='all')
            return \Drupal\Core\Access\AccessResult::allowed();

        if ($visibility ==='restricted')
            if (($target === 'group1') && ($user->hasRole('group1')))
                return \Drupal\Core\Access\AccessResult::allowed();

}

 return \Drupal\Core\Access\AccessResult::forbidden();

}


Troubles with adding video provider to Video Embed Field module I have installed Video Embed Field module, youtube links works good. Next I have installed Video Embed Wistia, and can't set valid Wistia's links. The error is

  Could not find a video provider to handle the given URL.

Video embed field and Video Embed Wistia modules are on in admin/modules

What I have missed? Why it doesn't work?

I've found solution, it's simple.

You need to go in the field settings of this field and find a checkboxes   with all video providers. Mark Wistia or any new provider here and it will work.


Theming User Profile Edit Form not Rendering results.... Help? I am not rendering any results. This is my template.php:

function fueldeluxe_theme($existing, $type, $theme, $path) {
    /**
    *  Account edit Forms
    */
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'template' => 'user-profile-form',
        'path' => drupal_get_path('theme', 'fueldeluxe') . '/templates'
    );
    return $items;
}

function fueldeluxe_preprocess_user_profile_form(&$variables) {
    $variables['account'] = drupal_render($variables['form']['account']);
    $variables['picture'] = drupal_render($variables['form']['picture']);
}

This is my user-profile-form.tpl.php:

        <?php echo $picture; ?>

        <?php echo $account; ?>

As you can see I'm trying to load the user profile field forms. However I'm not able to render any results. The page loads okay when I add dummy text but no account field forms.

Add a hook_theme() implementation

function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render_element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
Next we'll define some variables to pass into that template in a hook_preprocess_HOOK function. We can find the structured array of the form in $variables['form'] and assign the form elements to the variables we'd like to throw around our tpl.php file.

function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $variables['rendered'] = drupal_render($variables['form']['account']);
  $variables['rendered'] = drupal_render($variables['form']['picture']);
}

This example will put the general account info fields and the user picture upload field (if pictures are enabled) into a variable called "rendered."
Now that we have defined a variable, we can output it in a template file. Create a template file named user-profile-form.tpl.php in 'YOURTHEME/templates'. This is a demo example:

<div id="new-form">
  <?php echo $rendered; ?>
</div>

When you visit your user edit page, you should now see only some general account info fields and the picture fields. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the user-profile-form.tpl.php file, adding whatever markup you like.

Taken from HERE


Convert UTC to local time in date field I have a content type with a date field, which I convert to a specific date format in a preprocess function:

$variables['date'] =
\Drupal::service('date.formatter')->format($variables['node']->field_datum->date->getTimestamp(), 'long_date_without_time');

But as Germany is one hour ahead, a date like 2015-03-31 23:01:08 UTC converts to 1. April 2015. How can I convert this to our local time?

EDIT: I already set the correct timezone in the UI. And I just saw that the wrong dates are only shown when I set my system time between 11pm and 1 am...

The date formatter service automatically converts it to whatever time zone you selected when you installed the Drupal site, admin/config/regional/settings.

Also, if you allow users to set their own timezone in user/1/edit, it would use that time.

So either you need to change the timezone in admin/config/regional/settings and/or in user/1/edit


Cannot uninstall modules anymore Why do I get the following message when trying to uninstall a module with Drupal 8?

The website encountered an unexpected error. Please try again later.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;pantheon.aggregator_feed&#039; doesn&#039;t exist: SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table

LIMIT 1 OFFSET 0; Array()
in Drupal\Core\Entity\EntityStorageBase-&gt;hasData()</em> (line 588 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).
Drupal\Core\Database\Statement-&gt;execute(Array, Array) (Line: 631)
Drupal\Core\Database\Connection-&gt;query(&#039;SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table
LIMIT 1 OFFSET 0&#039;, Array, Array) (Line: 358)
Drupal\Core\Database\Driver\mysql\Connection-&gt;query(&#039;SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table
LIMIT 1 OFFSET 0&#039;, Array, Array) (Line: 510)
Drupal\Core\Database\Query\Select-&gt;execute() (Line: 267)
Drupal\Core\Entity\Query\Sql\Query-&gt;result() (Line: 83)
Drupal\Core\Entity\Query\Sql\Query-&gt;execute() (Line: 588)
Drupal\Core\Entity\EntityStorageBase-&gt;hasData() (Line: 56)
Drupal\Core\Entity\ContentUninstallValidator-&gt;validate(&#039;aggregator&#039;) (Line: 573)
Drupal\Core\Extension\ModuleInstaller-&gt;validateUninstall(Array) (Line: 99)
Drupal\Core\ProxyClass\Extension\ModuleInstaller-&gt;validateUninstall(Array) (Line: 121)
Drupal\system\Form\ModulesUninstallForm-&gt;buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 519)
Drupal\Core\Form\FormBuilder-&gt;retrieveForm(&#039;system_modules_uninstall&#039;, Object) (Line: 276)
Drupal\Core\Form\FormBuilder-&gt;buildForm(Object, Object) (Line: 93)
Drupal\Core\Controller\FormController-&gt;getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer-&gt;executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel-&gt;handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel-&gt;handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle-&gt;handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache-&gt;pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware-&gt;handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware-&gt;handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel-&gt;handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel-&gt;handle(Object) (Line: 19)

As @codesmith mentioned it looks like you have some issue with the Aggregator module but, usually you might also see other problems once you fix the aggregator module issue. The reason you see the issue on aggregator_feed is that it is the first table in your table list.

In case you are lucky and the issue is only on the aggregator module use the query below to recreate the missing tables (I am providing the two tables that are created when you install aggregator module).

CREATE TABLE `aggregator_feed` (
`fid` int(10) UNSIGNED NOT NULL,
`uuid` varchar(128) CHARACTER SET ascii NOT NULL,
`langcode` varchar(12) CHARACTER SET ascii NOT NULL,
`title` varchar(255) NOT NULL,
`url` varchar(2048) NOT NULL,
`refresh` int(11) DEFAULT NULL,
`checked` int(11) DEFAULT NULL,
`queued` int(11) NOT NULL,
`link` varchar(2048) DEFAULT NULL,
`description` longtext,
`image` varchar(2048) DEFAULT NULL,
`hash` varchar(255) CHARACTER SET ascii DEFAULT NULL,
`etag` varchar(255) DEFAULT NULL,
`modified` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_feed entities.';

and the second table

   CREATE TABLE `aggregator_item` (
  `iid` int(10) UNSIGNED NOT NULL,
  `langcode` varchar(12) CHARACTER SET ascii NOT NULL,
  `fid` int(10) UNSIGNED DEFAULT NULL COMMENT 'The ID of the target entity.',
  `title` varchar(255) DEFAULT NULL,
  `link` varchar(2048) DEFAULT NULL,
  `author` varchar(255) DEFAULT NULL,
  `description` longtext,
  `timestamp` int(11) NOT NULL,
  `guid` longtext
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_item entities.';


How do I remove node URLs? I have path aliasing, which gets the path from the title of the News article, working fine.

However, in the Google index, I noticed that the canonical URL for nodes is working as well. So, Google is indexing the node pages twice: with the canonical URL and with the path alias.

I want to disable the canonical URL for nodes, so I tried installing the node_page_disable module.  It installed fine, and I enabled it with Drupal 6.

In http://www.example.com/admin/settings/site-information, there is a  Default front page textbox, which by default contains node. If I remove node from the textbox, and save the settings, Drupal complains with:

  Default front page field is required.

The module I installed adds a Retain /node as an active url? checkbox.
If I click on that, I am required to remove node from the Default front page textbox.

How can I do it, since removing node causes Drupal to complain about a required value not given?

You must give a value for Default front page, and since you don't want to use node, you need to give another value for that setting.

Enable the Path module that comes with Drupal 6 core, from admin/build/modules

Create a Page node, from node/add

Add the path alias you want to use to the node being created

Save it
Change the default front page, and put the path alias you assigned to the node you just created, on admin/settings/site-information

Save the settings

Now Drupal will use that node as front page.

If you installed the Vertical tabs module, the node edit page would appear different. In this case, you can find the path alias text-box under the URL path settings tab.

I used a Page node for the front page, but you can use any content type you want.


Render element and caching I'm a little bit confused with hide() documentation.
It says:

  The first time render() or drupal_render() is called on an element
  tree, as each element in the tree is rendered, it is marked with a
  "#printed" flag and the rendered children of the element are cached. Subsequent calls to render() or drupal_render() will not traverse the
  child tree of this element again: they will just use the cached
  children. So if you want to hide an element, be sure to call hide() on
  the element before its parent tree is rendered for the first time, as
  it will have no effect on subsequent renderings of the parent tree.

First of all, I want to say I understand that hide() allow to avoid rendering of a specific element.

But documentation says more :

By talking about caching element as it is the default behaviour. For me, if #cache property is not defined for an element, when rendering the element will be not be cached.
And for me also, subsequent calls to drupal_render() will not use the cached element, because #printed property will be checked before trying to get the cached element (#printed=TRUE means return '';) .

I want to get your explanation about this.

Render arrays are trees. If you hide() the subtree P1.P2.P3.P4, it's stil possible for a supertree (P1.P2 or P1.P2.P3) to have caching enabled (i.e. have #cache set).

Also note that just having #cache set does not mean that the subtree with that element as a root does not get cached per se. Only when #cache[keys] is set is render caching triggered. #cache can also just contain cacheability metadata (tags, contexts, max-age) describing the cacheability of that subtree.

See https://www.drupal.org/developing/api/8/render/arrays/cacheability.


EntityFieldQuery display pager How do I display pager using EntityFieldQuery for fetch results?
I can't find complete example.

I am doing simmilar to:
Sortable, paged table retrieved using EntityFieldQuery

But I miss part to output simple pagination links (1,2,3... for every next page).

I suspect the only thing you're missing is adding the return from theme('pager') to the content you're building.

This is a small example that shows teasers for all nodes in the system, with 10 per page. You would use this in a page callback function:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->pager(10);

$results = $query->execute();

$content = node_view_multiple(node_load_multiple(array_keys($results['node'])));

$build = array(
  'content' => $content,
  'pager' => array(
    '#theme' => 'pager',
    '#weight' => 10
  )
);

return $build;

More specific based on your comments:

if ($type == 21) {
  $query = new EntityFieldQuery();

  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->fieldCondition('field_razred', 'tid', array (607,608,609,610), 'IN')
    ->pager(10) // this is the bit you're missing
    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));
  print render(node_view_multiple($nodes, 'teaser')) . theme('pager');
}


searching and entity references I have two content types documents and authors.
When creating a document a selection list of entity reference's to authors is used to select the author.

Searches for the author name find the correct author, but do not find the document that has an entity reference to the author. How do I get the search engine to to display both the author and the documents the author is referenced from.

EX Book "GOOD BOOK" is has an entity reference to Author "TOM".

When I do a search for TOM I get the "TOM"'s authors information but NOT an entry for "GOOD BOOK"

I suspect you need to configure your search view modes.

For each of your content types, visit the Magage Display page, eg admin/structure/types/manage/page/display

Unfurl Custom Display Settings, check Search Index and Search Result, and save.

Then for each, configure the search view modes.  Search Index will be used to build up the text that gets indexed.  Add / remove fields as needed.  The Search Result will be used to display the search results.


Is it considered bad drupal style to have a large number of 'static' pages scattered around the website? I'm developing a website in Drupal 7 which has a large number of pages that are either A) static, or B) dynamic in some sense, but not abstractable into a node.

My first instinct would be to just add implementing menu items in a hook_menu() function, then add hook_theme(), theme files, etc. etc. The thing is, across my website, I'll have probably 15 or more of these pages - that's a lot of URL's that are hard-coded into this site, in a way that isn't necessarily obvious to content managers who will be maintaining it.

The thing is, all of these hard-coded pages are going to be in the context of a landing-page. I am toying with the idea of creating a landing page content type, where they can edit the basic pieces (pretty much just the title and a single sentence) and assign it to a menu item, but then allowing them to select from a variety of pre-hard-coded solutions for each of the possible necessary pages. This is also a very sloppy solution, but it will give the content manager a tiny bit of control.

The pages in question are all too different, with too specific of requirements to make use of any module such as Views - they all need to be one-off, server-side code.

Any thoughts?

Have you looked at panels for assembling smaller pieces of content into a larger piece? Or even panel nodes which is a bit more lightweight than panels but allows layout and inclusion of other page elements in a regular node.


Views get OG mixed information Im trying to create a view that will get the following:

Organic group: Name.
Organic group: Members.
Organic group: Number of published nodes.

Its sounds like an easy task but really it isnt.
I got really confused with the type of view, and theres much relationships to be done, And after adding aggregation the view gets huge and frustrating.

I was thinking about creating each one as a separated view and embedding them on a page, but that might sound bad.

UPDATE
here is whats expected of the view to produce.

Organic group: Group A.
Organic group: X, Y, Z.
Organic group: 3 open tasks.

Organic group: Group Alpha.
Organic group: Alpha, Beta, Gamma.
Organic group: 0 Open tasks.

Organic group: Power rangers.
Organic group: Green dude, White dude.
Organic group: 15 open tasks.

Tasks being the content type that belongs to an OG.
Any help is greatly appreciated.

You are using Organic group module. So this module also provides two views called Og members and Og Content. Now download the module Views Field View which allows you to embed views as field in other view. See the Readme.txt file for more detail.

Create a new view and embed other two views Og members and Og Content in new view.


prepend one div in body in .inc file I want prepend one div using jQuery, But the div has to be generated dynamically, so I can not add it in html.tpl file.

I have tried below code

drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("'+download_list()+'"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}

But it is not working , whats the correct way to do this, please help

I am using Drupal 7

Thanks

It looks like you were using JS string concatenation syntax in PHP. Try

drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("' . download_list() . '"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}


How to test Drupal distributions and see examples Is there a way to see Drupal distributions already installed for testing as demo sites? I was searching drupal.org, where I only found 'case studies'. Sites there are sorted only by categories, not by used distributions, so it is difficult to check every site to find it out.

I want to use and feel distributions before installing them. It would be perfect if link to the demo site would be included in distribution description.

Distributions and modules can easily be installed and tested at simplytest.me


How do I access Session variables in Drupal that were set on non-drupal pages? If I go print_r($_SESSION) on a drupal page (say mysite.com/ )I only get Session variables set from drupal pages (which are none atm). I can set new ones and they'll show up.

Array
(

)

However If I print_r($_SESSION) on a non-drupal page (say mysite.com/somefolder/index.php) on the same domain I get a different (and desired) array:

Array
(
    [last_url] => /downloads/full.php
    [ip] => ::1
    [address1] =>
    [address2] => Australia
    [zip] =>
    [phone] =>
    [fax] =>
    [dealer] =>
    [referral] =>
    [software] =>
    [searchTerms] =>
    [user_type] => user
)

I have session_start(); at the beginning of all files.

How does my site seemingly have two $_SESSION arrays? How can I access my $_SESSION vars set on non-drupal scripts within drupal pages?

Thanks

You also need to boostrap drupal before use drupal's sessions (here: Properly bootstrap drupal for standalone PHP file?)


Out of memory error in composer when requiring drupal/bootstrap I currently set up a Drupal 8 website using Composer like described here.
Drupal is already running. Now I want to add Bootstrap theme by calling

composer require drupal/bootstrap

But I get

  Using version ^7.3 for drupal/bootstrap
  ./composer.json has been updated
  DrupalProject\composer\ScriptHandler::checkComposerVersion
  Loading composer repositories with package information
  Updating dependencies (including require-dev)

  mmap() failed: [12] Cannot allocate memory

  mmap() failed: [12] Cannot allocate memory
  PHP Fatal error:  Out of memory (allocated 515907584) (tried to allocate 20480 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/Pool.php on line 221

  Fatal error: Out of memory (allocated 515907584) (tried to allocate 20480 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/Pool.php on line 221

Im using Composer version 1.2.1 2016-09-12 11:27:19

This is related to your php.ini file's memory_limit entry which defaults to 128M. You need access to your server's php configuration file. If you do here is the step by step for making that change on an Ubuntu server with PHP 7 and PHP CLI extension.

Open the PHP CLI configuration file located at /etc/php/7.0/cli; e.g. I use vim as follows sudo vim /etc/php/7.0/cli/php.ini
Search for the line containing memory_limit by pressing the / (forward slash) key, type the phrase memory_limit and press enter.
Once on that line go to vim's insert mode by pressing 'ESC' followed by 'i'.
Change the value for the memory_limit to something higher, e.g. memory_limit = 1024M since you already have 512M for the limit.
Save and exit the configuration file by pressing 'ESC' type in 'wq' and then press 'enter'.

If you don't see any changes it could be that you have an error in you php.ini configuration file. You are always welcome to comment on the answers to get more help.


How do you override page.tpl.php in Omega 4? I am using the Omega 4 base theme, and am trying to override page.tpl.php.

This file is in the base theme in sites/all/themes/omega/templates/system.  When I copy it into my theme, edit it, clear caches, I don't see my changes?

Why can't I override this template?

Omega 4 includes a few changes.  From the project page (emphasis mine):

  The Omega theme provides layouts as a method of managing page
  templates along with layout specific stylesheets and regions. This
  allows you to write highly customized layouts that can be contextually
  switched. You can disable this feature to use the plain page.tpl.php
  or even use Omega 4.x together with Panels and Panels Everywhere to
  gain even more control over your pages if required.

If you want to use the new layout system, clone sites/all/themes/omega/layouts/simple into your theme, rename the files, edit the layout include, and clear caches.

The goto admin/appearance/settings/mytheme, and click on the Layouts tab.  If you did everything correctly, you can select the layout you just created, and then save your configuration.

If you don't want to use the layout system, and just want to use page.tpl.php, then untick Enable Layouts extension, and save your configuration.


How do I retrieve a plugin block field's translated value? I created a module that installs a block with some fields when installed. I added a schema file, and altered the blockSubmit() function so that the translation is saved in the schema.
Here is my module.schema.yml:
block.settings.worldwide:
  type: block_settings
  label: 'Worldwide'
  mapping:
    overtitle:
      type: label
      label: 'Overtitle'

Here is the blockSubmit() function from my Block plugin:
public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $block_name = $this->getPluginId();

    $this->blockConfigFactory->setBlockConfig($block_name, 'overtitle', $values['overtitle']);
    $this->setConfigurationValue('overtitle', $values['overtitle']);
}

When saving, I have no error, and can translate the field, which will keep the translation when updated. So everything seems to work. Additionnally, the website displays correctly what I saved for the default language.
Now, let's say that the default language is english and the alternative is french. My issue is that if I set the website in french, the default (english) value will keep displaying.
However, I can't figure out a way to displayed the saved translation when I want to look at the block in a language that has the block's translation saved. I have no idea where to look, and can't seem to find relevant stuff on internet.
Thank you in advance

Little did I know, the translation was correctly loaded, but not used in the twig files. Both the fields' content and configuration were loaded, were content was ie an image and a link, and configuration the field's translation.
Somehow, still, the configuration needed several cache rebuilds to show up, but then went ok and kept being updated if I made any modifications.
The twig files were using variables such as {{ content['field_worldwide_text'] }}, so I needed it to use config[] instead.
Additional notes for future self, here is how to load content and configuration:
$content = $this->blockConfigFactory->getBlockConfig($this->getPluginId());
$config = $this->getConfiguration();


Call to undefined function variable_get() I have an ansible script that transfers a production database to my devel server, then runs a few Drush commands to prepare it (e.g. updating the filesystem settings, clearing the cache).

A more complex task is updating a nested configuration value like the following one.

mail_system:
  default-system: SmtpMailSystem
  maillog: MaillogMailSystem

Supposedly I ought to be able to do this with drush ev (aka php-eval) and variable_get() and variable_set() as with drush7 ev '$v = variable_get("file_public_path")', but I get this error message.

  Error: Call to undefined function variable_get() in /usr/local/bin/drush7.4.0/commands/core/core.drush.inc(1122): eval()'d code, line 1

It does work correctly when I use the interactive shell.

drush7 core-cli
self> variable_get('mail_system');
array:2 [
  "default-system" => "SmtpMailSystem"
  "maillog" => "MaillogMailSystem"
]

I can work-around it by reading the content of $conf easily enough.

drush7 ev 'global $conf; echo $conf["mail_system"]["default-system"];'

Writing involves a database query and clearly variable_set() is in core.

Why cannot I use variable_get() and variable_set()?

I am using Drush 7.4.0 and Drupal 7.59.

(I also have Drush 8.1.16 available, but that's much use for this, Drush 8's cget and cset require Drupal 8, and Drush 8 doesn't have Drush 7's vget and vset.)

It seems you are confusing Drush 8 and 9 - Drush 8 has vget and vset.

Using Drush 8, the following two commands worked:

drush vget "mail_system"

drush ev 'print_r(variable_get("mail_system"));'

PS! Drush 7 isn't supported and you should use Drush 8 (currently 8.1.17) for Drupal 7.


Is there a module that can list all the views on a system? Is there a module that can list all the views installed on a system and their pages as well? If it can specify whether the Views are installed by modules or enduser created that will be helpful.

I am looking for something that create a list along this lines.

Name | Type of View | Page Name | Type of Page | Path

I don't think a module already exists for that.

To build it yourself, you'll need to implement hook_views_data(), and describe the views_view, and views_display tables.

These are the columns you'll have available from the views_view table:

name
description
tag
base_table
human_name
core

And from views_display:

vid (view id)
id
display_title
display_plugin
position
display_options

display_options is a serialised PHP array of data (containing the path and other specific information), so unless you implement some pretty advanced field/filters/etc handlers you won't be able to filter on those specific elements, or use them as fields.


how to display related node titles to taxonomy terms I want to display list of taxonomy terms and besides each taxonomy term need to display represented node title as well. For suppose To X taxonomy term a,b,c are taxonomy child terms. I have created a page and selected b term. Now I want to display in the below o/p.

>  X
>        a
>        b -> <node title>
>        c

The solution will be to use a taxonomy view using the views module and in the view add a relationship the content type where the terms are use. To finish you can display the results as an HTML list grouping by the parent term.


Access orders with own products In my store, i am allowing customers to create products like Courses using Drupal 7 Commerce module, Is there a way using views or whatever method to enable the sellers on my site to see orders placed for their products?
Example:  If Stanley is Selling  Product1 and Product2, he will be able to see orders for  product1 and product2, for now only admin can see the orders.
Your help will be highly appreciated.

Yes, you can use Views as Patrick suggests. Make it a View of Order entities with relationships joining Orders to Line Items and Line Items to the referenced Products. You can then apply a contextual filter to only show results whose Product uid matches the currently logged in user's uid.
A couple things to keep in mind...

Such a View would need to "Disable SQL rewriting" in its advanced settings, because it won't work so long as normal entity access control conditions are applied to the query.
You should include in the View itself all the information you need the course seller to see rather than trying to link them directly to a standalone page per Order. If that's what you want, you're going to actually need to hook into the access control system via custom code.


Get configuration settings not working I am writing this Drupal 8 module. I am setting up some configuration settings here

But when I retrieve it here using $this->config()->get() it is not giving anything. Any idea what am I doing wrong?

The problem is in your flood_control.settings.yml.

flood_control:
  user_failed_login_ip_limit: 50
  ...

This way, to get user_failed_login_ip_limit you must use $this->config(flood_control.settings)->get('flood_control.user_failed_login_ip_limit'). Or just remove flood_control: on first line for better use.


I am using node_save() to alter a node field, but HTML code is showing escaped This is the code I execute with "Execute PHP" with the Devel module.

$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'my_writings'; // Machine name of the content type

$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $node_type)
  ->execute();

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));

  foreach($nodes as $node) {

    $str=<<<END

 TITLE

Hello world.

END;
    // Replace field_foo with the machine name of the field to update.
    // - 0 refers to specific within the field array, for when the field contains
    //    multiple values. If the field only has one value, it should be 0.
    $node->field_author_box[$lang][0]['value'] = $str;
    node_save($node);
  }
}

The output I get is this HTML code like this.

 TITLE

    Hello world.

The input format is set to Full HTML, but the HTML tags are shown escaped, even if in the database they appear normal.

I tried to re-save the node; then, it is normal. I tried also to use html_entity_decode() without luck, if I do the same with body field then it works fine, but with a new field its showing escaped characters.

What could the problem be?

Drupal core does not modify the data you save in the database [*]. All filters are applied only when displaying the data - this ensures that you never loose any data.

Assuming that you are using Drupal 7, and that the field in question has filtered text enabled, then what is happening is that when you save your new field, you are not setting what the filter format should be - so it defaults to plain text. You need to set the format of the field when saving it. In your code, you would do this as follows:

$node->field_author_box[$lang][0]['value'] = $str;
$node->field_author_box[$lang][0]['format'] = 'full_html';
node_save($node);

[*] Though some contrib modules may do this. For instance WYSIWYG editors such as CKEditor do modify your data (though in that case only when using the UI).


How to get the view fields in rows in the word document generated using Views data export module? I am using Views data export module (version 7.x-3.1) to download content in Microsoft Word Format.

I am able to download the content but the fields of the view are coming out in columns rather than rows.

Please guide.

As an alternative to using the Views data export module, you may want to use the Forena module (disclosure: I'm a co-maintainer of it) to create a "report" that includes the data that you're interesting in (i.e. the "content" as in your question). As part of the report design, indicate which export formats you want to allow for exporting the data included in it. DOC (for MS Word) is one of the typical formats that are supported (apart from CSV,  XML, HTML, etc). By using Forena, the layout of the exported table (in your MS Word doc) would not  be "coming out in columns rather than rows" (as in your question).

Have a look at the Simple Table of States example, and think of it as the equivalent of your "posts that you want to export". And note the hyperlinks in the upper right, which are:

CSV.
XLS.
HTML.
XML.

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.

Forena versus Views

Forena can be used together with the Views module, or as an alternative to it, more specifically:

As an alternative to Views, to create reports (and derivatives such as charts and/or exports of data) which you cannot, or not easily, create with only Views. E.g. to pivot data, where you want to create tables in the format of what in Forena is called "Render a report in FrxCrosstab format".
Integrated with Views, as explained in the Forena tutorial pages, i.e.:

  Using the Forena integration with the Views module, it is possible to use Forena reports as a views row style, so that in a view you can use the Forena templating engine to do the formatting. Although this can be done through the views templating engine Forena users may find they have more control with this engine.


Workflow edit but not publish I am using workflow module to manage article moderation. I have created different state for that and for each state, I have set permissions using workflow content access.

Now, when an article is flagged, I am changing it's workflow state to say "s1" and unpublished the content.

In this state, author's can allow to edit the content but not publish it, the edited content will be sent to admin for review.

Now when I go to edit tab, it is showing "Publish" button too, by which author can Publish the content.

How can I remove these buttons ? Also is there any way, I can show workflow comment box in edit node page only.

-- Many thanks for your time.

The 'Publish' button isn't determined by the state of the node according to your workflow.  Actually, whether the 'Publish' button appears is determined by the permissions you have as a user.

So if you look at the content in the s1 state, you may see the 'Publish' button, because you're an admin.  An author looking at that same piece of content in the s1 state, however, shouldn't see that button based on the workflow moderation permissions you've given them.  Does that make sense?  It's not the workflow state, but the individual's permissions that determine whether that button is available.

So test it out by logging in as an author to see what they would see.  If you can still see the 'Publish' button when you're logged in as an author, that may mean that you've inadvertently given that role a permission you didn't intend, such as 'Administer content', so double-check the permissions again.  :0)

My authors definitely can't publish in some of my workflow states!


Create relation between two select list for Hierarchical select option In a content type, I want to have two select fields eg:

Select list 1 contains the Mobile phone brands names

Nokia
Samsung
HTC
Apple

Select list 2 contains the phone type like:

Lumia 520
Lumia 620
Galaxy S3
Galaxy S4
Hero
One
iPhone 4
iPhone 5

While adding new content, I want to make a Hierarchical select in this case, When a user selects Nokia from Select 1, then only Nokia phones are available for selection in Select 2 like:

Lumia 520
Lumia 620

But if nothing is selected in Select 1, then Select 2 doesn't show any options but still visible.

So far I tried Hierarchical select Module, but works only when I put the taxonomy term in hierarchical form instead of lists like:

Nokia
    Lumia 520
    Lumia 620

Samsung
    Galaxy S3
    Galaxy S4

HTC
    Hero
    One

Apple
    iPhone 4
    iPhone 5

and it only stores one value in the database (the phone Name). I want to be able to store both Brand and Phone name in Database as fields, so, I could display both fields using Views and also have exposed filter to filter through this.

Any suggestions how should I approach ?

Hope this will help you

function mymodule_form_alter(&$form, &$form_state, $form_id){

//put your form id
if ($form_id == 'two_state_node_form')  {

    $options_first = dynamic_add_options();

   $value_dropdown_first = isset($form_state['triggering_element']['#value']) ? $form_state['triggering_element']['#value'] : key($options_first);

    $form['#validated'] = TRUE;
    //put your first field name
    $form['field_select_list_1']['und']['#options'] = $options_first;
    $form['field_select_list_1']['und']['#default_value'] = $value_dropdown_first;
    $form['field_select_list_1']['und']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'dynamic_ajax_callback',
    'wrapper' => 'dropdown_second_replace',
 );
    //put your secon field name
  $form['field_select_list_2']['und']['#prefix'] = '
';
  $form['field_select_list_2']['und']['#suffix'] = '
';
  $form['field_select_list_2']['und']['#options'] = dynamic_second_dropdown_options($value_dropdown_first);
  $form['field_select_list_2']['und']['#default_value'] = isset($form_state['values']['field_select_list_2']) ? $form_state['values']['field_select_list_2'] : '';
 }
}

function dynamic_ajax_callback($form, $form_state) {

    return $form['field_select_list_2'];
}

function dynamic_add_options() {
  return array(
        'None' => 'None',
        'Nokia' => 'Nokia',
        'Samsung' => 'Samsung',
        'HTC' => 'HTC',
        'Apple' => 'Apple'
    );
   return $options;
}

function dynamic_second_dropdown_options($key = '') {
    $options = array(
        'None' => array(
            'None' => 'none',
             ),
        'Nokia' => array(
            'Lumia 520' => 'Lumia 520',
            'Lumia 620' => 'Lumia 620'
        ),
        'Samsung' => array(
            'Galaxy S3' => 'Galaxy S3',
            'Galaxy S4' => 'Galaxy S4'
        ),
        'HTC' => array(
            'Hero' => 'Hero',//trancate the code
            'One' => 'One'
        ),
        'Apple' => array(
            'iPhone 4' => 'iPhone 4',
            'iPhone 5' => 'iPhone 5'
        ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

this is demo for you demo


Importing Drupal Commerce Orders, Customers, Ship to and Bill to addresses Has anyone successfully imported customers, orders, ship to, and bill to addresses using anything other than a custom module?  If there a recipe for the process?

There's also Migrate Module ; but your question is vague regarding the source you are migrating from.  This module supports different sources to migrate from

https://drupal.org/node/1006986