Create path alias for hook_menu URLS based on node information I'm looking for guidance on how to dynamically create a path alias for dynamic paths that I create in a module using hook menu. For example, I have a module that defines a path such as subsite/template2/% where % expects the nid of a node. For that specific node, however, I want to create the alias based on the title of the node.

So if the title at subsite/node/5 is "Community Gardens" I want the path alias of subsite/template2/% to become subsite/community-gardens. I'm pretty certain this is possible, I'm just not sure how to do it. It even gets more complicated because there are sub tabs that need to be aliased but I figure if I can figure out the first part I can puzzle out the rest. (Using version 7)

For this I would use the pathauto module, which I am assuming you already have installed.

It provides a bunch of hooks to allow you to integrate with pathauto for your own needs.

For documentation, see the API.txt file in the pathauto module (from what I can tell though that file seems a little out of date).

You can look at working examples of its usage to give you an idea how to make your own.
To see these look in the pathauto.pathauto.inc file in the pathauto module.

Here is an example of what you might do (I haven't tested it but it should be close to what you need if it isn't exactly):

This is for the install file:

/**
 * Implements hook_install().
 */
function MODULENAME_install() {
  // Set the default value of the pathauto pattern.
  variable_set('pathauto_subsite_pattern', 'subsite/[node:title]');
}

/**
 * Implements hook_uninstall().
 */
function MODULENAME_uninstall() {
  // Remove the pathauto pattern.
  variable_del('pathauto_subsite_pattern');
}

This is for the module file (note you can move some of this out into an include file if you prefer):

/**
 * The internal path pattern for subsites.
 */
define('MODULENAME_SUBSITE_INTERNAL_PATH', 'subsite/template2/');

/**
 * Implements hook_path_alias_types().
 */
function MODULENAME_path_alias_types() {
  $objects = array();
  $objects[MODULENAME_SUBSITE_INTERNAL_PATH] = t('Subsites');
  return $objects;
}

/**
 * Implements hook_pathauto().
 */
function MODULENAME_pathauto($op) {
  switch ($op) {
    case 'settings':
      $settings = array();
      $settings['module'] = 'MODULENAME';
      $settings['token_type'] = 'node';
      $settings['groupheader'] = t('Subsite paths');
      $settings['patterndescr'] = t('Pattern for subsite');
      $settings['patterndefault'] = 'subsite/[node:title]';
      $settings['batch_update_callback'] = 'MODULENAME_subsite_pathauto_bulk_update_batch_process';
      return (object) $settings;
    default:
      break;
  }
}

/**
 * Batch processing callback; Generate aliases for subsites.
 */
function MODULENAME_subsite_pathauto_bulk_update_batch_process(&$context) {
  if (!isset($context['sandbox']['current'])) {
    $context['sandbox']['count'] = 0;
    $context['sandbox']['current'] = 0;
  }

  $query = db_select('node', 'n');
  $query->leftJoin('url_alias', 'ua', "CONCAT(MODULENAME_SUBSITE_INTERNAL_PATH, n.nid) = ua.source");
  $query->addField('n', 'nid');
  $query->isNull('ua.source');
  $query->condition('n.nid', $context['sandbox']['current'], '>');
  $query->orderBy('n.nid');
  $query->addTag('pathauto_bulk_update');
  $query->addMetaData('entity', 'node');

  // Get the total amount of items to process.
  if (!isset($context['sandbox']['total'])) {
    $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();

    // If there are no nodes to update, the stop immediately.
    if (!$context['sandbox']['total']) {
      $context['finished'] = 1;
      return;
    }
  }

  $query->range(0, 25);
  $nids = $query->execute()->fetchCol();

  MODULENAME_subsite_update_alias_multiple($nids, 'bulkupdate');
  $context['sandbox']['count'] += count($nids);
  $context['sandbox']['current'] = max($nids);
  $context['message'] = t('Updated subsute alias for node @nid.', array('@nid' => end($nids)));

  if ($context['sandbox']['count'] != $context['sandbox']['total']) {
    $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
  }
}

/**
 * Update the subsite URL aliases for multiple nodes.
 *
 * @param $nids
 *   An array of node IDs.
 * @param $op
 *   Operation being performed on the nodes ('insert', 'update' or
 *   'bulkupdate').
 * @param $options
 *   An optional array of additional options.
 */
function MODULENAME_subsite_update_alias_multiple(array $nids, $op, array $options = array()) {
  $options += array('message' => FALSE);

  $nodes = node_load_multiple($nids);
  foreach ($nodes as $node) {
    MODULENAME_subsite_update_alias($node, $op, $options);
  }

  if (!empty($options['message'])) {
    drupal_set_message(format_plural(count($nids), 'Updated URL alias for 1 subsite.', 'Updated URL aliases for @count subsites.'));
  }
}

/**
 * Update the sibsite URL aliases for an individual node.
 *
 * @param $node
 *   A node object.
 * @param $op
 *   Operation being performed on the node ('insert', 'update' or 'bulkupdate').
 * @param $options
 *   An optional array of additional options.
 */
function MODULENAME_subsite_update_alias(stdClass $node, $op, array $options = array()) {
  // Skip processing if the subsite has no pattern.
  if (!pathauto_pattern_load_by_entity('subsite')) {
    return;
  }

  module_load_include('inc', 'pathauto');
  pathauto_create_alias('test', $op, MODULENAME_SUBSITE_INTERNAL_PATH . $node->nid, array('node' => $node));
}

/**
 * Implements hook_node_insert().
 */
function MODULENAME_node_insert($node) {
  // Insert subsite alias.
  MODULENAME_subsite_update_alias($node, 'insert');
}

/**
 * Implements hook_node_update().
 */
function MODULENAME_node_update($node) {
  // Update subsite alias.
  MODULENAME_subsite_update_alias($node, 'update');
}

/**
 * Implements hook_node_delete().
 */
function MODULENAME_node_delete($node) {
  // Delete subsite aliases.
  pathauto_path_delete_all(MODULENAME_SUBSITE_INTERNAL_PATH . $node->nid);
}

/**
 * Implements hook_node_operations().
 */
function MODULENAME_node_operations() {
  // This will add an operation to update subsite aliases to the content
  // administration page.
  $operations['MODULENAME_subsite_update_alias'] = array(
    'label' => t('Update subsite URL alias'),
    'callback' => 'MODULENAME_subsite_update_alias_multiple',
    'callback arguments' => array('bulkupdate', array('message' => TRUE)),
  );
  return $operations;
}

This will use a default path alias pattern of subsite/[node:title] but allow you to configure it on the path auto settings page.

It will update the alias when a node is added, edited or deleted.

It will allow bulk updating of path aliases via the bulk update area of the path auto settings pages.

It will allow bulk updating of aliases via the options on the content administration page.

It would be trivial to add a views bulk operations action too.


Serve static files via S3 I'm developing a Drupal 7 website that will be served from multiple servers behind a load balancer.

I want all static files generated by Drupal cache (JS, CSS, and also theme and modules images) to be served via an Amazon S3 bucket.

I already did this for my content types' file upload fields, using the Amazon S3 module, but it's missing the feature I described above.

I saw there's Media Mover module, but it's far from D7 production ready.

What other solutions are there?

I ended up using the S3AutoPush module. I migrated it to Drupal 7 and hacked the hell out of it to make it fit my needs.

If anyone reads this and is interested, I'd be happy to share my code. I won't put it on drupal.org for now since it's a real hack-job and not worthy yet.


Overwrite twig (template) files from a contrib module in my custom subtheme? I need to overwrite and adjust the twig (template) files from the Facet module in my custom subtheme? Is that possible? I need to change below markup and CSS classes (to debug faster, I also added my template suggestion here):

            <input type="checkbox" class="facets-checkbox" id="contactvoorkeur-email" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Aemail">

                E-mail (4)

                E-mail (4)

            <input type="checkbox" class="facets-checkbox" id="contactvoorkeur-post" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Apost">

            Post (2)

                Post (2)

My main goal is to:

1) How do I add a bootstrap css-class list-group to the existing facet class js-facets-checkbox-links. So I get:

2) And how do I replace an existing facet class facet-item with list-group-item:

Since you didn't clarify any specific module, i'll explain it with Paragraphs.

In the Paragraphs folder there is a folder called "templates", this will be the default template used by all fields that use paragraphs.

If you copy these templates and paste them into your own custom theme you can edit them as much as you like, using twig debug you can specify it per field.

Don't forget to clear your cache when editing!


Send form values to JS file As clearly titled I want to send a form values to js file in Drupal 8.
I've made some researches and all I successfully coded was sending a PHP variable from a Controller to the JS file I'am using.

Here is the code:

library_name.libraries.yml

library_name:
  version: 1.x
  js:
    js/<js_file_name>.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

controller_name.php (class)

namespace Drupal\module_name\Controller;

use Drupal\Core\Controller\ControllerBase;

class <class_name> extends ControllerBase {

  public function <method>(){

      return array(
        '#attached' => array(
            'library' => array(
            '<module_name>/<library_name>'
            ),
            'drupalSettings' => array(
                '<module_name>' => array(
                  '<library_name' => array(
                      'foo' => 'bar'
                  )
                )
            )
        )
      );

  }

js_file_name.js (under /js folder)

console.log(drupalSettings.<module_name>.<library_name>.foo);

Everything works great!

But how about using a form? I've declared a form extending from FormBase and in the submitForm() overridden method I typed the same array:

return array(
        '#attached' => array(
            'library' => array(
            '<module_name>/<library_name>'
            ),
            'drupalSettings' => array(
                '<module_name>' => array(
                  '<library_name' => array(
                      'foo' => 'bar'
                  )
                )
            )
        )
      );

I know this won't work! But any ideas? I thought about using another library, point to a js file there, and use that js file to get the form values  using the #attached tag like above, and then send those values to the other js file using JSON

If any one can provide me with a better Drupal Standard? that would be great! cause this my first time using Drupal.

EDIT:

I fixed this, using: the module_name.settings.yml file under module_name/config/install folder and also by using the module_name.module file where I've implemented the hook_form_alter() method.

So,

From my module_name.module file, here goes my code:

/**
 * Implements hook_form_alter().
 */

function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

     if($form_id === your_form_id){

        $form['#attached']['library'][] = 'module_name/route_name';
    // that's the route name you've defined in your module_name.libraries.yml file
    // where you've located the js file you're going to use

        $form['#attached']['drupalSettings']
        [module_name][route_name][send_this_variable_to_js] = \Drupal::config(module_name.settings)->get(key);

        return $form;
    }

}

Now in your JS file, you can console.log like this:

console.log(drupalSettings.module_name.route_name.server.send_this_variable_to_js)

Hope this help!

You'll either need to add a js behavior that attaches itself to the normal submit event of the form, or create an AJAX Command that invokes a function in your script.

See: https://www.drupal.org/node/2290235


What should I name my overriding render-function? I'm just starting out with drupal and need some custom html for an intricate menu system. My plan is to override the html-generating functions in template.php.

My theme name is "Drupal subtheme" and the navbar I would like to target has the machine name "menu-usm-navbar-small". What should I name the functions that overrides the default html-printouts?

I think I have tried every possible combination of these. Some examples of what I've tried:

function drupal_subtheme_menu_link($variables) {
    return "foo";
}

function drupal_subtheme__menu_usm_navbar_small($variables) {
    return "foo";
}

It depends on what you want to target.

If it's the tree of the menu you can use theme_menu_tree :

function drupal_subtheme_menu_tree__menu__menu_usm_navbar_small($variables) {
   return '
' . $variables['tree'] . '
';
}

if it's the link, you can use theme_menu_link :

function drupal_subtheme_menu_link__menu__menu_usm_navbar_small($variables) {
   $element = $variables['element'];
   $sub_menu = '';

   if ($element['#below']) {
     $sub_menu = drupal_render($element['#below']);
   }
   $output = l($element['#title'], $element['#href'], $element['#localized_options']);
   return '
' . $output . $sub_menu . "
\n";
}

These functions need to be in template.php


show text on logo hover in over I've been testing the various overlay modules trying to find a simple way to implement a very minimalist designed text I want to display when hovering over my logo img at http://stefanbjorklund.info/.

I'm using Zen 5.x theme

Here's what I want to achieve (see the left side under the logo, nevermind the background-color of the emaillink):

I think that the best way to go is jQuery.

Create new block with text that you want to show
Using CSS, set block position that you want
Set display:none; for that block
Add jQuery script in your block (or implement on some other way).

Script should looks something like:

jQuery("#logo").hover(
        function () {
            jQuery("#blockId").fadeIn(); //change the blockId with Id of your block
            jQuery("#block-views-projects-block").fadeTo(1000,0.5);
        },
        function () {
            jQuery("#blockId").fadeOut(); //change the blockId with Id of your block
            jQuery("#block-views-projects-block").fadeTo(1000,1);
        }
    );

Of course, if you add this code in your block, it must to be added into <script>...</script> tag.


render or print image in a drupal 7 node.tpl? I am trying to theme a node with tpl and when i tried to print image , I cant find image path like in d6.. which function i have to call to properly output image .. I mean something like theme('')?

Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [fid] => 13
                    [alt] =>
                    [title] =>
                    [width] => 416
                    [height] => 335
                    [uid] => 1
                    [filename] => Capture2.PNG
                    [uri] => public://Capture2.PNG
                    [filemime] => image/png
                    [filesize] => 215377
                    [status] => 1
                    [timestamp] => 1346837738
                    [rdf_mapping] => Array
                        (
                        )

                )

        )

)

<?php print render($content['field_image']); ?>

If you want to change how the image is displayed (dimensions, link, etc), set them in Manage Display tab in the node type settings.

You can also do an imagecache preset like this:

<?php
print theme('image_style', array('path' => $node->field_image[LANGUAGE_NONE][0]['uri'], 'style_name' => [STYLE NAME]));
?>

But that's not the recommended way!

if you want to build URL from URI,

<img src="<?php print file_create_url($node->field_image[LANGUAGE_NONE][0]['uri']); ?>" />


How to select every date before now in timestamp? my database feild type is timestamp here is my code I used it but It also gave me today date
I need every date before today

"SELECT * FROM {mytable} WHERE  date <".$now_timestamp."  "

please help me
Thank you

You could just use strtotime() to get yesterday's date instead of using a DateTime object:

$yesterday = strtotime('-1 day');

$sql = 'SELECT * FROM {mytable} WHERE date < :timestamp';

$result = db_query($sql, array(':timestamp' => $yesterday));


write data in another drupal website / rest I need to implement the following setup:
- master site (drupal 7)
- child site (drupal 7)

User create/update nodes in the master site. Then the nodes should be copied to some child sites, depending on some selections. The records in the child site should be updated if they already exist. Also deleting should be possible. These sites are hosted at another hoster than the master website.

I was doing some research and found among other techniques the REST Services.
Did I understand right, that with the REST services I can implement what I want? Or are there better alternatives?

thanks for any help

Try the following modules.

Drupal Sync

  This module allows synchronizing content among multiple websites.
  Supported entity types: node and taxonomy, menu items.

  Many hooks were used during creation of the module. It allows widening synchronization functional by developing additional modules.

Deploy

  The Deploy module is designed to allow users to easily stage content from one Drupal site to another. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.


Using hook_page_alter to move node render items into blocks I have a gallery page where I want to move the thumbnails into the sidebar-first region as a block. I'm trying to get a handle on using the code in Drupal 7 so am attempting to do this via hook_page_alter.

In my template.php file I currently have...

/**
* Implements hook_page_alter()
*/
function MYTHEME_page_alter(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "imagegallery") {
    // edit only imagegallery nodes
    debug($page['content']['system_main']['nodes'][$node->nid]['#node']->field_image);
    $page['sidebar_first']['thumbs']['content'] = $page['content']['system_main']['nodes'][$node->nid]['#node']->field_image;
    unset($page['content']['system_main']['nodes'][$node->nid]['#node']->field_image);
  }
}

Debug is showing the array for the field_image from the language (['und']) and each of the thumbnails but nothing is rendered out into the sidebar-first region and the field_image is not unset from the node. I had also tried the hide() function unsuccessfully.

What is the correct way to move render objects from the main content to a region?

Well this ended up being a real pain in the bum - but ultimately got it solved. There may be a cleaner way of shifting the content so please comment if it could be done better.

I'll start by answering the question, then I'll try to go through what I think was going on under the hood to exacerbate the problem(s).

The answer is to use hook_page_build() instead of hook_page_alter(). hook_page_build() doesn't trigger from template.php so you need to build a custom module.

MYMODULE.module simply contains:

<?php
/**
 * Implements hook_page_build()
 */
function MYMODULE_page_build(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "imagegallery") {
    // edit only imagegallery nodes
    $page['sidebar_first']['thumbs'] = array(
      'content' => $page['content']['system_main']['nodes'][$node->nid]['field_image'],
      '#prefix' => '
',
      '#suffix' => '
',
    );
    unset($page['content']['system_main']['nodes'][$node->nid]['field_image']);
  }
}

And that's all there is to it.

Now to go through the various 'gotchas!'.

$page['content']['system_main']['nodes'][$node->nid]['#node']->field_image is not $page['content']['system_main']['nodes'][$node->nid]['field_image']! This took a freaking day to find. Using devel_themer I kept on inspecting the node-level elements rather than the block-level elements. No matter what I did ['#node']->field_image stayed where it was but I think that #node is just a reference of what was generated and isn't even ultimately rendered. Once I found that ['nodes'][$node->nid]['field_image'] was the render element for the thumbnails it was down-hill from that point. Lesson learned: Even if you find what you think is the actual render element keep checking up the tree.

hook_page_alter() is great if you are ALTERING existing content but not great if you are moving stuff around. By that I mean if you have content in a region and you just want to clean stuff up then fine, use hook_page_alter. But one of the problems I had was that I had no existing content in the sidebar_first region so by moving things across using this hook, the system already thought that sidebar_first was empty. So while it placed the content where the region should have been, it didn't actually render the region itself. This really screwed up my page display. I'm guessing that Drupal builds the page elements during hook_page_build(), then works out what is what as far as the regions it is going to render out, then allows final altering during hook_page_alter() for the absolute last-step tweaking before render() is run. By using hook_page_build() the system then knew that the sidebar_first region was active.

It also took a little while to figure out hook_page_build() didn't trigger from template.php. I should have started with a debug message in there to test that as well.


Ajax form works on page but not on block I've created an ajax form with drupal API. The ajax functionality works if I render the form on a page with hook_menu, but it doesn't when I render it in a block. This is how I create my block:

function hook_block_info() {
    $blocks['my_block'] = array(
      'info' => t('Title'),
      'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

function hook_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'my_block':
            $block['subject'] = t('Title');
            $block['content'] = drupal_get_form('my_form');
            break;
    }
    return $block;
}

Any idea how I can fix this?

Did you create the form in a separate file?  If you did, then it makes a big difference where in the main .module file you put the module_load_include() function to bring in the form.  I had this problem because my form definition was in a .inc file, but when I moved module_load_include() from hook_node_view() to hook_init(), it worked fine.

Edit:  Wait, better answer:  hook_init() isn't called on cached pages, so may not be the way to go.  Instead, call module_load_include() wherever it makes sense (e.g., hook_node_view() or hook_block_view()), but use form_load_include() within your form definition, like this:

function my_ajax_test_node_form($form, &$form_state) {
  form_load_include($form_state, 'inc', 'my_ajax_test', 'my_ajax_test.forms');
  $form['my_ajax_test_div'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
  );
  return $form;
}

Once the file has been loaded with form_load_include(), it will be loaded anytime the form is called.


How can I show a parent page's field on all subpages? I'm trying to get a Basic Page's Banner Image field to display on its Basic Page AND any of that page's children. Those children may or may not be the same content type.

Ideal outcome:

The content editor creates a new Basic Page called About Us
They upload an image for the Basic Page's Banner Image field
They create a new page of any content type, let's say a Contact webform
Contact's menu settings make it a child of About Us
Contact and About Us both automatically show the Banner Image that was set in About Us

I've tried solving this with php in my page template and with views & blocks, but I'm not getting very far. Any ideas?

For posterity, here’s the solution I came up with.

I turned my Banner Image into its own content type, used the nodeblock module so it would automatically be usable as a block, and then just scoped that block to myParentPage and myParentPage/*.

It’s not the elegant solution I wanted, I was hoping to give the user a one step process that would also keep them from creating top level pages without a banner image. But it gets the job done, so I’m happy enough.

Thank you Kevin for getting me on the right track!


Select list ajax callback fire only once to update textfield I face an issue when fire ajax callback function in my coding. I have a select list and a text box. If there is any change in select list field, the text box will be updated by selected value. I added my code in form_alter function. But, it fired only one time. Below is my code.

 function field_collection_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'employee_performance_node_form') {

$form['field_my_weight_select'][LANGUAGE_NONE]['#ajax']= array(
      'callback' => 'custom_test_entity_callback',
      'wrapper' =>'custom_test_entity_wrapper',
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'change',
    );

$form['field_text_for_test']['#prefix']='
';
$form['field_text_for_test']['#suffix']='
';

if(isset($form_state['values']['field_my_weight_select'])){
      $content_type = $form_state['values']['field_my_weight_select'][LANGUAGE_NONE][0]['value'];
      $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value']=$content_type;
    }
    else{ $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value']=1;}
}
}

function custom_test_entity_callback($form, $form_state){
  return $form['field_text_for_test'];
}

Could you tell me what is wrong in my code??

Thank you

Quickly tested your code and it works.

The only thing that looks a bit odd in your hook implementation, is the name of the function. It seems you are writing your custom code as if your module was named 'field_collection'. There is already a contrib module called that, and you may have already installed it. It would be better to place your function into your custom module's "namespace". Event better would be to also use the hook_form_FORM_ID_alter hook, since it's more efficient.

In any case, with those two small rewrites, the code ran as expected and I was able to get multiple ajax updates of the text_for_test field.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOUR_CUSTOM_MODULE_form_employee_performance_node_form_alter (&$form, &$form_state) {
  $form['field_my_weight_select'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'custom_test_entity_callback',
    'wrapper' => 'custom_test_entity_wrapper',
    'method' => 'replace',
    'effect' => 'fade',
    'event' => 'change',
  );

  $form['field_text_for_test']['#prefix'] = '
';
  $form['field_text_for_test']['#suffix'] = '
';

  if (isset($form_state['values']['field_my_weight_select'])) {
    $content_type = $form_state['values']['field_my_weight_select'][LANGUAGE_NONE][0]['value'];
    $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value'] = $content_type;
  }
  else {
    $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value'] = 1;
  }
}

/**
 * Ajax callback for updating field_text_for_test.
 */
function custom_test_entity_callback($form, $form_state) {
  $form['field_text_for_test']['#prefix'] = '
';
  $form['field_text_for_test']['#suffix'] = '
';
  return $form['field_text_for_test'];
}

Update: If you want to make sure, your form alter hook is called last (in relation to other modules):

/**
 * Implements hook_module_implements_alter().
 */
function CUSTOM_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'form_employee_performance_node_form_alter') {
    return;
  }
  $module = 'CUSTOM_MODULE';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);

  $implementations = $group + $implementations; //You want your implementation to run last.
}

Good luck!


make sure hook cron is only run once a day setting I'm building a hook_cron in my module but I actually don't want it to run at a maximum of once a day.
Is there a Drupal setting for this or do I need to check when the last cron was run and see if that was at least 24 hours ago? How do I do this?

I'm using drupal 7

I would check the implementation of hook_cron() in the Examples module.

The exact implementation is here, it's pretty straightforward!

Basically, you're setting the next execution time (in the example code as cron_example_next_execution) of your cron run as the very last step in your hook_cron() implementation, and then checking it as the very first thing.

If the variable doesn't exist, then cron will fire off your task, and then set it!


Drush features commands + git I have a doubt about the functionality of Drush Features commands when it works with git:

Before I do a git pull, can I do drush fu example? Will this command overwrite the changes of the feature coming with the pull and drush fr example will not work properly?

Thank you.

Your question is equivalent to asking if you can edit a file before doing a git pull.  The answer is yes, but if there are conflicts, then you will need to merge them.

Returning to your example, if there are no changes to your local configuration, then the files that drush fu will write will be the same as the files currently in the repository.  In this instance, git will happily do the pull, as it will consider the files to be unchanged, even if drush fu rewrote them.

If you do have changes (git status after drush fu will show this), then it would be a good idea to run git stash prior to git pull.  After you pull, git stash pop will overlay your stashed changes on top of the pull, and you can see what the conflicts are.

Disclaimer:  I have never hand-merged conflicts from features.  I always pull the database from live to dev, and push code from dev to live to avoid this.


Why is my Ajax callback not returning anything? I'm implementing an ajax callback function whats the issue with my code not returning anything.  I'm new to backend

  <?php
use Drupal\node\Entity\Node;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Query\QueryFactory;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Implements hook_form_alter().
 */
function hook_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'webform_submission_go_to_csv_import_add_form') {
    // Choose for "Featured Type" field "N/A" value by default.
    $form['elements']['name']= [
      '#type' => textfield,
      '#title' => 'sammy',
      '#ajax' => [
                'callback' => '::some_ajax_sample',
                'wrapper' => 'edit-name',
                'event' => 'keyup',
                'progress' => [
                  'type' => 'throbber',
                  'message' => 'loading.....',
                ]
              ],
            ];

  }
}

function some_ajax_sample(array &$form, FormStateInterface $form_state) {

  $response = new Response($form['elements']['name']['#title'] = 'Test');
    return $response;
   }

there are a few things that could go wrong with this. Ajax callbacks can be a really hard thing to do and often requires a bit of trail and error. Hope this helps.

First of all, when your ajax callback function should not contain the "::".
This is only used when you are programming inside a Class, right now you're in a .module.
So you can change to.

'callback' => 'some_ajax_sample'

Furthermore you should check with a breakpoint if you even get inside the function. This should be resolved when removing the ::.

Second thing you should do is add the wrapper div to your element.
You can do it like this:

$form['elements']['name']= [
  '#prefix' => '
'
  '#suffix' => '
'
  '#type' => textfield,
  '#title' => 'sammy',
  '#ajax' => [
            'callback' => 'some_ajax_sample',
            'wrapper' => 'edit-name',
            'event' => 'keyup',
            'progress' => [
              'type' => 'throbber',
              'message' => 'loading.....',
            ]
          ],
        ];
}

When you added the wrapper, Drupal knows which element should be replaced and update.

Last thing you can try is to remove the response and to just return the $form['elements']['name'].

Hope this helps.


I want the date view filter on current date, not on current time I have schedule view in my project. I want to show the current day schedule in my view. We have following option in date filter.

"An offset from the current time such as "+1 day" or "-2 hours -30 minutes""

which gives you option for show the schedule from current time. which did not allow you to show the current day result. I used the "Views between dates filter" module but it gives filter on node created date only.

We can override the view by using the "hook_views_pre_build" hook.

Is there any better solution for this?

I have a view similar to what you're trying to achieve. You have to install the Date module (https://drupal.org/project/date) and through that module, you'll be able to set the granularity to 'Day' instead of minutes or seconds. Then, just put +0 day or now


Simpletest for Sending Mail I've written the following testcase to send an email. In test results output it says

  "1 e-mail was sent during this test."

but acutally it's not.

I tried another way, I put the function in menu callback (test-mail) it's sending mail when I access the URL. But if I access the URL in simple testcase like
$this->drupalGet('test-mail'); the result still says the same "1 e-mail was sent during this test." but was not.

So is it by design? Is there any other way to send mail?

 public function testSendMail() {
  $this->sendmail();
 }

function sendmail() {
  $from = 'fromaddress@gmail.com';
  $to = 'toaddress@gmail.com';
  $message = 'testcase mail';
  $language = 'en';
  $module = "test_mails";
  $key = "notification_mail";
  $send = TRUE;
  $subject = t("subject line goes here", array(NULL),array('langcode'=>'en'));
  $params = array(
    'body' => 'hello from krishna',
    'subject' => $subject
  );
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  return 'Mail sent succesfully';

  }

 function test_mails_mail($key, &$message, $params) {
 switch ($key) {
   case 'notification_mail' :
     $message['subject'] = $params['subject'];
     //the email body is here, inside the $message array
     $message['body'][] = $params['body'];
     break;
 }
}

You need three functions.

1) module_submit.
2) Create a function to send the mail.
3) create hook_mail.

a complete example: file sendmailtest.info

name = sendmailtest
description = sendmailtest
core = 7.x

file sendmailtest.module

<?php

function sendmailtest_menu() {
 $items['sendmailtest'] = array(
   'title' => 'send mail test',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('sendmailtest'),
   'access callback' => TRUE
 );
 return $items;
}

function sendmailtest($form, &$form_state){

 $form['submit'] = array(
  '#value' => 'Send Mail Test',
  '#type' => 'submit',
 );
 //Fundamental devolver el objeto-array form
 return $form;
}

function sendmailtest_submit($form, &$form_state){

 drupal_set_message('Test ok');

 sendmailtest_send($form_state['values']);

}

function sendmailtest_send($form_values) {
  // All system mails need to specify the module and template key (mirrored from
  // hook_mail()) that the message they want to send comes from.
  $module = 'sendmailtest';
  $key = 'sendmailtest';

  // Specify 'to' and 'from' addresses.
  //$to = $form_values['email'];
  $to = 'jeremiselxi@gmail.com';
  $from = variable_get('site_mail', 'admin@example.com');

  // "params" loads in additional context for email content completion in
  // hook_mail(). In this case, we want to pass in the values the user entered
  // into the form, which include the message body in $form_values['message'].
  $params = $form_values;

  // The language of the e-mail. This will one of three values:
  // - user_preferred_language(): Used for sending mail to a particular website
  //   user, so that the mail appears in their preferred language.
  // - global $language: Used when sending a mail back to the user currently
  //   viewing the site. This will send it in the language they're currently
  //   using.
  // - language_default(): Used when sending mail to a pre-existing, 'neutral'
  //   address, such as the system e-mail address, or when you're unsure of the
  //   language preferences of the intended recipient.
  //
  // Since in our case, we are sending a message to a random e-mail address that
  // is not necessarily tied to a user account, we will use the site's default
  // language.
  $language = language_default();

  // Whether or not to automatically send the mail when drupal_mail() is
  // called. This defaults to TRUE, and is normally what you want unless you
  // need to do additional processing before drupal_mail_send() is called.
  $send = TRUE;
  // Send the mail, and check for success. Note that this does not guarantee
  // message delivery; only that there were no PHP-related issues encountered
  // while sending.
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  if ($result['result'] == TRUE) {
    drupal_set_message(t('Your message has been sent.'));
  }
  else {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }

}

function sendmailtest_mail($key, &$message, $params) {
  switch ($key) {
    // Send a simple message from the contact form.
    case 'sendmailtest':

      $message['subject'] = 'Test subject';

      $body= 'Test Body';
      $message['body'][] = check_plain($body);
      break;
  }
}


Adding an image base field to custom content entity consider the following situation: I have created a custom content entity with several base fields (string and string_long fields) and it works flawlessly. In addition I want the entity to hold an image field which I defined the same way I did with the other fields:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    …

    $form_options = array(
        'type' => 'string',
        'weight' => $key,
    );

    $view_options = array(
        'label' => 'hidden',
        'type' => 'string',
        'weight' => $key,
    );

    …

    $type = 'image';
    $settings = array();
    $form_options['type'] = 'image_image';
    $view_options['type'] = 'image_image';

    …

    $fields[$fieldname] = BaseFieldDefinition::create($type)
        ->setLabel(t($sections['labels'][$key]))
        ->setDescription(t($sections['descriptions'][$key]))
        ->setSettings($settings)
        ->setDisplayOptions('view', $view_options)
        ->setDisplayOptions('form', $form_options);
}

Now, why would I get the errors Notice: Undefined index: target_type in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::propertyDefinitions() (line 70 of core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php). and Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityManager->getDefinition() (line 256 of core/lib/Drupal/Core/Entity/EntityManager.php).?

Anyone has a hint?
Thank you in advance!

Looks like you need to specify the target_type.

It should get the default from FileItem::defaultStorageSettings(), I am not sure why that doesn't work.

Unrelated, but note that you should not call t() like that, as it makes it impossible for potx to extract translatable strings from your code. Also, watch out for https://www.drupal.org/node/2363099, you need to update it to use nt() then.

Edit: Turns out, the problem is that the code was using setSettings(), which is considered problematic because it replaces all existing settings, including defaults. Switching to setSetting() for specific settings should solve it.


Loop setting on video module? This seems like it should be simple, but: How do I make loop true on videos uploaded with D7's video module (HTML 5 Player)? The setting is no where on the front end, and when I dive into the module's theme options, 'loop' doesn't even seem to be a variable? The only variables seem to be:

 * $item
 * $width
 * $height
 * $autoplay
 * $autobuffering

Placing loop="true" inline would be the obvious option, but this also doesn't seem to be do-able via the D7 module.

You could try to override this in your theme. The video module provides the video-play-html5.tpl.php file. You can copy this file to your active theme (copy it to all if your site supports more themes) and add the loop="true" setting to the following line:

<video width="<?php echo $width; ?>" height="<?php echo $height; ?>" preload="<?php echo $preload; ?>" controls="controls" poster="<?php echo $poster; ?>"<?php echo $autoplayattr; ?>>

Clear the cache to have Drupal detect your template override. That should make the video loop. However this would make every video always loop. If you need control per video, you will have to patch bigger portions of the module, add variables etc. It should be handled in the feature request instead. (It would be out of scope here.)


How do you order meta tags added by drupal_add_html_head()? I'm adding Open Graph support to a Drupal site and I have a bunch of drupal_add_html_head() calls, like:

  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => $node->title,
    ),
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/' . $node->nid, array('absolute' => TRUE)),
    ),
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

In total, I have 10 of these. They don't seem to output in the same order they are called (all in a single function).

Is there some kind of weighting I can use to set the order?

Use the #weight property. As drupal_get_html_head() uses drupal_render() to render the meta tags, #weight is used when rendering them.

I uses the following code to make a test on my local site; it is the same code you are using, except it doesn't have any reference to the node object.

  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => "This is the title",
    ),
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/1', array('absolute' => TRUE)),
    ),
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

  dsm(drupal_get_html_head());

The output I got is the following one.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta property="og:url" content="http://tero.local/dr72/node/1" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<meta property="og:title" content="This is the title" />

As you see, the last added tag is the first to appear.

I then run the following code.

  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => "This is the title",
    ),
    '#weight' => 10,
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/1', array('absolute' => TRUE)),
    ),
    '#weight' => 200,
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

  dsm(drupal_get_html_head());

The output I got is the following one.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<meta property="og:title" content="This is the title" />
<meta property="og:url" content="http://tero.local/dr72/node/1" />

As you see, the order of the meta tags has been changed; the meta tags added from the code appear after the default meta tags added from Drupal.

_drupal_default_html_head() (the function that returns the default meta tags) uses #weight for the "Content-Type" meta tag.

  $elements['system_meta_content_type'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'Content-Type',
      'content' => 'text/html; charset=utf-8',
    ),
    // Security: This always has to be output first.
    '#weight' => -1000,
  );


Commerce line item fields - getting value I have a custom line item type that has a List(Text) field. When I do this:

$line_item = commerce_line_item_load($lid);

I get an object that contains the value, but not the label of the selected option.

$line_item->field_ring_size[LANGUAGE_NONE][0]['value'] // returns 2 instead of, say, Large

How can I get the value's label instead?

I've tried using field_info_instance to get all values, as follows:

$info = field_info_instance('commerce_line_item', 'field_ring_size', 'ring_setting');

...but this does not return the values as far as I can see. Similarly, I've tried field_get_items, but this gives me the key back again.

How can I get the value (or a list of all values) instead of the key?

You can do it using list_allowed_values function

  $field = field_info_field('field_name');
  $allowed_values = list_allowed_values($field);


Get entity reference node object from within rendered entity reference My specific problem is similar to the one here but I am needing for it to work when the file field is within a node that is rendered within another as an entity reference.

If I use:

$node = \Drupal::request()->attributes->get('node');
$variables['node_title'] = $node->getTitle();

I get the title of the main node currently being displayed and not the node of the rendered entity reference. Is there a way I can get this instead?

You're setting $node to the current request. On any node/* route that will be the node in question, not other nodes included on the page.

Since it is an entity reference field, you can access it like (for example, in a preprocess):

$foo_id = $node->field_reference_name->value;
$referenced_node = Node::load($foo_id);

// or
$referenced_file = File::load($foo_id);

If $node->field_name->value returns the id (node id).

However it isn't really clear if you are talking about a file, or, a node.


Is it possible to run 2 different sites in Acquia Dev Desktop on the same computer? I'm running Acquia Dev Desktop and I'm wondering if it's possible to clone 2 different sites with different Drupal versions.

I tried cloning both sites, but when I cloned the second one and tried to view it, I got the following message.

Is there a way I can use both in the same computer?

Yes, you can install more than one Drupal site on the same computer using Acquia Dev Desktop. Check out Acquia's documentation here:

https://docs.acquia.com/dev-desktop/sites/

It looks to me like maybe you have specified an identical name for the local database. The error screen that you see is one that commonly appears when a new Drupal installation attempts to run install.php but the database is already set up.

As an experiment, click on the link that says "View your existing site." If my hunch is correct, you should see the content of your other site.

Instead, try selecting "Create a new database" when setting up the second site, and make certain that you give it a different name than the first site uses.

If the two cloned sites just happen to have identically-named databases, you should still be able to create a new one with a new name, and then import a sqldump of the second site's database into that.


Setting commerce sales price with views I am trying to set up a sale price on certain products on a drupal site, however from the project page of commerce_saleprice there is this patch https://drupal.org/files/commerce-views_precalculated_price-1020050-5.patch that should be applied but am stack because i dont know to which module this has to be applied as i tried applying it to commerce_saleprice and it fails.

My requirement is to put some products on sale and then call them in a view... any insight on this, i already have price savings formatters installed.

From the looks of the patch file it needs to be applied to commerce_price -

cd to /sites/all/modules/commerce (or wherever you have the commerce module) and a command like this should do it:

patch -p1 < /path/to/file.patch

And then write down what you've done so you don't forget next time you update the commerce module ;)


How can I set a Feeds Importer to accept multiple values for a field? I created a Feeds Importer for commerce products. One such product is an album which contains multiple mp3 files. So in the files field of the content type, this is set to unlimited.

but my feeds importer isn’t accepting multiple values. Ive tried using the the pipe char  (|) but it’s not working.

my CSV looks like this. fyi - having one commerce mp3 file reference in the csv does work. but when adding another and separating w/ the pipe symbol, it does not.

How can this be achieved?

my csv file so far -

SKU,Title,Album cover front,Price,Files
SKU_ALB#8_CD_SOME_TITLE,http://staging.MYSITE.com/feeds/album_artwork/cd_cover_front.jpg,1000,private://albums/Killer Track.mp3|private://albums/Heavy Groove.mp3

Have a look at feeds tamper.

Using the pipe symbol is alright. The next step would be to enable Feeds Tamper and chose to "Explode" the "Files" with the pipe character as separator.


Get id of an organic group inside a view How can i get the organic group id inside a view?
I tried to get it like this:

function HOOK_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'MYVIEWSNAME') {
    $nid = $vars['view']->result[0]->nid;
    $node = node_load($nid);
    $og_id = $node->og_group_ref['und'][0]['target_id'];
    dpm($og_id);
  }
}

This is printing the correct id to my devel debug,
but i cant access $og_id in my view-template.

Or maybe you got an other solution to create the /node/add/document .. link.

Do you have a corresponding template file in your sub-theme?

Themes cannot have a preprocess function without a corresponding .tpl.php file

https://drupal.org/node/258089


How to give a roll only access to add a certain content type? In D8:
I have a content type call fooCT.
I have a role called:  "fooRole"

I give fooRole the following permissions:

fooCT: create fooCT
use simple editor

So the checkbox: View published content is not checked

A person with this role cannot do anything in the system anymore.

How to give this person only access to add a a fooCT?

I tried several options but do not get the desired result.

Any suggestion?

The Permission View published content is very important, without the users of that role won't be able to see Published content. What do you mean by "cannot do anything in the system anymore"?

Do you want that Role to be able to create new nodes of that type, but not to be able to View those nodes once they're created?

You should look into the Editorial Workflow, and Content Access module.


How to write page.tpl.php file for bootstrap site I have the below code in the page.tpl.php file.

<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">

      <?php if ($logo): ?>
      <a class="logo navbar-btn pull-left col-xs-12 col-sm-12 col-md-2 col-lg-2" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

      <?php endif; ?>
............

As you can see, I have written bootstrap class col-xs-12 inside a class:

<a class="logo navbar-btn pull-left col-xs-12 col-sm-12 col-md-2 col-lg-2" ....

Then I uploaded an image whose original size is 658 x 318 (Appearance > bootstrap sub theme > Logo image ).

When I visit my using in mobile phone, I still see the logo in original size. I thought me adding col-xs-12 will instruct bootstrap to fit the image in 12 column grid system of my mobile screen. Do you know why image is still in original size even though I added the bootstrap class col-xs-12?

#Test1 - Passed

In tpl file > header region > I have added img-responsive class:

">

      <?php if ($logo): ?>
      <a class="logo navbar-btn pull-left col-xs-12 col-sm-12 col-md-2 col-lg-2" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" class="img-responsive"  alt="<?php print t('Home'); ?>" />

      <?php endif; ?>
.....

After that, I have uploaded the logo (appearance > bootstrap > Upload image...). When I view the page in mobile, I see that image was responsive. This is good.

#Test2 - Failed

In tpl file > main container region > I have added img-responsive class:

/** I have added this for all the images to be responsive for main contents */

    <?php if (!empty($site_slogan)): ?>

<?php print $site_slogan; ?>

    <?php endif; ?>

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

    <?php if (!empty($page['sidebar_first'])): ?>

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

    <?php endif; ?>

............

After that, I uploaded some images to content types. When I view the node in mobile, I still see those images in original sizes. How do I update the tpl file so all the images in main container class become responsive as well?

Use .image-responsive class in your tpl.php file on your image or link tag like that

Image

The .img-responsive class makes the image scale nicely to the parent element (resize the browser window to see the effect):

image-responsive in bootstrap


Get UC product attributes using Views Global PHP I tried using below code in Views > Global PHP field.

<?php

$request = db_query("SELECT data FROM {uc_order_products } WHERE order_id= $row->order_id")->fetchField();
$att =  $request;

$data = unserialize($att);

if (is_array($data['attributes'])) {
  foreach ($data['attributes'] as $attribute => $option) {
    echo $attribute . ':   ' . implode(', ', (array)$option) . '<br>';
  }
}

?>

Adding above code I get the below error :

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Also how do I print each attribute in a different field?

If you use a variable in your request, it's preferable to use it like this : WHERE o.order_id = :oid', array(':oid' => $row->order_id).

So I guess it would be :

$request = db_query('SELECT o.data FROM {uc_order_products} o WHERE o.order_id= :oid', array(':oid' => $row->order_id)')->fetchField();

To have different fields, you can do this processus for each field, by using multiple PhP fields in your view. But to rationalize requests, I would first do that request in the "setup code"  and set all your data in the $static variable.


How do you create a link to a modal dialog? The following code does not work:

All Topics

Drupal 8.6.5. Bootstrap subtheme. Chrome console log shows no errors. Rather than a modal, the referenced page opens.

So, how do you create a link to a modal dialog in Drupal 8?

This html looks ok, but did you include the core/drupal.dialog.ajax js library that attach event to your link ?

In twig :

{{ attach_library('core/drupal.dialog.ajax') }}

In PHP, it looks like this :

$renderArray = [
            '#title' => t('All Topics'),
            '#type' => 'link',
            '#url' => Url::fromRoute('XXX'),
            '#attributes' => [
                'class' => ['use-ajax'],
                'data-dialog-type' => 'modal',
            ],
            '#attached' => [
                'library' => ['core/drupal.dialog.ajax'],
            ],
];


How to build Druapl 7 bilingual website? How I can build a bilingual version of my newly build website using Druapl 7.
I am using module Locale and entity_translation.When I clicking the arabic(my intention to support English,Arabic),that is not intending to RTL.
I have updated content type field  "Language" to "Language Neutral",how I can add the feature of bilingual in a manned which could change the language and indentation of each content?

Thanks in advance.

The Internationalization (i18n) module is good, Here is an excellent tutorial.

It's fairly robust, so I imagine it supports LTR script.


Right way to start with a Bootstrap subtheme? I create my first Bootstrap subtheme (version 7.x-3.0) and I have 3 questions:

1) Theres is the file css/style.css which has more than 6400 lines, is this normal. I expected to it to be an empty page to start adding my custom css styles. Is this right?

2) I guess that I should not add anything in css/style.css and create my own files.E.g: blocks.css, prodcuct.css. Am I right?

3) How to create and declare a new .less file. E.g: blocks.less, products.less, etc. I know that the .css files must be declared in the .info file, but not sure about this kind of files.

I uploaded a capture where you can see the folder structure of the subtheme.

First of all, there is a guide to begin with subtheming with Bootstrap here. And I recommand you to download the starter kit to get ready-to-use subtheme.

1) and 2)
To create a subtheme, you don't have to edit any files in your base theme. Just create a custom theme, in sites/all/themes/, just next your bootstrap folder, and declare the yourtheme.info file like this:

name = yourtheme
description = Custom Bootstrap subtheme
core = 7.x
base theme = bootstrap
stylesheets[all][] = css/style.css

It is going to make the heritance of all your bootstrap files automatically.

You can create a new empty css file, in yourtheme/css/style.css, and customize.

You can also create multiple css files, as you said, but you have to declare it in the .info file aswell.

3) LESS is supported by Bootstrap. You just have to follow the guide I told you and have a local LESS compiler to generate CSS.

======

BIG EDIT:

======

How to set up a new Bootstrap subtheme

A) Download Bootstrap project (7.3 is fine to me). Place the bootstrap folder in sites/all/themes/.

B) Download jQuery Update project, which is required by Bootstrap. Go to yoursite/admin/config/development/jquery_update and set the default jQuery version to 1.9.

C) In your bootstrap folder, you're gonna find bootstrap_subtheme folder. Move it to sites/all/themes/ and name it banana (let's suppose your custom theme is called Banana). So you have bootstrap and banana folders at the same level.

D) In banana, rename the bootstrap_subtheme.info.starterkit file to banana.info. And edit its content like this:

name = Banana, a Bootstrap Sub-theme
description = A Bootstrap Sub-theme called Banana.
core = 7.x
base theme = bootstrap

E) Now you have a pretty new Banana theme, inheriting all from Bootstrap theme, and that you can activate in yoursite/admin/appearance/.

F) If you want to try a customization, go to sites/all/themes/banana/css and make a little change to style.css (see, it is not 6400+ lines ;-)). Refresh your site and see if it is applied.

G) If you want to work with LESS, you have to set up a local LESS compiler on your computer. This one seems to be simple to install and configure. Personaly, I use SASS and Ruby Gem to compile, so I cannot give your further information about another compiler here. Maybe someone will.

H) Once you're ready with your compiler, you just need to make your edit in sites/all/themes/banana/less/ folder. All the .less files that appear here are included in style.less. This is the one you have to compile (only this one) to generate css/style.css. Bootstrap gives you 3 empty files where you can put your code, content.less, footer.less, header.less. You can use them or just create new ones (don't forget to import them in style.less if you add new files).

I) Make some changes, compile and refresh your site. See if it is applied.

I wish you good luck (and a merry Christmas ^^)


How to use hook_url_outbound_alter for emails only? I have a Rule set up that sends a mail to a certain user with a link to a certain node. This link is altered using hook_url_outbound_alter to include additional details.

The problem is that hook_url_outbound_alter also alters the URL everywhere else. Closing an overlay on the node view page rewrites the URL, clearing the cache (admin toolbar + devel) on the node pages rewrites the URL and so on.

I already attempted to check for an absolute URL in $options, but that does not solve the problems above.

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^node/([0-9]*)|', $path, $matches) && $options['absolute'] {
      $options['query']['parameter'] = $foo;
    }
  }
}

Can I use hook_url_outbound_alter() to only alter URLs when it was invoked from a specific module or something?

Can I use hook_url_outbound_alter() to only alter URLs when it was invoked from a specific module or something?

You cannot, if that module doesn't put in $options (the same argument passed to url()) something that makes you understand that. To make an example, entity_uri() uses $options['entity_type'] and $options['entity']; if you were trying to intercept the calls to url() done from entity_uri(), you could check the presence of those options.
Otherwise, the context given to hook_url_outbound_alter() doesn't allow to understand which module called url(). Maybe you could get that using debugging functions, but I am not sure I would put that kind of code in a module.

Since you seem to trying to alter links in an email sent from Drupal, you could implement hook_mail_alter(), assuming the emails are sent using the correct way of sending them with Drupal.


Add a graphic element in content type without modifying the .tpl I would like to add a "like" icon at the end of articles. It’s just an icon which allow the reader of the article to click on the icon and increment a counter. It’s not a social button.

For now, i can add this icon directly in page.tpl

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

It works but i was wondering if it was possible to add it directly in the content type "article" in admin without modifying the file.tpl

You can modify it in a preprocess_page_hook, in template.php file... but I would recommend you to stick with the tpl file approach, as you've done it there.


Approach to create headless drupal with login I am curious on the approach I will have to take if I would like to build an app that connects to Drupal. I have already built simple headless drupal app using only get requests.

I am able also to make posts requests with Basic Auth or Auth0 mainly via postman and the concept of this is clear.

What is not clear to me is how I will be able to manage a logged in user from let's say a React/Vue.js app.

Let's say we have an app that servers 2 types of content: News and Events.
News is public and Events is for logged in users.
News and Events will be two Rest Export views in Drupal and Events will have an authentication method.

Now if a user wants to see Events he/she must be logged in. So the user will login via a login form and the session should be persisted. The app sends the request to Drupal, logs the user in and give a cookie/token/jwt back? So I will be able to use that cookie/token/jwt to access events and events/nid?

What should I use in this case in order to persist a login?

Thanks in advance.

I'd recommend you look at OAuth 2.0, which more or less standardizes the process of how to get to a valid login state/token.

I used https://www.drupal.org/project/simple_oauth recently in a project, which depends on the oauth2 component of the phpleague, which comes with great documentation: https://oauth2.thephpleague.com/. And the module itself also has a lot of documentation and whole video series on how to configure and use it.

OAuth2 provides 5 different ways to handle what it calls a grant, based on whether your client is an API, another website, a 3rd/1st-party client and so on: https://oauth2.thephpleague.com/authorization-server/which-grant/

E.g if you're OK with the user entering his password then you can just use the password grant, if you don't want that, you can use the oauth/authorize page which then redirects the user back to the app and so on.


Drupal database: how to join 2 tables? Currently I'm learning drupal database command as I'm pretty new to Drupal, I'm more familiar with mysqli api. I want to check the role of user before they are logged in to the system, the role table maps rid with a role (for example 1 - admin, 2 - author, etc.), the users table and users_roles table are linked by uid, which is unique. The role i want to verify before user login to the system has rid (role id) = 2. This is what I have so far, but it doesn't really work:

function is_author($name) {
$query = db_select('users_roles');
$query->join('users', 'users_roles.uid = users.uid'); // JOIN users_roles with users
$query->fields('users_roles', array('rid')) // SELLECT the field rid from users_roles
    ->fields('users', array('name')) // SELLECT the field name from users
    ->condition('users.name', ':name');

$result = $query->execute();

while ($record = $result->fetchAssoc()) {
    if ($record == 2) {
        break;
    }else{
        return false;
    }
}
return true;

}

This is the users and users_roles table:

table users:

uid | name | pass | .....

1 | Michael | (encrypted password)

2 | Ted | (encrypted password)

3 | Mark | (encrypted password)

Table users_roles:

uid | rid

1 | 2

2 | 3

Please help!! Thanks in advanced!

To check user role before login you need to create a validate function for login. You can put this code in template.php of your theme or in custom module file. e.g my custom module name is MYMODULE.

<?php

/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_login') {
$form['#validate'][] = 'MYMODULE_user_login_validate';
}
}

/**
* Additional handler for user_login form validate.
*/
function MYMODULE_user_login_validate($form, &$form_state) {
  // check user role here by the function mentioned abve
   $name = $form_state['values']['name'];
   $user = user_load_by_name($name);
   $role = array_key_exists(2, $user->roles);
   // do something
}

Hope it will help you.


Stop Mini Panels adding --1/2/3 etc to blocks I'm using mini panels in a build and am annoyed that when using a mini panel it adds for example a --1 to the block id in the HTML which makes it really hard to style with CSS.

Is there a way to turn this off so I just get the original block ID?

Drupal blocks aren't particularly aware of other blocks on the page, and you could legitimately have a mini panel block added with Panels and another  of the same added somewhere else with Drupal's regular block system or some other display module -  they would be completely unaware of each other and therefore without the appended numbers could end up with the same ID. Certain things in Javascript can break if two elements on a page  have the same ID, so it's pretty important to make sure this can't happen.

The best way to get a good stable clean ID for styling purposes is to add the mini panel block using  something with the panels/context interface (panels or page manager (comes with ctools, under Structure > Pages in menu) or panels everywhere etc), and use the block settings option to set an id that is specific and semantically relevant. It takes slightly longer in the short term, but saves a lot of trouble in the long term and gives you cleaner, more readable, more manageable HTML.

Generally speaking, replacing Drupal's default generated markup with clean lean semantic markup is a good idea (if somewhat tedious and time consuming).  Remember that Drupal's default auto-generated markup is intended for stability and flexibility in development more than it is for best practices in production. See also this similar common complaint about messy markup: Changing the HTML produced by Panels: Is it possible?


How can I update multiple drupal 7 sites on my server, using drush I just installed drush in my ssh home directory. Is there a drush command for updating all sites inside home directory that have drupal 7?

There is to mention that i have also non drupal sites and i would not like drush to mess with these.

Thanks

You can simply create a Bash script, and feed in all the folder names in the sites/dir into Drush.

See this script for updating a Drupal site; modify it according your needs-

Remember that testing is a very important part of every site upgrade. You should include a manual testing phase after the pm-update, and then push each tested site back to the live site as they are found to be working.


Why doesn't drupal_render work, but render does? I've a piece of code what is rendering a custom table (see var_dump below) what is shown on for specific states of the node. The data of the table is for both states the same.

array(1) {
  [0]=>
  array(5) {
    ["#theme"]=>
    string(5) "table"
    ["#header"]=>
    array(2) {
      [0]=>
      string(4) "test"
      [1]=>
      string(9) "geen test"
    }
    ["#rows"]=>
    array(2) {
      [0]=>
      array(2) {
        [1]=>
        string(6) "e1a1r1"
        [2]=>
        string(6) "e1a2r1"
      }
      [1]=>
      array(2) {
        [1]=>
        string(6) "e1a1r2"
        [2]=>
        string(6) "e1a2r2"
      }
    }
    ["#prefix"]=>
    string(38) "
Table
"
    ["#attributes"]=>
    array(1) {
      ["class"]=>
      array(1) {
        [0]=>
        string(15) "previous-scheme"
      }
    }
  }
}

The custom states of the node are determined by a condition what prints one of the following gathered variables.

For the variable at the line below works with both drupal_render and render.

$kickoff_deadline .= '
Between kickoff and deadline
'.drupal_render($table);

For the variable at the line below only works with render, without it wont show anything.

$after_deadline .= '
After the deadline
'.render($table);

So what is happening? Why doesn't drupal_render work for a similar printed variable what does work?

Once you've done this:

$kickoff_deadline .= '
Between kickoff and deadline
'.drupal_render($table);

The render array is marked as #printed, and won't be rendered again. So this

$after_deadline .= '
After the deadline
' . drupal_render($table);

Will do nothing.

If you take a look at the code for render():

function render(&$element) {
  if (is_array($element)) {
    show($element);
    return drupal_render($element);
  }
  else {
    // Safe-guard for inappropriate use of render() on flat variables: return
    // the variable as-is.
    return $element;
  }
}

You can see it runs show($element);, making it available for rendering again. Which is why this works:

$after_deadline .= '
After the deadline
'.render($table);


How to autoupdate quiz question to newest version? We have round about 200 quizzes with 5-10 questions. And most of the questions were updated by us. But we realized that quiz shows only the old versions.

Only solution so far is to check quiz by quiz and click updated to newest version question by question.

In settings I didn't find any possibility to auto switch to newest version as soon as the question got updated.

Any ideas to solve this problem?

Of course, we can switch every question to newest version as soon as we update them. But what about all the aprox 1000/2000 questions in system that still run on old version instead of newest?

quiz.info: version = "7.x-5.0-alpha8+14-dev"

According to the issue queue its says that the update issues only happen when manual revisioning is enabled. You can find out more here: https://www.drupal.org/node/1652936
Also make sure to update to latest version and run update scripts.


How to load a internal page content within div? I have following code in a basic page on drupal 7

Test Title

Test Nav

Content of the above internal link should display here.

So, when I click "Test Nav",  the content of the like which is originating from the same site should load within the div below.

EDIT: The content is from another page is part of a CRM form which gets generated automatically. So what I need to load is the “content” part of that linked page.  I have managed to load the page by “object load”, but that loads the entire webpage. I do not need the menu, header, footer. Just the content part of it. Hope this clears the query.

Can anyone suggest a way to do it please?

You can use jQuery $.load() to load a section of a page:

(function($, Drupal) {
  function loadContent(context) {
    $(context).find("#the_container_div").once("arbitrary-key", function () {
      // $(this) refers to #the_container_div
      $(this).load("http://example.com #container");
    }
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function (context) {
      loadContent(context);
    }
  };
}(jQuery, Drupal));

The function loadContent() loads the content of the #container div at the page example.com into your local container of #the_container_div.


How to alter checkout panes based on order contents I want to remove billing and payment for free orders. Currently, I have the code below.

Am I safe to user global $user in this case? Is there any better way to get the user account & order involved when this hook runs?

I ask because, after installing this hook, I've seen payment and billing panes hidden under admin/commerce/config/checkout, but I didn't hide them there. This seems to be intermittent.

function MODULE_commerce_checkout_pane_info_alter(&$checkout_pane) {

  global $user;
  $order = commerce_cart_order_load($user->uid);
  if (!empty($order)) {

    //get the order wrapper and order total
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_total = $order_wrapper->commerce_order_total->amount->value();

    // hide payment and billing info if the order total is <= 0
    if ((int) $order_total <= 0) {
      $checkout_pane['customer_profile_billing']['enabled'] = FALSE;
      $checkout_pane['commerce_payment']['enabled'] = FALSE;
    }
  }
}

You're seeing them hidden on the admin page because you're making no differentiation here in your code that would restrict the checkout pane info altering to only occur on checkout pages for customers, not administrators.

I'm divided. I recently created a checkout experience with an optional checkout pane, and I ultimately decided to alter the form directly instead of altering the checkout pane info. Part of it was that desire to ensure I had an identical definition on the front end / back end for all customers, but I'm not sure it was strictly necessary.

If you do end up altering the form instead, you need to supply new custom validate / submit handlers for the conditional checkout panes that wrap their default handlers and only invoke them if the pane was actually presented on a checkout form.


Installing Drush - permission denied error I just successfully installed Drush user composer into the .composer/vendor/bin folder.  When I try to run "drush status" I get an error
sh: /Users/Marianna/drush: Permission denied

What do I do now?

You can follow following two links, they are simple two steps and make the Drush running perfectly with no issue, even you can upgrade drush with that.

(1) How to install the Drush using Homebrew. And after that follow following steps to Symlink the php file location between your servers and MAMP.

(2) MAMP: Symlink PHP to /usr/bin/php

I was facing the same issue and re-installed using above steps and this set of two links worked perfectly.


How to show images uploaded only on "read more?" How to show images uploaded only on "read more?"

drupal is so confusing...

The 'Read more' button appears on the teaser display.

If you go to /admin/structure/types and select your content type, under the 'Manage display' tab you will see the display types for that content. Select 'teaser' and make the images 'Hidden' on the teaser. Then the images will only display when the full node is viewed.


page_cache_maximum_age wrongly set In our production server, we wrongly set page_cache_maximum_age a long value,

$conf['page_cache_maximum_age'] = 12960000;

Now viewers are complaining they are seeing old contents in there homepage.

I am able to see new contents with a force reload (CTRL + F5).

Is there any way to force the client side to refresh the pages in this stage?

We have our architecture Drupal+Nginx+Varnish and CloudFlare on top of it.

Either you don't need, or you can't:

If this was translated to HTTP header, and browser "knows" not to ask for the page again, nothing you would try to do about it will have any effect, because browser simply won't contact your server anyway, so it will not download any remedy you might try.

If it affected only server-side systems, tuning it down and clearing caches should be enough already, and server shouldn't send "304 Not Modified" to your clients.

Hard to tell which case is it without knowing your caching setup, but I'm afraid "fix it and wait" is the only way either way.

Unless, for some reason, you can identify uncached JS file included on affected pages. This would be a bug, so I don't expect it to happen, but if, it might be a bug you could use - ask for it on Stack Overflow, then, as this is much less Drupal-related.

If your front page isn't cached that way, you can alter all affected links. It will not help people having issues with bookmarked pages, but it will direct regular users to current content.


drush site-alias array I'm trying to script something up to completely automate synching sites around, and I want to be able to get a value out of the site alias which is an array.

If I do a

root@dev-drupal-www:~# drush sa @www.mysite.org.au
$aliases['www.mysite.org.au'] = array (
  'remote-host' => 'prod-drupalsites',
  'remote-user' => 'root',
  'uri' => 'www.mysite.org.au',
  'root' => '/vhost/www.mysite.org.au',
  'path-aliases' =>
  array (
    '%site' => 'sites/default/',
    '%files' => 'sites/default/files',
    '%dump' => '/tmp/drush_www.mysite.org.au.sql',
  ),
);
root@dev-drupal-www:~# drush sa @www.mysite.org.au --component="path-aliases"
Array
root@dev-drupal-www:~# drush sa @www.mysite.org.au --component="path-aliases:%dump"
The element path-aliases:%dump was not found in the alias record for @www.mysite.org.au.                                                                                [error]
root@dev-drupal-www:~#

How can I extract an item from the path-aliases?

Thanks!

Unfortunately, (as you discovered), the site-alias command is not flexible enough to do what you want. There are other ways, though.  For your specific example above, which happens to involve paths, you can use the drupal-directory (dd) command:

$ drush dd @www.mysite.org.au:%dump
/tmp/drush_www.mysite.org.au.sql
$ drush dd @www.mysite.org.au:%files
/vhost/www.mysite.org.au/sites/default/files

For a more general-purpose solution, you could use the php-eval (ev) command:

$ drush ev '$a = drush_sitealias_get_record("@gk.dev"); print_r($a["path-aliases"]);'
Array
(
    [%boo] => /usr/local/boo
    [%root] => /srv/www/dev.greenknowe.org
)

This can, of course, be customized to suit, as the ev command will evaluate any arbitrary php you care to throw at it (as long as you escape special characters correctly). This is more complicated to use than the dd command, but it will also work for elements other than paths in the path-aliases element.


Can I remove write protection for all Drupal files? Just to prevent hacks, can I remove write protection in all files and directories in my installation, except for in sites/default/files?

I mean I want to chmod to 555 and chown them all to root:root except for files within sites/default/files. For installation/uninstallation I use Drush.

I'm talking about the "Config 1: Web server is running as owner" as described as in What are the most appropriate users and permission levels for Drupal sites on shared hosting?

It seems  my four sites are working fine with this. Is it OK?

This is because to ward off hack attacks which place php files in within site folders.
This almost saved my site from this Highly Critical hack attack but the hacker was able to place php and execute file within sites/default/files as my .httacces was not protected from running php scripts within the files directory.

Yes, although it will disable the installation of modules through the web interface (it writes in sites/all/modules), but I would consider that a feature.

You also probably want to use 0644 for files (rw/r/r), and 0755 for directories (rwx/rx/rx). By convention, you don't want files to be executable unless they are really meant to be.

Here is the official Drupal documentation on the issue:
https://www.drupal.org/node/244924

And this answer also has good advice:
What is the suitable file permission for 'files'?


Map to collect nodes I have a content type with +3000 nodes, and it has a field set as Term Reference for countries. I would like to have a map that count all these nodes (maybe with Views), but all solutions I have found was to set a geofield using Gmap module, and in my case it will be hard to go through the +3000 nodes to give each node its location.

So is there is any module that can count nodes of each term, showing it on its country? Also if I would like to show only five countries instead of whole world map, is that a map library or map modules can do that?

Although it doesn't look too complicated, I'd normally use the following modules to easily add and display nodes on a map:

Leaflet;
Leaflet Views;
Leaflet More Maps;
Views;
Geofield;
Geocoder;
Geocoder Autocomplete;
GeoPHP;
Entity;
Entity Reference;
Chosen;

I don't work with Taxonomy terms. Instead, I create a node type named, let's say "Category" and add the right categories as nodes instead of terms in a vocabulary. It is easier like this and offers me more flexibility in the future.

The Category content type is based on a form that only includes Title as field. I'm adding them manually, which is not as simple as adding tags (terms) with the autocomplete options. As an alternative, I think you could use Inline Entity Form to add Categories during node add form. Not sure though.

When adding nodes, you need:

an entity reference field pointing to the Category (using Chosen could help, if you don't have 10k categories);
a textfield using Geocoder text field with autocomplete;
a Geofield using Geocode from another field.

Now, when adding nodes, you get the Google Geocoder autocomplete option and the geofield will auto-fill with the right coordinates.

Then, I'm using Views to display items on the map with Leaflet. Here you can choose displaying only first 5 items, based on whatever filter criteria and order options you'd like. The view is a block and has an Entity Reference relationship poiting from the node to the category node + a contextual filter NID type my-node-type, with content ID from URL argument that uses this relationship.

Block will show up only on Category node-type pages in the content area.

Doesn't look very simple but there are a few tutorials on how to achieve that with leaflet, geofield and entities on Youtube. There are other ways to solve your problem, like using EVA with DS, adding blocks as fields in your DS display.


view contents flagged by other users I would like to make a view to select the contents flagged by a list of users.

I tried this:
https://www.drupal.org/node/1191228

but it works only for one user at time. I would need that for multiple users.

In the "uid" contextual filter I tried to set "Allow multiple values" in the "more" area, but when I use more than one user ("uid1, uid2" or "uid1 + uid2"), the view is not ran.

any idea?

thank you

Try to uncheck the "require this relationship" checkbox in the relationships of your view


Panels overlay capability I'm building with D7 and looking for an easy way to build a page rendered into an overlay.

Wouldn't it be awesome if Panels could be configured to spit out it's contents into an overlay -perhaps the core admin overlay.

Has anyone seen anything like this? Is it worth building?

In Panels under Settings -> Basic for your page there is a checkbox with the label "Use this page in an admin overlay." that you can use for this.


Can't get a Redirect Hook to Fire I'm attempting to use hook_redirect_alter() as described in redirect.api.php.

I created my_module.module and entered the hook as: function my_module_redirect_alter($redirect) To test I just entered a drupal_set_message and attempted to write a notice to the log but I can't seem to get it to actually fire.

function my_module_redirect_alter($redirect) {
  $message = "redirect_alter worked!";
    \Drupal::logger('my_module')->notice($message);
}

What am I doing wrong here? Am I misunderstanding this hook?

Good afternoon.

1) install the devel module.

2) Install the modules, devel, kint.

3) change your code for the following:

function my_module_redirect_alter($redirect) {
   dpm($message = "redirect_alter worked!");
   kint($redirect);
}

4)  try to perform a process such as updating a node and when redirecting, you must show the messages.

Note: dpm() and kint() are functions of the devel module to inspect a variable


Why subscribe/unsubscribe button in the custom entity named group cannot appear? I have created a custom render in group_module.js exactly as the example Rendering Entities with the exception of the line items['group/%'] = { instead of items['team/%'] = {. All other content nodes but group nodes (group/%) show ok. Group nodes show no subscribe/unsubscribe button and no menu tabs mentioned below in the groups_menu_module.js. I suppose that this module, groups_menu_module.js, is not loaded somehow.
I have to mention that without the custom rendering of entity group and with 2 LOCAL_TASK_MENU menu tabs, everything works perfect.

groups_menu_module.js

function groups_menu_module_menu() {
  try {
    var items = {};
    items['group/%']={
      title: 'view',
      page_callback: 'drupalgap_get_entity',
      page_arguments: ['groups_menu_module_default_page', 'node', 1]
    };
    items['group/%/provoli'] = {
      title: 'view',
      type: 'MENU_DEFAULT_LOCAL_TASK'
    };
    items['group/%/melh'] = {
      title: 'members',
      type: 'MENU_LOCAL_TASK',
      page_callback: 'groups_menu_module_melh_page',
      page_arguments: [1],
      title_callback: 'groups_menu_module_melh_page_title',
      title_arguments: [1],
      access_callback: 'groups_menu_module_page_access',
      access_arguments: [1],
      options: {
        reloadPage: true
      }
    };
    items['group/%/anarthseis'] = {
      title: 'posts',
      type: 'MENU_LOCAL_TASK',
      page_callback: 'groups_menu_module_anarthseis_page',
      page_arguments: [1],
      access_callback: 'groups_menu_module_page_access',
      access_arguments: [1],
      options: {
        reloadPage: true
      }
    };
    return items;
  }
  catch (error) {
    console.log('groups_menu_module_menu - ' + error);
  }
}

function groups_menu_module_default_page(node) {
  try {
    var content = {};
    content['title'] = { markup: node.title };
    return content;
  }
  catch (error) {
    console.log('groups_menu_module_default_page - ' + error);
  }
}

I have to mention that all functions needed are present in the actual .js file, i just opted them out because i think they are irrelevant.
The pageshow function of the other module is as the example in the above link:

group_module.js

function example_team_pageshow(nid) {
  node_load(nid, {
    success: function(node) {
      var content = node.title; // Add other content here...
      $('#' + example_team_container_id(nid)).html(content).trigger('create');
    }
  });
}

So to conclude the question is how to make the subscribe/unsubscribe button appear in the custom entity render? How to call og_ui_field_formatter_view() from my module to make the button appear?

I don't know if i made my self clear what is needed. If anyone need more information please ask so in the comments below to clarify some points.

Since you are taking over the display of Organic Groups nodes using your custom page callback path group/%, DrupalGap doesn't know to apply the field format view functions to your fields. Essentially you need to manually create/render your own widgets in your page_callback:

var content = {};
content.title = { /* ... */ };
content.subscribe = { /* ... */ };
return content;

There are helper functions in the og.js file related to joining/leaving groups that will be of help. From there just use simple HTML/CSS/JS to build your button(s) (perhaps with an onclick handler) to help the user interact with the group subscriptions.

If you want to call the og_ui_field_formatter_view() function directly (not recommended) you can, you just need to pass it all the correct parameters:

(entity_type, entity, field, instance, langcode, items, display)

the entity_type is typically 'node'
the entity will be the fully loaded JSON of the entity (already delivered to your page_callback)
the field and instance can be retrieved from http://api.drupalgap.org/7/global.html#drupalgap_field_info_field and http://api.drupalgap.org/7/global.html#drupalgap_field_info_instance respectively.
the langcode will most likely be und unless you are using a multi-lingual site
the items will be the value(s) within the field itself
the display you should default to { type: 'og_group_subscribe' }.

Not the easiest things to do to be honest, and you'll probably find yourself happier in the long run by building your own custom widget to subscribe/unsubscribe from the Group.

Feel free to copy any code you need from the og.js file to make your life easier.


In Drupal Commerce, on what page does this order status fire? When an order is first paid in full I'm currently setting up my Drupal Commerce checkout Rules and came across that you have setup your own Paid Status on payment sucess. By default Drupal Commerce only updates the status to PENDING.

What I need to know on what page does the following Rule Event get fired?

  When an order is first paid in full

This event is triggered on whatever page request results in the named event - an order first being considered paid in full. This means it's going to vary based on the payment method. Sometimes a transaction is completed as part of a checkout form submission. Sometimes it happens while the customer is on a third party payment gateway page. Sometimes it happens after the fact when an administrator captures an authorization created during the checkout process.

When a payment transaction is saved, however it happens, Drupal Commerce compares the total of all payment transaction amounts for an order against the order total to determine whether or not the order has now been paid in full. If so, it triggers this event and updates the order to prevent the event from being triggered again - hence the "first" part of the event name.


Field rendered invisible when code block enabled I have this weird issue when altering a webform. Below are two versions of my code:

function tubitekuz_form_webform_client_form_97_alter(&$form, &$form_state, $form_id) {
  $form['submitted']['kullanici_adi'] = array(
    '#type' => 'textfield',
    '#ajax' => array(
      'event' => 'blur',
      'callback' => '_tubitekuz_do_stuff',
    ),
  );
}

The above code renders my field invisible, while

function tubitekuz_form_webform_client_form_97_alter(&$form, &$form_state, $form_id) {
 $form['submitted']['kullanici_adi']['#ajax'] = array(
    'event' => 'blur',
    'callback' => '_tubitekuz_do_stuff',
  );
}

gives me .

What might I be doing wrong?

I found out why. It seems our designer chose to add display:none to ajax-processed class, which is added to #ajax calls.


Add html ID to content field When I create the content (specific to the content, not to the content type), I want to type in an optional ID, that would be set on the html element.

Is there a module for this?

In Drupal 6, you can theme cck fields by copying content-field.tpl.php from the CCK module's includes directory to your theme directory and then creating a content-field-FIELDNAME.tpl.php to customize the look of that individual field.  Or, if you want to wrap every field with a uniquely id'ed div, you could edit your copy of content-field.tpl.php and add:

<div id="<?php print $field_name_css . '-' . $node->nid; ?>">

-- php code between the check if the field isn't empty --

</div>

to the template, or around whatever portion in it you needed.  Just be careful with multiple field items, their ids would need a -$delta added to them if you put this inside the code of the template instead of wrapping it entirely, or adding the id= to the first div, etc.  If you want to id it with a user supplied field, you can grab that from the $node given, eg

$node->field_my_optional_id[0]['value']

but you have to sanitize it.

Now, I know you said Drupal 7, and I am sure it's subtly different there, but this should put you on the right path.  Hope it helps!

UPDATE/EDIT:  It's field.tpl.php from the system module field's theme directory in D7.


Stop account's activities for 24 hours How can I temporarily ban an email address for up to one month?

I am using Drupal 6.

There is the Troll module, which seems to do what you need; it isn't looked after.
For other options you also have the Cave your trolls module, which hides user's posts from anyone other than themselves, or the Misery module, which makes the site unusable for certain users.


What are Entity tags (Etags) and how do you configure them in relation to your Drupal site's files? The GTmetrix Page speed & optimization test notified me that 13 components in my site (all are files) have "misconfigured Etags", so I ran a search query like " Drupal Entity tags " in Google and found almost nothing that was instructive for me (for my knowledge and understanding) on how to solve it via the Drupal UI. Therefore my question is first of all what are these Etags (or Entity tags) and how can I add them (or just configure them right, if they exist), For the relevant files?
Much thanks,

https://en.wikipedia.org/wiki/HTTP_ETag

Inside your .htaccess file add this to the bottom
FileETag MTime Size


redirect to prod url when creating content I have a Drupal 7 development site that is a subdomain of the production site, eg. dev.prod.com, for example.

When ever I create a content type, new content, a new user, install a new module, etc on the development site it redirects to the production URL after the form is submitted.  I don't have permission on production so I get "access denied". When I go back to the development site and refresh the browser, the content have been created.  But this does not work for installing a module. The module is not installed.  Obviously, this makes it impossible to work on dev.

I have reviewed .htaccess and settings.php for any rewrite rules that could be causing this but I have not found anything.  $base_url is set to the correct URL for the development server. I have cleared the cache many times.

Any suggestions?

Looks like you need to check the value specified for $base_url, within the settings.php of your dev.prod.com site. Assign a value of (eg) dev.prod.com and see what happens then.


How to open accordion when setting error? I have custom validation on an element using ['#element_validate'].

But the element is within an accordion item within an accordion and the error doesn't signal to the parent elements to open up when the form is reloaded with the errors.

Is there a way to signal to an elements groups to open up when doing $form_state->setError($element) on an element?

I have added this an issue on the field_group module and have posted a patch: https://www.drupal.org/project/field_group/issues/2923831


Modifying only node forms, not forms appearing in blocks? I have a contact webform in a block in a sidebar that appears on every page.

I also have some webform nodes.

I want to use hook_form_alter() to modify the forms that are nodes, not those that appear in blocks.

How can I differentiate between the two in code?

Using hook_form_formID_alter()

You could use hook_form_formID_alter() to target this Webform node specifically.

For example:

function hook_form_webform_client_form_429_alter(&$form, &$form_state, $form_id) {
    // Alterations here.
}

webform_client_form_429 in this example is found using the <form id=''> from the node in the block you want to alter.

Using hook_form_alter for all Webforms rendered in a block

If the Webform block was created using webform_block_view() then $form['#node']->webform_block should be TRUE.  Pages on the other hand should be $form['#node']->webform_block == FALSE

Try using dpm() from the Devel project to poke around the $form variable for webform_block specific items.

My assumption would be that you could use:

hook_form_alter(&$form, &$form_state, $form_id) {
   if ($form['#node']->webform_block == FALSE) {
      // Alterations
   }
}


What is the recommendation for mapping state? The configuration in D8 is nicely mapped in config schema file so any developer knows what configuration changes can be made. But what about state? Is there a recommended way to map state? Or is it the same situation as with variables in D7?

Would it be a good idea to store default values for state as part of the config schema under some specific key, like "state"? Althoguh that would mean dependency on config(factory) in different places within the code.

There is no mapping/schema for state nor for the underlying key value system.

This question can't be "answered" other than saying "None". Anything else would need to be in the form of a feature request and I'm not convinced this makes sense.


How to modify form fields before validation I have a custom content type with a lot of fields, and some are required.
Under some circustances these required fields can be computed from other fields.
I tried to use also hook_node_validate, but i have always the error message because the field is empty when the user sends the form.
It's not easy to implement a javascript solution, since the algorithm to compute the values is not trivial.
Which kind of solution do you suggest to use?

From the documentation:

  Note: Changes made to the $node object within your hook implementation will have no effect. The preferred method to change a node's content is to use hook_node_presave() instead. If it is really necessary to change the node at the validate stage, you can use form_set_value().