Views Menu Tabs and Ajax? Is it possible to use menu tabs/default menu tabs available in Views, along with ajax, so that hitting a tab does not load a new page?

If you want to user tabs and have blocks inside them coming from then, then one very beautiful module which you can use is Drupal Quick tabs: http://drupal.org/project/quicktabs

This module works amazingly. It also takes arguments and allow you to do a lot of advanced modifications like Ajax call to the tabs or directly load them etc. You can check the Techtree website for an example of quick tabs that we have used in the side bar.


How do I translate Field Group labels? I have two field sets

In the admin/config/regional/translate I have translated the "Account settings" label

But in the Form display I still have the english label:

What can I do to translate the field group labels?

Field groups are configurations which are not translated via the translation interface. I am quite sure that the string "Account settings" that is translated in your project does not come from your field group. Just change the label of a field group to any other string - you will not find the string in the translation interface.
You need to activate the "Configuration Translation" module.


Need to print all the function calls Drupal makes I need to examine all the function calls Drupal makes during it loads a page (even if there are no errors). I guess debugging software can do this but I would also like to know a way to do this without xdebug etc.

I found this link:
https://drupal.stackexchange.com/questions/545/how-to-debug-drupal
but I'm not sure where to put for example this code:

<?php
$bt = debug_backtrace();
foreach ($bt as $key => $value) {
  if ($key == 0) {
    continue;
  }
  unset($bt[$key]['args']);
  unset($bt[$key]['object']);
}
drupal_set_message(str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(print_r($bt, TRUE)))));
?>

I would recommend using Xdebug as opposed to any other methods.

Xdebug can easily be installed and then all you have to do is enable profiling and navigate around your site.

Not only does it list all function calls but it counts how many times each is called during a request and also times the function call, so you know exactly where to look to resolve bottlenecks.

The results can be viewed using Webgrind (browser-based) or KCacheGrind (KDE/linux), amongst others.

This is more efficient because you are not tampering with the code and littering it with debug statements.


Are there any disadvantages in placing form elements in custom containers? I've got a form layout in which form elements are separated between 2 divs: one with float: left, the other with float: right. I have to keep it that way.

Is it fine to place form elements in different containers? Could I get any troubles with form validation or submitting?

What's the best way to do it, via hook_form_alter(), or something else?

P.S. I'm not developing a custom module, but a theme. Here is an example of the form HTML; it's not precisely what it's going to be, but it gives an idea.

            <input type="text" id="name" />
            First name:

            <input type="text" id="surname" />
            Surname:

I can't comment yet so I'll try to be broad.  First, there are not any disadvantages to customizing your output html, the form process and validation will work just fine as long as you're not adding form tags to your html that you are hoping Drupal will also process.

You don't need hook_form_alter if you only want to modify the html. You can use, in your template.php file, hook_theme().

The first thing you would need is the id of the form.  You can get this via viewing source or using the devel and devel themer modules.

Once you have your form id, within template.php:

/**
 * Implementation of hook_theme
 */
function yourthemename_theme($existing, $type, $theme, $path) {
  return array(
    'user_login' => array( // to modify user_login form, for example
      'render element' => 'form'
      )
  );
}
/**
 * Theme function
 */
function yourthemename_user_login($variables) {
  $user = drupal_render($variables['form']['name']); // use the devel module:kpr($variables), or print_r($variables) to look at the $variables['form'] element
  $pass = drupal_render($variables['form']['pass']);
  $remainder = drupal_render_children($variables['form']);
  // put the user field and pass field inside a custom div
  $output = '
' . $user . $pass . '
';
  $output .= $remainder;
  return $output;
}

Take a look at drupal_render() and drupal_render_children() but, basically, when you call drupal_render it 'renders' the element and remembers that it was already rendered.  You use that with as many elements as you need to but always remember to render the children as well so that all of your hidden fields and drupal form stuff doesn't get left out.

Alternatively, I don't think I've come across a Drupal form I couldn't wrangle with some well-targeted CSS, if you'd rather go that way.


How to delete a module from the Modules menu? I have installed a few modules that I don't use at all. I can't find any option to uninstall them. How do I do it? Is there a separate module to do it?

The module uninstall page in Drupal 6 is at http://mysite.com/admin/build/modules/uninstall.

For Drupal 7 it's at http://mysite.com/admin/modules/uninstall.

Once you disable a module using the main modules page, visit the uninstall page and you'll be able to safely uninstall. After that it's just a matter of deleting the module folder from your server, and you won't see it in the module list any more.

Whatever you do, don't just delete the module folder without disabling/uninstalling it first, or you could easily wreck the site.


How to use Rules to disable access to selected fields while editing an existing node? Based on couple of features I require to restrict/disable access to certain field based on other fields while editing the node.

The problem is that in Rules module, there's no "While editing an existing node" event.

What I want is to set an action for the user while editing the node.

You're right, there is no such event like "While editing an existing node". Probably because an event is something that takes like a fraction of a second, while editing may take minutes (hopefully not hours!).

However, you might get it to work by implementing an "edit-in-progress" (= EIP) feature using the Flag module, combined with using the Rules module. Similar to what I described in my answer to "Can the Flag module be used to lock content while editing to prevent concurrent edits?" (BTW, that question is a variation of yours, I don't think it's a duplicate though ...).

After you'd have such EIP-flag available, it should be straight forward to use it in appropriate Rules to "restrict/disable access to certain fields" (eg based on a data comparison to validate selected field values (using their before and after save values).


Feeds - How to set a blank source value programmatically I'm triggering a Feeds import in a custom module I made. I need to set a value of a blank source in that code because that value is not in the source file (in this case is a xml). Is it possible to do this?

Below is the code I have.

$path = $url . '/path_to_my_file/myfile.xml';
$feeds_source = feeds_source($feeds_importer);
$feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);

$file_exists = get_headers($path, 1);

# check if file exists:
if ($file_exists[0] == 'HTTP/1.1 200 OK') {
    $feeds_config['source'] = $path;

    $config = array(
        'process_in_background' => TRUE,
    );

    $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
    $feeds_source->importer->addConfig($config);
    $feeds_source->save();
    $feeds_source->startImport();

    while (FEEDS_BATCH_COMPLETE != $feeds_source->import());
}

UPDATE:

Below is a more complete code. I have 3 functions. The first one is the original but one. Notice tha I get the $VALUETOPASS variable from the function arguments.

The other 2 functions are the ones rooby suggested.
The problem is how to have the $VALUETOPASS in the last function. At this moment I only need that.

function MYMODULE_CustomImport($VALUETOPASS) {
  $path = $url . '/path_to_my_file/myfile.xml';
  $feeds_source = feeds_source($feeds_importer);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);

  $file_exists = get_headers($path, 1);

  # check if file exists:
  if ($file_exists[0] == 'HTTP/1.1 200 OK') {
    $feeds_config['source'] = $path;

    $config = array(
        'process_in_background' => TRUE,
    );

    $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
    $feeds_source->importer->addConfig($config);
    $feeds_source->save();
    $feeds_source->startImport();

    while (FEEDS_BATCH_COMPLETE != $feeds_source->import());
  }

function MYMODULE_feeds_processor_targets_alter(array &$targets, $entity_type, $bundle) {
  // Set a custom value setter callback for the my field on my node type.
  if ($entity_type == 'node' && $bundle == 'my_bundle') {
    if (isset($targets['my_field'])) {
      $targets['my_field']['callback'] = 'MYMODULE_set_custom_field_value';
    }
  }
}

function MYMODULE_set_custom_field_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
  $xml = simplexml_load_file($url . $VALUETOPASS . '/api/xml');
  $multijob_array = json_decode(json_encode((array)$xml), TRUE);

  if (isset($multijob_array['action'][2]['cause']['upstreamBuild'])) {
    $multijob_build = $multijob_array['action'][2]['cause']['upstreamBuild'];
  } else {
    $multijob_build = '';
  }

  $entity->{$target}[$entity->language][0]['value'] = $value;
}

In the code where you run the importer you can only alter the field mapping.

To modify the field mapping configuration at that point to add custom data (you can also do things like remove fields from the mapping here):

// Load the importer.
$importer_id = 'my_importer';
$feeds_source = feeds_source($importer_id);
// Get the current field mappings.
$field_mappings = $feeds_source->importer->processor->getMappings();

foreach ($field_mappings as &$mapping) {
  // Add an arbitrary value to the mapping of my_field for
  // use later in the processor target callback.
  if ($mapping['target'] == 'my_field') {
    // Your logic goes here to populate this.
    $mapping['my_custom_value'] = 'My custom value';
  }
}

// Set the new field mappings.
$feeds_source->importer->processor->addConfig(array('mappings' => $field_mappings));
// Save the new field mappings.
$feeds_source->save();
// The previous call to FeedsProcessor::getMappings() cached
// the mapping, so we need to clear that before we run the import.
drupal_static_reset('FeedsProcessor::getMappings');

// Run the import.
$feeds_source->startImport();
while (FEEDS_BATCH_COMPLETE != $feeds_source->import());

Then to change the actual value that goes into the field, you have to do that at import time, when feeds is getting the value from the source and saving it to the target.

To do that you can implement hook_feeds_processor_targets_alter(), like this:

/**
 * Implements hook_feeds_processor_targets_alter().
 */
function my_module_feeds_processor_targets_alter(array &$targets, $entity_type, $bundle) {
  // Set a custom value setter callback for the my field on my node type.
  if ($entity_type == 'node' && $bundle == 'my_node_type') {
    if (isset($targets['my_field'])) {
      $targets['my_field']['callback'] = 'my_module_set_custom_field_value';
    }
  }
}

/**
 * Custom feeds target setter callback.
 */
function my_module_set_custom_field_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
  // Set the field value to our custom value if it's there.
  if (!empty($mapping['my_custom_value'])) {
    $entity->{$target}[$entity->language][0]['value'] = $mapping['my_custom_value'];
  }
}


Couldn't display body field on a view with Search Api I have a view that I set it up with Search Api and Facet Api, I couldn't display the body field of indexed nodes.

I tried to add it to the Search Api index fields but it still the same result.

There are 2 solutions to add body field:

Solution 1:

Browse to search api index field configuration at /admin/config/search/search_api/index/hone_and_strop/fields
Now add The main body text field from Add related fields list.
Now do reindexing and you would be able to add body field into view.

Solution 2:

Create view mode with body field in it.
Now in view, use Rendered entity instead of fields.

  Note: You always need to do reindexing whenever you add or remove
  field form search api index field configuration.


Why file attachment has different URLs in icons links and default link on node page? I have node with attached file. Node attachments view look:

sample.pdf link has url like sites/default/files/sample.pdf. I can download file via this link.

Links with icons has URL like download/file/fid/[id]

I can't download some of files via icon links (403).

How can I change this behaviour? I want those links point to `sites/default/files/sample.pdf

I believe, there can be custom or some contributed module doing the trick.
The menu - download/file/fid/[id] is created by some module and allowing you to download the file.
Might be a case that the logic is written in the same callback.

try searching your modules with this callback and you might see some results...


PDF Module, PDF full pageheight or full scroll I managed to get a PDF in a content type and to show the full PDF. I do this with the PDF module in drupal 7.
But I want't the height of 1 page (A4 always) or just the full height of the document.

How can I manage this? 100%, auto doesn't work. I can only give a certain amount of pixels. But when it's resized, it's not perfect, the frame is higher then the document.

When I try to use the option PDF: Continuos scroll, it breaks. That should also be a solution for me, just the height of the document. But I have the following errors:

  Uncaught (in promise) TypeError: Cannot read property 'getDirection'
  of undefined at webViewerLocalized (viewer.js?opdors:7109)
  viewer.js?opdors:4958 Uncaught (in promise) TypeError: Cannot read
  property 'firstElementChild' of null at PDFViewer
  (viewer.js?opdors:4958) at viewer.js?opdors:5790 at Promise () at
  Object._initializeViewerComponents (viewer.js?opdors:5778) at
  viewer.js?opdors:5692
  /sbsdebrug/sites/all/libraries/pdf.js/build/pdf.worker.js:50046 The
  provided value 'moz-chunked-arraybuffer' is not a valid enum value of
  type XMLHttpRequestResponseType. supportsMozChunkedClosure @
  /sbsdebrug/sites/all/libraries/pdf.js/build/pdf.worker.js:50046
  pdf.js:28 Uncaught (in promise) ReferenceError: getOutputScale is not
  defined at renderPage (pdf.js:28) pdf.js:28 Uncaught (in promise)
  ReferenceError: getOutputScale is not defined at renderPage
  (pdf.js:28) pdf.js:28 Uncaught (in promise) ReferenceError:
  getOutputScale is not defined at renderPage (pdf.js:28) pdf.js:28
  Uncaught (in promise) ReferenceError: getOutputScale is not defined at
  renderPage (pdf.js:28)

I did something similar with print module , it also may be posible with PDF module. Override print--pdf.tpl.php file to fit your needs, copy print.tlp.php file from print-module directory (or look for a similar file in pdf module), paste it in sites/all/themes/your-sub-theme/templates folder. in line 100 is print $content, there add a css class "myclass" with higth=100%; done!.


How to disable adsense for this error page I want to disable adsense ads for this url: http://www.indiacustomercare.com/node/167/submission/274

which is accessible only to the admin.

How can I do it for my D6 site?

use the Adsense module, you can specify pages where to display it or not to display it using :

Show AdSense on specific pages:

Show on every page except the listed pages.
Show on only the listed pages.
Show if the following PHP code returns TRUE (PHP-mode, experts only).


db_select orderRandom With range I'm trying to query a random node from the last 10 that were created.

So far I've used this but it doesn't produce the right results:

 $query = db_select('node', 'n');
 $query->fields('n', array('text','created_time'))
   ->orderBy('n.created', 'DESC')
   ->range(0, 10)
   ->orderRandom();
$result = $query->execute()->fetchAll();

How can I get the data I want?

The node table doesn't have a text or created_time column so I'm not sure what data you're trying to select. Regardless, here are a couple of examples that use a subquery to select the title and created columns for a single random node from a pool of the ten most recent:

Subquery in the FROM:

$subquery = db_select('node', 'n')
  ->fields('n', ['title', 'created'])
  ->orderBy('n.created', 'DESC')
  ->range(0, 10);

$query = db_select($subquery, 'n2')
  ->fields('n2', ['title', 'created'])
  ->orderByRandom()
  ->range(0, 1);

Which is roughly equivalent to:

SELECT n2.title, n2.created
FROM (
  SELECT n.title, n.created
  FROM node n
  ORDER BY n.created DESC
  LIMIT 10
) AS n2
ORDER BY RAND()
LIMIT 1

Subquery in the WHERE:

$subquery = db_select('node', 'n2')
  ->fields('n2', ['nid'])
  ->orderBy('n2.created', 'DESC')
  ->range(0, 10);

$query = db_select('node', 'n')
  ->fields('n', ['title', 'created'])
  ->condition('n.nid', $subquery, 'IN')
  ->orderByRandom()
  ->range(0, 1);

Which is roughly equivalent to:

SELECT n.title, n.created
FROM node n
WHERE n.nid IN (
  SELECT n2.nid
  FROM node n2
  ORDER BY n2.created DESC
  LIMIT 10
)
ORDER BY RAND()
LIMIT 1

And the code:

You could also try a JOIN approach, it's worth trying a few methods to see which has the best performance.


Should I call my function in Drupal custom modules? I've been trying to implement  a redirect to user register page if an anonymous user tries to access a specific page. I used the following code in my custom module.

function myregistration_init(){
  global $user;
  if ($user->uid == 0  && $_GET['q'] == 'order_translaton' ) {
    drupal_goto('user/register');
  }
}

However, this code did not work until I wrote myregistration_init() after the function body. I know that in Drupal modules function works automatically without the need to call it. For instance, the following code works without function call:

function myregistration_form_user_register_form_alter(&$form,&$form_state){
$form['#submit'][] = 'myregistration_submit';
function myregistration_submit(&$form,&$form_state) {
$form_state['redirect']= 'order_translaton';
}
}

Please explain how all this works in Drupal modules.

Do not get confused with drupal hooks and functions.

Drupal Hooks:

They allow you to interact with core functionality without hacking it. In our custom module we implement hooks which are invoked by drupal at the event the hook is exposed for automatically. So consider the hook_init(), so when drupal is initialized the system will look inside each contributed, custom module if any of the module has implemented hook_init(), and if so, drupal will invoke functionality written inside the hook implementation for every single module in the order of their module weight.Basically all we do is implement the hook in custom module and clear the caches (clearing the caches is important step as drupal caches all hook implementations so that it doesn't have to look inside every enabled module files to find if there is a matching hook implementation in order to be executed, but since a new hook is added to system we have to clear the cache so that drupal can rebuild information about implemented hooks.), we never explicitly call the hooks, as they are invoked by drupal system itself.
So hooks are kind of functions invoked by drupal itself.

functions:

Set of code which gets executed when called explicitly.

About your code

  /**
    * Implements hook_init()
    */
    function myregistration_init(){
      global $user;
      if ($user->uid == 0  && $_GET['q'] == 'order_translaton' ) {
        drupal_goto('user/register');
      }
    }

About your code:

function myregistration_form_user_register_form_alter(&$form,&$form_state){
  $form['#submit'][] = 'myregistration_submit';
  function myregistration_submit(&$form,&$form_state) {
    $form_state['redirect']= 'order_translaton';
  }
}

I am not sure why this code is working, it should be rather like following.

/**
  * Implements hook_form_alter()
  */
function myregistration_form_user_register_form_alter(&$form,&$form_state){
  $form['#submit'][] = 'myregistration_submit';
}

/**
  * Custom submit hanlder.
  */
function myregistration_submit(&$form,&$form_state) {
  $form_state['redirect']= 'order_translaton';
}

Both hook implementation codes above should work, but you might need to clear your caches after implementing the code. But do not call it explicitly anywhere in code.


Show content that referenced to a user to him In my site I have a content type with a user reference field.

I want to create a view to show  contents to a user that are referenced by this user reference field.

How would I do this?

If you have a content type with a user reference field and you want to display a list of these content types that reference the currently logged in user, you could create a view, Filter it on published nodes of that type, and then add in an Argument, which would be the field in question, and then supply as the default argument the uid of the currently logged in user.  Then just set up whatever Fields you want displayed and you should be on your way.


How do I create a list of Nodes within a list of taxonomy terms, within a node? I want to make an awards event where users can log in and nominate their products in specific categories.

I have a node: "Awards Event" where the details of the event are defined
I have a taxonomy: "Awards Event Categories" - these are the categories which can contain multiple nominated products. These categories will be used for multiple awards events. Within 'Awards Event' node the admin defines which of these categories will be available in this particular event.
I have nodes: "Products" - these are controlled by the users who'll assign them to a category

Basically what I want is a way to build a list of which products are nominated in each category within each Award Event.

Is there an easy way to accomplish this?
I could just simply add a new field within the product node where the taxonomy term can be selected - but this would require me to add that new field each time an awards event is created. I'd prefer if there was a more automated way.

You could create a view which will display content filtered by a category, note that the category filter should be a contextual one.

In the node, you should have a taxonomy term reference field and then in preprocess, you can create your own variable by rendering the view with a contextual filter.
The contextual filter in this case will be the value of the taxonomy term reference field.

This will handle the desired behavior but won't be as flexible. It will cover choosing a different term for each node, but you will be stuck to the same view.


how can I export table content to excel or csv I am using drupal 6, I have created a table using

$tableHeader = array (
  array('data' => 'Ebooks','field' => 'etitle'),
  array('data' => 'Volumes','field' => 'Volume' ),
  array('data' => 'Chapter','field' => 'ctitle'),
  array('data' => 'Total Sale'),
);

$TableRows[] = array (
  l($row->etitle,$ebookinfo),
  $row->name,
  str_replace("&amp;", "&" ,$row->ctitle ),
  round($row->totalsale,2).' $',
);

$output .= theme('table', $tableHeader, $TableRows);// get the pager
$output .= theme('pager', NULL, 5, 0);

How can I export it to MS Excel or CSV?

May the below custom code will helpful for you.

set  the header

$filename= 'export.csv';
  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

you can write a function(just an example below) by sending the row values, filename, and column title

<?php

function export_to_excel_page($row_array, $filename,$column_titles) {

  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

  foreach($column_titles as $key => $value) {
           $keys[] =$value;
  }

  if($keys) print implode(',', $keys) ."\r\n";
  unset($keys);

    //fetching the field values
  foreach($row_array as $key => $value) {

   $values[] =$value;

  }
    print implode(',', $values) ."\r\n";
    unset($values);
    }
    exit;

?>


How to enforce role selection on the user's create, so they can edit other certain users? I have three roles.

registry
teachers
students

How do I enforce role selection on user's creation?

I want the registry role to create and edit users (ONLY teachers or students role).

Look at Auto Assign Role module.
This documentation will help you.


What are the "Files" that Metatag module allows adding Metadata to? In Drupal 7, if you go to Configuration > Search and metadata > Metatag > Settings (Tab) the module Metatag allows you to add Metatags to "Files"... What are these files?... As everyone are knows, files are not webpages and I guess there aren't very much good reasons to build themselves as web pages... So why would the module attach them \ associate them with meta tags???

They are all the files managed by Drupal through attachments, images & file fields. In D7, these managed files are entities. As such, the metatag module supports it.

This isn't useful with the metatag module alone, but if you had a configuration where files had their own display page (e.g. the file entity & media module), it could be utilized.


How to add points using User Points in Drupal 6 I want users to be able to give points to other users through "User Points"

I think it's the API: http://drupalcontrib.org/api/drupal/contributions!userpoints!userpoints.module/6
http://drupalcontrib.org/api/drupal/contributions!userpoints!userpoints.views.inc/6

I don't want to use views module, I'm looking for a PHP code to place it in template and to give point.

Thanks

Check nodevote module. It does something similar. You may use it directly or base your code on it.

If you want to use a more sofisticated solution with VotingAPI you can use  userpoints_votingapi and use rate module for the widgets

Cheers.


How to show list & thumbnail widget in plupload? I have installed the following modules:

FileField Sources Plupload, FileField Sources, Plupload module and added latest plupload library.

While uploading multiple files it is showing only list of files but its not showing the widget for thumbnail & list view.

So how to show that widget.

The Plupload integration module does not support the UI components of the Plupload Library. It is just as the module name suggest an integration with the library. The actual preview/thumbnails of uploaded images is handled by other modules like in your case FileField Sources Plupload and FileField Sources. You can check the module maintainers answer here. For modules that integrate with Plupload scroll down to the list on the module page.


How to add a field to menus? I am trying to add an extra text field to the menu entity. My field is showing up and saving input but the input saves for all menus not just the one I entered the data for.
This is how it is now:
function myModule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'menu_edit_form') {
    $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
    $my_field = $config->get('my_field');
    $form['my_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $my_field,
    '#weight' => '0',
    '#required' => FALSE,
    );

    $form['actions']['submit']['#submit'][] = 'myModule_menu_edit_submit';
  }
}

function myModule_menu_edit_submit($form, $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set('my_field', $form_state->getValue('my_field'))->save();
}

I need to save different data for each form, so I was trying to do change the submit function to:
function myModule_menu_edit_submit($form, $form_state) {
  $key = $form_state->getformObject()->getEntity()->id();
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set($key, $form_state->getValue('my_field'))->save();
}

If I do this though, when I enter the data in the field and save, it says updated successfully but the field is blank. Not sure what I'm doing wrong.

I figured out how to add a field to the menus (not menu links, the actual menus). I use the machine name of the menu's title as a key and store the value with the key I use in the $form variable.
Here is my code:
function myModule_form_menu_edit_form_alter(&$form, $form_state, $form_id) {
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $my_field = $config->get(str_replace('-', '_', $form_state->getformObject()->getEntity()->id()));

  $form['my_field'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => $my_field,
  '#weight' => '0',
  '#required' => FALSE,
  );

  $form['actions']['submit']['#submit'][] = 'myModule_custom_submit';
}

function myModule_custom_submit($form, $form_state) {
  $key = str_replace('-', '_', $form_state->getformObject()->getEntity()->id());
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set($key, $form_state->getValue('my_field'))->save();
}


Using TableField with Node:Create? I've been struggling with this for a few days. I currently have a form which I am creating and rendering through Drupal 8's Form API. I am saving the inputted field values using Node::create() which has been working great. I am now using the Tablefield module for some of the fields. I am struggling to save this data as part of the Node::create() function however. I am reasonably new to Form API so I'm sure I'm missing something obvious.

My current Node::create() is a little like this

$node = Node::create([
      'type'                      => 'business',
      'status'                    => 1,
      'field_membership_type'     => $form_state->getValue('type_of_membership'),
      'field_type_of_business'    => $form_state->getValue('membersInTheQuarter_type'),
      'field_business_size'       => $form_state->getValue('businessSize_antique'),
      'field_business_size_shop_' => $form_state->getValue('businessSize_independentShops'),
      'field_category'            => $form_state->getValue('businessCategory'),
      'field_additional_category' => $form_state->getValue('additionalBusinessCategory'),
      'field_category_custom_'    => $form_state->getValue('businessCategoryCustom'),
      'title'                     => $form_state->getValue('business_name'),
      'field_tag_line'            => $form_state->getValue('tag_line'),
      'field_about'               => $form_state->getValue('about'),
      'field_opening_hours'       => /**This is where I need to access the individual cells of tablefield to set values from my form**/
    ]);

  $node->save();

This has not much to do with form API, only with the structure of the field.

You need to pass in the values that the field type expects, based on its propertyDefinitions() method for example. Looking at http://cgit.drupalcode.org/tablefield/tree/src/Plugin/Field/FieldType/TablefieldItem.php?h=8.x-2.x#n141, it does some special processing on it, so might have to account for that.

The easiest option for that kind of stuff is usually to just create a node in the UI, then load it and call $node->toArray(). The structure that you get back ther for your field is usually also what it expects to be set.


How to make blocks contextually aware of current webform page I have a multipage Webform that lives at a single URL and I would like to place certain blocks depending on which page the Webform is on.

None of the webform hooks give access to page number, and the only way to do so seems to be through a hook_form_alter which afaict is a bit late in the page build to pass information to other modules like Views and Context.

Any ideas how this might be achieved?

This is currently not possible through the default UI due to the URL of all webform pages being the same.

There are two possibilities as far as I know.

(1) If your blocks only show help texts or any other static information, you should probably not use blocks at all but add markup components and place them after each page break.

(2) If you are indeed using dynamic blocks (e.g. coming from views), you would need to create a custom theme file (e.g. webform-form.tpl.php) in which you may enter the logic defining which block should appear. The currently viewed page number of your webform should be available through $form['details'].


What is easiest way to debug variables in nodes, views, blocks and page twig templates? What is easiest way to debug variables in nodes,views,blocks and page template.

Earlier we used devel module in drupal 7 ,by using dpm() function it shows very neat and clean structure ,it was so easy to find out the values of variables.

Also what is the easiest way to get protected variables values.

why debugging became so complex in drupal 8?

What is easiest way to debug variables in nodes,views,blocks and page
template

Welcome to Kint 101
Installing
Using Kint with Devel 8.x-2.1, which comes with the Devel module.
Using Kint with Devel 4.0.1. Kint no longer comes with Devel, you'll need to do  composer require kint-php/kint and apply patch.
Important: in order to use kint() in a twig file you need to enable debugging for twig. If you're not debugging inside a twig/template file, you can skip this part.
If you have Drupal Console installed drupal site:mode dev, remember to set it back to drupal site:mode prod when your developing is done.
If you don't have Drupal Console, do the following:

You enable Twig Debugging in sites/default/services.yml. (If
services.yml does not yet exist; copy default.services.yml and
copy it to services.yml.)
Set the debug variable to true. And clear cache.
parameters:
  twig.config:
    debug: true

Remember to turn debug back to false after you're done developing.
Source Debugging Twig templates
Now do the following to prevent issues with Devel 8.x-2.1, skip this part if using Devel 4.0.1
For starters, you are likely to run into this issue when you try a kint dump, specially if you just try{{ kint() }} without passing any parameters

This is due to the array or object being too big for your server resources to handle the default kint settings.
Edit /modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.
Ok, lets use kint
Note: If you're trying to dbug when logged out, you'll need to give Access kint information permission to the anonymous user role.
For Example, in comments.html.twig we do a {{ kint(content) }} and you will see

Tip #1 Do not click the + button, it's pure Evil
The + button will automatically open every single children and their children.
Instead, click on anywhere on the bar but the + button, for example, click here

Look how nice a tidy our Kint is

Also what is the easiest way to get protected variables values.

Getting a value
Lets say we're interested in the User. So click on user, but again do not click on the + button. You will see this

The id is protected, how do we get this value?
Tip #2 click on the available methods tab
This will reveal all methods that we can use here

So simply go with the one that makes most since, here being id() to get the user id.
{{ content.user.id() }}

why debugging became so complex in drupal 8?

It's not, as long as you know how to use Kint
Using all the above tips and tricks, I was able to answer this question Show comment author e-mail in comment.html.twig


How to display a Paragraph field with a condition Hello here is my problem, I have a paragrah type with an illimited value image field in which I store image(s) to display them in 200*200 but also a single Json file with mapping data linked to the image(s) in the paragraph.

But in the drupal conf I can not hide the json file name since it's stored in the same field, they would both be invisible (json and image).

However I'd like to display in the Frontpage view and so (/node/xxx) only the image(s) and not the json file name even though they are in the same paragraph field, is that possible directly in drupal configuration or do I have to make a template ?

Depending on how complex your logic is, you can either write it inside the paragraph preprocess function, as in:

function THEME-NAME_preprocess_paragraph_PARAGRAPH-TYPE($variables, $paragraph) {
  if(some_condition) {
    $variables['field_name'] = $paragraph->get('field_name')->value;
  }
  // ...
  return $variables;
}

or write the same logic inside twig template if its simpler, as in:

{# paragraph--PARAGRAPH-TYPE.html.twig #}

{% if condition %}
  {{ content.custom_var }}
{% endif %}

I can elaborate and edit this answer if you are more specific.


Different user form for registration and edit I'm trying to make different forms layout for user registration and user edit account:
- User Registration: Display it paginated, like a wizard.
- User edit: Display it in only one page.

I can use FieldGroup Multipage field to make a paginated user registration form. But it affects the edit page too.

There's some module that can accomplish this?

Any help would be appreciated!

the multistep registration module will help you with this I think.
Together with the profile2 module.
Those 2 modules will help you with the multi step registration part. For the user edit page you should check the checkbox in the profile2 preferences where it says use a seperate page for editting user profiles


How do I strip HTML markup or use plain text in the body field? I am using a view to create a block that display a set of data. The data appears as expected, but it shows HTML markup between body fields, which I want to strip or render as they are like in nodes. I am using hook_views_pre_render(), but I am not able to strip HTML markup with that.

How can I achieve this? Is there any view settings for removing HTML markup?

I was using Aggregation (Group Results Together) which caused body field to print the unrendered HTML which is fixed by checking the Format option in additional fields to true.


Alter appearance of content types in teaser view through code? What I would like to accomplish is the following:

When a list of a certain content type is displayed, I would like an "edit" link to be placed at the end of the summary text that, when clicked, would take the user to the node edit page for that particular node.

This list would either be created using the Views module, or through a taxonomy. That part isn't important.

How can I do this through custom module code? I'm trying to learn more about writing modules on my own, and would prefer to avoid using an already built module in this particular case, since I will already be creating the content type in question through a module anyway.

Would I do this through module code, or through theme code?

The best example of this I can think of is the Read More module which adds a "read more" link to the end of the body teaser (in teaser mode obviously).

The idea is to use the node view hooks and teaser build mode to target what and when you want to edit.

For Drupal 7 you can look at the read_more module source for an example.
For Drupal 6 you can look at the ed_readmore module source for an example.


How to find drupal 6 ubercart Persian translation? Does anyone has drupal 6 ubercart persian translation or Anyone know how can I find it?
Please help me
Thank you

You can find the direct link here:

http://ftp.drupal.org/files/translations/6.x/ubercart/ubercart-6.x-2.9.fa.po

In case you're interested (and for future reference) that comes from the Ubercart translation downloads page on Drupal.org.

You're pretty lucky, it was only generated 2 days ago!


How can I print subparagraphs? I have a content type with a paragraph field. That paragraph field has two paragraph fields which I will refer to as subparagraphs.

I want to print one of the two subparagraphs depending on the flag set in the preprocess function.

Paragraph: field_banner_header

Subparagraphs: field_banner_header_single, field_banner_header_multi

Twig:

<div class="callout-options">
    {% if callout_options == 'Single' %}
        {{ content.field_banner_header[0]['#node'].field_banner_header_single.value }}
    {% else %}
        {{ content.field_banner_header[0]['#node'].field_banner_header_multi.value }}
    {% endif %}
</div>

I have a preprocess hook that stores the value ('Single' or 'Multi') of a bool in callout_options:

function cse_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];

  if ($node->getType() == 'unit_landing_page') {
    $variables['callout_options'] = $node->get('field_active_callout_tab')->value;
  }
}

On page render, I get the following error:

  drupal.js?v=8.4.6:13 Uncaught Quick Edit could not associate the
  rendered entity field markup (with
  [data-quickedit-field-id="paragraph/426/field_banner/en/default"])
  with the corresponding rendered entity markup: no parent DOM node
  found with [data-quickedit-entity-id="paragraph/426"]. This is
  typically caused by the theme's template for this entity type
  forgetting to print the attributes.

I could be wrong, but this seems to be telling me that I am referencing the subparagraph incorrectly.

What is the correct syntax for printing a subparagraph?

Seems your preprocess function is the key. To get the value of a field, do the following:

$callout_tab = $node->get('field_active_callout_tab')->first()->getValue();
$variables['callout_options'] = $callout_tab['value'];

Really, please install the Devel submodule Kint and then check first what you get:

ksm($node->get('field_active_callout_tab')->value);

Which will most likely get you NULL or an array. So {% if callout_options == 'Single' %} can never work.

And regarding the subparagraph, all I could get was the entity ID:

{{ kint(content.field_paragraphs.0['#paragraph'].get('field_subparagraph').value) }}

but maybe I'm doing something wrong (and you already solved that yourself). But if the entity ID really is the maximum you can get you are better off loading the subparagraph in the preprocess function as well and pass the render array over to Twig like you did pass the bool. In theory this should work :)


How can I enforce a minimum length for private messages? I previously asked how to enforce a minimum length for fields and received some great answers.

Now, I would like to enforce a minimum length for private messages only when it is the first message in a conversation (the private message module calls "threads" of messages conversations).

Use case: I don't want users to be able to send messages consisting only of "hey" or "hi"; thus, I need to enforce a minimum length for the first message.  However, once users are talking to one another, it is completely possible that a reply could be "yes" or "no", etc., so follow-up messages should not be limited in length.

Looking through the Privatemsg API, it looks like this might be able to be done with hook_privatemsg_message_validate(), but I'm not much of a coder and I'm at a loss about how to proceed from here.

You will need to create a custom module to use that hook it will allow you to run custom validation on top of the standard validation done by private msg.

A hook allows you to add functionality to a module without having to hack the module causing issues when the original module needs to be updated. When a module makes a hook available it allows other modules to perform additional processing during the execution flow in this case additional validation
more on hooks here - http://drupal.org/node/292

As a minimum your module will need a info file telling Drupal about your new module and a module file containing the hook with your extra validation code.

You can see what to put in your info file here - http://drupal.org/node/1075072

This page will guide you through setting up your module folder and naming http://drupal.org/node/1074362

Now you have your module structure set up you need to add the hook_privatemsg_message_validate() to the module file

function MYMODULENAME_privatemsg_message_validate($message) {

}

Replace MYMODULENAME with the name of your module.

From looking at this page it looks like the original message id becomes the thread id if its a reply http://api.worldempire.ch/api/privatemsg/privatemsg.api.php/group/message_hooks/7-2

array (
 'mid' => 3517, // message id, identifies a message
 'author' => 27, // author id
 'subject' => 'Message subject',
 'body' => 'Body of the message',
 'timestamp' => 351287003, // unix timestamp, creation time
 'is_new' => 0, // If the message has been read by the user
 'thread_id' => 3341, // thread id, this is actually the mid from the first                          message of the thread
)

My guess is you could do something like this to test:

if($message['thread_id'] == 0 || empty($message['thread_id']) && strlen($message['body']) < 25) {
form_set_error("Message must be n chars long");
}

I'm not that familiar with the module so you might need to investigate by printing out the message array to confirm this.

Putting it all together it would look something like this

function MYMODULENAME_privatemsg_message_validate($message) {
    // Uncomment next line print out the message array if you need to confirm what contiton to use for checking if first msg or not
    // echo print_r($message);
    if (empty($message->thread_id) && strlen($message->body) < 25 /* Change this to whatever length you want*/) {
        form_set_error('body][value', t('Message must be n chars long.'));
    }
}

Hopefully thats enough to get you started


drupal loses track of a library (leaflet), randomly I have an strange problem with a library (leaflet).

I have some maps, and it works fine, but randomly (as far as I have been able to detect) drupal is unable to find leaflet.js and leaflet.css (it is allways located in sites/all/libraries/leaflet , as indicated in leaflet drupal module website).In fact I can see in Firebug that Drupal is not even trying to get the library (I get no server error message saying it cannot find the files or similar)

When this 'error' happens, I have to do strange things like moving the leaflet.js file to another folder or change the name and then, after drupal fails and I rename the file again, MAYBE drupal is able to find it again. Sometimes it seems like flushing cashes helps but not allways...I know it sound dummy but it only happens with this libarry and it seems completely random. Hours wasted trying to set up again...

The folder is 755 in permissions. Have tested in a different PC and the same problem! changing browser or clearing its cache doesn't help neither.

thanks in advance

How do you see that drupal does not find that files? Is it correct that you just get 404 for that files in browser? Try to load these files in browser window like http://yourdomain.com/sites/all/libraries/leaflet/leaflet.js. If it's not loaded, it's your server issue, rather than drupal one.


How to link a view to the current language with a no results fallback to the default language? I've already figured out how to link views to content language by the Content: Language filter. I know that I can create a second view to use as the No Results fallback and use the Global: View area to feed the other in. But to do this I have to:

pollute my site's blocks with Localized and Unlocalized duplicates and hope
the client understands that they should only enable the Localized block.
make sure to maintain a duplicate of the original with only the Content: Language filter changed.
tolerate a full second set of queries to generate the block? Some blocks are ordered by random, so they can't really be cached well.

Isn't there a better way to do this?

Also, I know I can use the rearrange feature on the languages to set up conditions like:

Content: Language (In user's current language) OR
Content: Language (In default site language)

But the issue is that then these languages are mixed. I need the default site language to appear only when there are no nodes in the current user's language.

Check out http://www.webomelette.com/drupal-views-pre-render-alter-display, u should be able to use hook_views_pre_render() in a custom module and check your result set before rendering.

In the case of no results, change language to sites default in the view object, although im not sure that this hook will trigger your new query to run and bring the default lang contents, but its a start!

http://drupalcontrib.org/api/drupal/contributions%21views%21views.api.php/7


Request referer gets cached I need to grab referer and save it for the first time (I save it to sessions) and when the user gets to a specific page forward it. My problem is that after opening page with the same referer few times, I am not getting referer anymore. I tried it with few different browsers in private/incognito mode but after a few tries it gets cached and does not return anymore. My Code :

function HOOK_template_preprocess_default_variables_alter(&$variables)
{
    $request = Drupal::request();

    var_dump($request->headers->get('referer')); //stops dumping after few times

    $_SESSION['referer']['url'] = $request->headers->get('referer');
    $variables['#cache']['contexts'][] = 'headers:referer';
}

Is there a way to save referer for every anonymous user that comes to website?

For doing this, i won't use a hook but the drupal eventSubscriber :

First your need to make a custom module with the file for declare to drupal your new service :

  myModule.services.yml

services:
  myModule.services:
    class: Drupal\myModule\EventSubscriber\MyServiceSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

Then in the file :

  myModule/src/EventSubscriber/MyServiceSubscriber.php

<?php

namespace Drupal\myModule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

    /**
     * Class myServiceSubscriber.
     *
     * @package Drupal\myModule
     */
    class MyServiceSubscriber implements EventSubscriberInterface {

        public function onRequest(GetResponseEvent $event) {
           // here your code, this method ll be call on every call request
           // so you can code your logic here
        }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {

          $events[KernelEvents::REQUEST][] = ['onRequest', 900];

          return $events;
      }

    }


Creating Custom Drupal 7 Registration Form I am trying to create a custom registration form on D7.
According to this article

The steps should be (theme name is icompany)

Modify template.php to override the registration form

function icompany_theme(&$existing, $type, $theme, $path){
  $hooks = array();
  // Make user-register.tpl.php available
  $hooks['user_register_form'] = array (
    'render element' => 'form',
    'path' => drupal_get_path('theme','icompany'),
    'template' => 'user-register',
    'preprocess functions' => array('icompany_preprocess_user_register_form'),
  );
  return $hooks;
}

Create a second function which builds the form

function icompany_preprocess_user_register_form(&$vars) {
  $args = func_get_args();
  array_shift($args);
  $form_state['build_info']['args'] = $args;
  $vars['form'] = drupal_build_form('user_register_form', $form_state['build_info']['args']);
}

Create user-register.tpl.php with the newly styled form

My problem is this does not work.  My custom form does not seem to be called.

The alternative approach is to create page--user--register.tpl.php.  This sort of works, any text I put on the page appears but the form fields do not using the syntax

<?php
print render($form['account']['name']);
print render($form['account']['mail']);

?>

I have tested the code and it's almost working as it's intended to be. One thing to note is when you placed the template file inside of the templates folder then the following should work.

On the icompany_theme() function, change the path value from 'path' => drupal_get_path('theme','icompany'), to 'path' => drupal_get_path('theme','icompany') . '/templates', which specifies to look for the file inside the templates folder.

Then flush your caches.


Prepopulate a field in a Reference Dialog Box I have 2 content types named Incident and Migrant. Both of them have fields that reference each other. My question is how to prepopulate a field in a reference dialog box while the node is being edited?

How am I going to prepopulate Incident field with Incident 36 nid. When the popup/dialog loads? Assuming that Incident field is a Autocomplete Text Field?

Here's what I tried, I have tried Entity Reference Prepopulate but, I figured that that the Reference Dialog is displayed via iframe so getting the nid from the URL wont work.

I'm very new to drupal and still in the learning curve so if possible answer me in a detailed fashion.

Modules i used

Entityreference prepopulate
Reference Dialog

Yes, you can.
What you need for this?
1) references_dialog
2) entityreference_prepopulate
3) your custom_module.
For example field that you want to make with prepopulated field in url is entityreference.
Here is link to youtube how to use entityreference_prepopulate and URL https://www.youtube.com/watch?v=z9C4Uf6euLY.

After this you should override your "Create ..." link. How to do this?
Easy. Just implement hook_references_dialog_widgets_alter in your custom module and change name of function that generate add link

/**
 * Implements hook_references_dialog_widgets()
 */
function mymodule_references_dialog_widgets_alter(&$widgets) {
  $widgets['entityreference_autocomplete']['operations']['add']['function']
    = 'mymodule_references_dialog_entityreference_add_link';
}

And than you can define your add link function:

function mymodule_references_dialog_entityreference_add_link($element, $widget_settings, $field, $instance) {
// blah blah from original function
// Here you can catch field what you need and define url with $_GET parameters for it.
}

That's all. Enjoy reference dialog with get params in url.


Unable to save textfield on node_save() $fbuser = new stdClass();
   $fbuser->first_name = 'abc';
   $fbuser->last_name = 'cde';
   $fbuser->location = 'Vas';
   $fbuser->link = 'http://www.facebook.com';
   $fbuser->gender = 'male';
   module_load_include('inc', 'node', 'node.pages');
   $node = new stdClass();
   $node->type = 'profile2';
   node_object_prepare($node);
   $node->uid = 1;
   $node->field_profile_fn[0]['value'] = $fbuser->first_name;(textfield)
   $node->field_profile_ln[0]['value'] = $fbuser->last_name;(textfield)
   $node->field_profile_city[0]['value'] = $fbuser->location;(textfield)
   $node->field_profile_facebook[0]['value'] = 'http://www.facebook.com';(textfield)
   $node->field_profile_gender[0]['value'] = $fbuser->gender;(select list)
   node_save($node);

In the above code I am trying to create a new content of type profile2 .
My node is created but some of the fields show empty text like

field_profile_facebook which is textfield does not show value provided above and gives empty text.

You forgot to add the language to your fields:

$node->field_profile_fn[LANGUAGE_NONE][0]['value'] = $fbuser->first_name;

But even then, this is not the way to go. You should take a look at https://www.drupal.org/documentation/entity-metadata-wrappers

This approach allows you to use something like this:

 $wrapper->field_profile_fn->set($fbuser->first_name);
 $wrapper->save();


How to make node delete confirmation inline? I need to know how to override the normal delete node confirmation (preferably for a specific content type). My site has one content type that users are able to delete and right now it forward them to an unstyled /delete/ page to do so.

I'd like the same functionality but with an inline delete confirmation on that content type, ideally without additional modules.

Edit: Just realized I would have to manage permissions to account for deleting the content. May need to do it directly bypassing regular methods

you can put this in your node--node-type.tpl.php file:

$item = menu_get_item("node/$nid/delete");
if ($item['access']) {
    include_once(drupal_get_path('module', 'node') . '/node.pages.inc');
    $page_title = drupal_get_title();
    $delete_form = drupal_get_form('node_delete_confirm', $node);
    print render($delete_form);
    drupal_set_title($page_title, PASS_THROUGH);
}

also you can remove Cancel link from $delete_form


Deadlock issue on my server I am getting the following error:

  PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: INSERT INTO {domain_source} (nid, domain_id) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1); Array([:db_insert_placeholder_0] => 101712 [:db_insert_placeholder_1] => 0)

This happens hook_node_update(). Do you have an idea on how to solve the issue?

After applying this Patch, these errors are reduced however not fully rectified. This patch prevents empty delete queries being run and thus reducing the load on the domain_source table.


Need help modifying the OG "add user" form to replace the user search box with first and last name searches I could really use some guidance with an OG related task. I'm needing to modify a form used to add existing users to organic groups. The path is "/group/node/1/admin/people/add-user". I need to remove the user search box and instead implement a couple of name searches: "Firstname, Lastname", and "Lastname, Firstname".  Not sure what I should be modifying via a hook_form_alter, or other hook. Any thoughts?

Attached is a before and after view of the form. I appreciate any guidance anyone can provide.

Thanks!

I ended up using a custom callback to populate a new field called "full_name", and then used JQuery to populate the username field on blur of my new field, and also hid the username field to make the interface a little more intuitive. It worked well enough, but it would be nice to completely override the submit function and use a custom one to ensure everything worked as expected. If a user enters in an invalid name and clicks enter, the default validation fires off, and nothing I've created works without a page reload. Kind of stinks, but at least it's working for the time being.


Check if referenced field exists in commerce product display I have to render different types of product (with different fields combinations) in a generic product display tpl file.
I created an array with all possible field names (they all are referenced product:field_name) which passes through a

if ($content[$my_field]){
  //some code
}

that is supposed to check if the field exists and then do things...

The problem is that it actually checks the existence of the field but shouts out a notice: undefined index warning for every field that is not present.

Is there a way to execute this check in a cleaner way?

Thanks!

If I understood your question correctly, you should check if that element exists; here's how:

if (isset($content[$my_field])) {
  //
}

This way if the field is not set, you won't get the undefined index error.


Google translate service not available on Translation Management module(Drupal 6) When I using the translation management to translate my node, I got "Google translation failed to Chinese, Simplified: Google returned error #403: Quota Exceeded. Please see http://code.google.com/apis/language/translate/overview.html", anyone know what happen and how to fix it?

Thanks

Like is said on that page http://code.google.com/apis/language/translate/overview.html access to Google Translate API is now limited.

If you still want continue to use the module you should have a look into this discussion http://drupal.org/node/1215426 where they are looking for another solution.


Adding jQuery to a view (exposed filter: search terms) I'd like to add some jQuery (for search highlighting) to my Drupal 7 Views with exposed search terms filter. The point is that when a user clicks a search terms (or terms) the jQuery then highlights those words they searched for in the returned results.

I created the following preprocess function in my template.php file:

    // add jquery.highlight-5.js just to the search views page
    function themename_preprocess_node(&$variables) {
      if(arg(0) == 'node' && arg(1) == '8' && arg(3) == null) {
        drupal_add_js(drupal_get_path('theme', 'themename') .
'/js/jquery.highlight-5.js');
      }
    }

But as I put this together I realize I don't know what to put in arg(1) for my Drupal View. Anyone know how to find out the 'nodeid' of the Drupal View?

Use hook views pre render instead.

function themename_views_pre_render(&$view) {

   if ($view->name == 'view_name' && $view->current_display == 'block_1') {
    drupal_add_js(drupal_get_path('theme', 'themename') . '/js/jquery.highlight-5.js');
   }
}

replace themename with your theme name
replace view_name with your view name
replace block_1 with your machine name


Exposed Filter Fulltext Search having the Searched fields as options along with the text box I have created a exposed fulltext search filter with the searched fields["tile", "Description","Keywords"]. This brings the widget to the form as a textfield, which searches the input for all the three fields.

I'm trying to bring the searched fields["title","Description","Keywords"] to the form as a radio button list, So that the user can type the input and select under what field to refine the result.

Any help really appreciated!

I found a work around for this. We can create a radio button list in hook_form_alter() having the searched fields. Using hook_search_api_views_query_alter(), we can alter the fields that are passed in the $query object, so that the result set is returned only for the field that is been searched.

function MYMODULE_search_api_views_query_alter(&$view, &$query) {
    if(isset($_GET['your_field_name'])) {
        switch($_GET['your_field_name']) {
            case 'field1':
                $fields = $query->getFields();
                $fields = array( 0 => 'field1_value');
                $query->fields($fields);
            break;
            .....
            .....
          }
        }
      }


Issue using Exposed filters along with contextual filters in views I have a view page listing my stories/articles. I have a contextual filter based on the field Country which is a taxonomy term reference field. I have defined the path of the page as article-search/% to accommodate the contextual filter value.

I have an exposed filter on the field article-category which is also of type taxonomy term reference. I use better exposed filters to display the exposed filter values as links.

The contextual filter works fine and I configured the url to display taxonomy name instead of term id. This part works fine but when I click on any of the links in the exposed filter the taxonomy term name for the contextual filter value changes to %25 instead of the taxonomy name and the contextual filter fails. It works fine if I use the default dropdown option for the exposed filter instead of better exposed forms.

Any idea if there is an issue with better exposed filters when used along with contextual filters?

Sorry! I should have looked at the issue queue. There is already an issue logged for this. Here is the link to the issue https://www.drupal.org/node/2179169

The issue got resolved when I applied the patch provided by Jim Keller in the issue link
https://www.drupal.org/files/issues/better_exposed_filters-fix_exposed_block_link_path-2179169-1.patch


Cannot acquire lock for source node / 0 This error showing when I tried to import a CSV file on my live site. Same file I tried in local site working fine.

  Cannot acquire lock for source node / 0.

The modules I am using are the following:

Feeds
Feed Excel
Libraries (PHP Excel)

I examine the issue and found that the error occurred when I tried to import an image. Have anyone faced this issue?

To release the lock, remove it from semaphore table, e.g.:

drush sqlq "DELETE FROM semaphore WHERE name LIKE 'feeds_source_%'"

If you got different error like:

  The feed is currently importing.

then you need to clear out state and fetcher_result data from feeds_source table, e.g.:

drush sqlq "UPDATE feeds_source SET state = NULL, fetcher_result = NULL WHERE id = 'FEEDS_MACHINE_NAME' AND feed_nid = 'NID'"

Note: Change FEEDS_MACHINE_NAME and NID into appropriate values.


Is there an easy way to serve low quality images for low-bandwidth users? I'm designing a site that wants to use lots of images, but while some users will be on broadband, other user groups will be on dial up or similar.

Is there some trick/module that can serve lower quality images based on a cookie, for example?

I guess I'm thinking perhaps a parallel set of image styles that uses a lower quality (these could be provided by image style quality module) and something that detects when one style is requested and switches it for the lower quality version?

Long shot asking for a technical solution to a design-based problem, but thought I'd ask in case anyone else has come upon this problem.

I don't know that there's a way to determine benchmark throughput performance on the fly without wasting a lot of the users time running a test, on every login. You could do something like:

add a field to the user profile that the user can change which dictates the speed they use
use a custom style or set of styles for all images
create a custom module to override hook_image_styles_alter() to adjust (if necessary, based on the user field value) the style to suit

  This hook allows modules to modify, add, or remove image styles. This
  may be useful to modify default styles provided by other modules or
  enforce that a specific effect is always enabled on a style. Note that
  modifications to these styles may negatively affect the user
  experience, such as if an effect is added to a style through this
  hook, the user may attempt to remove the effect but it will be
  immediately be re-added.

This way the user can determine which speed they are using, and the system should adjust the images on all subsequent logins to fit their choice


backing out of a module update after uploading it and before the database update (new update is incompatible with my version of PHP) I got a situation here and I don't know what to do. Drupal 7.

There's an update for reCAPTCHA so I click the button and checkboxes and whatever to update it, it uploads the files to the server and unpacks them and stuff, and then I click the "update database" link. BTW, there's two other modules being updates: rules and GA.

On the resulting page, /update.php, it first check the requirements (I rarely see this screen, it usually breezes right past it) and there's a big red error message saying that "reCAPTCHA requires at least PHP 5.5.*" and I have PHP 5.4.45.

Should I delete the reCAPTCHA module from /sites/all/modules/, and then put the files for the old version in there? If I do that, will the database updates script be confused?

Thanks!!

Should I delete the reCAPTCHA module from /sites/all/modules/, and then put the files for the old version in there?

Yes, that's exactly what you should do.

  If I do that, will the database updates script be confused?

They shouldn't be - when you start an update, the current versions of modules are queried from fresh again. So as long as the current version of the module in the database matches the version in the file system (which it will if you restore to before the file system change), you should be fine.


Can't install drush8, having drush6 I installed drush, and when I do "drush status" it says that my drush version is 6.6.0.

I want to have drush7 instead, so I downloaded it from github, and did following commands:

chmod +x drush.phar

sudo mv drush.phar /usr/local/bin/drush

drush init

I get following error: the drush command init could not be found.

When I do drush status, it still says I have drush6 version... what do I need to do?

Can always install manually

# get drush latest 8 version from
# https://github.com/drush-ops/drush/releases
# or any version that you want
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar

# move it to home directory or any other directory
mv drush.phar ~/drush

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bash_profile
# or in some systems
# nano .bashrc

# add this the end of the file
alias drush='/home/your_user/drush'

# use the alias you just setup
source ~/.bash_profile

NOTES:
Above example works in ubuntu but should be similar on other distros

According to the docs drush 8 works with D8, D7 and D6 so no reason to install drush 7

If you want to call it with drush8 use following alias drush8='/home/your_user/drush' in .bash_profile file


Programmatically get the list of fields of a custom content I want to programmatically create a custom content (custom content created via the admin UI). Before the creation, I want to check the types of fields of my custom content.

My custom content contains a field "body" (type text), a field "description" (type text), an int field (type int), an attached file field (type fid ?).

I tested several ways; this is my last try.

// I get the entity object "my_custom_content"
$entity_object = NodeType::load("my_custom_content");
dpm($entity_object); //Work perfectly

$test = \Drupal::getContainer()->get("entity_field.manager")->getFieldDefinitions("my_custom_content",$entity_object->bundle())

The code returns an error:

  The my_custom_content entity type does not exist.

With this $entity_object, how can I get the list of the fields of my custom content?
I see the EntityFieldManager class, the FieldItemList class, but I still do not understand how to play with Drupal 8.

You're mixing up entity types/node (content) types/bundles. Common mistake :)

Especially since the UI naming is... very unfortunate.

What is called Content in the UI is actually the entity type node. And Content types are node types (you figured out that much), which are bundles of the node entity type.

getFieldDefinitions() expects an entity_type ID and a bundle. In your case, that is:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

Note that this will also return base field definitions like nid, vid, title, status and so on.

Tipp: Once you have a node object, you can get the same definition from that object and other useful information too:

$node = Node::create(['type' => 'my_custom_content']);
$node->getFieldDefinitions();
$node->getFieldDefinition('body');
$node->hasField('body');

So if you want to dynamically do something like this, it can simplify your code a lot if you first create the node with the information that's always enable and then work with the methods on your entity object.

Default recommendation when working with entities in 8.x: http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet


Hiding Field(s) if Date is Expired I'm using Drupal 7 date field. Using views, when the date has expired, the page goes to a section labeled 'past events.' In the template page, the date and time are both separated for instance. $date_output and $time_output. I need to hide the time field after the date has expired. any ideas?

If your date is in one of the supported date/time formats, you can use strtotime() and date() to compare.  Wrap the printing of $time_output in an if statement.  For example:

if ( strtotime($date_output) > date() ) {
  // $date_output is greater than now, eg, not expired
  print($time_output);
}

If $date_output is already a timestamp, no need to use strtotime()


Having required (*) show up on the component itself and not the label I'm creating a webform select options component and I want to hide the label.

Because this is a required, it needs to display with the red asterisk that the field is required.

However, the asterisk is displayed against the label header and when you hide the label, it doesn't get displayed in the option itself.

Is there any way around this?

Have you tried Form Placeholder? It will hide the label and add the asterisk on the select field.


How to call a Rules action settings form via drupal_get_form So, I'm trying to embed the form I find at '/admin/config/workflow/rules/reaction/manage/commerce_payment_paypal_wps/edit/3' - which contains the settings for the PayPal business, etc (from commerce_paypal_wps.module).

Looking in rules/ui/ui.controller.inc I can see it's called thus:

$items[$base_path . '/manage/%rules_config/edit/%rules_element'] = array(
      'title callback' => 'rules_get_title',
      'title arguments' => array('Editing !plugin "!label"', $base_count + 3),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('rules_ui_edit_element', $base_count + 1, $base_count + 3, $base_path),
      'access arguments' => array('administer rules'),
      'load arguments' => array($base_count + 1),
      'file' => 'ui/ui.forms.inc',
      'file path' => drupal_get_path('module', 'rules'),
    );

I'm not entirely sure what extra things I should be passing into drupal_get_form('rules_ui_edit_element') to make it render the form as it does normally.

How on earth do I get that rules action settings form to render either through drupal_get_form, or some other mechanism, so I can put it at the URL of my choosing, and make it look a bit more presentable to our clients?

You must be using an old version of commerce to get an url like that. It was changed long ago to dmin/commerce/config/payment-methods/...

In hook_menu, the commerce_payment_ui module creates the path, where the rules forms should be located:

// Add the menu items for the various Rules forms.
$controller = new RulesUIController();
$items += $controller->config_menu('admin/commerce/config/payment-methods');

You could alter those if you want to change the url. You should however be aware that this url is also used elsewhere:

/**
 * Builds the payment settings page using the Rules UI overview table filtered
 *   to display payment method rules.
 */
function commerce_payment_ui_admin_page() {
  RulesPluginUI::$basePath = 'admin/commerce/config/payment-methods';

  ...
}

Since most of what Rules does, including creating these settings form is classed based, it wont exactly be easy to create the form. I haven't delved much into the Rules code, but I remember seeing public functions called

form
form_validate
form_submit

I believe these are used to create the form, but how it ends up in the FAPI is beyond me. If all you want is to change the path, you could just use hook_menu_alter and for commerce, overwrite the commerce_payment_ui_admin_page function with your own to create the overview table.


How to style a webform like a spreadsheet? I've been asked to develop a webform to look like a spreadsheet.
Unfortunately, the site is written in D6 and I've only really developed in D7.

Can anyone recommend a module / method to achieve this?

It sounds like you're looking for Webform Table Element that will render your webform inside a table.

  This module will add a new component to Webform module that allows you
  to render multiple components inside a table element.


Batch API on a Dreamhost dedicated server I am on a Dreamhost dedicated server. I use it to host Drupal sites that our company creates. We recently moved on to this server from another hosting company and have noticed that Batch API features do not work for Drupal 6 or 7. (This same dataset that's failing worked on our last server)

What is the difference? I have upped max_allowed_packet to 100mb, I have increased the Apache timeout to 900 seconds, and have changed the following PHP vars to some pretty high amounts:

max_execution_time = 1600
max_input_time = 1600
memory_limit = 2048M
post_max_size = 2048M

It still won't seem to work. It hangs on initialize and gives me the following message:

  An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging
  information follows. Path: /batch?render=overlay&id=3329&op=do
  StatusText: Forbidden ResponseText: Access denied

I can run them in the background with Drush, however I have to run core-cron several times over and over to make the import work. This works for some items, but is not ideal as some clients like to use Views Bulk Operations on their sites for managing content.

My server is the top of the line server with 16GB of memory.

I solved this by updating "FcgidIOTimeout" in httpd.conf. I set it to an hour.


Run javascript code on Form Submit I want to run JavaScript code upon a form being submitted preceding other default tasks that are carried out on form submission.

May anyone suggest some approaches?

Depending on the type of code that you need to run, and from the Drupal version, AHAH and AJAX could be the answer.

On Drupal API, there is example code for AHAH (Drupal 6), and AJAX (Drupal 7 and higher).


What is the equivalent of drupal_set_content()? I am searching for something equivalent of drupal_set_content() for Drupal 7, to assign a block to a region. Do you have any idea?

The equivalent of drupal_set_content() is drupal_add_region_content().

  Adds content to a specified region.

  Parameters

  $region: Page region the content is added to.

  $data: Content to be added.

Notice there was a bug in Drupal that didn't allow this function to work, since drupal_region_content() was not properly called. (See Content added via drupal_add_region_content() is not added to pages.) It has been fixed on March 2015; if you are using any version earlier than 7.36, drupal_add_region_content() will not work.


Installing a site from existing configuration I tried importing a configuration after installing Drupal 8 using the standard installation profile but was getting into errors related to the installation profile being already present.

I need a clean drupal slate with only the configuration and no content.  Is it possible to do that?

I found out we can do this by running the following drush command

drush site:install --existing-config

However you might encounter an error related to hook_install found in standard install profile. To mitigate that you would need to install this patch.

https://www.drupal.org/files/issues/2018-11-27/2982052-22.patch


How to find all views and panels that use a certain field I want to delete a field but I am not sure if there is still a view or a panel somewhere on the site that is still using it. So I want to know if there is any possibility to find all views and panels that use a certain field?

In D7, you can see this for views at least at
/admin/reports/fields/views-fields (Admin -> Reports -> Field list -> Used in views)

(Similarly for content types it is at
/admin/reports/fields/ (Admin -> Reports -> Field list)

Don't know about panels though.


Does Drupal keep timestamps of every time node is updated I'm wondering whether Drupal keep tracks (keep timestamps) of every time a node is updated (not just the last updated). If it does, how could I access this in the front end?

Yes, Drupal stores the updated date, but for that you need to enable revisions on  the content types you need it. From your revision table, you can get when a node has been modfied. You can also get how many times you have created a revision and other revision details.

Check the node_revision table; you will get the details.


Specifying a CSS class for a view In Drupal 7 using Views 7.x-3.3, I've specified a CSS class for the view under Advanced -> Other -> CSS class.  I have my CSS class defined in my custom theme CSS file as...

TABLE.listView {
  border: 0;
  border-spacing: 0;
  margin: 10px 0;
  width: 100%;
}

but the view is not using the class.  When I look in FireBug I see it using a class "views-table cols-5".  If I overwrite that class in FireBug with the one I created in the theme, the view table is styled the way I want it to look.  How can I get views to use the CSS class I've specified?  All I'm trying to do is get the table styled the way I want it to look.

Given the commentary above, all you should need to do is cascade your class/table, eg, something along the lines of...

.listView table {
  border: 0;
  border-spacing: 0;
  margin: 10px 0;
  width: 100%;
}


Display Search Block in template DRUPAL 8 VERSION

Hi i am trying to display the search block in a custom view named as menu--main.html.twig. Below is the code in my theme function

function bootstrap_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('bootstrap_search');
  $variables['block_search_form'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

I am able to display the search block in page.html.twig. But i want to display the block in menu--main.html.twig Can someone guide me how can i achieve this?

I was using the wrong hook as suggested by kevin. The hook to be used there was bootstrap_preprocess_menu__main .... It all became cleared after reading this comment https://api.drupal.org/comment/62602#comment-62602


Getting the entire index of nodes from REST API I'm looking for a way to get all the nodes to be shown on my REST service.
When I query the endpoint index http://server/api/node it only returns 20 results. Are there any additional parameters I can send along to unset this limit?

I would be really thankful for a quick answer. I have been spending a couple of days now to get the REST service in Drupal to work the way I need it to work.

P.S. I'm on Drupal 7

The index actually sends 20 results per page. I highly recommend you check out the ServicesResourceNodeTests.test file in the services module for a better explaination but basically you can pass the page number you want to get each page of results.

The test file shows how it checks to see if the next page is empty:

// The n+1 page should be empty.
    $responseArray = $this->servicesGet($this->endpoint->path . '/node', array('page' => $page_count + 1));
    $this->assertEqual(count($responseArray['body']), 0, t('The n+1 page is empty'));

Another (my preferred) option would be to use the Services Views module instead and that way you can get all the nodes in whatever format you wish!


Comment pagers in D7: They appear even when the page has only 1 comment! I have this Drupal 7 site (updated from my D6 site).
I have nodetypes wich allows comments.
I have the pager for comments at the very end of the comment lists that shows (as you can imagine) the complete pager:
<< 1 2 3 4 ... >>

The thing is that the max comments allowed per page is 50, and even in nodes that have 1 or 2 comments the complete pager appears!

How can I prevent that from happening?

Thanks!!

After researching for quite some time, I´ve found this reply in the Omega issue queue that gave me the answer. Even when the answer has nothing to do with the theme layer.

In short: When this happens to you, it´s probably because the pager is conflicting with a views block with it´s own pager activated, all in the same page.

You actually fix this by giving the Views pager a different value than the default zero.

Posted it here just in case anyone encounters with this issue again!

Cheers,

Rosamunda


how to add taxonomy terms to admin/config/people/accounts/fields programmatically? I know I can use the UI at admin/config/people/accounts/fields to add existing taxonomy fields.

But I want to create them automatically using my module.

I know I can use hook_enable() or hook_install() for this but I don't know which hook or function I need to use to make the field show up in admin/config/people/accounts/fields ( and on the user edit / registration page )

I've read somewhere something about a bundle but I'm not sure if I'm looking in the right direction there.

You need to create an instance of the field, and then attach it to your content type. This is done using the field_create_instance() function.

There's a nice example in the standard profile of attaching the 'Tags' vocabulary to the article content type upon install:

$instance = array(
  'field_name' => 'field_' . $vocabulary->machine_name,
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'article',
  'description' => $vocabulary->help,
  'widget' => array(
    'type' => 'taxonomy_autocomplete',
    'weight' => -4,
  ),
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
  ),
);
field_create_instance($instance);

The documentation page has a full list of all the available properties for your field instance, but the above code is an excellent place to start.

I also have this piece of code in my arsenal which dumps the field/instance definitions of an existing field so I can inspect it and just chop and change what I need to:

$entity_type = 'node';
$field_name = 'field_FIELDNAME';
$bundle_name = 'BUNDLE_NAME';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');


Change content color based on Date Range I am building a website using Drupal 7, Views, Rules, Ctools, Panels, etc.

I need to change the content color based on the date. The idea is that each quarter's reports have a different color to make them easier to sort over the life of the student.

Any ideas on how to achieve this?

In your theme, you can implement hook_preprocess_page(&$variables) were you can retrieve the currently displayed content (if any) as $variables['node']. From there, you can retrieve the value of a date field using field_get_items() and use that value to assign classes to the <body> of the page in $variables['classes_array'].

function THEME_preprocess_page(&$variables) {
  if (($node = $variables['node']) && ($node->type == 'report')) {
    if ($items = field_get_items('node', $node, 'field_report_date')) {
      $variables['classes_array'][] = drupal_clean_css_identifier('report-month-' . format_date($items[0], 'custom', 'F'));
    }
  }
}


hook_cron_queue_info doesn't run I am using hook_cron in my module to create a queue.  The queue will process a couple of non-drupal database tables and synch some data around (a process that can take close to 10 minutes).  I'm creating a single item (createItem) and don't need to pass anything to the function.  I'm passing null to createItem and I've also tried passing an StdClass object.

$queue = DrupalQueue::get("alltimesynch");
$queue->createItem(null);

However, hook_cron_queue_info never runs.  I know this because the watchdog function never adds the string to the log

function timesdb_cron_queue_info() {
  watchdog("timesdb","timesdb_cron_queue_info called");
  $queues['alltimesynch'] = array (
    'worker callback' => 'timesdb_import_alltime_start',
  );
}
function timesdb_import_alltime_start($null) {
  watchdog("timesdb","Starting alltime import");
  timesdb_import_alltime();
}

What am I doing wrong?

You have to return $queues in your hook_cron_queue_info..

function timesdb_cron_queue_info() {
  watchdog("timesdb","timesdb_cron_queue_info called");
  $queues['alltimesynch'] = array (
    'worker callback' => 'timesdb_import_alltime_start',
  );
  return $queues;
}


Deleting users who have created content can lead to access bypass? The statement below appears in several places on the Internet about Drupal security. Is it the case that someone once wrote this and people repeat it in the their '10 Drupal security tips' posts without checking - or is there some truth to it?

  Disable user accounts and keep their contents. Deleting users who have
  created content can lead to access bypass.

Thanks.

Indeed the page at https://drupal.org/node/1732920 has an example scenario of how this can happen. I don't remember verifying that myself, but believe it came out of some research on an issue reported to the security team. I think Greg_1_anderson's comment about "edit own page content" is probably an important element to that scenario.

I've also seen this happen with node access modules. In discussing it with people, the theory that seems most likely:

User 42 exists and has been granted access to view and/or edit some nodes on a site using a node access module.
User 42 gets deleted, this invokes hooks including in the node access module which may take some action like updating the records it previously stored about user 42 to now point to uid 0 instead of 42
OR...perhaps it forgets update those records and instead they just exist with user 42 on them
When node access records are rebuilt, the code of this node access module either sets faulty records with uid 0 (based on step 2) or it fails to properly load a user and php/mysql will behave in their usual loosely typed ways and take the need for a record with a missing uid value and just insert a zero for the uid.

It's definitely a bug that has occurred more than once. If it can be prevented in code then it should be submitted to that module's issue queue to fix it.


How to use #element_validate and #value_callback in Drupal 8 I have followed the official Form API Documentation, but this code don't work for me on Drupal 8:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['upload'] = array(
      '#title' => t('Upload Images'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://image_example_images/',
      '#element_validate' => array('file_generic_settings_max_filesize'),
    );
    return $form;
  }

  private function file_generic_settings_max_filesize($element, &$form_state) {
    form_error($element, 'This is an error.');
  }

I have trying to remplace form_error() by $form_state->setErrorByName() but same problem, the file is uploaded and the validation is not called.

Have you a solution please ? The documentation of #element_validate is outdated ?

My objective:
Upload a lot of images, use a custom validation and insert all images thumbnails inside a

 with a field for name each images.

Example:

(After upload, display thumbnails and title field for name all each images)

Else, after upload, for display Thumbnails and other field (title and description) for each image, I need to use #value_callback, #process, #attached (manage field/display with js after upload) or an other option please ?

Thanks.

To use an instance method for #element_validate/#value_callback etc you need a callable. e.g.

$form['upload'] = array(
  '#title' => t('Upload Images'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://image_example_images/',
  '#element_validate' => array(
    array($this, 'file_generic_settings_max_filesize'),
  ),
);

You'll need to mark file_generic_settings_max_filesize() (which if you were being a stickler for standards should really be named fileGenericSettingsMaxFilesize) as public to accommodate, as your class won't be invoking the method.

Documentation for this is ongoing, the change notice is here.


I disabled a module and my website turns into code I am working on an old Drupal website. I disabled the Electric Embers subscribe module - to get rid of a newsletter subscription option to a dead list.    Previously my website was in off-line mode, but otherwise worked.    Now the website looks like pure text or code.

www.rachel.org

I checked the database and the ee-subscribe module is still enabled.

Unfortunately I didn't make a backup before turning off this module.  However, I've never seen turning off a module cause so much havoc.

I currently cannot use my admin log in or do anything directly through drupal.

Update
When does Drupal 5 change the filename field in the system table? The problem occurs when it sets the "filename" field to "modulename.info" (or .install or .js) for 10-20 modules.  I can manually set it to "modulename.module" but the fix only lasts an hour or so.

I don't think that cron is running as there are no cron jobs scheduled and I do not use poormanscron.  However I don't know how to test this.

Try using Drush if you have installed it.

> drush dis your_module_name
> drush cc all


Cannot install any theme I am new to Drupal and am facing an issue where any theme that I try to install will fail with the following message:
Installing light_skeleton
An error has occurred.
Please continue to the error page

An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: /core/authorize.php/core/authorize.php?batch=1&id=4&op=do_nojs&op=do
StatusText: Forbidden
ResponseText:
403 Forbidden
403 Forbidden
nginx/1.9.10

The root folder is owned by www-data:www-data and I have given the directory 775 permissions. I have also tried to give it a full access using chmod 777 but without success.
I have checked the logs of nginx and php but there are no errors displayed. The site itself, using the standard theme, works without any issues.
After getting the error, I get:
Notice: Undefined index: log in update_authorize_install_batch_finished() (line 291 of core/modules/update/update.authorize.inc).
Warning: Invalid argument supplied for foreach() in update_authorize_install_batch_finished() (line 291 of core/modules/update/update.authorize.inc).
Notice: Undefined index: log in update_authorize_install_batch_finished() (line 332 of core/modules/update/update.authorize.inc).
Notice: Undefined index: tasks in update_authorize_install_batch_finished() (line 333 of core/modules/update/update.authorize.inc).
Installation failed! See the log below for more information.

This is an nginx configuration issue and discussed intensely on this page Yet curiously no solid solution could be offered. Some guy on an other page proposed a solution. I applied that proposed solution and can confirm that in works!

To apply proposed solution go to your nginx configuration file under

/etc/nginx/sites-available/ directory on Ubuntu and add

rewrite ^/core/authorize.php/core/authorize.php(.*)$ /core/authorize.php$1;

just above the

location ~ \..*/.*\.php$ {
    return 403;
}

block. Location does matter!.. Restart your server:

  sudo service nginx restart

and that's it. The problem solved!


Fluch cache on all sites in multisite platform Is there a way to clear cache on all sites in platform by using platform alias? For example, drush @platform_name cc all ? (its multisite setup via aegir).

The problem I am facing with is, when I run that command or the one with @sites, I get a message

  Could not find a Drupal settings.php file at sites/default/settings.php.

So, I then copied default.settings.php as settings.php (which is by default fully commented out) in sites/default, and then it says

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

Which is obvious, as default doesn't have database (Aegir creates all sites in platform as separately and never touches default).

I also tried to delete default folder but Drush is telling me it needs to have settings.php there (even after I cleared drush cache). Drush in question is 8.1.0.

An easy way is via the views bulk operations.
When you select some or all sites you can expand the operations menu at the top, where you should find 'Site: Flush_cache'. It's part of the hosting_tasks_extra module (which is included by default now)

Note that you currently do have to enable the operation in the sites view. See https://www.drupal.org/node/2715945


HTML Special characters in preprocess I'm trying to add a bullet to a string in _preprocess_node() and am running into problems.
I am using Drupal 7.

My code is as such:

if($node->type == 'contact_page'){
    $vars['content']['field_fax']['#title'] = t("F &#8226;");
    $vars['content']['field_phone']['#title'] = t("P &#8226;");
  }

I get the literal string instead of the bullet. I've tried a bunch of things, but nothing seems to work. Am I missing something?

try:

t("F !bullet", array("!bullet" => "&#8226;"));
t("P !bullet", array("!bullet" => "&#8226;"));

Drupal escapes any characters passed through t() function so you need to use variables like this:

@variable: Escaped to HTML using check_plain(). Use this as the
default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(),
which makes it display as emphasized text.
!variable: Inserted as is, with no sanitization or formatting. Only
use this for text that has already been prepared for HTML display
(for example, user-supplied text that has already been run through
check_plain() previously, or is expected to contain some limited HTML
tags and has already been run through filter_xss() previously).


What's the best way to implement a system to allow the end-user to download and buy documents? I need some advise on how to build a system to allow users to download and purchase pdf files. A purchase option is a one time only thing and no order history of login is required.

The end user just needs to see a list of documents, some of which can be purchased and then when the hit buy the can pay at a Payment Provider and download.

I don't need a shopping cart, order history, login or anything.

What is the best way to approach this with Drupal 7? I was thinking of maybe using the Entity API to create a download entity, would that make sense.

There's a module in progress that provides that for Drupal Commerce, here:
http://drupal.org/sandbox/recrit/1118266

You could use it as a starting point, or just for inspiration.