dynamic route not updated I have dynamic route: from this example

/**
 * @file
 * Contains \Drupal\example\Routing\ExampleRoutes.
 */

namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * Defines dynamic routes.
 */
class ExampleRoutes {

public function routes() {
  $route_collection = new RouteCollection();

  $route = new Route(
    // Path to attach this route to:
    '/example',
    // Route defaults:
    array(
      '_controller' => '\Drupal\example\Controller\ExampleController::content',
    '_title' => 'Hello'
  ),
  // Route requirements:
  array(
    '_permission'  => 'access content',
  )
);
// Add the route under the name 'example.content'.
$route_collection->add('example.content', $route);
return $route_collection;
}

}

the problem here is: the route is not automatically updated (or accessible)
until i clear cache, then it works.

question is: how to make the new created route immediately works?
*i try to avoid clear cache command (which i don't think this is the right solution)

Thanks

To update the routes you have to call RouteBuilder::rebuild:

\Drupal::service('router.builder')->rebuild();

This is not what you want to run very often during normal operation of the site. This can take several seconds. It's also not possible to run more than one update process simultaneously. So routes are in general static, even the dynamic ones.


How to print block generated by views in the tpl file? I have a block with name: "Share Product"(block number 5) generated by my view with name: "main_product_deal". In this view i have 9 blocks.

Now in my .tpl file i need to print this block.

I have seen the function 'module_invoke' but not working.
My code is:

//On my tpl file
<?php
$block = module_invoke('views','block','view',"main_product_deal-block_5");
print $block['content'];
?>

I working in drupal 6.x. Is it correct my code? Or exist another solution?
Note: I can not set the block in the administration, because I'm programming certain things in the tpl

Thanks :D

Have you tried views_embed_view()?
http://drupalcontrib.org/api/drupal/contributions!views!views.module/function/views_embed_view/6


How to check that cron is reindex the complete site? I'm using drupal 7 and cannot find a log that the site is reindexed.

Cron is running every 3 hours which I can see in the log. How can I check that the cron is reindex my site as well?

Go to admin/config/search/settings or Configuration > Search and the top of the page will tell you how much of the site has been indexed.

The button "re-index" will let you re-index the site and the status above it will still tell you how far along the indexing process is. By default, Drupal indexes the website during cron runs and the option below the "re-index" button lets you select how many nodes are indexed per cron run.


How to use user feedback from Webforms Say I want to ask the user to rate articles on usefulness from 1-10.

How can I apply that rating to weight calculations for future searches of the same issue/tags?

I would like the most useful articles to appear higher in the search results.

Best using of any of below module to solve your query. I think as per your query, no any module for 1-10 rating. Hope these module help you to do same as you want.

Star Rating

  Star Rating is a simple module that provides star rating field and
  display formatter using Drupal 7's Field Type API.

Rate

  This module provides flexible voting widgets for nodes and comments.

Fivestar

  The Fivestar voting module adds a clean, attractive voting widget to
  nodes and comments and any entity.


How to get selected Value in the listbox by using form api I have created a form with fields titled State and City. After selecting the state's appropriate city records, they will be loaded into city listbox. Until now they were working fine, but after clicking the submit button I am not able to store the city's value into variable called $data1. How can I get it to return the city value?

Source code

function form_test_form($form,&$form_submit) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();
  $options_state = array();

  foreach($state_results as $state_record) {
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  return $form;
}

Ajax Function

function _ajaxfunction($form, $form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  foreach ($city_results as $city_record) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,);

  return $form['city_element_wrapper'];
}

Now I am trying to store the value of what I have selected in City listbox into $data1 variable but I am not able to store it, Please guide me how to store. It is printing empty value (i.e blank)

function form_test_custom_form_submit($form, $form_state) {
  $data1 = $form_state['values']['city_element_wrapper'];
  print_r($data1); // it is printing empty value
}

1) Try form_test_custom_form_submit($form, &$form_state) {}

2) Try to print all values. print_r($form_state['values']);

  // $form_state['values']['city']; you may get values here.

You can write $form['city_element_wrapper']['city'] array inside the form_test_form itself, instead of writing inside ajax callback.


Drupal Commerce Check out I am using Drupal 7 commerce; I would like to set up the check out process to skip the payment portion and just send an email to the admin and the customer. How do I do that?

Thank you for you help.

Just disable the Payment module and edit the default checkout completion rule that emails the customer to include an action that emails the administrator.


Gif animation and responsive image styles are not working I have a multiple image field and need it to upload images and animated gifs. These images might be resized. When this happens, the animated gif loses its animation.

Has anyone solved this problem in drupal 8?

There's now imagemagick for Drupal 8. I've been using it with D8 responsive image styles and it works well, the gif animation stays intact.

You'll need to have imagemagick installed on your server and will need the path to the convert binary as well. Typically it's usr/bin or for example with MAMP, it's /Applications/MAMP/Library/bin/


Can't print breadcrumb I'm trying to move the breadcrumb from one part of my theme to another, and they have different template files (using an Omega subtheme). $breadcrumb seems to be an array. I've tried l($breadcrumb) and theme($breadcrumb) to no avail. How do you print out a properly themed and string-ified breadcrumb in a template?

Here's my code btw.

<?php
function rescue_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    if (!empty($breadcrumb)) {
    $crumbs = '
';
    foreach($breadcrumb as $value) {
       $crumbs .= '
'.$value.'
';
       }
       $crumbs .= '
';
    }
      return $crumbs;
  }
$breadcrumb = drupal_get_breadcrumb();
if ($breadcrumb): ?>
  <div id="breadcrumb" class="grid-<?php print $columns; ?>"><?php print $breadcrumb; ?>

<?php endif; ?>

theme_breadcrumb() would probably be the best choice:

print theme('breadcrumb', array('breadcrumb' => $breadcrumb));

It expects the breadcrumb variable to be an array, each item of which makes up one part of the breadcrumb trail. So this array:

$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('Page', 'page');
$breadcrumb[] = l('Subpage', 'page/subpage');

will produce:

Home > Page > Subpage

You can also use plain text instead of links for the breadcrumb items in case you need to.


How do I add a JavaScript file to a form? I'm trying to add a JavaScript file to a form that I have in a modal.  Although I followed the information found here, here, and here, the file doesn't appear in the Network tab of the inspector and nothing is logged to the browser console when the modal is launched.

The form modal is triggered in
themes/custom/my_theme/templates/controllers/my-controller-theme.html.twig.

Click here to add

The library is defined in my custom theme in themes/custom/my_theme/my_theme.libraries.yml.

my_modals:
  version: 1.x
  js:
    js/my_modals.js: {}
  dependencies:
    - core/jquery

The JavaScript file is themes/custom/my_theme/js/my_modals.js.

(function ($) {
    Drupal.behaviors.my_modals = {
        attach: function (context, settings) {
            console.log('test');
        }
    };
}(jQuery));

The form itself is defined in my custom profile in
profiles/my_profile/src/Form/MyModalAddForm.php.

public function buildForm(array $form, FormStateInterface $form_state) {
  // ...
  $form['#attached']['library'][] = 'my_theme/my_modals';
}

There is no use to attach libraries to a form that is displayed in a modal window because the window has no place for assets (JS and CSS files). Instead I would suggest using hook_page_attachements or attaching the library to page element that is responsible for triggering that modal window.


Drupal config error "module.settings" depends on the module that will not be installed after import I'm having this error on Travis Build.  I can't go pass this error.  I've been removing dblog from the list of config and also delete from my localhost database before I export drush cex sync -y
 The import failed due to the following reasons:
  Configuration dblog.settings depends on the <e
  m class="placeholder">Database Logging module that will not be install
  ed after import.
  Configuration views.view.watchdog depends on t
  he Database Logging module that will not be in
  stalled after import. '

What else should I try to solve this problem?

This usually happens when the module isn't enabled in core.extension.yml but you are trying to import the config for that module.
It can usually be fixed by adding it to core.extension.yml
E.g.
  dblog: 0

Note that the "zero" indicates the "weight" of the module, and does not indicate a 0/1 enabled/disabled boolean.


Dynamic product catalogues So, I work at a web development agency and we recently decided to give our custom CMS up and start developing with Drupal. Currently, I am developing a wholesale product website. What I need to do is to create some product catalogs without using commerce since we do not need the purchase, checkout and payment features and I thought that using the built-in Content, Taxonomy and Views features we can get our job done.

I have created the product categories in Taxonomy. The main (root) categories are main Taxonomy objects and the subcategories are terms.

I created a custom Content type called: products. In this type I have the following form fields: Product Code, Name, Image, Description and a list field to choose the Terms I would like the product to be displayed in.

I would appreciate some help in order to set the whole structure up as I am still heavily influenced by the custom CMS we used to work on that had similar content management with Joomla!

In conclusion, I would like to:

Set a sidebar menu up that contains the categories and the subcategories as a tree. I would also like the menu to be updated if any changes occur in the taxonomy (e.g I add a term in taxonomy and it shows up on the menu).
Set the structure so that when someone clicks on a category that does NOT contain products but subcategories, gets the list of the categories bellow the active one.

I am really looking forward to your answers and I'd like to thank you in advance.

Personally instead if all Vocabularies are part of same "Tree" they should be in one "vocabulary" and current items should be displayed as parent terms -> children terms tree structure

1. regarding first bullet point

https://www.drupal.org/project/taxonomy_menu <- allows adding
taxonomy items to any menu of your choice
https://www.drupal.org/project/taxonomy_menu_block <- creates a block
in sidebar with list of your terms of selected vocabulary with
options such as "Count" that is updated on cron run
taxonomy_manager <-  I use to mess around with the order of things or
importing lots of terms it really speeds up the process if you would
need to move taxonomies from different vocabularies into one :)
Google it as I cannot post more then 2 links :)

2. regarding second bullet point

For that you would need to create "Taxonomy view" instead of content view and set it up so that the categories would be displayed for example: (cant post example as not enough rep)


Can't get data from drupal_http_request result I'm requesting a zip file from a remote location, and I'm getting some strange affects here. Here is a snippet:

$result = drupal_http_request($serviceUrl, $options);
    $file = $result->data;

    dpm($result, 'file result'); //returns the object, and I can see $result->data is a string of characters
    dpm($result->data, 'data'); //But, this is empty
    dpm($file, 'file'); //This is also empty
    dpm($result, 'file result'); // Still shows me the object with $result->data

The http request works fine as it returns with a code 200

I want to use it as follows (example):

temp_filename = "my_zip.zip";
$zip_file = fopen($temp_filename, "w+");
fwrite($zip_file, $file); //$file is $result->data, but is empty.
fclose($zip_file);

Anybody got an idea why I can't get $result->data?

The code is inside an object method, not a standard PHP function. Not sure if that has anything to do with it.

Also worth mentioning that I can read $result->code and $result->status_message with no problems.

I got it working myself.
Kudos to Clive who mentioned that the data is binary which probably means why I can't view it with dpm().

In closure, here is a code example to fetch a zip file with drupal_http_request where you can set header information.

function MY_MODULE_download_zip($service_url, $token, $request_body) {
    $request_headers = array(
        'Content-Type' => 'text/xml', //sending additional data as XML
        'Content-Length' => strlen($request_body), //See options['data']
        'charset' => 'utf-8',
        'loginToken' => $token, //I needed to pass a login token
        'Cache-Control' => 'no-cache',
        'Pragma' => 'no-cache',
        'Connection' => 'keep-alive'
    );

    $options = array(
        'method' => 'POST',
        'headers' => $request_headers,
        'data' => $request_body, //I needed to pass more info here as a XML
        'timeout' => 60.0, //it's a big file
    );
    $result = drupal_http_request($service_url, $options);

    if ($result->code != 200) {
      watchdog('ERROR', 'ERROR: :error', array(':error' => $result->error);
      return FALSE;
    }

    $temp_filename = "my_zip_file.zip";
    $zip_file = fopen($temp_filename, "w+");
    fwrite($zip_file, $result->data);
    fclose($zip_file);

    return TRUE;
}


Show/hide menu link based on changing custom $tempStore value I'd like to show/hide a main-menu link based on a $tempStore variable the user can set and modify during their session, i.e.

user sets $tempStore['vlaue'] = 0; --> menu link is hidden
user sets $tempStore['value'] = 1; --> menu link is shown.

The menu link is provided by a view (page). What I started to do is to implement my own custom RouteSubscriber which adds a custom access check  (which is defined as a service in mymodule.service.yml) to the view. The custom access check in myCustomAccessCheck.php basically does the following

   ...
   $value = $tempstore->get('value');
   return AccessResultAllowed::allowedIf($value == 1);
   ...

Apparently Drupal by default hides all menu links that the user does not have access to, so this approach should work (which it actually does!). However, caching is a problem, i.e. when the user changes the value, the link is shown/hidden only after a cache-rebuild.

Now my question:

Is there a better/more elegant approach to do this? (I could not find any)
If not, can I use some hook to add my custom cache tag to the menu-link? (the view itself already has this cache tag, but the provided menu link does not respond to it)
Is it "better" to make a view-block instead of view-page, using a hook to add the custom cache tag to the block and add the block to the menu via *.links.menu.yml to have more control over the behavior?

You can try to add the custom cache tag to the access result:

return AccessResult::allowed()->addCacheTags(['custom_cache_tag']);
return AccessResult::forbidden()->addCacheTags(['custom_cache_tag']);


Where are all the controller classes instantiated? In Drupal 8, if I want to create a form, I have to define a class inside the module folder like this.

class MyForm extends FormBase{

   public function getFormId()
   {
     return 'my_form';
   }
   public function buildForm(array $form, FormStateInterface $form_state)
   {

   }
   /* AND ALL OTHER OVERRIDDEN METHODS  */
}

Then I need to register a path for it in module.routing.yml.

module_name.myform:
  path: '/admin/structure/myform'
  defaults:
    _form: '\Drupal\my_formr\Form\MyForm'
    _title: 'My form'
  requirements:
    _permission: 'administer banner configuration'

Where is the MyForm class instantiated? What calls all the methods we are overriding?

We just define the class and register a path for it; neither we create an object of that class, nor we invoke any of the methods.

So, how does Drupal 8 manage these classes?

So, first, this is not a controller, it's a form class. Controllers are instantiated by the routing component.

Every route must have a controller. _form and some other special cases are processed after routes were collected and the actual controller is added. For forms, that is \Drupal\Core\Controller\HtmlFormController.

The actual processing happens in \Drupal\Core\Controller\FormController::getContentResult(), which calls \Drupal\Core\Controller\HtmlFormController::getFormObject(), which in turn uses \Drupal\Core\DependencyInjection\ClassResolverInterface::getInstanceFromDefinition() to instantiate the form class.

FormController then hands of the processing of the form to \Drupal\Core\Form\FormBuilder, which uses various other classes in the Form namespace.


Exporting Site Configuration Settings into Features This is on a Drupal 6 site, and we want to export several settings (like CSS aggregation) into features, however it doesn't appear like there's anyway to do this. Do we need to write a custom feature hook?

We installed Ctools and are going to install Features Extra, but nothing seems to support CSS aggregation - a basic site configuration setting - out of the box.

How can we accomplish this?

In order to export Drupal 6 system settings like the CSS and JS aggregation. Or anything else stored in the {variables} table, you can use the strongarm module. https://www.drupal.org/project/strongarm


use solr for /search In my site (camperlife.it) I have installed sorl + search api solr and all works for sections where solr is active (like /aree-di-sosta-italia.html). Now I want to substitute /search (search modules) with search api + solr.

Is there a module/way to do it (simple) or I need to create a view for this?

I'd just disable the core search module for performance reasons and create a view with Search API views unless you're already using panels and you can integrate a much richer solution, for example the one described in: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels


How can I force users to input a shipping address when using the Commerce Paypal WPS submodule? I just built a store in Commerce using Drupal 7 and I am taking payments by the Commerce PayPal WPS submodule.  However, when I tested checkout, I found it was possible to buy a product without supplying a shipping address.

In the PayPal Express Checkout documentation, it shows there is an option for forcing users to provide an address.  However, the WPS documentation is less comprehensive and does not include any information about whether it is possible to force a shipping address to be displayed or not.

Have you tested this:

You need to activate the Shipping pane under checkout process:

Go to Administration > Store settings > Advanced store settings > Checkout settings (admin/commerce/config/checkout),
Check Shipping service under "Checkout pane configuration" or if you use recent version of DC move "Shipping information" pane from disabled panes section to Checkout section,
Save.

If you want to alter data before sending, use the hook_commerce_paypal_wps_order_form_data_alter(). You need to fetch the customer shipping profile for the current order using commerce_customer_profile_load() and add the values you need from the shipping profile to the $data array.


Get the taxonomy term field in Views 3 override title Is it possible to get a taxonomy term field in the title of a view, using the override title in the contextual filters? I know I can get taxonomy fields using relationships, but is there an argument or something similar that I can use in the override title?

I am asking for Drupal 7.

I was able to solve a very similar issue in which I needed to override the view title with a field from the first result.

I used hook_views_pre_render() to accomplish this in drupal 7.

function tag_views_pre_render(&$view) {
  if( $view->name == 'flex' ){
    if ( count($view->result) ){
      $view->build_info['title'] = $view->result[0]->node_title;
    }
  }
}


Weird Character output Field Collection data with Views Data Export (CSV) I am using Field Collections on a content type, in Drupal 7. I am exporting this data as a Views Data Export with these collections. I can get everything to print out, however, I get a weird special character and I cannot seem to get rid of it. Below is the output. I don't like the way it looks but getting rid of the special character is paramount.

Name of Conference:Â Conference TypeTitle of Abstract:Â Testing each field and its meritsAuthors:Â Tim Snip, Fish Head, Testing Page, Water CupCity:Â AtlantaState:Â GACountry:Â U.S.A.Date:Â June, 2018

I have been clicking every check box and testing everything I can but not luck. Is there a way to get rid of this? or find out why it is even showing up?

You have UTF-8 characters in your data. The Â character in your case is a UTF-8 non-breaking space, but it's being rendered with the wrong encoding.

You might be looking at the output in something that can't render UTF-8 correctly (some old, dumb text editor), or if you're using something that does understand UTF-8, perhaps the wrong encoding (i.e. iso-8859-1) was chosen when you opened the csv.


Drupal adds unneeded folder to urls I've got the following problem:

We've got a hosting with 2 domains applied (second domain (the drupal site) is pointing to a subfolder of the first domain):
    /data/user/www/   < php-docroot & web-root of first domain
    /data/user/www/domain2/   < web-root of second domain & drupal install

calling http: //domain2.tld/ succesfully showing the drupal site,
but instead of:
http: //domain2.tld/content/contact, drupal generates url like:
http: //domain2.tld/domain2/content/contact

I think the problem may be the php-docroot, which is the same for domain1 and domain2.

How to tell Drupal to supress the /domain2/ part in urls?

Like i noted above, drupal thinks it's installed in a sub-folder because of the php-docroot lies in the parent-folder of the drupal-install, so it added /domain2/ to the $base_url.

To fix it, just edit your current settings.php in sites/* folder:

$base_url = 'http://domain2.tld';  // NO trailing slash!

Make sure settings.php is writable, it's often read-only!
(this was the problem here, otherwise i would've saved a lot of time searching a alternative ways to fix the $base_url... looks like there's a overhaul needed in my svn:post_commit-ftp_upload-script ;)


How to hide username displayed in code with Omega 3 theme Drupal 7 with Omega version 3 theme generates a username class for the article tag in the HTML code, something like :

class="node node-page node-published node-not-promoted node-not-sticky author-USERNAME odd clearfix".

I'd like to avoid having the username displayed in the code for security reasons.

After investigating, this comes from the code "omega_alpha_preprocess_node()" in the "sites/all/themes/omega/omega/template.php" where you find the following line:

"$vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name); "

I copied the code of "omega_alpha_preprocess_node()" to the "template.php" of my Omega subtheme, I renamed the "omega_alpha_preprocess_node()" to "MYTHEME_alpha_preprocess_node" and removed the line "$vars['attributes_array']['class']". Unfortunatly, it does not work.

As of today, the solution I found is to remove the line "$vars['attributes_array']['class']" from the initial Omega template.php file, which is not the best practice, but it works and the username output as a class of an article tag is no longer displayed.

Can someone help me find a more elegant solution, as I'm not a very experienced Omega developer and I need guidance? Thank you.

The theme function your trying to us is theme_preprocess_node, and you'r correct in replacing the Omega with [yourtheme].

The reason the function isn't getting called though is MYTHEME_alpha_preprocess_node should just be MYTHEME_preprocess_node. Alpha is part of the theme name, so if you remove it, the function should start working for you once you clear your cache.

EDIT ---------------------------------

Because drupal's template functions are still hooks, you can't just override the preprocess_node function, as omega's preprocess function is still going to run. However, what you can do is edit the $vars variable. Make sure you have the & in the param ( ie function (&$vars) ) so the vars is a reference.

From there, you should be able to modify the $vars['attributes_array']['class'] array and remove the unwanted class.

So if you put something like this in your code, that should get you close to where you might need to be.

function mytheme_preprocess_node (&$vars){
    $count = 0;
      foreach($vars['attributes_array']['class'] as $class){
        if(substr( $class, 0, 7 ) === "author-"){
          unset($vars['attributes_array']['class'][$count]);
        }
        $count += 1;
      }
}

EDIT 2 ============================

When I say remove the class from the var, I mean you should just be able to unset the variable (I updated my code snippet to show it inside the preprocess function).

You don't need to copy the whole of the omega_alpha_preprocess_node. What you actually are doing when you define your own theme_preprocess_node function is your telling drupal you would like to modify the variables for the node before it processes it. Because your working from a subtheme, the parent theme is still going to run it's own preprocess functions. So that class will always be added via omega. However, because your subtheme's preprocess function is downstream, it will get the &$vars reference with that class already added to it. So instead of rewriting the function, all that is needed is to simply remove the class from the $vars variable that you received in your params.


What is the difference between rendered entity and content in views 3? In the Format option for a view, the options include Content and Rendered Entity.

They both offer you a selection of view mode for the content. The former includes some extra options on comments/links.

So what is the point of Rendered Entity if it's a single configuration of Content?

Suspect I'm missing something!

At a guess...

The "Rendered Entity" format is available so any type of entity can be rendered. The "Content" format is only available for nodes, and as such can't be used generically.

Nodes are entities (as are users, taxonomy terms, and a whole host of others provided by contrib modules) and so just happen to be one of the 'items' that the "Rendered Entity" format can handle.

It also happens that Views already implements a format specifically for nodes ("Content"), so it does kind of look like there's repetition; but in reality it's not repetition at all, they're two separate things that just happen to have a bit of crossover in functionality.


Getting index of item in items inside twig template If I use any loop in Drupal, I can get loop.index to get the index of looped item. - Ref#1

For example -

    {% for tag in content.some_array %}

{{ tag.content }}

    {% endfor %}

This is a field containing paragraph type -

field--field-container.html.twig

and its content is {{items}} ({{items|length}} gives the desired count)

The above template iterate through it's items and include the following template multiple times-
paragraph--multiple-blocks.html.twig
and its html is

    =====CONTENT=====

But I cannot get the loop.index (Ref#1) in the paragraph--multiple-blocks.html.twig template. I tried (surely google search shows all links visited) kint() debugging but could not get anything related to the count or index of the item iterated.

I will be grateful to any guide/help (don't want to code in PHP) close to get this done in twig files will.

You can't, because the loop index is local. And you don't need a class with the index in the paragraph when you have it in the surrounding div for targeting it in CSS.

There is also a fundamental aspect with rendering referenced entities. They are cached and not necessarily rebuild when the order in the field changes. This is even more problematic for other entities than paragraphs, which can be used in more than one place in different orders.


Best way to insert video (vimeo and youtube) into content What is the best way to embed videos into content? Often it's not ideal just to have video content at the beginning or end end of page content. More often then not it something like
[text]
[video]
[text]

I'm looking at the best way to insert video content into a page while keeping a video content type field. I also want to avoid just adding video embed code into the full html body editor as then it's impossible to use the video in other places.

How do I go about adding a view field and then have a 'placeholder' for which to render the video in the middle of the text content?

The easiest way by far, is to use video embed field. I have built a video sharing site with a co-worker that generates very high rates of traffic. He built the site mostly by himself 80% in a couple of days, and the video embed module was used heavily for the management of video content types.


Why does module_invoke() return an empty array for anonymous users? I'm using module_invoke to return an array of blocks in a hook_block_list_alter

function MY_MODULE_block_list_alter(&$blocks) {

 $foo = &drupal_static('foo');
 foreach ($blocks as $key => $block) {
  if ($block->module == 'bean') {
   $bar = module_invoke($block->module, 'block_view ', $block->delta);
   $foo[] = $bar;
  }
 }
 return $foo;
}

When I'm logged in with admin privileges, $bar will be an array containing $bar['content'], $bar['subject'] etc. But for anonymous users, the array is empty. I can't find any reason for this, hopefully I'm missing something obvious and easy (to others!).

You are invoking the function bean_block_view(), which contains this code:

if (bean_access('view', $bean) && $bean) {
  $content = $bean->view($bean->view_mode);
  if (!is_array($content)) {
    $content = array(
      '#markup' => $content,
    );
  }

  $return = array(
    'content' => $content,
    'subject' => isset($bean->title) ? $bean->title : '',
  );
}

Looking at the first line of code, you can see the block is only built if the viewer has 'view' access for beans.

So it's a permissions issue of some sort with the beans module. Anonymous users don't have the required permission, so the block is empty.


Alter fields on add more I'm used Field collection to add content type as field with unlimited but i want to alter this form fields for adding #autocomplete_path on each field
so i'm added the autocomplete for the first field as
 $form['field_1']['und']['0']['field_1']['und']['0']['value']['#autocomplete_path'] = 'admin/path/autocomplete';

when i add more field collection field i want to added the same autocomplete for the next fields
any solution for this ?
Thanks in advance!.

After one day search i'm found solution in
https://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/function/form_example_tutorial_9/7
this example adds default values so that when the form is rebuilt, the form will by default have the previously-entered values.


Filter criteria not working on new field because data table is not storing data I have a view based on a content type. I added a new boolean field Premium to the content type that I wanted to add to the view as filter criteria. However when I added it I got no results in my view, no matter whether I set its filter value to '1' or '0'.

After doing some investigation, I queried the tables and found that field_data_field_premium had no values, while field_revision_field_premium was storing values. I tested checking and unchecking the Premium checkbox on various nodes. The state of the checkbox was preserved on the node, and I confirmed that data was being stored in the revision table, and still there were no rows in the data table. After checking and unchecking the box and saving several times on a single node, the data only stays in the revision table and rows are never inserted in the data table.

This causes my view not to work, because the query that views creates does a join on the data table, not the revision table. Since there are no rows in the data table, the query returns no rows overall since there is nothing to join to.

Thinking that the field was somehow broken, I deleted it and re-created it, but I am still getting the same behavior of data only being stored in the revision table. For further testing, I created another stock Drupal site, with a content type that has a boolean field. My test site is storing data in both the data and revision table.

What is going on? Is the field screwed up somehow on this site? The content type I'm adding this field to is in a feature -- could that be the source of the problem?

Edit I just exported and reverted the feature with my field added, and I still get the same behavior of values, either 1 or 0, only being stored in the field's revision table.

Okay, I figured it out. We have the workbench module installed on this site for multi-stage moderation, and the node I was editing was not the published version of the draft :þ


Import a view during installation I want to import a view during the installation of Drupal.

Does anybody have an idea on how to do this?

You don't usually programmability import views, instead you provides default ones by implementing hook_views_api() (usually in MODULE.module) and hook_views_default_views() (usually in MODULE.views_default.inc). Your module should return an array of views object has build with the code provided by the export views UI:

/**
 * Implementation of hook_views_api().
 */
function MODULE_views_api() {
  return array(
    'api' => '3.0',
  );
}

/**
 * Implements hook_views_default_views().
 */
function MODULE_views_default_views() {
  $export = array();

  $view = new view;
  $view->name = 'foo';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Foo';

  [ ... ]

  $export['foo'] = $view;

  return $export;
}

The Features module can generate the code for this.


Returning alternate HTTP codes for unpublished content Sometimes when nodes are unpublished, they are not meant to be taken live again.

Under those circumstances, I would like to return a 410 Gone status, instead of the default 403 Forbidden.

Implementing the 410 itself is a 1 line patch to Page manager, but I soon realize that there is no easy way to get the response to the client, as the router system itself checks the node status, and denies access.

How can I force the menu router to process my request for an unpublished node as usual?

I haven't tried this myself, but I think the main problem is that in your cases, the "unpublished status" means two things.

I think your best bet is to use something like Workbench Moderation, and defined a "retired" state.  Then, in a hoot_init(), check the status, and generate the 410.

Something like:

function mymodule_init ()
{
   $node = menu_get_object();
   if (isset($node->nid) && this_is_a_retired_node($node)) {
     drupal_add_http_header('Status', '410 Gone');
     drupal_exit(); // may want exit instead; not sure of other hook_inits()s should run
   }
}

I think you have to take the sledgehammer approach so that you don't get too far into the request where you may have a race condition with other modules.


Fast way to test (manually) commerce checkout process For a Drupal 7 Commerce site, I am working on the behavior of a payment and invoicing service during checkout. Among other things, there is one implementation of hook_commerce_checkout_complete(), the behavior of which I want to improve.

So far, for testing this, I always do a complete shopping and checkout process:

Visit a product page.
Add the product to the cart.
Enter a (new) address. (For a realistic experience, I think I need to type in a new address, because most buyers on this site are one-time anonymous customers.)
Choose a payment method, confirm.

After this, I will look at the logs, the order that was created, and the emails I received. Then I will start over with the next iteration.

My browser does a half-decent job of prefilling the form with the address. Just one field (city) is left empty consistently.

But even if this would work, there are still some steps too many for my taste, for rapid iteration of manual tests.

Is there a way to automate some of this?

Note: I am not talking about automated tests here. I am talking about manual testing during development.

EDIT: Automated vs manual testing

The comments indicate that my question might be confusing. Maybe I chose the terms poorly, so I will explain how I want them to be understood for this question.

"Automated testing": I have a machine that bakes a cake according to a codified recipe. And another machine that determines if the cake is according to expectations, e.g. by testing chemical properties or the color. The expectations are also codified, and do not change. The result is either "passes" or "does not pass".

What I want instead: A machine that bakes a cake according to a codified recipe. But then I want to taste the cake myself, and determine how I want to change the recipe. This means in this case, the expectations are not known beforehand, and they are not codified.

Without any automation, I would have to bake the cake manually, then taste it, then bake another cake, taste it again, etc.

According to the answer by @PatrickKenny, Selenium can do both things for me.

If someone can suggest a better way to say this, I will be grateful.

This is not specific to Drupal, but you can use Selenium IDE.

Selenium is a framework for automated testing, but the IDE allows you to do lazy manual testing too.

You need to install Firefox and the Selenium IDE addon.

Basic explanation of how to get started

Open the IDE (addon) and press the red "record" button.
Go to your site and carry out all the steps manually. Selenium IDE will automatically record the steps as you go along.
You can also add steps manually or edit the steps in the displayed editor.  This supports cut and paste so you can edit it pretty quickly.
When you're done, save the file.  You can then open this file again in the IDE and press the play button to automatically carry out all the steps.


How to change filed type from integer to string using D8. I have a field field_number just in one bundle (a node content type that I called law). Now I found that I need to change the field type; it needs to be of type string and not integer.

I wonder if there is a quick/easy way of using migrate or something similar

I remember that time ago I used VBO in D7 but seems that the PHP option is not available in the D8 version of the module. Like in this case:  https://drupal.stackexchange.com/a/28349/5422

I'll like to try using a hook_update_n on a custom module like in this example: How do I change a field type? but not sure if the the new field (as is created programatically) will be easily available for views and other modules and I don't want to end with a mess.

I ended up following this path. The reason I opened a new question was to see if there were any module or alternative to custom code.

My main concern was that the example was converting text to text and not number to text, but after executing some code using devel + webprofiler + kint (locally) I was able to see that even that same code was going to do the trick as the schema is affected only when needed.

For anyone looking at this same issue: take in mind that after running the custom code via the update process you will need some manual steps: recreate some views (when the field is used) and reconfigure the form display, presentation and so on of the bundles that are using the field.

As I have configuration of the site in git, my path was running the code locally, reconfigure the corresponding views, form displays, etc and then export the configuration, commit and push; then on production ran the upgrade and then import the config; it was pretty clean except that some views that have menu links assigned I had to manually edit its ordering.


How to schedule an action to reliably be performed once every 5 minutes? I have a need for a function to run every N minutes (it doesn't need to be EXACTLY every N minutes, but it should still occur within a reasonable amount of time, maybe N+/- 5 minutes)

I've been bouncing around between the DrupalQueue class, job_scheduler, rules, actions, etc., and each time it seems like I run into a wall.

My current set up is that I use job_scheduler_trigger. I seem to have it setup correctly (using a basic UI created action of "Send email"), and I have it set to go every 5 minutes, but it NEVER fires. The "Next" run time just keeps incrementing itself properly,  but the "Last" run time is always "Never". I have no idea what I'm doing wrong, or even if this is the best way to go about it.

Using Rules and Rules scheduler (submodule of Rules) seems to me "a" valid approach.

What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 5 minutes (instead of only after 1 hour). And you need to run cron every 5 minutes also (not hourly as in that tutorial).

And as explained also in that tutorial: Initially execute the component manually (from then on every other 5 minutes the rule will be executed again).

Note: How to schedule a regular job using Rules in Drupal 7 is another tutorial that covers this topic.


Entering views result to field through rules When I create a new OG, I would like the user with the least number of OG subscriptions automatically to be added to this group. So I created a views block where I count and least the user with the least number of OG subscriptions. Under actions, there is an option named subscribe user to group. Is there a way for me to use the views result in data selector of this action? Otherwise, how would you tackle this issue.

I created a sql query through the Views Rules module and it did the trick.


Translated taxonomy term in contextupal filter not validating I have a translated taxonomy term:

And have a simple view:

With a contextual filter on the translated taxonomy term:

Which works in english:

But not in french:

Any idea ?

I had to set the taxonomy vocabulary type from "Localize" to "Translate".


How to create date remainder e-mail? HI i have date field  in user profile,after user has been registered based upon current date for every one week i want trigger a mail to user.
example-you are one week old,two week old,like that i want to trigger a mail to user,thanks in advance.

This can be done using the power of Rules Module and exactly Rules Scheduler which is a part of rules.

Create a Rule component with the condition "User has role: Role A" and the action "Send email".

Events: After saving a new user account
Conditions: None
Actions: Schedule component evaluation

In that Action, I chose these options:
Component: the component from step 1
Scheduled evaluation date: account:created
Add offset: 7 days
User > Data Selector: account

For an in-depth tutorial on how to set this up please see this blog post on how to use Rules Scheduler to send emails
You also need to likely have your drupal cron job properly configured as well.


Adding class to image-link in render array In the render array of an image with link, i tried to add the class 'colorbox-load' to the link, i.e. the <a> tag of the link, but i can't get the adding of the class to work:

$node = node_load(52);
$my_image = field_view_value('node', $node, 'field_image', $my_image[0], array(
          'type' => 'image',
          'settings' => array(
          'image_style' => 'thumbnail',
          'image_link' => 'content',
          ),
        ));

$my_image['#path']['path'] = 'http://www.example.com';
$my_image['#attributes']['class'][] = 'colorbox-load';

What am i doing wrong?

To get your class on the image's link you'll need to set it in the path options:

$my_image['#path']['options']['attributes']['class'][] = 'colorbox-load';


"It is not safe to rely on the system's timezone settings." I'm finding the following error in the Recent log messages report:

  Warning: DateTime::createFromFormat(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in Symfony\Component\HttpFoundation\Response->sendHeaders() (line 331 of /var/www/drupal/drupal-8.1.1/vendor/symfony/http-foundation/Response.php).

My site does include any custom module, but as far as I can see, the only date function it calls is time(). Shouldn't Drupal handle the timezone setting?

Is there any way I can isolate where this function is getting called from?

It's not a major problem, but I'd prefer to minimise unnecessary warnings in my log.

This is a php setting, put this into php.ini:

date.timezone = 'Europe/Dublin'

All timezones:

http://php.net/manual/en/timezones.php


How to display content from a second database I have two separate mysql databases setup:

1) With all the Drupal 7 related tables etc etc

2) A custom database into which I will feed simple high score data from an external source eg. username, score, time etc

Is there currently a module which will turn my second database into something an end user can view/sort in a Drupal Page or content type? Obviously there is little point in collecting user high scores data is the users can't see it. I have come across only the Data module, but it is unclear to me as to if this does exactly I would need it too. For example there doesn't seem to be an options to change the tables appearance or style, something which the D6 only module Table Wizard did do. Has anyone used this module before, and if so has it been for a purpose similar to mine?

Maybe consider the Forena module for accessing your data in your custom database. It seems like a perfect fit for what you're asking for. It also includes charting features, which is typically a related requirement. Not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS. You didn't specify if your custom database is any of those, but any of these will do ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

Note: I'm a co-maintainer of Forena.


Override menu name shown by Superfish in mobile view mode? I've installed Superfish and set a new menu. All works fine but when I dive into mobile-view I see the machine-name of my menu printed on a rectangle. This could be nice sometimes but I really want to override it to something else rather than "Main Menu".

How will you change that?

You can change this in superfish settings. If you have accordion menu it can be set under "Accordion Menu title".

If you have select menu, there is also an option to change that at "Select settings".


about constructing a database for student multi-step form I need to construct a database for students. I am wondering how to implement the database. Do I add the students data into the users table? Do I create a student's table, and when a new student is added add part of the data of the student into the users table and the other part into the students table?

The "users" table is for containing information about what the Drupal site sees as authenticated users, which means the users with a login in a Drupal site.

If you are adding information about users that don't need to login on the site, e.g. people working for an organization for which you keep information, then you should not use the "users" table. You should create your own table that contains the necessary dat; possibly, you should create a custom module that creates that database table when installed.

If you are adding users as authenticated users, and you need to store extra information about those users you can:

In Drupal 7, you can add extra fields to the user's account.
In Drupal 6, you can enabled the Profile module, which allows you to add extra fields for the user profiles.
In Drupal 6, and Drupal 7, you can create a module that handles that information.

Of the two solutions, on Drupal 7 it is better to use the fields provided by the field API; if you need to handle the fields in a specific way, you can implement a new type of field in a module.

If you need something more customized, such as a multi-step form to fill the information, then you could write your own custom module that creates its own database table, and uses the user ID as primary key. In this case, you would need to write more code, such as the one that deletes rows from the database table when a user has been deleted from the "users" table. In Drupal 6, that could would be in a hook_user('delete') implementation, while in Drupal 7, it would be in a hook_user_delete() implementation.


Render custom html below a custom form I am new to drupal, I am using drupal 8, I have develop a custom form by extending FormBase controller and i am trying to render it using a custom controller like below.

$form = $this->formBuilder->getForm('Drupal\xyz\Forms\XyzActionsForm',$parameter);

return [
  '#form'=>$form
]

This works fine form me. But now i also want custom html below this form so try below code

$form = $this->formBuilder->getForm('Drupal\xyz\Forms\XyzActionsForm',$parameter);

$form = render(form);

$form .= '<div>custom html </div>';

return [
  '#markup'=>$form
]

But this didn't work for me, Can anyone let me know how to achieve this.

You have to use the power of render arrays.

For your example, I would use something like that :

$form_class = 'Drupal\xyz\Forms\XyzActionsForm';
$form = [
  'form' => $this->formBuilder->getForm($form_class, $parameter),
  'custom' => [
    '#type' => 'container',
    'inside' => [
      '#markup' => 'custom html', // Or use the power of render with html_tag type
    ],
  ],
];

return $form;

Then you can manage cache and other stuff on your render array and build your response with it.


How would I by default have a dropdown block expanded instead of collapsed? I want to be able by default have a dropdown block expanded instead of the current default which is to show just the link and if the user clicks on it then it would expand.
Below is some code related to collapsing and expanding dropdown blocks which is contained within a .js file within the default theme (sites/all/themes/fusion/mapsindeed/js).
How would I, by default, have a dropdown block expanded instead of collapsed?

//ability to expand and collapse dropdown blocks
Drupal.behaviors.mapsindeedDropdownBlock = function (context) {
$('.mapsindeed-dropdown-block .content').hide();
  $('.mapsindeed-dropdown-block h2.block-title').bind('click', function(){
  $(this).siblings('.content').slideToggle('slow', function() {
     });
   $(this).parents('.mapsindeed-dropdown-block').toggleClass('expanded');
});
}

Remove $('.mapsindeed-dropdown-block .content').hide(); from the above, and replace it with the following code:

$('.mapsindeed-dropdown-block .content').addClass('expanded');


Files that can be excluded from backup If you need to restore a Drupal 8 site from a backup, which files are essential?

core -> -
modules -> +
profiles -> +
sites/default/ -> +
sites/default/files/config_* -> -
sites/default/files/css -> -
sites/default/files/js -> -
sites/default/files/php -> -
sites/default/files/styles -> -
sites/default/files/field -> + (and any other user uploads)
themes -> +
vendor -> -

"-" means not needed, because Drupal core or cached files; "+" means files necessary to restore a Drupal 8 site.

For a backup script that allows to restore a site on another server in case of a server crash, can I leave out all cache data, or should I backup some of them to run Drupal without problems?

The key directories are modules, themes, and profiles. You also want to backup all settings.php files, and uploaded files as well. Although, I would separate the two into two backup files, since, depending on the site, the uploaded files directory could be in the low MBs or hundreds to even GB of files. Give them both a readable date timestamp for a filename.

Also, backup your composer.json and composer.lock files. If you control your site build using Drupal Project or Acquia BLT which has a composer driven approach, composer.json will contain the information needed to rebuild your site (this does not include data, only code). Then it's just a matter of backing up custom modules and custom themes, since composer can fetch all the code and rebuild core.


Features along with configuration synchronization I am planning to use features to bundle some of my specific works. Example: I want to bundle article content types along with its views, fields and related other stuffs. Can I just use features to create new article module through features ui and use it? How would it behaves when there is already configuration related to article in my sync folder which contains entire site configuration? Does anyone has experience on working with both of them simultaneously?

Thanks,

CIsSharp

Can I just use features to create new article module through features
  ui and use it?

Except for some very trivial use cases: No.
But Features still is a good starting point and a big time saver.

Don't expect Features to produce ready-to-use modules of complex Features. It is a great code/stub generator, but be prepared for finetuning both before in Features UI and afterwards on file level.
Plan your fields carefully: While single-use fields make it easier to create Feature modules, but reusing fields (or more exactly: reusing field storage) across different node types saved me a lot of work later in Views and themeing.
I always use "Mark all config as required" and "Allow conflicts", and afterwards move the generated config from config/install to config/optional. I guess this is not the standard Features workflow, but I do this for 2 reasons:

It prevents clashes between Features and existing core config/sync. If an optional config setting already exists, it will silently be ignored instead of stopping with errors.
I found it way easier to manage larger but meaningful modules with some duplicated config, than to split everything into super-small modules with a dependency nightmare.

I'm not quite certain if my experiences are useful to you though, because we are a small company with me being the sole developer. We are trying to reuse Features across different projects, not to avoid collisions on the same project.


Batch API processes next operation if existing operation is taking too much time I am using batch api for processing the operations.
In my operation I am sending xml request to different-different external server and waiting for its response, after getting its response I am processing it.

But sometimes it is taking too much time.
In case where it is taking too much time (If response is taking more than 2 minute). I want to process the next operation.

I checked batch_set but could found the way.
How to implement it?

I have achieved this using php.

Here is the sample code

$operations[] = array('batch_function_1');
$operations[] = array('batch_function_2');

$batch = array(
  'title' => t('Processing'),
  'operations' => $operations,
  'init_message' => t('Please wait processing is starting.....'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('Processing has encountered an error.'),
  'finished' => 'processing_finished',
);

batch_set($batch);

In case of soap I achieved using default_socket_timeout

function batch_function_1 () {
  ini_set("default_socket_timeout", $time);
  try{
    $client = new SoapClient($path_to_wsdl));
  }
  catch(Exception $e) {
    dpm('Timeout'); // echo 'Timeout';
  }
}

And timeout when using exec.

function batch_function_2 () {
  // $command : Which needs to be executed for communicating with server.
  exec("timeout {$time} {$command}", $output);
}

I also tried the set_time_limit which was not working with batch api.


how to bypass video conversion for mp4 files? I am using the Video module on my site, and would like a would like to bypass video conversion and a user uploads a file in MP4 format.

Is there any way that the bypass video conversion?

The reason for this is that due to the high volume of video submissions, and the fact that most often the video is already mp4.  The conversion takes a lot of hard drive space, and also required a lot of RAM and CPU resources.  I am hoping that bypassing some of the unnecessary conversions will help alleviate this problem.

If you haven't already, look at these options under admin/config/media/video

Bypass video conversion

(Bypass video conversion when creating videos.)
Video convert on node submit

(Convert videos on node submit will enable by default for all users.)


What does this error mean and how can I fix it? I do not know what this "notice" means:

  Notice: Undefined index: content in ds_render_block_field()
  (line 947 of
  /home/magpie/public_html/mysite.com/sites/all/modules/ds/ds.module).
  Notice: Undefined index: content in ds_render_block_field() (line 947
  of
  /home/magpie/public_html/mysite.com/sites/all/modules/ds/ds.module).

I am tempted to just delete the line but I think it is best to check first and verify that it is not important.

Can somebody help explain how errors like this occur? And how to prevent them and deal with them?

It's a notice, not a big deal to make you worry as it says, there is an undefined line in your display suit module


Returning from ajax callback ruins view Currently I am hooking into the add to cart form on my website. I added ajax to the edit quantity buttons like :

    $form_quantity[$key]['#ajax'] = [
      'callback' => 'update_cart_order',
      'disable-refocus' => FALSE,
      'wrapper' => $form_div_id,
      'event' => 'change',
      'progress' => [
        'type' => 'throbber',
        'message' => t('Updating Cart...'),
      ],
    ];

Which works lovely. I will note that $form_div_id is an id I'm wrapping the entire form in just above this.
Now I don't think I fully understand what I am supposed to return from my ajax. The view I am hooking into lists the products on one side and the order total on the other.

In my callback I (seem to) successfully update my cart quantities. But returning gets rid of the order total from this form.
I do nothing to edit the form and just return $form. All I do is update the order item.

I've looked around and think I may not understand what the ajax return really does but cannot seem to make sense of it. I just want to update my total price without refreshing the whole page.

In 'update_cart_order' I am changing the quantities and ending with this :

  $order->save();
  $order->recalculateTotalPrice();

  return $form;

This causes the total price display to disappear. After refreshing the page to get it back the quantities are properly adjusted.

Please let me know if any more information is needed. :)

It sounds like you have your AJAX callback working fine. But you said that the #ajax wrapper is wrapping the entire form. The elements returned from the ajax callback replace everything in the div provided as a wrapper. Since you are wrapping your whole form with the wrapper, everything inside that div (the whole form) is replaced with the elements from the ajax callback.

You'll need to be more selective with your wrapper element. Set it to only wrap the elements that should be replaced.


Search inside title and body

  Test Committee 1

Test Committee one description

  Test Committee 2

Test Committee 2 description

This is the array string i got when i do a print_r($header); in my template.

<?php
                    $doc = new DOMDocument();
                    $doc->loadHTML($header);
                    $links = array();
                    $arr = $doc->getElementsByTagName("a");
                    foreach($arr as $item) {
                    $href =  $item->getAttribute("href");
                    $text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
                    $links[$text] = $href;
                    }
                    $serch = $_GET['combine'];
                    $arr = array();
                    $arr =  explode(" ", $serch);
                    foreach($links as $key => $value) { ?>
                    <?php if ( stripos( $value, $arr[0] ) !== false ) {?>

<a href="<?php echo $value; ?>"><?php echo $key; ?>

                    <?php } }
            ?>

This is my code to print the result and search the link title in the array. I need to add the body field (views-field-description) to result display and need to search the keyword ($serch = $_GET['combine'];) inside the body (views-field-description) content.

The title search works fine for me. How can i add it.

It is much more easier to implement this using views module. In this tutorial, you can ask user an input, and search on any field in the content type.


How to call jQuery functions from my form with Ajax? There is an ajax callback which occurs on change of a field in my drupal 8 form.  This populates a wrapper with information from the server.  however I also want to excecute a jquery command to make the visibility of another field be visible after that .  How can this be done?

I tried this  $form['ajax-wrapper']['#attributes'] = array('visibility'=>'initial');

but that doesnt have any effect I need to be able to run this jquery command or this javascript but dont know how to trigger it after the ajax

document.getElementById( 'ajax-wrapper' ).style.visibility = 'initial';

           $("#ajax-wrapper").show();

You need to read the documentation as you are conflating the idea of ajax and what the AJAX capability of Form API is. A form item needs to add an #ajax item to perform ajax callbacks (php), and those functions can trigger AJAX commands some of which can trigger external JS functions.

On top of that, your actual JS code needs to conform to Drupal JS / behavior format so that it is leveraged by Drupal properly. The minimum here is it at least has to be enclosed in an anonymous function to prevent a jQuery conflict:

/**
 * @file
 */
(function ($) {

  "use strict";

  // All the JavaScript for this file.
  $("#ajax-wrapper").show();
  // other code or behaviors

})(jQuery);

Plus, if you have form fields that are dependent on other fields as far as being visible, you might be able to just use #states.

Here are resources:

https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
Behaviors
AJAX API
Ajax Forms in Drupal 8
AJAX command usage example
InvokeCommand
Form API #states
Using InvokeCommand


How can I use the logged in user's group ID as a contextual filter in Views? I have Views, Context and OG installed on Drupal 7.

One of the default views is OG User Groups (/user-groups.) It is a content view that shows the user which groups they belong to.

I'm trying to create something similar, as a block (and therefore cannot use URL arguments.) I want a user view that shows all of the users from the logged in user's group.

In Views, it would make sense that I get the user ID from the logged in user as a contextual filter and then perhaps pass it as an entity ID (etid) to get the group ID (gid). But no matter what I do I cannot make a view that allows this to happen.

Does anyone know I can get the group ID from the current logged in user to use in this view?

http://i.stack.imgur.com/xU2zi.png

Once you enable OG Context, that comes with Organic Groups module, you can clone the og_members view since it does almost what you want: it shows members from one group.

The OG Context module allows the "OG membership: Group gid" contextual filter to have a default value set to "Current OG Group from context". Nice, but we need members from all of the current use groups. So change the default value to "User ID from logged in user" to pass in the current user as the default argument. Then check the "Specify validation criteria" checkbox and choose PHP Code.

// let's see if there is a logged in user
if ($argument) {
  // og_get_entity_groups() returns the logged in user groups
  $groups = og_get_entity_groups();
  // setting $handler->argument changes the argument value
  $handler->argument = implode('+', $groups);
  // you have to return TRUE, else nothing works
  return TRUE;
}
// this will run if $argument is 0, for anonymous users
else return FALSE;

The "Action to take if filter value does not validate" should be "hide view": no block is shown if there is no logged in user. Expanding the "More" fieldset should be a "Allow multiple values" checkbox. Check it: that's why we imploded the groups array in the argument validation — this way we can pass several groups as arguments.


A view to display only nodes related from user field So I have user accounts and have added some custom fields to the user accounts. One of the fields is 'field_procedures' which is a entity reference to a content type called procedures.

Inside a view now, which is a calendar view, I want to display ONLY the procedure nodes that have been selected in the 'field_procedures' field that match that user. So that I am able to set which procedure nodes that are related to this user and want him to only see the calendar with of that node type he has been selected for.

I can't figure out how to set this up.

In Views add a relationship to the "Entity Reference: Referenced Entity", then add a contextual filter for UID with a default value taken from the URL.

See also http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7


Why is my theme's block preprocess function not reordering elements? I'm trying to do something that seems fairly basic, but I'm having loads of trouble.

The drupal search_form block outputs an input field and a submit button, in that order.  I'd like to swap the order of those fields.  I'm using theme_preprocess_search_block_form to attempt to reverse the order.  This is my current function:

function mytheme_preprocess_search_block_form(&$data)
{

    $data['form']['search_block_form']['#attributes']['placeholder'] = 'Search ...';
    $data['form'] = array_reverse($data['form']);
    foreach(element_children($data['form']) as $k) {
        if(!empty($data['form'][$k]['#weight'])) {
            $data['form'][$k]['#weight'] *= -1;
        }
    }

    $data['form']['#sorted'] = FALSE;
}

This function does get called, since a var_dump will output to the browser, however, the changes don't make it to the front end. So, what is unchanging my changes?

I figured this out. Drupal can be so infuriating when you are new to it.

The rendering of the search_form_block was happening in a template function file:

bootstrap-search-form-wrapper.func.php.

containing:

function bootstrap_bootstrap_search_form_wrapper($variables)

The function customizes the rendering of the search form by calling out elements specifically - thus ignoring '#weight'; the wrapper function is part of the bootstrap theme.

The solution is to overwrite the bootstrap theme function with a similar function in our child theme: function mytheme_bootstrap_search_form_wrapper($variables)

o.O

Hopefully this helps someone.


Display/hide CCk field with custom PHP and rules or I have custom variables stored in sessions, those variables are obtained remotely via URL arguments fired by remote website.

I am currently using Drupal 7, and I want to enable custom custom field A or B based on the value of the custom variable; if the custom variable is empty, it should enable field A, otherwise, enable field, B.

Can you please assist on what needs to be done?

Two quick ways come to mind.

Off the cuff...

You could use the preprocess_node() hook, something along the lines of:

MYMODULE_preprocess_node(&$variables) {

  if ($variables['node']->type=='THISKINDOFNODE') {

    if (empty($_SESSION['VARIABLE')) {
      unset($variables['node']->field_B;
    } else {
      unset($variables['node']->field_A;
    }

  }

  // other preprocessing here

}

You also could create a node--TYPE.tpl.php file and inside it, do something like this:

if (empty($_SESSION['VARIABLE'])) {
  hide($content['field_B');
} else {
  hide($content['field_A');
}


Inserting a view in node edit form In a node edit form i want to display an editable view, so an author can not only edit the node itself but also can alter some values of other nodes represented by the view, which is editable via the editable views module. How can i alter the node edit form in order to display that view?

It took me a while to find out how to do it in Drupal 8, and since this post is one of the first google hits I'll add the solution here:

function MODULE_form_node_NODETYPE_alter(&$form, FormStateInterface $form_state, $form_id) {
    ...
    $form['my_embedded_view'] = [
        '#type' => 'view',
        '#name' => 'my_view_name',
        '#display_id' => 'block_1',
        '#arguments' => [
            'arg1' => $arg_1,
            'arg2' => $arg_2,
        ],
        '#weight' => 30,
    ] ;
...
}

I used a block display for the view, I don't know if it's relevant.


User Import with inactive status I have a site where we need to bulk import users into the system, however the client wants to be able to import the users into the system but have them inactive until a later date,

The idea is that we operate online training courses, so we will receive user data from an organisation as part of our onboarding - however we do not want to give the users access to the system until it is time for them to start their course.

My idea was to use the User Import module to bulk import - however I can not see a way to set the 'status' of users when importing - as a result all users have instant access to the system. Is there any way to do this with the User Import module?

If it was possible, we would then use a VBO operation to change the status of the users to active at the appropriate date - this would also mean that users would receive the site configured activation email with the appropriate log-in information,

Any help or alternative implementation suggestions would be greatly appreciated,

Thanks,

The Feeds module - https://www.drupal.org/project/feeds - provided me with the solution to this issue.

Feeds allow you set both the Status of the whole import, and a per user status by adding a Status column to your CSV,

For users who have the same problem, this how you do either:

1. General Status for User Import

Once you have installed the Feeds module go Structure/Feeds Importer/User Import - admin/structure/feeds/user - and go to the Settings option in the Processor section, here you will find an option to set the Status of all imported users:

2. Status column in Import CSV

If you want to add a status column to your CSV file, allowing some users records to be imported as active and others as blocked, then you need to edit the Mapping in the Processor section - again at admin/structure/feeds/user. Add a new field to the mapping selecting 'Account Status' as the target field.

Inside your CSV use the values 0 or 1 for the status - where 0 is 'blocked' and 1 is 'active'.

Note: this will override any default status defined by the steps outline in Option 1 above.

I can also confirm that VBO operation to unblock users will also result in the correct Activation emails being sent out to the users (provided you have an activation email configured in Account settings)


Duplicate Urls for many terms I don’t know why most of my parent terms have duplicate URLs:
One like this:

     taxonomy/term/1

And a second one like this:

     taxonomy/term/1/0

I have installed Global Redirect and Pathauto, and all urls in the first format are redirected to their alias. However urls in the second format are not.
Now google is reporting a large list of duplicate title tags. How can I solve this?

There's a setting under the Global Redirect settings to Remove Trailing Zero Argument:

According to the description for this option:

  If enabled, any instance of "/0" will be trimmed from the right of the URL. This stops duplicate pages such as "taxonomy/term/1" and "taxonomy/term/1/0" where 0 is the default depth.

That should fix the problem you're having.


Views: Output field as a link with URL provided by another field? So I have a content type with fields: image_field and url_field.

The view displays the field_image for all items. Now I want the user to click this image and go to the link in url_field on the same item.

If I try to write the output as a link it requires me set a path for field and it will always be the same URL for all items.

How do I tell it to display image_field with URL from it's own url_field?

You can use replacement tokens. URL field first in the list, hide the field, rewrite the image to render with a link, use the replacement token for the URL field as the link.

Example: https://www.youtube.com/watch?v=fuNkaGOwnR0


Preprocess function for body field? I have a client with a D8 site who wants curly quotes and apostrophes on all rendered content. I was able to do this for the page titles with this preprocess function:

function mytheme_preprocess_page_title(&$variables) {
// Load the node entity from the current route
if ($node = \Drupal::request()->get('node')) {

    // Get the title
    $title = $node->getTitle();

    // Replace left quotes
    $title = preg_replace('/"(?=\w)/', '&ldquo;', $title);

    // Replace right quotes
    $title = preg_replace('/(?<=\w)"/', '&rdquo;', $title);

    // Replace single quote/apostrophe
    $title = str_replace("'", '&rsquo;', $title);

    // Return the title variable
    $variables['title'] = t($title);
}
}

Is there a way to do this for the body field as well? hook_preprocess_field isn't getting me anywhere.

Instead of using a preprocess function, you could accomplish the desired behavior using CSS.

Using the ::before and ::after selectors you can insert additional content. This content could be the textual " character (i.e., content: '"';) or you could display it as an (inline-)block, provide width, height, margin and padding and set a background image.

For example:

.field--name-body {
  padding-left: 1em;
  padding-right: 1em;
}

.field--name-body::before {
  content: '"';
  position: absolute;
  top: 0;
  left: 0;
}

.field--name-body::after {
  content: '"';
  position: absolute;
  right: 0;
  bottom: 0;
}

This creates some space around the body field and provides " characters at the top left and bottom right location.


Changes to leaflet Settings not working I am unable to alter a settings of a leaflet map generated by a view using the method described here in a custom module. https://www.drupal.org/node/1883788

Using the code below in my custom module does not work.

  function MYMODULE_leaflet_map_info_alter(&$map_info) {
      $map_info['esri-world-street-map']['settings']['scrollWheelZoom'] = TRUE;
      $map_info['esri-world-topo-map']['settings']['scrollWheelZoom'] = TRUE;
  }

Where MYMODULE is the name of my module.

Someone else had this same issue and we have been talking trying to solve the issue. https://www.drupal.org/node/2831593

The code shown in your question can never work: you need, at least, change the function name from "MYMODULE_leaflet_map_info_alter" to the actual name of your module.

PS: debugging is the art of taking away all possible reasons why something doesn't work as expected. This is for sure 1 of the possible reasons ...


Creating custom form at registration process for unknown number of nodes I have a project where I want to add one OR more "nodes" or content types at registration time. For example, I enter my name and email adress, and then I can add one or more trip (example) I made, and then, later, the content of the site itself will be modified by this information. For example, the main menu could display a tab for each trip (trip1, trip2, etc.).

Any idea where I should start?

You can try with

field_attach_form to attach the 'trip' content type's fields to user form. (with an alter can become multivalue)

on submit you can use these values to populate the trip entity with entity_metadata_wrapper and create a new node

you can build N menu_items than are the trip of the user by a custom menu


How to execute custom code at Drupal startup What's the correct way to execute code from an existing custom module at Drupal startup? The code checks certain private_tempstore values and sets other values based on what it finds. It should be executed before page processing occurs so that pages can respond to the changed values.

I've read many posts, looked through the list of hooks, tried a few without success, looked at event subscribing, etc. All my searching and trying hasn't found an approach that works correctly for my situation.

Example custom code (not the real code):

$rsc = \Drupal::service('user.private_tempstore')->get('rsc');
$val = $rsc->get('temp_val');

if ($val == 100) {
  $rsc->set('temp_val', 200);
}

What I've tried:

hook_page_build() // in mymodule.module
hook_page_alter() // in mymodule.module
path: '/*' // in mymodule.routing.yml

No error messages, just no results via an error_log() in the custom code to show that it was executed.

First of all, User module's user.private_tempstore and user.shared_tempstore services moved to core. So we want to use the tempstore.private.

The code below will get your started. you will want to read more about how getSubscribedEvents() works, as here is where you tweak the where and when of your event.

Don't forget an .info.yml file!

/mymodule/mymodule.services.yml

services:
  mymodule.mymodule_subscriber:
    class: Drupal\mymodule\MyModuleSubscriber
    arguments:
      - '@tempstore.private'
    tags:
      - { name: 'event_subscriber' }

/mymodule/src/MyModuleSubscriber.php

<?php

/**
 * @file
 * Contains \Drupal\mymodule\MyModuleSubscriber.
 */
namespace Drupal\mymodule;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\TempStore\PrivateTempStore;

/**
 * Provides a MyModuleSubscriber.
 */
class MyModuleSubscriber implements EventSubscriberInterface {

   /**
   * The PrivateTempStore Service
   *
   * @var PrivateTempStore
   */
   protected $privateTempStore;

   /**
   * MyModuleSubscriber constructor.
   *
   * @param PrivateTempStore $privateTempStore
   */
   public function __construct(PrivateTempStore $privateTempStore)
   {
     $this->privateTempStore = $privateTempStore;
   }

   /**
   * // only if KernelEvents::REQUEST !!!
   * @see Symfony\Component\HttpKernel\KernelEvents for details
   *
   * @param Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The Event to process.
   */
  public function MyModuleLoad(GetResponseEvent $event) {
    // @todo remove this debug code
    drupal_set_message('MyModule: subscribed');
    // Interact with the tempstore
    $value = $this->privateTempStore->doSomething();
  }

/**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('MyModuleLoad', 20); // Like hook_init (Cached)
    // Priority greater than 200 alow to skip caching, like functionality of hook_boot.
    //$events[KernelEvents::REQUEST][] = array('MyModuleLoad', 300); // Like hook_boot (not Cached)
    return $events;
  }
}


hook_update_N() for more than 100 updates or 10 major releases The documentation for hook_update_N() says the following:

  Implementations of hook_update_N() are named (module name)update(number). The numbers are composed of three parts:

  1 digit for Drupal core compatibility.
  1 digit for your module's major release version (e.g., is this the 7.x-1.* (1) or 7.x-2.* (2) series of your module?). This digit should be 0 for initial porting of your module to a new Drupal core API.
  2 digits for sequential counting, starting with 00.

These are hypothetical questions:

What happens if you get to something like 7299? Are you required to release a major version update next even if you don't implement the hook, or if you do?

What happens if you have a lot of branches or major releases and get to something like 8900 and want to release a new one for that version of Drupal... 8(10)00? I know some modules go from 7.x-3.x to 8.x-4.x, so this could potentially happen if they continue in that way.

The one time I dealt with this, I just kept on going. After 7199, I moved to 71100, then 71101 etc. It wasn't a problem (Drupal 7).


How to dynamically Prepopulate / Prefill addressfields I have an single entityform of type 'letter generator' this contains two addressfields:

'To' addressfield
'From' addressfield

I would like to prepopulate / prefill these addresses with content from elsewhere on my site.

'From' addressfield populated from the 'User addressfield' attached to my 'user' entity type.
'To' addressfield populated from the 'School addressfield' attached to my 'School  info' 'node' entity type (also the parent node for the letter generator)

I am new to php and programming so this is my first attempt at a custom module. So far I have the following php that attempts to address point (1.)

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

// Check to see if the form alter function is actually running
dsm($form);

    // Only do this for a new, not-yet updated entityform -NB might need a 'return' here
    if (!isset($form['#entity']->is_new)) {

        //Ensure, we're updating field info on the correct entity type
        if ($form_id == 'letter_generator_entityform_edit_form') {

            // load user information
            global $user;
            $current_user = user_load($user->uid);

            //Populate the entityform addressfield with values from the user addressfield
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['thoroughfare']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['premise'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['premise']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['locality'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['locality']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['administrative_area']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['postal_code'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['postal_code']['value'];

        }
    }

}

...
Ok I got this working:

global $user;
$user_fields = user_load($user->uid);
//useful ...
dsm($user_fields);
$userthoroughfare = $user_fields->field_user_address['und']['0']['thoroughfare'];
$userpremise = $user_fields->field_user_address['und']['0']['premise'];
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $userthoroughfare;
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['premise'] = $userpremise;

  NB adding ['value'] to the line:

$form['field_user_address'][LANGUAGE_NONE][0]['#address']['administrative_area']['value'] = $useradministrativearea;

  will select the state for you...

I cant find any reference of hook_form_entityform_alter if it is available you will want to take out the hook part and replace this with you module name.

I have re written the code using hook_form_alter. You will need to replace $address1 etc with your own code.

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

// Ensure, we're updating field info on the correct entity type
//This needs to be more specific incase more entity forms are created
if ($form_id == 'yourformname_entityform_edit_form') {

// Only do this for a new, not-yet updated entityform -NB might need a 'return' here
if (!isset($form['#entity']->is_new)) {
//Populate the entityform addressfield with values from the user addressfield
$address1 = "address1";
$address2 = "address2";
$county = "county";
$postcode = "postcode";
$form['field_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $address1;
$form['field_address'][LANGUAGE_NONE][0]['#address']['premise'] = $address2;
$form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = $postcode;
  }
}


Why getMimeType() is returning wrong value for xlsx file Below is my 2 line code to get the Mime Type of an attachment in a preprocess function

$file = $node->get('field_attachment_file')->entity;
$variables['attach_type'] = $file->getMimeType();

The $variables['attach_type'] is always getting the value of 'application/pdf' despite the attachment being an Microsoft Excel spreadsheet

The value returned as MIME type of a file is the value returned from the file.mime_type.guesser service which, on a default Drupal installation, uses three classes to guess the MIME type:

The ExtensionMimeTypeGuesser class (a Drupal core class) guesses it from the file extension, but it doesn't have a mapping for the .xlsx files, for which it returns application/octet-stream (See ExtensionMimeTypeGuesser::guess() and ExtensionMimeTypeGuesser::$defaultMapping.)
The FileBinaryMimeTypeGuesser class (a Symfony class) returns the output of file -b --mime <filename> 2>/dev/null
The FileinfoMimeTypeGuesser class (a Symfony class) returns the output of finfo_file()

It is also possible that a module implements hook_file_mimetype_mapping_alter() to change the value returned from the first class, the file used from file or fileinfo_file() contains the wrong values, or another module implements another guesser class that is used before the other classes and returns the wrong MIME type.


How to increase default Drupal minimum cache lifetime options to a custom value? Currently the max page cache age is 1 day. I would like to icnrease to 1 year. How can I do that?

These settings are located at
/admin/config/development/performance

"Minimum cache lifetime"
"Expiration of cached pages"

Boost had a patch http://drupal.org/node/326683, wonder if this somehow could be applied for the core cache.

Just set the variable 'page_cache_maximum_age' using variable_set in custom module to the value 31536000

variable_set('page_cache_maximum_age', 31536000);

If you install the Devel Module there is a page for viewing and editing variables.

Above is a quick fix. If you want to do a perfect way then you need to form alter the "system_performance" form and change the option of below field.

  $period = drupal_map_assoc(array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400), 'format_interval');
  $period[0] = '<' . t('none') . '>';
  $form['caching']['cache_lifetime'] = array(
    '#type' => 'select',
    '#title' => t('Minimum cache lifetime'),
    '#default_value' => variable_get('cache_lifetime', 0),
    '#options' => $period,
    '#description' => t('Cached pages will not be re-created until at least this much time has elapsed.')
  );
  $form['caching']['page_cache_maximum_age'] = array(
    '#type' => 'select',
    '#title' => t('Expiration of cached pages'),
    '#default_value' => variable_get('page_cache_maximum_age', 0),
    '#options' => $period,
    '#description' => t('The maximum time an external cache can use an old version of a page.')
  );


How to print node id in a block in a module? I have created a ctools jump menu in a block in a module. I need to get the node id for use in the links. How can I get the node id printed in the block?

Here is my code;

<?php

function boathood_block_info() {
$blocks = array();
$blocks['boathood_ABC'] = array(
'info' => t('Boathood Block'),
);
return $blocks;
}

 function boathood_block_view($delta = '') {
 $block = array();
switch ($delta) {
case 'boathood_ABC':
  $block['subject'] = '';
  $block['content'] = _boathood_BLOCK_ABC_CONTENT();
  break;
 }

  return $block;
  }

 function _boathood_BLOCK_ABC_CONTENT() {
$output = boathood_page();
 return $output;
 }

 function boathood_page() {
 global $user;
 ctools_include('ajax');
 drupal_add_js($sample_style, 'setting');
 ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
 ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');
 ctools_include('jump-menu');
 $form = drupal_get_form('boathood_jump_menu_form');
 $output .= drupal_render($form);
 return array('markup' => array('#markup' => $output));
 }

  function boathood_jump_menu_form() {

 $mynid = $node->nid;

 $url = url('node/' . $mynid);
 $url2 = url('node/' . $mynid);
 $url3 = url('node/' . $mynid);
$form_state = array();
$form = ctools_jump_menu(array(), $form_state, array($url =>    t('one!'),$url2 => t('two'),$url3 => t('three')), array());
return $form;
}

You can get the ID of the current full-page node with menu_get_object:

$node = menu_get_object();
if ($node) {
  // Do something with $node->nid
}


Parsing bad dates automatically with feeds and date api? My company is trying to load an event calendar with events from another company's online calendar's web service. I'm using the Feeds Module and everything's working, except the dates because their service returns dates in a text format like so: 'MM/DD/YY[ - Ongoing]'. The Dates API doesn't seem to know how to handle this, so it just defaults to today's date.

I've tried using the Partial Date module, but there doesn't seem to be a way of feeding Feeds results into a partial date field. I've also tried talking the other company into fixing their service and returning proper dates, but they have no idea what they're doing.

Any ideas?

I am not certain if Feeds can handle this, but if you are importing CSV files, maybe OpenRefine is the quickest fix.


views slideshow jquery interfering with nice menus Building a site for my friend who is a lawyer. Every time views slideshow changes slides, it resets the hover state for views slideshow. I tried calling the nice menu javascript at the bottom of the page but that did not help.

http://www.tripodi.devserver2012.com/

I think it's z-index and it's a CSS issue, not a Javascript issue.

Put the following in your CSS sheet (any one of them that's included in your homepage):

#views_slideshow_singleframe_teaser_section_slideshow-block_1 {
  z-index: 1;
}

ul.nice-menu li {
  z-index: 10;
}


How to make base path available in views 3 Drupal 7? Without use of Views PHP module, I need to use base_path for a link. Although using views_php module, we can add it inside php code but is there any way without using this module OR we'll have to write code to create something like handler.
Currently available fields in my module are following:

 Content: Add comment link
Display the standard add comment link used on regular nodes, which will only display if the viewing user has access to add a comment.
 Content: All taxonomy terms
Display all taxonomy terms associated with a node from specified vocabularies.
 Content: Author uid
The user authoring the content. If you need more fields than the uid add the content: author relationship
 Content: Body
Appears in: node:page, node:article, node:event_calendar.
 Content: Comment count
The number of comments a node has.
 Content: Comment status
Whether comments are enabled or disabled on the node.
 Content: Delete link
Provide a simple link to delete the content.
 Content: Edit link
Provide a simple link to edit the content.
 Content: Event Date
Appears in: node:event_calendar.
 Content: Event Status
Appears in: node:event_calendar.
 Content: Has new content
Show a marker if the content is new or updated.
 Content: Image
Appears in: node:article.
 Content: Last comment author
The name of the author of the last posted comment.
 Content: Last comment time
Date and time of when the last comment was posted.
 Content: Last comment uid
The User ID of the author of the last comment of a node.
 Content: Link
Provide a simple link to the content.
 Content: New comments
The number of new comments on the node.
 Content: Nid
The node ID.
 Content: Path
The aliased path to this content.
 Content: Post date
The date the content was posted.
 Content: Promoted to front page
Whether or not the content is promoted to the front page.
 Content: Published
Whether or not the content is published.
 Content: Sticky
Whether or not the content is sticky.
 Content: Title
The content title.
 Content: Type
The content type (for example, "blog entry", "forum post", "story", etc).
 Content: Updated date
The date the content was last updated.
 Content: Updated/commented date
The most recent of last comment posted or node updated time.
 Content revision: Delete link
Provide a simple link to delete the content revision.
 Content revision: Link
Provide a simple link to the revision.
 Content revision: Log message
The log message entered when the revision was created.
 Content revision: Revert link
Provide a simple link to revert to the revision.
 Content revision: Title
The content title.
 Content revision: Updated date
The date the node was last updated.
 Content revision: Vid
The revision ID of the content revision.
 File Usage: Entity ID
The ID of the entity that is related to the file.
 File Usage: Entity type
The type of entity that is related to the file.
 File Usage: Module
The module managing this file relationship.
 File Usage: Use count
The number of times the file is used by this entity.
 FullCalendar: Google Calendar
Display events from a Google Calendar.
 Global: Contextual Links
Display fields in a contextual links menu.
 Global: Custom text
Provide custom text or link.
 Global: Math expression
Evaluates a mathematical expression and displays it.
 Global: View result counter
Displays the actual position of the view result
 Scheduler: Publish countdown
Time until the article will be automatically published
 Scheduler: Publish on
Date/time on which the article will be automatically published
 Scheduler: Unpublish countdown
Time until the article will be automatically unpublished
 Scheduler: Unpublish on
Date/time on which the article will be automatically unpublished
 Search: Score
The score of the search item. This will not be used if the search filter is not also present.

There is something in the view core.
If youre planning to output some field with base path, follow the steps to get an absolute path.

Click on the Field
Scroll down to REWRITE RESULTS
Check Output this field as a link checkbox
Check Use absolute path checkbox

If you're looking this for just a link Views PHP is a good choice.

If youre not happy with this method take a look at How to create a custom Views handler


How to get details like duration, type, etc from uploaded videos and store them in fields? I'm building a site that will handle a lot of media files, both image and video. Currently, I have video and image content types setup along with the ability to bulk-upload them.

I'm wondering if there is a way to scrape details from an uploaded video—such as duration, type, etc and store these in fields. I'm not sure how to approach this.

Presumably we are talking mp4/webm video here? Start with checking out getID3. Then it is pretty simple to do:

$id3 = new getID3;
$file = $id3->analyze($filename);

Must always have "new getID3".