Ajax via Jquery and attach behaviors The Ajax framework is very nice but i want more complex effects. So I am trying to do the Ajax calls via Jquery. The goal here is to load nodes by clicking some links on the menu but the nodes  contains an image which pop ups with a lightbox and also contains a from which submits via Ajax. For demo site i am using Drupal commerce. here is the demo to check out.

I am using    Drupal.attachBehaviors(document); to re-attach the needed js scripts. The problem is that some of the behaviors are attached and some others are not. For example the first menu link 'Products' is a view and it uses ajax pagination but it loses this functionality but the image lightbox in this view does work. So i am little confuse here.

This is my code.

/*
 *  Implemets hook_menu()
 */

function myajax_menu() {
$items = array();

$items['myajax'] = array(
    'title' => 'Ajax',
    'page callback' => 'myajax_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

$items['myajax/view'] = array(
    'title' => 'Ajax',
    'page callback' => 'myajax_view_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

return $items;
}
/*
 *  Ajax handling
 */
function myajax_callback($nid = '') {
      $node = node_load($nid);
      $vnode = node_view($node);
      return theme('node',$vnode);
}

function myajax_view_callback($view = '') {
      print views_embed_view($view, 'default');
}

and my js file

(function ($) {

Drupal.behaviors.myajax = {
    attach: function(context,settings){
        $('#main div.column').before('
Loading...
');

        $('a.ajax_link', context).once().bind('click',function(e){
            $(this).addClass('ajaxafy');
            e.preventDefault();
            var url = $(this).attr('href').split('/');
            //console.log(settings);
            $('#loading').fadeIn();
            $.ajax({
               type: "POST",
               url: Drupal.settings.basePath + 'myajax/' + url[2],
               data: {'js':1}, // you can also pass block name and act more dynamicly
               success: function (response){
                  $('#loading').fadeOut()
                  $('#main #myajax', context).html(response)
              Drupal.attachBehaviors(document);

              },
            });
        });
        $('a.ajax_link_view',context).once().bind('click',function(e){
            e.preventDefault();
            var url = $(this).attr('href').split('/');
            $('#loading').fadeIn();
            $.ajax({
               type: "POST",
               url: Drupal.settings.basePath + 'myajax/view/' + url[1],
               data: {'js':1}, // you can also pass block name and act more dynamicly
               success: function (data){
                  $('#loading').fadeOut()
                   $('#main #myajax', context).html(data);
                   Drupal.attachBehaviors(document);
              },
            });

        });

    }
};

})(jQuery)

Alse the webform submits also using Ajax but it loses that behavior.

What i am missing here? Please check the demo to see what's going on. Thanks in advance.

Must be:

Drupal.attachBehaviors($('#main'), context);


I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick.

I added a css file and edited the slick skin php file to use the css file depending on the user's choice. I also added a bootstrap class to the slick.html.twig template so that the slider would disappear on mobile devices.

Should I make a custom module that acts like slick_examples?

In my opinion, the easiest way to preserve changes to contributed code is to manage your dependencies through Composer and use patches. When you update slick in the future, the output of the command will directly tell you which of your patches have been broken by the update.

i thought that you can override or extend controllers or plugin, its the only way to preserve the changes after updates


In Node References, how to show a custom field, instead of the Title? Is it possible to show in a select list, another field instead of the Title when referencing a node?

As dobeerman says you can use a View as a source, but CCK does some playing with the View behind the scenes (I just found out as a result of this question;). If you look in nodereference.module at the function _nodereference_potential_references_views() you'll find the following code:

// We do need title field, so add it if not present (unlikely, but...)
$fields = $view->get_items('field', $display);
if (!isset($fields['title'])) {
  $view->add_item($display, 'field', 'node', 'title');
}

// If not set, make all fields inline and define a separator.
$options = $view->display_handler->get_option('row_options');
if (empty($options['inline'])) {
  $options['inline'] = drupal_map_assoc(array_keys($view->get_items('field', $display)));
}
if (empty($options['separator'])) {
  $options['separator'] = '-';
}
$view->display_handler->set_option('row_options', $options);

So this means that

if you don't include a title field then it will be included for you;
if you don't make all fields inline and define a separator then it will be done for you.

So if you configure the title field to be hidden, and specify an appropriate separator, you should be able to create just about any effect. If you can't achieve what you want with a view (eg. ordering nodes by their menu position) then you want to use a different approach.

You could create your own CCK widget, or (simpler) you can use a form_alter hook. If you do the latter, you can't edit the form the normal way because CCK hasn't processed the form at this stage - you'll want to use a #after_build function.

I have an example of the second approach used to show nodereferences ordered by the menu if you're interested.

/**
 * Implements hook_form_alter().
 */
function banners_form_alter(&$form, &$form_state, $form_id) {

  // Modify nodereferences for banners so that pages are shown in primary links
  // order.
  if ($form['#id'] === 'node-form' && isset($form['#field_info']['field_pages'])) {

    if (!isset($form['#after_build'])) {
      $form['#after_build'] = array();
    }
    $form['#after_build'][] = 'banners_after_build';
  }
}

/**
 * After_build callback for modifying CCK field select options.
 */
function banners_after_build($form, &$form_state) {
  // Get the menu data
  $new_options = banners_generate_page_options();

  if (isset($form['#field_info']['field_pages'])) {
    $old_options = $form['field_pages']['nid']['nid']['#options'];
    $final_options = banners_process_options($new_options, $old_options);
    $form['field_pages']['nid']['nid']['#options'] = $final_options;
  }

  // Return new form
  return $form;
}

/**
 * Uses the old options to filter out unreferenced nids and add those that
 * weren't detected in a menu structure to the other option group.
 * @param $new_options
 *   The options list created by scanning the menus.
 * @param $old_options
 *   The options list originally passed to the form.
 *
 * @return
 *   The final options list with option groups for each menu and for orphans.
 */
function banners_process_options($new_options, $old_options) {
  // Have to assume that $old_options could get quite large, whereas
  // $new_options is based on menus, and shouldn't get too large.

  // Iterate through $new_options (the menu nids) and remove nids from
  // $old_options that exist in $new_options, and remove nids from $new_options
  // that don't exist in $old_options. After this $old_options has valid nids
  // that aren't under the menu hierarchy.
  foreach ($new_options as $menu_title => $options) {
    foreach ($options as $nid => $title) {
      if (isset($old_options[$nid])) {
        unset($old_options[$nid]);
      }
      else {
        unset($new_options[$menu_title][$nid]);
      }
    }
  }

  $final_options = array();

  // If the field is not marked required, there'll be an option for - None -
  // and it's keyed to the empty string.
  if (isset($old_options[''])) {
    $final_options[''] = $old_options[''];
    unset($old_options['']);
  }

  $final_options += $new_options;

  $final_options['Others'] = $old_options;

  return $final_options;
}

/**
 * Generates FAPI options for the allowed menus' node links.
 *
 * @return
 *   A FAPI options array with all node links on the allowed menus (NB this has
 *   not been filtered in any other way).
 */
function banners_generate_page_options() {

  $menus = array('primary-links', 'menu-top-menu');
  $options = array();

  foreach ($menus as $menu_name) {
    $tree = menu_tree_all_data($menu_name);
    $menu = menu_load($menu_name);
    $options[$menu['title']] = _banners_process_tree($tree);
  }

  return $options;
}

/**
 * Recursive function to generate the options array, keyed by nid.
 */
function _banners_process_tree($tree, $depth = 0) {

  $options = array();

  foreach ($tree as $item) {
    $matches = array();
    if (preg_match('~^node/(\d+)$~', $item['link']['link_path'], $matches)) {
      // Link points to a node
      $nid = $matches[1];
      $options[$nid] = str_repeat('--', $depth) . ' ' . $item['link']['title'];
      if ($item['below']) {
        $options += _banners_process_tree($item['below'], $depth + 1);
      }
    }
  }

  return $options;
}

if you just include the title in views, but you set it not to show, this works fine, and keeps title out.

//edit

"Is it possible to show in a select list, another field instead of the Title when referencing a node?" when using nodereference (apart of CCK) well from my own experience you can only use the default panel in a view to populate the nodereference dropdown - if you choose to just show the node title then fine - works great - but if you list a custom field from the node instead of title you will find it still appends the node title - so if you include the node title anyway and choose to not display it in the output, this gets around that - now re-reading the question I think OP was asking how to show custom fields - i missed that but this is useful for after he is showing the custom fields using views.


How we can make weekly calendar block with ajax? How we can make weekly calendar in drupal 7 module same as attach screenshot?

My R&D

I am using jQuery week calendar (https://github.com/themouette/jquery-week-calendar) .

Use calendar module (requires views module). Calendar module comes with bunch of blocks (block views) available and you can set for them to use AJAX instead of refreshing page. With views you can do a lot of customization.

I have achieved weekly calendar functionality using the php date function .

  $date = date('m/d/Y');
  // parse about any English textual datetime description into a Unix timestamp
  $ts = strtotime($date);
  // find the year (ISO-8601 year number) and the current week
  $year = date('o', $ts);
  $week = (int)date('W', $ts);


How to hide views page title I need to hide the page title in Views but still have it appear as the page title on the browser's window tab (for SEO). Could someone help me with that? I've looked around many times for answers but I haven't had any luck yet.

The CSS solution might not be the best for SEO purposes...
Another better alternative is to write in the page title field :

<No Title>
or : to leave it blank

And the title wont be displayed


D7: How to deal with the variables visibility? Now I have some variables collected from POST

$a = $_POST['a'];
$b = $_POST['b'];
$c = $a * $b

I need to use them in 2 functions: hook_form() and the callback mail_send() the function that format and sends my email with form elements.

I have implemented the following hooks:

function MYMODULE_page() {...}
function MYMODULE_form() {...}
function MYMODULE_form_submit($form, &$form_state) {
mail_send($form_state['values']);
}

//a custom callback mail function call in the submit.
function mail_send($form_values) {}

...

Now I don't know where to place those variables to have maximum visibility:

if I place them in MYMODULE_form() the show up in the form but they are not available in the mail_send().
if I place them outside everything they are not available inside functions.
if i place them inside a hook_init() the same as above.

I need a place where all variables are visible. Thanks

For the maximum visibility use global variables like below

$a = $_POST['a'];
$b = $_POST['b'];
global $c;
$c = $a * $b

and you can anywhere like below,

function mail_send($form_values) {
  global $c;
  print_r($c);
}

There is no special methods exists in drupal, it is just like php.


Using pathauto to create multiple aliases, one for each term? If I have a taxonomy tags so that I can tag a node with foo and bar and baz, is there any way to make the pathauto module create three aliases?

If it would normally create content/my-new-node, is it possible to make pathauto create foo/my-new-node and bar/my-new-node and baz/my-new-node?

Under Configuration, if you go to Modules and click on Configure for Pathauto, you should see the option for the URL patterns. There is a section for taxonomy as well. However, I realize you want to change a node's URL based on the taxonomy term you've associated with it. At this point, it's just a matter of figuring out what token is going to do that for you.I have not used it, but I would imagine the Field Tokens module may help you do what you want to do. If you search for "pathauto" on that page, some people discuss using it with Pathauto down in the comments.


Print specific field of a specific node I have the content type of "Front Page Section" where there are the fields "body" and "field_home_section_photo".

On the home page (page--front.tpl.php) I would like to be able to print the body and image fields separately for particular nodes with their formatting in place:

Print Node 42 Body

Print Node 42 Image

Print Node 43 Body

Print Node 43 Image

Print Node 44 Body

Print Node 45 Image

You can do this by hook_preprocess_node(&$vars) function. By this function you can check the Node ID then if it is some custom IDs, fetch the appropriate data and assign them in $vars array.

In the aggregate we have

function THEME_preprocess_node(&$vars){
    if(drupal_is_front_page() == true){
         if($vars['node']->nid == 44){
             $newNode = node_load(45);
             $wrapper = entity_metadata_wrapper('node',$newNode);
             $image = $wrapper->field_home_section_photo->value();
 //here use kpr($vars) to get the correct syntax of  field_home_section_photo in $vars
// suppose it is $var['fields']['field_home_section_photo']->value
              $var['fields']['field_home_section_photo']->value = $image;
           }
      }
}

don't forget to install entity module.

If you're not familiar with the module layer of drupal I would suggest using the views module to build a view page of all the nodes of type "Front Page Section" and use this as the front page.
https://www.drupal.org/project/views


Command to list all media entities in console? I have an issue in my site which is not allowing me to visit the /en/admin/content/media page.

I'm looking for an approach to list and delete media entities on the command line.

When I run drupal debug:entity media I get an error:

[ERROR] Notice: Undefined index: media in Drupal\Console\Command\Debug\EntityCommand-&gt;execute() (line 79 of /home/ubuntu/site/vendor/drupal/console/src/Command/Debug/EntityCommand.php
         ).
Drupal\Console\Command\Debug\EntityCommand-&gt;execute(Object, Object)
         (Line: 255)
         Symfony\Component\Console\Command\Command-&gt;run(Object, Object) (Line: 971)
         Symfony\Component\Console\Application-&gt;doRunCommand(Object, Object, Object) (Line: 248)
         Symfony\Component\Console\Application-&gt;doRun(Object, Object) (Line: 185)
         Drupal\Console\Core\Application-&gt;doRun(Object, Object) (Line: 64)
         Drupal\Console\Application-&gt;doRun(Object, Object) (Line: 148)
         Symfony\Component\Console\Application-&gt;run() (Line: 89)
         require(&#039;/home/ubuntu/site/vendor/drupal/console/bin/drupal.php&#039;) (Line: 4)

The docs of this command is also really uninformative.

What's the best approach to list and delete media entities on the command line?

If you use Drush, you can try drush sql-query like this :
 drush sql-query "Delete from name_table weher condition"


Show a popup after saving a new node How do I create a popup which can use the node variables after saving a new node?
For example, I want to show a popup with the social media share button. Should I use node_save()?

When a node is saved, the user is normally redirected to the page showing the node, which is not a form. In that case, hook_form_alter() doesn't help. I said the user is normally redirected to the page showing the node, as that is what Drupal does, but there could be a module that redirects the user to a different page, such as the one showing the node edit form to add a new node.

To show the popup when the node is viewed, you can use hook_node_view(), which can be used to add HTML tags to the node view page.

The example shown in the documentations shows how to add markup to the node view page.

function mymodule_node_view($node, $view_mode, $langcode) {
  $additional_markup = 'Markup to add to the page';

  $node->content['my_additional_markup'] = array(
    '#markup' => $additional_markup,
    '#weight' => 10,
  );
}

As for showing the popup right after the node has been saved, you could implement hook_form_alter() to add a form submission handler to the "Save" button; that submission handler would add a session variable that is the checked from your implementation of hook_node_view(). Its code should then be similar to the following one.

function mymodule_node_view($node, $view_mode, $langcode) {
  if (isset($_SESSION['nid']) && isset($_SESSION['timestamp']) && $_SESSION['nid'] == $node->nid && mymodule_check_timestamp($_SESSION['timestamp'])) {
    $additional_markup = 'Markup to add to the page';

    $node->content['my_additional_markup'] = array(
      '#markup' => $additional_markup,
      '#weight' => 10,
    );
  }
}

The values in $_SESSION are the ones set by the form submission handler. mymodule_check_timestamp() should return TRUE when $_SESSION['timestamp'] doesn't contain a value too past in time; this would help in the case there is a module that redirect the user to a different page, and then the user visit the node page to review the node s/he saved. For example, it could return TRUE when $_SESSION['timestamp'] is a timestamp 5 seconds earlier. It is up to you to decide how much delay should be acceptable between when the node is saved, and when the node is viewed from the same user who edited it.

You can change the weight used in hook_node_view(); that changes where in the node view page your markup is added.

drupal_add_js inside a hook_form_alter, like so:

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
  if ([your logic to pick out the node form])
    {
      drupal_add_js([your javascript]);
    }
}

Or you could probably do it with Rules calling some custom code.


How to get term by path or alias? I've seen this question posted many places, but no answers - or relevant answer. i.e. how to get term object or ID from path or alias e.g. /cat/subcat or /taxonomy/term/6??

I usually do something like this:

<?php

use Drupal\taxonomy\Entity\Term;

function hook_preprocess_page(&$vars) {
  $route = \Drupal::routeMatch();
  if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = $route->getRawParameter('taxonomy_term');
    $term = Term::load($term_id);
  }
}

If you are using original path not URL alias then you can explode you path like that

$exp = explode('/','/taxonomy/term/6');
$tid = $exp[2];

Then you can load your term object using this tid as@Ronnie say.


My custom CSS is not taken into account I add a CSS file (mymovies.css) to a custom form (SeenMovies) in a custom module (eric) with this code I inserted at the end of buildForm
$form['#attached']['library'][] = 'eric/mymovies';

and this code in eric.libraries.yml
mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}

But my css doesn't override bootstrap.min.css as you can see in Firefox inspector:

How can I fix that?

This question has nothing to do with Drupal but with CSS order of precedence. If more than one identical CSS rules are found, the last one takes precedence.

As @leymannx pointed in their comment, your page is loading first your CSS file, then Bootstrap. Just move your Bootstrap into a new library as you just did with 'mymovies', then add a dependency to 'mymovies'. Declaring it as a dependency, it will load first the need libraries, then the library being called.

Edit - after saying you are using OnePage Zymphonies theme:

If you check 'onepage_zymphonies_theme.libraries.yml' you will see that the Bootstrap library is defined. Following my answer:

mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}
  dependencies:
      - onepage_zymphonies_theme/bootstrap

Instead of adding an additional selector for all the css in future to override the bootstrap css you can try using the weight flag of libraries like this:

mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: { weight: N }

Just determine the weight of bootstrap library and replace N with the number greater than that.

In this way your mymovies.css will load after bootstrap css and you will no longer need to write that extra selector


storing value in session with ctools wizard I have created a multi-step form using Ctools wizard and its working fine.

In multi step form, there is only images, so user will select the image and click on "Continue" button for next step. In the final step, I am showing the result of merged images which are selected in all previous step.

Images are rendering as ajax link in each step and when user click on any image, an ajax callback be executed.

In each step form load and ajax callback, fid of the images be stored in $_SESSION variable.

But the problem is that $_SESSION are not updating on the ajax call.

Suppose, there are five images in step 1 in the Ctools multi step form. When step 1 load, I am storing fid of first image into $_SESSION variable and If user click on any images, I am updating the fid in $_SESSION variable.

But, if I check print_r($_SESSION) in next step, its not showing the updated fid. Its only showing fid of the first image in previous step.

If I check ajax callback in fire bug console, its showing correct value of fid and $_SESSION variable.

Please suggest me what I am doing wrong.

Thanks in advance.

you cannot use form_state. every step will have it's own.
cache the date with ctools_object_cache_set

Here is a nice example how to create customizable multistep form without ctools wizard.


$form['redirect'] = "something=$someId"; doesn't work in Drupal 7 I am here again with a problem! I want to make a form redirect usign a url with ids and somethings else as parameter, but when the code is executed something encode my url, so, if I put something like this $form_state['redirect'] = "page=$nid"; I get this in the url "page*%3D*123456789" %3D is the =$. So, how i have to do that? I tested with utf8_encode too.

Can I use a drupal_goto() inside a form? Why yes? Why not?

Thanks people!

What you set in $form_state['redirect'] can be:

a string containing the destination, such as node/1, admin/reports/status, or user/1.
an array of arguments compatible with drupal_goto().

The examples shown in drupal_redirect_form() are the following ones:

This redirect the form to node:

$form_state['redirect'] = 'node';

This redirect the form to node/123?foo=bar#baz:

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

In your case, if you want to redirect to page/$nid, you should use the following code:

$form_state['redirect'] = "page/$nid";

If you really want to redirect to page=$nid, then you should use the following code:

$form_state['redirect'] = array(
  array(
    'query' => array(
      'page' => $nid,
    ),
  ),
);

How to achieve,the below issue in drupal SAVE and NEW button.

If I want out of ten fields the top four fields of the same form to be pre filled again with the same data as I click on the submit button.

Thanks In Advance.


How do I reset all user passwords to 123 with drush or SQL? For testing purposes I like to reset all user passwords to 123.

Is this possible in Drush or SQL?
I guess the query will be someting like this but cannot find the exact yourhash:

UPDATE `<mydatabase>`.`users` SET `pass` = '<yourhash>' ;

Can I run the final query with drush?

Yes, you can do this using Drush, with following steps (e.g.):

1.Generate a password hash using following command:

$ cd [/var/www/html/drupal7]
$ php scripts/password-hash.sh '123'

2.Now run following drush command:

$ drush sql-cli
mysql > UPDATE users SET `pass` = 'pasted_big_hash_from_above' WHERE uid > 1;

Update pasted_big_hash_from_above with password hash generated using php command in step #1.

Solved.

Query can be done in Drush with:

drush sql-query UPDATE `users` SET `pass` = '$S$DM7xrCBIKOrShBhgb1eUkpPlnnAq36QKIlMfdkKhvaTS2iv0PuJ3'


I installed the Civicrm module on drupal but it s not showing in the navigation bar I just installed the CiviCRM module on my Drupal website. But nothing new about the CiviCRM module is listed on the navigation except in configurations. And of course i have already set all the permissions for CiviCRM accessible for the administrator of the site.

How i can have access to the CiviCRM module?

Installing the CiviCRM module on Drupal requires a few more steps than just enabling the module itself. Check out how to do this in the Drupal Installation Guide for CiviCRM for the version you're using.

I've seen this happen before. Just add the link manually.


How to remove language indicator in content region? It took me a while to figure out how to remove the language switches from the bottom of each page. Eventually the switch was in a somewhat logical location (Multilanguage settings > Article options). (Oh, new question. I translated those menu items myself, because - mysteriously - my "backend" is in German. I don't remember how that happened. Everything I can find, default language, user language, is set to English. Where can the "backend" language be set?)
But what I've come here for:
There still is a language indicator at the bottom of each page ("Language: English"), and I cannot find how to get rid of that. CSS would be fine, but it does not have a specific class/id, so I cannot grab it.

Home » Administration » Configuration » Regional and language »
  Multilingual settings

then

go to the "Node Options" tab

check

  Hide content translation links

For Drupal 7:

In Structure > Content types > [Content Type] > Edit, select "Publishing options" then click "Disable" under "Multilingual support".


How to export content from dev environment for deployment to production environment? We have to deploy content of around 37 content types from development to production environment. Each content type is having around 10 to 12 nodes.
So, we have around 360 nodes for migrating to production environment.

How can i proceed it with at drupal end ?

I haven't done it myself but a colleague of mine had to do this last week. It's just exporting and importing the database. He used HeidiSQL with this link: https://support.appliedi.net/kb/a1034/how-to-import-and-export-a-mysql-database-using-heidisql.aspx


How to reload page after ajax form submit I'm using FAPI #ajax to make the form more user friendly (it reloads in-place on validation). Works like a charm. However I would like to reload the page after form is submitted. How to that?

Obviously if I call for example drupal_goto(current_path()) inside submit handler it won't do anything since this function is called via AJAX call. The actual page that user is on is not reloaded.

Is there some neat Drupal AJAX API trick that will allow whole page reload after AJAX form submit?

For the purpose of the question, an easy-ish way to do a redirect after ajax is with ctools and ctools_ajax_command_redirect

// In your ajax form submit callback
ctools_include('ajax');
ctools_add_js('ajax-responder');
// Path to redirect to
$path = 'node/12';
$commands[] = ctools_ajax_command_redirect($path);
// you can also use ctools_ajax_command_reload() –  xurshid29
print ajax_render($commands);
drupal_exit();

Note, it depends on ctools, which is a popular contrib module.

Instead of messing with ctools i've just set a flag in submit handler to let the ajax callback know that the form was submitted correctly and the page can be reloaded. Then inside the callback function I just returned some JavaScript instead of a form.

function my_module_ajax_callback($form, $form_state) {
  if ($form_state['my_flag']) {
    $ret =  '<script>';
    $ret .= 'jQuery(document).ready(function($) {';
    $ret .= '  location.reload(true);';
    $ret .= '});';
    $ret .= '</script>';
  }
  return $form;
}

Works perfectly.


Automatic Node Expire / Unpublish with Renew Option I have a classifieds site and would like to have a node expire after 45 days (unpublished), no matter how many times the user edits and saves the node. However after the node expires, the user has the ability to renew (publish) for another 45 days. I would like the time to be strictly 45 days with simple a renew button when it is expired.

Here is the workflow:

User creates node
Email is sent to node author indicating successful post.
Node is automatically expired 45 days later.
Email is sent to node author indicating expired post.
User has the ability to easily renew ad (expiry date is 45 days later yet again)
Email is sent to node author indicating renewed post (different from step 2)

I would also like to have a countdown for the days remaining until the expiry date.

I have successfully built steps 1-4 using rules only, however the rules are based on the event 'After saving new content', which means when a node is republished/renewed the rules do not follow because it is not new content.

I have also tried using the Scheduler module to set the unpublish date but cannot figure out how to enable renew only after it has expired.

I have also tried Auto Expire but I think it only gives the ability to renew before it expires, not after.

I would have opted for a custom code solution with the above work-flow.As an alternate contrib module option classified Ads module can be potential option.

Module Features:

  Renewable expired ads during the 'grace period' Simple taxonomy-based
  browsing Ad expiration depending on category selection Per-user
  classified ads lists – custom lists totally sortable Length-limited
  body text with live counter of characters Advanced Help, CCK, Context,
  Panels, Token and Views support

This is an idea/suggested code but not solution. Use node_save to re-publish node.

$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);


How to count the number of posts by a author? D8 I see how to do this in D7. I tried to do something similar in D8.

I tried using Entity instead of Content because there is no content:nid option in D8 my view looked like this

(author) COUNT(File Usage: Entity ID) (Count by User) | Aggregation settings

but my results where all 0

There is no difference between Drupal 7 and Drupal 8 on how to accomplish this.

From a default Content view:

Add the "Content: Authored By" field to the view.
Click "Use Aggregation" and change to yes.
Click "Aggregation Settings" to the right of "Content: Title".
Change to COUNT and Entity ID respectively.

View export:

langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_with_author_count
label: 'Content with author count'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          offset: 0
      style:
        type: default
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: count
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: false
          group_column: entity_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: author
          settings:
            link: 0
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          set_precision: false
          precision: 0
          decimal: .
          format_plural: 0
          format_plural_string: "1\x03@count"
          prefix: ''
          suffix: ''
          entity_type: node
          entity_field: uid
          plugin_id: field
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts: {  }
      header: {  }
      footer: {  }
      empty: {  }
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: author
          required: true
          entity_type: node
          entity_field: uid
          plugin_id: standard
      arguments: {  }
      display_extenders: {  }
      group_by: true
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }

Drupal 8 is new and many things still unclear. It will take some time before sufficient information will be available. If you need a quick solution I recommend to inspect database tables and get the needed information using db_query and SQL select. Should be straightforward.


access the view but not the node I have a view that displays a list of items. How to make anonymous user see this list of items but when accessing the node, it has to be logged? Any idea?

I use the latest version of drupal

You can disable node_access check for the view (Edit the View → Advanced → Query settings → Disable SQL Rewriting).

you can also create a page and embed your view inside it. in this way users can see your view. also create a node page and check this condition

if($logged_in)
{
    //your code
 }


Why Calling the theme path in a multinlingual site adds a language prefix? In my template whenever I call the path to my theme in a particular language it adds a language suffix dir like mysite.com/fr/sites/all/themes/mytheme while I'm expecting a path without a prefix (e.g. mysite.com/sites/all/themes/mytheme).

I'm use drupal_get_path() or path_to_theme().

How can I ensure I get the right path in my template?

You can use base_path() and drupal_get_path('theme', 'yourthemename') functions to get correct path.

Example:

$output = base_path() . drupal_get_path('theme', 'yourthemename');

Result:

/sites/all/themes/yourthemename


Create template suggestion for item-list.html.twig I have to change the markup and I have to add CSS classes to themes/classy/templates/dataset/item-list.html.twig. But only for a specific item-list.html.twig in a specific block.

How do I create a preprocess function, which create a template suggestion for this item-list.html.twig? So I am able to use e.g. item-list-facets.html.twig?

I think it's better to use hook__theme_suggestions_HOOK_alter:

Something like this:

 /**
 * Implements hook__theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_item_list_alter(&$suggestions, $variables) {
  $suggestions[] = 'item_list__' . str_replace('-','_',$variables["attributes"]["id"]);
}

Just make sure that in your suggestions name you use _ instead of -, otherwise you will get suggestions in the debug, but Drupal won't use it.

If its a class you might not need to have a separate twig file, but can simply add a class in your preprocess.

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_item_list($variables) {
  // conditional class
  $variables['custom-class'] = _some_function_to_return_class();
}

Copy the item-list.html.twig to your custom theme folder, and use the class.


Bullets and numbers not visible in CKeditor When I edit something in CKeditor and insert a list, the bullets or numbers are not rendered in the result.
Is it possible to correct it?

CKeditor uses CSS from either your default theme or it's own stylesheet. If you are are using your site theme maybe it is set to hide the bullets and numbers.

Add

list-style-position: inside;

to your ol, ul css


Drush rsync command failed: No such file or directory I am new to use Drush.

this following is my .drushrc.php file

$aliases['server'] = array (
  'remote-host' => '162.243.78.240',
  'remote-user' => 'root',
);
$aliases["dxb"] = array (
  '#name' => 'dxb',
  'root' => '/var/www/dev/daxuebao',
);

I try to use this following command to sync local site to remote site

$ drush rsync @self @dxb

But it alert me:

rsync: mkdir "/var/www/dev/daxuebao" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at /SourceCache/rsync/rsync-42/rsync/main.c(544) [receiver=2.6.9]
rsync: connection unexpectedly closed (8 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at /SourceCache/rsync/rsync-42/rsync/io.c(452) [sender=2.6.9]
Could not rsync from /Users/tangmonk/Sites/drupal/daxuebao// to      [error]
/var/www/dev/daxuebao/

It seems directory /var/www/dev/daxuebao do not exist, so I try to mkdir to my server :

$ mkdir /var/www/dev/daxuebao

The I type $ drush rsync @self @dxb again, But still above problem.
How to solved it?

Make sure the string containing the directory does not have extra blank spaces at the end. Trim it if possible. I was getting a similar message when I was using the option --files-from=myDirList and I have some spaces after the directory name inside the myDirList.


Organic groups and "Create content" I want to replicate the Drupal "Create Poll,Event" links etc of the Drupal groups.
How can I accomplish that with Organic groups?
Thanks

In case you use panels, Organic Groups module comes with a content create panel pane that allows to select the content types to include in such a links list.

You can do this using a custom block with format as php option. You need to use l function to generate links.

$links = "";
$linkList .= l(t('Create Poll'), 'node/add/poll', array('html' => TRUE, 'query' => array('gid[]' => arg(1))));
$linkList .= l(t('Create Event'), 'node/add/event', array('html' => TRUE, 'query' => array('gid[]' => arg(1))));
print $links;


Turn /node off but keep aliases I want my node page turned off.  I don't want mysite/node/3 to work.  I want it to display 404.  I tried rabbit hole and it worked but the problem ws that it also stopped the aliases from working.

Is there a solution where I can turn off the node/whatever but keep my aliases?

I'm guessing you're on drupal 7?

Rather than trying to disable/show a 404 you could install this module:
https://www.drupal.org/project/globalredirect

That will make it so that if anyone tries to access one of the "node/*" urls they will be automatically be redirected to the proper alias of the page. Would that work for what you need?

You can check the path in a preprocess function using this algorithm:

If current route is /node/* and current route is not an admin/config path then

Redirect to 403 page

End if


How to configure drupal-nodejs with https? In drupal-nodejs configuration we have IP with port but how can I have the https for that configured.

Go to /admin/config/nodejs/settings and select https.

Then scroll down a bit to javascript and also select https here.


Problem changing language - Redirection to installation By browsing my website in Drupal, I can browse perfectly through all the sections.
The website has 3 languages.
For Spanish, I can navigate well.
For English, I can navigate well

But any page I try to access in Portuguese, redirects me to "core / install.php"

I have cleaned cache, I have reviewed everything, and it only happens to me when I change or try to navigate in Portugues.

Because it can be?
Drupal version: 8.3.7
Drush version: 9.0-dev-g105e0aa

Increase the size of max_allowed_packet = 16M in the my.cnf file of mysql


Cannot access Administration > People page I cannot access the People page.  There is no error message.  If I click on People in the menu bar, the Administration home page is shown.

The other Administration pages are accessible.

Similarly, if I click on Permissions for any module, I get the Administration home page; not the Administration > People page.

The User module is enabled.  I am logged-in as user #1.

I have checked the .htaccess file and do not see anything that would cause a problem.

I have tried disabling the handful of modules I have added.

What should I do next?

I'm not sure 100% if my solution will solve your issue or not but give it a try

first set base url in settings.php

$base_url = 'http://baseurl.com/Drupal/htdocs';

then check if clean urls enabled from

/?q=admin/config/search/clean-urls

just in case try to clear Drupal cache from

/?q=admin/config/development/performance

I had the same error with PHP 7.1. Updated to the latest version of PHP and it worked!

Solution: upgrade your PHP.


Change Log in or register to post comments for content type We are using the comments for a particular content type to post reviews for that content type. I have searched the web but can't find a proper solution how to change the text

"Log in or Register to post comments" to something like "Log in or Register to add Review"

only for this one content type. Any suggestions how this can be done, also happy if I can figure out how to hide this for this content type.

I don't believe I can alter comment_links() via template file or custom module (in drupal 7)

Thanks

Go through this link will give you a nice work around

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

Then, you need to change code: Find your modules/comment/comment.module file, open it in a text-editor (like wordpad or the like), and search for the text you don't want to see on pages. You need to comment out (or delete) a bit of code, something like:
//

 if (variable_get('user_register', 1)) {
//      return t('Login or register to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('Login to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

The added 'return' is just for case, to ensure nothing to show - I didn't test this.

You can either edit the original file (which is quick but unclean, and requires you to redo the change after every unpgrade), or override that function in your theme properly by placing its copy into your template.php file (whole function!), renaming it to "phptemplate_[name]", and changing as needed. I think (not tested!) that it should look like this (added to 'template.php' in your theme's folder / create the file if not existing yet, with

function phptemplate_comment_post_forbidden($nid) {
  global $user;
  if ($user->uid) {
    return t("you can't post comments");
  }
  else {
    // we cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages
    if (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
      $destination = "destination=". drupal_urlencode("comment/reply/$nid#comment_form");
    }
    else {
      $destination = "destination=". drupal_urlencode("node/$nid#comment_form");
    }

//    if (variable_get('user_register', 1)) {
//      return t('Login or register to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('Login to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

  }
}

But still, you'll probably need to check on every upgrade, whether this copied code is in sync with core's possible new changes.


Restrict admin from disabling userprotect I've installed the user protect module on a site to allow another user to have complete admin access to the site, without the ability to edit my own administrator account. The problem with this it, they need to be able to access pretty much absolutely everything else, except for the ability to circumvent user protect.
At the moment, it is set up to stop them from editing my user, which works fine, unfortunately they are easily able to simply disable user protect.

What can I do to let them do almost everything except lock me out? So they shouldn't be able to disable that module, and they shouldn't be able to change their own permissions to be able to access that module.

Create another custom role, and add all of the permissions they will need, to that role. Leaving out the ability to administer user roles, and such.

It probably sounds tedious, considering you'll be adding back almost all of the same permissions that admin has. But, that "almost" is important and makes all the world of a difference with regard to security of your website.

"Hide the Administrator role selection in admin/config/people/accounts unless the user has the 'administer permissions'"

http://drupal.org/node/1356964
(roleassign module)

http://drupal.org/project/fixcore


Displaying HTML entities in title through a view I have a site (D7) where I need to have HTML entities in the title like the copyright, trade mark signs with the subscript tags. Like:

Product name®

The solution at the node level is simple using the page.tpl.php:

<?php print html_entity_decode($title); ?>

But in a view no matter how I try to format the title it will always return it like

Product name<sup>&reg;</sup>

I try a formatter, but they don't reach the title. Any other ideas?

Yes! You need to add the attribute 'html' => true. This is a link property in Drupal 7. If you render any link in Drupal 7 and want to add some extra HTML inside it you need to set array('html'=>true).

I had the same problem, and I solved it, but I think my method is not perfect.
I created another filed, called "title2", text field with "Full HTML". Make Title2 = title, and view it in views, it will be html_entity_decoded.
Sorry for my n00b english.


Drupal 7 dynamic dropdown list options An illegal choice has been detected I have created a node type of Advertisement which holds all the information for adding new advertations to the website, including categories.

there are 3 levels of categories and i need to make a seperate box for them. The content type which i created through the GUI of drupal already has a term reference select box for category, sub category, and level 3 category..
So i made a module and implemented hook_form_alter and i added the #ajax attributefunction

<?php
adverts_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'advertisement_node_form') {
      $topLevelTermArray = array('_none' => ' - Select a value -');
      $topLevelTerms = array(5275, 5245, 5299, 5341, 5702, 5681, 5826, 5555, 6039, 5592, 5776, 5994, 6027, 5451, 5852, 6016, 5496, 5475, 6049);
      foreach($topLevelTerms AS $value) {
        $term = taxonomy_term_load($value);
        $topLevelTermArray[$term->tid] = $term->name;
      }
      $form['field_specific_category']['und']['#prefix'] = '
';
      $form['field_specific_category']['und']['#suffix'] = '
';
      $form['field_sub_category']['und']['#ajax'] = array(
        'callback' => 'ajax_sub_category_callback',
        'wrapper' => 'field_specific_category_replace',
      );
      $form['field_sub_category']['und']['#prefix'] = '
';
      $form['field_sub_category']['und']['#suffix'] = '
';
      $form['field_sub_category']['und']['#options'] = array('_none' => t('- Please select a category -'));
      $form['field_specific_category']['und']['#options'] = array('_none' => t('- Please select a sub category -'));
      $form['field_category']['und']['#options'] = $topLevelTermArray;
      $form['field_category']['und']['#ajax'] = array(
        'callback' => 'ajax_category_callback',
        'wrapper' => 'field_sub_category_replace',
      );
  }
}
?>

And 2 callback functions

function ajax_category_callback($form, $form_state) {
  $subCats = array();
  $tree = taxonomy_get_tree(5, $form_state['values']['field_category']['und'][0]['tid']);
  foreach($tree AS $term) {
    $subCats[$term->tid] = $term->name;
  }
  $element = $form['field_sub_category']['und'];
  $mainCatTerm = taxonomy_term_load($form_state['values']['field_category']['und'][0]['tid']);
  $element['#title'] = t('Sub categories for @cat.', array('@cat' => $mainCatTerm->name));
  $element['#options'] = $subCats;

  return $element;
}

function ajax_sub_category_callback($form, $form_state) {
  $subCats = array();
  $tree = taxonomy_get_tree(5, $form_state['values']['field_sub_category']['und'][0]['tid']);
  //var_dump($form_state['values']['field_sub_category']['und'][0]['tid']);
  foreach($tree AS $term) {
    $subCats[$term->tid] = $term->name;
  }
  $element = $form['field_specific_category']['und'];
  if(empty($tree)) {
    $element['#options'] = array('_none' => '- No specific category -');
  } else {
    $mainCatTerm = taxonomy_term_load($form_state['values']['field_sub_category']['und'][0]['tid']);
    $element['#title'] = t('Sub categories for @cat.', array('@cat' => $mainCatTerm->name));
    $element['#options'] = $subCats;
  }
  return $element;
}

But when i go to node/advertisement/edit and i select a category and sub category is show's:

An illegal choice has been detected. Please contact the site administrator.

How can i get that error too dissapear?

The value you are submitting was not present during the page or form loading time.

If you populate some values using ajax which was not present in initial page loads and try to submit the form, then Drupal will not allow you to submit the form. It will always shows "An illegal choice has been detected" message.

I'm afraid there is only one solution and that's to comment out line 1388 & 1389 of form.inc


Drupal 7 - How to loop foreach in multiple value in custom view I'm customizing a view (in views-view--myview.tpl.php) based on a node which has a field with multiple value (field_galerie_image).

I'm trying to list in a foreach loop that particular field, and I am wondering how to write it down.

In the following code, I can access a value with $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; but I need to loop through it.

$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][1]["filename"];
$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][2]["filename"];

The code I am using is the following one.

<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php print $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; ?>
  <?php endif; ?>
<?php endforeach; ?>

I found it out; the correct code is the following one.

<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php foreach ($vue->_field_data["nid"]["entity"]->field_galerie_image['und'] as $val): ?>
      <?php print $val['filename']; ?>
    <?php endforeach; ?>
  <?php endif; ?>
<?php endforeach; ?>


Colorbox plugin installed but status report is not recognizing it I have installed the Colorbox plugin version 5.1.14 in /sites/all/libraries/colorbox but on the status report page I get the following:

  You need to download the Colorbox plugin and extract the entire contents of the archive into the sites/all/libraries/colorbox folder of your server.

Sometimes what happens with these libraries is that the download you get from the library site (colorbox in this case) packages its code in a folder itself. For the master download of colorbox, for example, the code comes in a folder called colorbox-master. If you unpack it into

sites/all/libraries/colorbox

then the code ends up in

sites/all/libraries/colorbox/colorbox-master

What you may need to do is unpack it into

sites/all/libraries

and then rename

sites/all/libraries/colorbox-master

to be

sites/all/libraries/colorbox

Drupal needs to have a v in front of the version number:

Original code in jquery-colorbox-min.js

/*!
    Colorbox 1.5.14
    license: MIT
    http://www.jacklmoore.com/colorbox
*/

Changed to:

/*!
    Colorbox v1.5.14
    license: MIT
    http://www.jacklmoore.com/colorbox
*/

jedsmith13 https://www.drupal.org/node/1074474#comment-9138455


Drush cannot connect to mysql I have a problem with Drush to enable or disable module. But downloading modules works perfect! However I want to use Drush in its full range.

Yesterday, I saw my Drush would not succeed in connecting to the database. I already tried to update the path in .bash_profile to the AMPPS path. But after that, my bash cannot find the database any more. I already deleted the line but bash don't find mysql.

Anybody has an idea about what to do to resolve this?

Below are the various messages I received:

  Sams-MacBook-Pro:demo Sam$ drush en views -d

  Starting Drush preflight. [0.01 sec, 1.82 MB]                        [preflight]

  Cache HIT cid:                                                         [debug]

  7.0-dev-commandfiles-0-9942ce60ec4ba1e3ca6f94d08d021773 [0.01 sec,
  1.88 MB] Bootstrap to phase 0. [0.09 sec, 5.75 MB]                   [bootstrap]

  Bootstrap to phase 6. [0.09 sec, 5.76 MB]                            [bootstrap]

  Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.09 sec,    [bootstrap]
  5.76 MB]

  Initialized Drupal 7.34 root directory at                              [notice]

  /Applications/AMPPS/www/demo [0.1 sec, 6.09 MB]

  Cache HIT cid:                                                         [debug]
  7.0-dev-commandfiles-1-68c4337f6c538cdf6d3ca715c4afb7a3 [0.1 sec,
  4.17 MB]

  Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.1 sec, 4.18[bootstrap] MB]

  Initialized Drupal site default at sites/default [0.1 sec, 4.18 MB]    [notice]

  Cache HIT cid:                                                         [debug]
  7.0-dev-commandfiles-2-9518eda12b48158193bd617384d95a7d [0.11 sec,
  4.18 MB]

  Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.11[bootstrap] sec, 4.18 MB]

  sql-query: SELECT 1; [0.11 sec, 4.3 MB]                              [status]

  Executing: mysql --defaults-extra-file=/private/tmp/drush_9NOj8N
  --database=demoDB --host=127.0.0.1 --silent  < /private/tmp/drush_gIJn4w

  sh: mysql: command not found

  Bootstrap to phase 5. [0.12 sec, 4.3 MB]                             [bootstrap]

  Command pm-enable needs a higher bootstrap level to run - you will   [error]

  need to invoke drush from a more functional Drupal environment to run
  this command. [0.12 sec, 4.3 MB]

  The drush command 'en views' could not be executed. [0.12 sec, 4.3   [error] MB]

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

  Hint: This may occur when Drush is trying to:

  bootstrap a site that
  has not been installed or does not have a configured database. In this
  case you can select another site with a working database setup by
  specifying the URI to use with the --uri parameter on the command
  line. See drush topic docs-aliases for details.
  connect the
  database through a socket. The socket file may be wrong or the php-cli
  may have no access to it in a jailed shell. See
  http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:

  Drupal version         :  7.34
  Site URI               :  http://default
  Database driver        :  mysql
  Database hostname      :  127.0.0.1
  Database port          :
  Database username      :  demoDB
  Database name          :  demoDB
  PHP executable         :  /usr/bin/php
  PHP configuration      :
  PHP OS                 :  Darwin
  Drush version          :  7.0-dev
  Drush temp directory   :  /tmp
  Drush configuration    :
  Drush alias files      :
  Drupal root            :  /Applications/AMPPS/www/demo
  Site path              :  sites/default

  [0.17 sec, 6.42 MB]   Sams-MacBook-Pro:demo Sam$

Ok i solved that problem my own. I have deleted the Drush Version 7.x and installed the 6.x Version. it works like a charm.


How can I remove self-closing source tags when rendering HTML markup? I use this markup in a node body.
<video>
  <source src="myvideo.mp4" type="video/mp4" />
  my title
</video>

The following markup is instead rendered in the node view.
<video>
  <source src="myvideo.mp4" type="video/mp4" />
    my title
  </source>
</video>

</ source> is added to the markup, and renders the full HTML not valid.
How can I avoid </ source> is added?

I use this code for replace < /source> in theme
  $content_this =  render($content['body']);
  print str_replace("</source>","",$content_this);

in node.tpl.php


How do I programmatically get a field's value? I copied node.tpl.php and I pasted it to node--my_content_type.tpl.php. My content type has a price. How can I get its value as a string?

Make sure the field is displayed in the display settings of your bundle (admin/structure/types/manage/bundle/display; replace bundle with the machine name of the content type) and define its settings (e.g., delimiter, prefix suffix).

In your template file, add <?php echo render($content['your_field_name']); ?>

You can use one of the following code snippets.

 $val = $node->field_price[$node->language][0]['value'];
 print ".$val.";

<?php
  $my_field_items = field_get_items('node', $node, 'field_price1');
  if ($my_field_items) {
    $my_field_first_item = reset($my_field_items);
    $my_field_value = $my_field_first_item['value'];
  }
?>


How to grant Userpoints after adding a comment once? I created a Rule that grants Userpoints to users when they comment on a node. However, I would like to grant these points only once per node per user. That means future comments from the same user on that node should not result in extra points.

How can I do that?

I solved my problem with the Flags module: I created the flags called 'Commented on this node' & 'First reaction'* and rule called 'Commented on a node'. These are my rule's settings:

EVENTS: After saving a new comment

CONDITIONS:

Content is of type Parameter: Content: [comment:node], Content types:
Article
NOT Node is flagged Parameter: Flag: Commented on this node, node:
[comment:node], User on whose behalf to check: [comment:author]

ACTIONS:

Grant points to a user Parameter: User: [comment:author],
Points: 2, Points category: Reaction, Entity: [comment:node],
Description: New reaction, Operation: Add,
Display: false, Moderate: Automatically approved
Flag a Node Parameter: Flag: Commented on a node, Node:
[comment:node], User on whose behalf to flag: [comment:author], Skip
permission check: false
Flag a Comment: Parameter: Flag: First reaction, Comment: [comment],
User on whose behalf to flag: [comment:author], Skip permission
check: false

So, every time a user adds a comment to a certain node for the first time, the node is flagged as 'Commented on a node', the reaction is flagged as 'First reaction' and the user who added the comment is rewarded 2 points.

**I use the 'First comment' flag in a related question.*

I would create a new role and use rule module to grant points.
Point will be granted only (along with the role) if the user doesnt have the role assigned to him already.


JQuery Accordion closes unintended when ajax-link from inside gets response I'm working on a page where a user can click on ajaxified links inside a JQuery-Accordion-Widget.

Currently every time a link is clicked and the response is loaded, the accordion gets closed and it is not possible to click it anymore - but no JS-error is raised.

Did i miss something i have to call i.e. to change the focus ?

Thanks for your help,
piezo.

You can probably use one of the jQuery Accordion API functions to manually control the state of the accordion

e.g:

// getter
var active = $( ".selector" ).accordion( "option", "active" );
// setter
$( ".selector" ).accordion( "option", "active", 2 );

more info here

the event is ajaxSuccess on the child .ui-accordion-content divs


Feeds for the module information of drupal.org http://simplytest.me/ has a nifty autocomplete option for the module suggestions. Screenshot attached.

I did a little digging and figured it out that ajax call being made is to the following url.

  http://simplytest.me/simplytest/projects/autocomplete?string=views

I could be use the same end point but I need to get the permission and also the data available is not sufficient for my use case. I wanted to know if Drupal.org provides any authentic feeds of modules so that I will be able to list other details, say the download url for the tarball file.

The official Drupal.org feeds available can be found at https://www.drupal.org/api/rss.  There is a feed for projects, but to get the information about releases you'll need to parse the JSON of an API request like
https://www.drupal.org/api-d7/node.json?field_project_machine_name=media

You can read more about the APIs available and how to use them at https://www.drupal.org/api

UPDATE:  If the goal is to a list of all projects and pull their releases, this cannot be done with just an official "feed".  It requires scraping the list of projects from Drupal.org and writing code to get the release into, but the code to do that already exists.  Lin Clark's ScraperWiki code still works (http://lin-clark.com/blog/2011/07/22/writing-scripts-clone-contrib-projects-gitdrupalorg/).  Export the scrapper output as SQL, import that into a custom table, write some code to loop those the projects calling Drupal.org's API to get the release information you are looking for, and save that response.  Not as easy as just pulling the information from a feed provided by Drupal.org, but it can be done.

There's over 9,000 d7 modules up on drupal.org, and I'm not sure if they put out an rss feed that provides every single module there is. I know drush does a fairly good job of keeping track of modules, so you might want to have a look at that.

There's also an internal function called module_list, not sure how much use that would be to you.


How to overwrite a file upload so that the filename is always the same? I am trying to implement a file upload form in which files are saved. I had written the following code

<?php

/**
 * @file
 * Contains \Drupal\avenue_product_import\Form\avenue_product_importForm.
 */

namespace Drupal\avenue_product_import\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

class AvenueForm extends FormBase {

  public function getFormId() {
    return 'AvenueForm';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['description'] = [
      '#markup' => '
Use this form to upload a CSV file of Data
',
    ];

    $form['import_csv'] = [
      '#type'              => 'managed_file',
      '#title'             => t('Upload file here'),
      '#upload_location'   => 'public://importcsv/',
      '#default_value'     => '',
      "#upload_validators" => ["file_validate_extensions" => ["csv"]],
      '#states'            => [
        'visible' => [
          ':input[name="File_type"]' => ['value' => t('Upload Your File')],
        ],
      ],
    ];

    $form['actions']['#type'] = 'actions';

    $form['actions']['submit'] = [
      '#type'        => 'submit',
      '#value'       => $this->t('Upload CSV'),
      '#button_type' => 'primary',
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $csv_file = $form_state->getValue('import_csv');

    /* Load the object of the file by it's fid */
    $file = File::load($csv_file[0]);

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();

    drupal_set_message('File Uploaded Successfully');
  }

}

But here the problem is if the filename in which I am uploading is same. It is getting renamed. But I want to replace old with the new one. How can I achieve this? I had seen file_move() and file_save_upload() function. What changes should I make to replace existing filename with the newly uploaded CSV file?

This would save always save the latest upload to public://importcsv/avenue.csv:

public function submitForm(array &$form, FormStateInterface $form_state) {

  /* Fetch the array of the file stored temporarily in database */
  $csv_file = $form_state->getValue('import_csv');

  /* Load the object of the file by it's fid */
  $file = File::load($csv_file[0]);

  $file_real_path = \Drupal::service('file_system')->realpath($csv_file->getFileUri());
  $file_contents = file_get_contents($file_real_path);
  file_unmanaged_save_data($file_contents, 'public://importcsv/avenue.csv', FILE_EXISTS_REPLACE);

  drupal_set_message('File Uploaded Successfully');
}

You could check if a file exists with that name beforehand? If so, remove it and continue saving.

https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file_delete/8.5.x

or

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!File!FileSystem.php/function/FileSystem%3A%3Aunlink/8.2.x


How can I add a cancel button to the content add form for a single content type? I have several content types on a site and most of them are user-editable but not user-creatable.  However, one content type, Image, allows users to upload a picture.  Sometimes, however, users upload the wrong picture and they panic because they don't want that picture to be submitted to the site.

Of course they could always hit the browser's back button, but I'd like to add a Cancel button for additional assurance.

I found this thread that gives various solutions for adding cancel buttons on Drupal.org as well as this feature request for adding a cancel button to D8.  However, there are several different general approaches and I don't know how to limit one to a given content type (in this case, my_image).

I would use the following code.

function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}

Notes

markup is the default form element type; there is no need to use #type = 'markup'.
In the node edit form, all the buttons are inside $form['actions']. The weights used from the buttons that form is using are 5 (Save), 10 (Preview), and 15 (Delete). I used 20 to show the link after those buttons, but you can change its weight to show it in a different position.

// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);
$form['actions']['preview'] = array(
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
  '#type' => 'submit',
  '#value' => t('Preview'),
  '#weight' => 10,
  '#submit' => array('node_form_build_preview'),
);
if (!empty($node->nid) && node_access('delete', $node)) {
  $form['actions']['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#weight' => 15,
    '#submit' => array('node_form_delete_submit'),
  );
}

There isn't the need to use arg() to understand if the form is for editing an existing node, or for creating a new one. I checked !isset($node->nid) || isset($node->is_new) is TRUE, to verify the node is being created. Drupal seems to simply check empty($node->nid), even though node_object_prepare() uses !isset($node->nid) || isset($node->is_new).
If $_GET['destination'] is set, the link added with l() will point to that path.

You can do that using the hook form alter:

function myModule_form_alter($form_state,$form_id){
 if($form_id=='myFormId'){
  // add the cancell button to your form
 }
}

Give that a shot.


Removing title from content pane I have used a content pane in a panel to add a description on top of it. It was a success but I can't find a way to remove the pane title in the view. The screenshots are below:

I have also set the content pane title to none

There is no option in the panel for title.

So how can I remove it?

In the view, there is an 'allow settings' link (bottom right of your screen shot). This allows you to select which settings can be changed within panels, including the title.

You can then, in panels, override the title with an empty string.

You can hide the title using CSS, for example with style="display:none;".


Hide Alt and Title for image field How to hide Alt and Title fields for anonymus users when they upload images? I use tokens for these field that's why I need to hide them.

Here a solution for hide the alt and title fields:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
    // If this is an image field type
    if ('image' === $context['field']['type'] && 'MY_FIELD' === $context['instance']['bundle']) {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
        // Add the new process function to the element
        $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
    }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
    $element['title']['#access'] = FALSE;
    $element['alt']['#access'] = FALSE;

    // Return the altered element
    return $element;
}

Et voila :)

This could work with Field Permissions module...


The simplest way of get an emerging modal window I want to open a modal emerging window, with some HTML on it and a close button. It should open when the user visits the page. What is the simplest way of doing that and what modules should I use? I have tried with CTools and a javascript (jQuery) emulation of click on a hidden link, but that gives me problems and seem so convoluted to me. Is there any simplest way?

You can check one of the module:

Splashify
Pop-up announcement
Popup On Load


No option to validate for email in drupal webforms validation I've installed both the Clientside Validation module, and Webform Validation, but there is no option to validate for "valid email" in the "Form Validation" tab of the webforms edit panel. Clientside Validation claims to validate for email - what's going on?

How should I go about adding email validation?

Currently it seems there is no such functionality, as it still sits in issue queue as a feature request. You can either:

Use plugin from feature request, it's already there in issue queue.
Use regex validator, with one of the rules you choose. Simplest "usually OK" would be \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b and you can find more at Regular-Expressions.info

Webform Validation  with this module you can set validation rules for each fields see the below image.

  This module adds an extra tab to each webform node, allowing you to
  specify validation rules for your webform components. You can create
  one or more of the predefined validation rules, and select which
  webform component(s) should be validated against those.


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

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

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

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

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

Not sure about a separate module for this, but you can just delete the module folder in your sites/all/modules folder. Works for me every time.


How to override configuration variables in settings.php I need to override configuration variables declared in the settings.php. How this can be possible? Any help me on?

Note: I am trying to override a custom configuration variable, not any default one.

You can't overwrite the variables in settings.php.


How do you add custom help text to content entry/edit screens unrelated to field? I use field groups to break my fields into "tabbed" areas for my content editors. I would like to be able to put some kind of help text at the beginning of each of those blocks to explain the entire section of entry. Each of the fields already have their own help text, this would be above all the fields.

I usually do this with a form_alter myself in PHP code or I use the help entry for a Field.

Recently I found out about the Markup module. I recommend you try it out. I have no added it to any of my projects yet, but it's on my todo list.

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.

  The module does not add anything to the $node object for the content
  being created, and utilizes form_alter to remove unnecessary fields
  from the '_content_admin_field' form when this widget is being
  created.

The markup module is pretty easy to use and would do what you're looking for. https://www.drupal.org/project/markup

Other plus is that you can easily move it around on the page with no theming and you can still fine tune the look and feel with css if needed


Caching $_SESSION data for anonymous users I recently inherited a Drupal 6 website that is using $_SESSION to store a lot of anonymous user data. Currently none of this $_SESSION data can be accessed while caching is enabled.

I have considered using cookies to work around this limitation but would like a fallback for users without javascript enabled.

Is there a way to do this in D6, D7 or the upcoming D8?

I think your best option is to use 2 cookies. Set one cookie that checks to see if the browser has JavaScript enabled. If JavaScript cookie is not there, the user gets an uncached page. If JavaScript does exist then drop a cookie containing the session data. Do the uncached page check in your settings.php file.

If you have something like Varnish or Nginx on your web stack, checkout ESI as it can work how you want it if the browser doesn't support JavaScript.

Also checkout http://drupal.org/project/authcache as it might be what you're looking for (minus the JS part...)

If you are having issues with creating the session for anonymous user, then it can be the issue with missing the user whose user ID is zero (anonymous user) from the users table.

You can restore it by running this SQL query from PHPMyAdmin.

insert into users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
update users set uid = 0 where name = '';

Drupal 7 always need a user with that user ID to create a session for it.


How to get the feeds log entry from hook_feeds_after_import I have a feed and I want to email the log entries from feeds_log after it has completed a run. I thought that if I could get the feed_id, I could query the db to get the log entries.

I'm using hook_feeds_after_import(), which gives me access to the $source object, but in looking through some documentation, I don't see a way to get the feed_id.

How can I get the log entries from a feed run?

From hook_feeds_after_import($source), I have access to $source->imported, which is the timestamp value in feeds_log.request_time. So I have

$result = db_query('SELECT message, variables FROM {feeds_log} WHERE request_time = :imported',
    array(':imported' => $source->imported) );

If you have the module Views turned on there is a view provided by Feeds that has the path node/%nid/log where you can see the log.

If that is not what you wanted you could clone the view and adjust it to your settings.

If you want to code it instead you could always query the database. Have a look in feeds.install to see what the tables are named.


Export menu to html? The project I'm working on has a specific requirement where I need to export the main menu as an HTML file. I figured the simplest way to do it would be using views but I found that views doesn't interact with the menu system.

I looked up the menu_import module to see how it exports menus to JSON files to see if I could rewrite the output to be HTML but haven't really gotten too far with that.

Any ideas how I can approach this?

Use the next code:

$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));
file_put_contents('myfile.txt', $menu_html);

Source: Programmatically load a menu.

EDIT
If you want to make it downloadable you can add next code to your page or submit callback:

// Get menu tree.
$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));

// Download menu txt file.
$filename = "menu.txt";
drupal_add_http_header('Content-Type', 'text/plain; charset=utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
drupal_send_headers();
echo $menu_html;
drupal_exit();

XML Sitemap module or Sitemap module

Using the XML sitemap module would allows you to generate your content and/or your data on XML file that you can manipulate on a different end.

Sitemap Module would help you to generate a list of all your items on your menu on a Drupal page.


Drupal file upload field via popup So I'm using a "file" type input inside a form which is called within a popup...but then whenever I submit that form inside the popup after having selected a file, the popup always return an error....

Is there a way to prevent this from happening and to successfully submit the form accordingly even with a file upload?

I made it by creating 'VIEWS' by selecting the facebook style micro publisher images as 'field' and filtered according to my requirement.


Drush needs a higher bootstrap level to run Do you have any idea on what might be causing this error when I execute:

drush si geoslate --db-url='mysql://root:root@localhost/geoslate' --site-name=Geoslate

  Command site-install needs a higher bootstrap level to run - you will need to invoke  from a more functional Drupal environment to run this command.
  The drush command 'si vimn_geoslate' could not be executed.
  A Drupal installation directory could not be found

?

This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.

Setup an alias for your site in the alias.drushrc.php file.  Make sure MySQL executable is in your path variable.


How Can I add a Hierarchical taxonomy Select in views filters and when editing content in Drupal 7 I have created a taxonomy vocabulary called Cars makes  and models  with a structure similar to this:

    -Car Make
    ----Car model
    -----------Year

I want to give the customer, options  to sort them in a View , like many cars sites do:
 a customer choose first the Car make, and automatically models from this make shows in a second level list.
But I want also to use this functionality in the (add content )page,  so when customer  try to sell a car, he will not need to scroll a very large list with makes and  models in the same field.
I cannot use Hierarchical Select. As many topics in this site suggest, because it doesn’t work for exposed filters in Views, with  Drupal 7:
http://drupal.org/node/1170192

I have spent hours and days, trying to fix this issue without any success, my options are very limited:

Turn back to Drupal 6, Just  to use HS with Views exposed filters.
(not a brilliant idea)
Use other CMS like Joomla, in fact there  is
many  Joomla plugins offering this functionality:
http://extensions.joomla.org/extensions/vertical-markets/vehicles ,
but then I will lose all the power of Drupal taxonomy.
Add autocomplete functionality to the views filter and Use
Autocomplete term widget , in the (create content page) , but this
is not very user-friendly method for no experimented users. More,
Autocomplete term widget will allow the creation of new terms, and
I do not want users to accidentally create new terms when they enter
an incorrect model  or make  in the field. Maybe I can correct this
using Content Taxonomy
module(http://drupal.org/project/content_taxonomy), which can deny
the creation of new terms. But this is not a global solution to my
problem.

Is there a module or any JavaScript or PHP snippet  to fix this ?

Response is late but I think(/hope) accurate. You can use the "Simple hierarchical select" http://drupal.org/project/shs. With the help of this module you can make use of the hierarchical select functionality both through views->exposed filters and of course when adding content.

  The widget is available in node forms and as Views exposed filter.


Appropriate way to include a PHP file in a theme tpl I guess this is more of a "Drupal way" question than a technical question. I have a multi-site install with a base-theme shared by all of the sites.  The base theme has two 'page' theme files (one is specifically for the homepage).  As you can imagine, there are shared elements to the layout (let's say a header and footer for conciseness). I'd like to keep the 'header' and 'footer' in separate PHP files so that I have one place to edit them versus going into 2 separate files and editing four blocks of code if something changes.

What is the appropriate way to create php files for 'header' and 'footer' and include them in the page.tpl and page--homepage.tpl templates?

Should they be in a folder called includes with a .inc extension, should this not be done at all, etc..?

I think the "Drupal Way" would be to create a variable in your template.php file, and then just call the variable in your page theme.

http://drupalize.me/videos/overview-templatephp


Where is the Migrate UI page? In Drupal 8.2.x there is the new migration UI tool. I've enabled it, but I can't find any link going to any UI page. Back in Drupal 7 when you enabled a module, it would have a configure link next to the module name in the modules page, but Drupal 8 doesn't. How would one find these configure links to the module pages?

modules -> migrate UI -> configure.

Press on the gear and you will enter the migration process.

The path for this module's config page is example.com/upgrade.


What does "Entity API" add to the Drupal API, and why would a module depend on it? The Entity API module extends the entity API defined in Drupal. In which cases should a module use the API provided from that module? Are modules that implement new entities easier to be written if they depend on the Entity API module?

By "easier to be written" I mean that modules using Entity API would require less code to be written compared to a module that doesn't use Entity API.

I read the project page, but I still don't completely understand the reason to prefer creating a module that depends on the Entity API module, rather than a module depending only from Drupal core code. I understand that a module extending rules and implementing an entity should use the Entity API module; in the first case, the reason is also that the Rules module depends on the Entity API module.

Not complete, but here are some advantages that I know of:

Drupal core only provides an EntityController for loading entities. For save, update and delete, you either need to write it yourself or use Entity API.
You you can expose the base properties of your entities wit hook_entity_property_info(), see privatemsg_entity_property_info() for an example. The advantage of this is that rules.module knows your entity properties and you read and write them with rules. And you also get token integration for free.
It can also automatically provide you with an administrative UI for your entities

i do believe, the entity api (module) was basically removed from drupal 7 core prior to release because it was considered incomplete..  Only the basic entity api CRUD functions where left in drupal core for its GM release .


Enable a flag automatically for specific users using Rules I have a content type called testimonials, and in that I have a user reference field with multiple selection option.
I have a flag called 'Request to review' enabled on nodes of 'testimonials' content type.
I wrote a rule for sending mail to the author of the node if any user clicked on that flag.

What I need to do here is, I want to enable that flag automatically when a new node is saved only for the users who are selected in the form field user reference. And for remaining users the flag should not be enabled automatically i.e., they have to enable it manually by clicking the flag link.

Thanks

I achieved it by writing a new rule, in that i wrote a loop for getting all the selected users.

thanks


Changing Global: Text Area based on an exposed filter in views? A client wants to display different text in a page depending on the value of the View's Exposed Filter.

I could throw this logic into the template.php or use javascript (showing and hiding a span depending on the value), but this feels like a very poor way to do this when considering maintainability?

Does there exist a Views plugin to perhaps show different text blocks in the header based on the value of an exposed filter?

Currently on Drupal 7.31 using Better Exposed Filters. I'm open to using something other than Global: Text area if there is a better mechanism.

You could use

hook_views_pre_render(&$view){
    $view->attachment_before = $view['exposed_input']['your_desired_field'];
}

Hope it works


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));

Timestamp is basically how many seconds have passed since 1st Jan 1970 UTC. To get the exact timestamp of Yesterday at 23:59 hour 59th second I can think of the following approach:

$yesterday = strtotime(((string) date('d-m-Y', strtotime('-1 day', time()))) . ' 23:59:59');

It's not really elegant, but if you really need exact time, then the above code should do the trick.

A breakdown of what's happening is:

$now = time();
$yesterday = strtotime('-1 day', $now);
$yesterday_date = date('d-m-Y', $yesterday);
$yesterday_date_string = (string) $yesterday_date . ' 23:59:59';
$yesterday_timestamp = strtotime($yesterday_date_string);


How to use Drupal Code Sniffer in windows? How do you configure and use Drupal Code Sniffer in Windows?

On the project page there are instructions for each IDE.

The one you're after (Eclipse) is here.

In case anyone uses something else, the other instructions are as follows:

Vim, Sublime Text, and Komodo

Netbeans

PHPStorm (install the Codeing Standards globally first, as described here, then Drupal should be available in the list or rulesets.

You won't get this working in Notepad.

On another note, I'd probably also just stop using Notepad.  If you must use a basic tool, then Notepad++ is a million times better.

You can try

Drupal API for Dreamweaver

Drupal for Eclipse


How to add fields to menu items I need to build a main menu that is a subset of the regular menu. The design team thinks it would be better for user to have only the most important links in the main menu and not have everything. Some links are top level menu and some are sub menus. For this I was hoping to be able to add a field to the menu link item form as a drop down. When creating a link the user could use this dropdown to "promoteToMainMenuAsBigLink" or "promoteToMainMenuAsSmallLink" or leave none to not show the item on the main menu.

I'm looking for a similar solution as this Drupal 7 solution but for Drupal 8.

I was hoping to be able to add a column in the table menu_link_content_data beside 'expanded'. I was hoping not to have to record this information in an other table like shown in the d7 solution.

I was able to add a field to the link form in a custom module I build, just for test purpose I only added a text field to start with:

custom_menu.module:

function custom_menu_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'menu_link_content_menu_link_content_form') {
    $form['promoteToMainMenu'] = array(
      '#type' => 'textfield',
      '#title' => t('Promote to main menu'),
      '#description' => t('Promote link menu to main menu.'),
      '#default_value' => '',
      '#weight' => -9
    );
  }
}

The field is indeed shown in the link form but it is never recorded.

Can someone help me with this?

Unfortunately, Drupal 8 core developers have not made Menu links fieldable.
So it is not possible to add fields to menu links for now.

The site builder "work around" is to create a custom vocabulary which can have custom fields.


How to expose $user->data to views? Do I need to use hook_views_data like a custom table?

Actually, this can be done within the Views UI by selecting the user:data field and then choosing a key.

You need to first add relationship with 'author' in the view and accordingly you will get the user data fields which you can use in your fields as well as in filters.


How to Table sorter in node page? I have a table in node page. i have requirement to make it sort-able on click.

can anyone help?

I used something like this in one of my installations:

// create a table of nodes of a specific content type
function MYMODULE_create_table($node_type) {
  // setup headers
  $headers = array(
     array('data' => 'Nid'),
     array('data' => 'Title', 'field' => 'title'),
     array('data' => 'Status')
  );
  // build query
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->limit(30);
  $query->fields('n', array('nid', 'title', 'status'));
  $query->condition('n.type', $node_type, '=');
  // make it sortable
  $query = $query->extend('TableSort')->orderByHeader($headers);
  // execute query
  $result = $query->execute();
  $rows = array();
  foreach($result as $node) {
    $rows[] = array(
       $node->nid,
       $node->title,
       $node->status
    );
  }
  // add a pager if needed
  if(count($rows) && ($pager = theme('pager'))) {
    $rows[] = array(
      array(
    'data' => $pager,
    'colspan' => 3,
  )
    );
  }
  // return html for table
  return theme('table',
            array(
                'header' => $headers,
                'rows'=>$rows,
                'empty' => 'No products found...',
            )
    );
}

The above perhaps work just as is, but it might give you some clue on how this can be done.

TableSort

Try out these:

Tablesorter
Tsort
DataTables
FooTable


How to translate strings available in JS library? I'm showing some images on my site where those are displayed using jquery.magnific-popup.min.js library. I'm not able to translate a string in that library. i.e.

  "%curr% of %total%"

It is not searchable even in the translate interface. How can I translate it?

See the plugin's translation documentation for a list of strings and their option names.
Pass these strings through Drupal.t() when attaching your popup.

Do not waste your time with the interface translation, you may find strings started with "" in jquery.magnific-popup.min.js file, just locate there with your editor, and change them. Just before make a backup of the javascript file for sure.
Then clear your site's cache /admin/config/development/performance and reload your page.
Hope it can help, that's worked for me.


how to save a field created by using hooks in database I added fields mobile no,landline no, using the below code to the form which i created with webform module. when i fill the fields along with two added fields and submit them .i cannot find the two added field in results.how can i make them appear in results.

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

if($form_id == 'webform_client_form_2') {
  $form['mobile no'] = array(
  '#type' => 'fieldset',
  '#title' => t('mobile no'),
  '#collapsible' => TRUE,
  '#weight' => 30,
);
$form['mobile no']['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This is a test to see the form_alter hook in action1.'),
);

$form['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This is a test to see the form_alter hook in action.'),
  '#title' => t('land line no'),
  '#weight' => 10,
);
}
}

first create submit button

$form['submit_button'] = array(
                '#type' => 'submit',
                '#value' => t('Click Here!'),
                );

when you create submit it calls this function and feilds submitted or updated to your database

function form_try_form_submit($form, &$form_state)
            {
                echo '<pre>';
                var_dump($form_state['values']);
                echo '</pre>';
                $insert=db_insert('DB')
                ->fields
                (
                    array
                    (
                        'phone' => $form_state['values']['phone']
                                 )
                 )
            }