How to create a Views relationship using the Address Field module? I am trying to create a view to filter content types assigned to a specific country (set using Address Field module), determined by the current node's title.

My address field is not being listed under relationships in views.

How am I able to set contextual filters by a nodes country? Is this currently possible, or am I just missing something?

The country should be filtered by the current node's title

The better approach is to create Taxonomy Terms, so you can tag your nodes.

In admin/structure/taxonomy Add a vocabulary called Countries.

Then add a term reference field to your content type and select countries as your vocabulary, and use auto complete widget.

So all you have to is type the country name here and it will tag your node with that name.

In views, for contextual filter add Has taxonomy term ID

PS: You could use the Rules module to auto tag your nodes based on the Country field value.


How can I have links to anchors in menus? How can I add a menu link as /test#anchor and link to #anchor section on the test page?

I need to add a menu item that links to specific section on the target page. Drupal 7 had menu tokens to achieve it. How can I do this in Drupal 8?

Add/edit a menu link
Enter  /test#anchor in the "Link" field
Save the link
You're done, make tea :)

Point being - fragments are accepted as part of the link in Drupal 8.

One exception seems to be the home page; it doesn't work with the <front> token, nor /#anchor. The fragment isn't rendered in either case.


Shopping cart views are not show product links I am using Commerce Kickstart V t-7.x-2.2

I realized the next: When I add a new product and I add to cart it, not show the link "view product" . But when I edit that product and modify something on product variation and save again. The link "view product" appears in Shopping cart.

Somebody could tell me what is happening? Is it a bug of the commerce kickstart ? or Am I doing something wrong?

Any help will be highly appreciated. Thanks.

Try to edit the shopping cart views, go to
admin/structure/views/view/commerce_cart_form/edit/default

On the Fields Setting Make sure there is Display path field, exclude from display. see the Global: Custom text, and you must inlcude the Dsiplay path field token there


Add Google Analytics to track a button press I have the Google Analytics module installed with Drupal 7.  On a page, how would I track the press of a button with id "myButton".  There's a great example here:

https://developers.google.com/analytics/devguides/collection/analyticsjs/events

but I'd like to learn how to leverage the GA module in Drupal 7 to do this.

take a look at Google Analytics Event Tracking:

  Event Tracking is a way to track user interaction with out registering
  a page view. Using Google Maps as an example site, event tracking
  would allow the user to track Zoom, Drag, and View Change events
  without contaminating the page view statistic.

  This module allows an interface for Google Analytics event tracking
  capabilities. It provides a hook for other modules or "glue code" and
  also has some handy drush commands.


Form validation not triggered at first submit, but on second submit I'm in the need for a extra validation on an existing drupal commerce form (commerce_cart_add_to_cart_form_##), strangely the validation function is not called on the first form submit, but on the 2nd submit and all the submits after the 2nd. There are multiple commerce_cart_add_to_cart_forms on a single page.

Here's my module code:

function val_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'commerce_cart_add_to_cart_form_') !== false) {
        $form['#validate'][] = 'val_commerce_cart_add_to_cart_form_validate';
    }
}

function val_commerce_cart_add_to_cart_form_validate($form, &$form_state) {
    dpm('validating function called');
    form_set_error('quantity', t("ERROR"));
}

Any Ideas?
And, as a second question: there are different $from_ids (commerce_cart_add_to_cart_form_##) that will all need the same validation. Is there a way to call them all other than I did?

Thanks!

I added your code to a quick dummy function, tested it, and the it seems to be working fine. I created a dummy item, added it to my cart, and the that produced a print out like:

I also added a watchdog() call to the validate function and that confirmed the validation was being called when it should be. I'm not sure if maybe you have something else interfering with your form alter or possibly your dpm is printing out late (I know it can happen with themes, not sure with modules), but you might want to try using watch dog to see if the validation form isn't being called when it should.


Drupal Commerce Stock Availability or Out of Stock I am working on Drupal Commerce website. Using Commerce Stock I am able to manage the inventory but on product details page I want to print the following.

Availability: In Stock

or

Availability: Out of Stock

Also if possible

Availability: Limited Stock

If I am displaying stock filed its showing number of items available in stock, which I don't want to display.

Is there any way in Drupal I can acheive this task?

On Drupal 7.61 & Commerce Stock 7.x-2.3 I've solved it with hook_commerce_product_reference_default_delta_alter:

/**
 * Implements hook_commerce_product_reference_default_delta_alter().
*/
function test_module_commerce_product_reference_default_delta_alter(&$delta, $products) {

foreach ($products as $product) {
  if ($product->commerce_stock['und'][0]['value'] > 0){
    $product->commerce_stock['und'][0]['value'] = "On stock";
  }else {
    $product->commerce_stock['und'][0]['value'] = "Out of stock";
  }
 }
}


Redirect to a view with contextual filters I would like to redirect the user to a view with some contextual filters on the submit of a custom form.

For now I use this :

$form_state->setRedirect('view.search.page_1', ['myvalue' => $value]);

But it add "myvalue" like this : /search?myvalue=$value

and what I want is : /search/$value

Thanks

You have to use the route parameter names defined in the route.

You can check the route definition of this view display with Drupal Console:

drupal router:debug view.search.page_1

When you define contextual filters the route parameter names are usually {arg_0}, {arg_1} ...

So this could work:

$form_state->setRedirect('view.search.page_1', ['arg_0' => $value]);


A question about Drupal Books and assigning classes to the body based on last viewed book I have client site with a few different books in it. There are also some basic pages and other nodes that are not within the books. When you are in the first book the sidebar is blue, when you are in the second book the sidebar is green and the the third has an orange sidebar. This is controlled by a class that is applied to the body from a field in the book module.

Currently, when you access a global page (meaning a page or view outside a book) the sidebar color is a default color. But the client wants these global pages' sidebar color to stay the same as the last viewed book and not switch to a different color until a new book is viewed.

I am not even sure how to begin to go about doing this and am looking for ideas.

Thanks

Thanks to No Sssweat's comment my solution for this was to use Jquery to look for the body class that controls the sidebar color then use jQuery.cookie (already packaged in Drupal just need to make sure it loads on every page) to set a cookie with that value. Then if a page visited that doesn't have the body class that indicates it was a book and therefore also doesn't have the color class then I had jQuery .addClass to add the cookie value to the body element.


problem with Views module (installation) I had a views page created on my site and it seemed to work well. Then I started to update some of the modules that updates wre available for and then all of a sudden, my views module didn't seem to be installed anymore. So what I did, went back to reinstall it, now the link to my views page on the site is back (http://www.quaaoutlodge.com/special-events) but when I click on it, I get this error: Fatal error: require_once() [function.require]: Failed opening required '/home/content/q/u/a/quaa7882/html/sites/all/modules/commerce_kickstart/modules/contrib/views/includes/view.inc' (include_path='.:/usr/local/php5/lib/php') in /home/content/q/u/a/quaa7882/html/includes/bootstrap.inc on line 3047
commerce_kickstart is a module I have removed in the meantime and am no using it anymore nor is it in my modules directory. Why is something still referring to it? How can I fix this?

Thank you,
Ron

The views module was installed as a part of commerce_kickstart in sites/all/modules/commerce_kickstart/modules/contrib. You removed that distribution, which is a good idea because it was installed in the wrong directory (should be in /profiles).
Most probably you then downloaded and reinstalled a fresh views in sites/all/modules.

If you move a module you should clear the cache or (in some cases) rebuild the registry.

The easiest way to clear the cache when you cannot reach the admin of the site is to go to /update.php and run the update process (take a backup first).
Other options are the Registry Rebuild module or Drush (drush cc all).


Why is my field not displayed? I got a template for drupal 8 and modifying a content type, when editing a new field, it does not show up.

I'm attaching the images of the structure (fields, form display, display), creation of content and impression.

For more that adds any field I do not manage to make it visualize at the end, in web portal

AND, As in the last page of print (celestial circles) I can not edit that, for more that I have edited in: filds, form display and display. Please where else is it that you can edit these texts in drupal 8?

Can someone help me please

regards

The template most likely does not print content directly only specific fields, you need to add {{ content.field_name }} to the template, where you want to have it displayed.


NotFoundHttpException after changing webiste hosting, sub-domain After changing webiste hosting (Drupal 8) I got this very un-intuitive error message:

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

Symfony\Component\HttpKernel\Exception\NotFoundHttpException: in Drupal\Core\PathProcessor\PathProcessorFront->processInbound() (line 43 of core/lib/Drupal/Core/PathProcessor/PathProcessorFront.php).

Drupal\Core\PathProcessor\PathProcessorManager->processInbound('/', Object) (Line: 157)
Drupal\Core\Routing\RouteProvider->getRouteCollectionForRequest(Object) (Line: 141)
Symfony\Cmf\Component\Routing\NestedMatcher\NestedMatcher->matchRequest(Object) (Line: 258)
Symfony\Cmf\Component\Routing\DynamicRouter->matchRequest(Object) (Line: 185)
Symfony\Cmf\Component\Routing\ChainRouter->doMatch('/', Object) (Line: 155)
Symfony\Cmf\Component\Routing\ChainRouter->matchRequest(Object) (Line: 84)
Drupal\Core\Routing\AccessAwareRouter->matchRequest(Object) (Line: 154)
Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest(Object, 'kernel.request', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request', Object) (Line: 120)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

The files are all the same, other files on ftp/website (besides Drupal) are accessible and works fine.

I've cleared cache via Admin Panel before moving anything.

I've also tried remove it manually:

TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;

but I guess it's not the point.

The previous website was working on http://someurl1.com/site/ (sub-domain) and new one is under http://someurl.com/ (top domain). But even moving everthing on new hosting to /site/ doesn't change a thing.

When I changed database connection settings in settings.php to something wrong intentionally I get:

PDOException: SQLSTATE[HY000] [1044] Access denied for user...

So I guess it's not the database connection problem either.

Using http://.../core/rebuild.php also didn't help.

Check database connection through drush sql-cli and show tables, I got the same error because of an empty database once.

If the data is of no importance, you can run drush site-install to re-install Drupal from scratch.


How to display view in all available languages? I need to set up a view that lists content in all available languages despite user's current language. I tried creating content translation relationships to all languages and setting fields to use these relationships, but it doesn't work. It only shows fields with the user's current language. How do I get it to list all fields in all languages?

You could try to do this with the field language setting in view.
I would try to set this to language neutral.

I have not tested this myself, just my 2 cents ;-)

Look to screenshots for clarification


How to use AJAX for an exposed filter form of a Views block? I have a View, in a block, assigned to a region. I have enabled Ajax for the view.  Pagination works with Ajax. Exposed filters do not. Exposed filters "submit".

I am definitely willing to cut corners at this point, so if there's a method that can be done with a simple JS function I will do that.

I believe that the problem is related to using the exposed form as a block. When "exposed form in block" is set to "no" ajax filtering does work.

update/solved:
I disable "exposed form in block" which I was using to change the position the filters. I then edited the view's template to get the position where I wanted it. so this is "solved" but I am not sure why it didn't work before.

You must install the Better Exposed Filters module:

  What else can I do with BEF?

  Add help text for each exposed filter
  Tame long lists with scrollable checkbox/radio button lists or select all/none links
  Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed
  Use the jQuery Slider widget for greater-than, less-than or in-between types of filters

You can read more about this in Views exposed filters without "Apply" button


Create View for a Content Type it is a simple question. Probably the answer is simple too but it stole my 2 hours.

I have a contenty type: Article.
When i create a content from it normally it shown a default display.

I want to create a view and control this display from it.
How can i do that.. what should i write to url part in my view?

It's pretty simple.

1 - Go to admin/structure/views/add
2 - write view's name & (auto)machine name.
3 - select Content as of your content view from select list.. second select list choose YOUR content type you want to filter the result of.
4 - Select Create a page .. you'd have to write the title of the page .. then the path to this page example: my_player // example.com/my_player

other options would be up to you!

hope this helps


How to add active class to link which is loaded via views and links comes from content type I have created a content type calls as "XYZ Inner Pages".
Here I am adding a Fieldset and inside field set I am adding field type as Link.
Now I create a page using XYZ "Inner Pages" Content Type, add content and the links.
I am hiding the Links from Manage display because I want to show those on the right side of page.
Now I am creating a view which will pull all the links from "XYZ Inner Pages" Content Type.
Now I am showing the views block in the right section of "XYZ Inner Pages" Content Type page.
This right block will list the link.
Now I want to add active class to links so when I open any of the link from that list, then opened link from the list should be highlighted.

Example:

In my content type I added a link field called "link", so the machine name is field_link

In this link field for url I put http://example.com/node/3

I created a View called "Test".

In fields I added link.

In fields I added link again, but this time I change the formatter to URL, as plain text

We are going to use template_preprocess_views_view_fields

In your theme's template.php file you add

function mytheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "test"){

    $field_link = strip_tags($vars['fields']['field_link_1']->content); // use strip_tags function to remove HTML markup.
    $field_link = str_replace('http://', '', $field_link); // remove http://
    $field_link = str_replace('www.', '', $field_link); // remove www.

    $node_url = $_SERVER['SERVER_NAME'] . '/' . request_path(); // see https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/request_path/7.x

    if ($field_link == $node_url){

      $vars['fields']['field_link']->content = '
' . $vars['fields']['field_link']->content . '
';

    }

    $vars['fields']['field_link_1']->content = null; // hides the field_link_1 field

  }

}

replace mytheme with the actual name of your theme.
replace test with the actual name of your view.
replace field_link with the actual name of your field.

Then you add the CSS to your theme's style.css file, Example:

.active-link a { color: green; }


How to show parent terms in view for restricted nodes categorised with child term? I have a number of nodes with individually restricted permissions. Logged-in users only see a selection of nodes depending upon their permission roles.

My view lists the taxonomy terms of the nodes, but only shows the terms containing nodes the user has permission to see by a relationship between the term and node (which is a good thing).

However, I have some instances where the following is the case:

Parent term (no nodes visible to user in this category)
    Child term 1 (10 nodes visible to user in this category)
    Child term 2 (no nodes visible to user in this category)

And the taxonomy view only lists "Child term 1", but I would also like to list "Parent term". How is this possible?

Thanks.

In case anyone has the same issue, I gave up in the end and wrote a custom module since I find views a pain in the ass.

My module uses nested queries which is embarassing, but it's still fast to run (unless you have a massive list of taxononomy terms) so it doesn't matter too much for this purposes.

The module outputs a Drupal block, the content of which comes from this function:

function list_of_resource_tags(){

// Retrieve the logged in user
global $user;

// Select all "Metadata" terms for the nodes the logged in user
// has permission to see
$sql_terms = '
SELECT DISTINCT(term_data.tid) AS term_id, term_data.name, term_hierarchy.parent, term_data.weight
FROM node_access
INNER JOIN node ON node_access.nid = node.nid
INNER JOIN term_node ON node.nid = term_node.nid
INNER JOIN term_data ON term_node.tid = term_data.tid
INNER JOIN term_hierarchy ON term_data.tid = term_hierarchy.tid
WHERE node_access.grant_view = 1
AND node.status = 1 /* Published nodes */
AND term_data.vid = 9 /* Taxonomy terms of "Metadata" vocabulary only */
AND node_access.gid IN (SELECT rid AS roles FROM users_roles WHERE uid = %d) /* Logged-in user is granted permission to these nodes */
ORDER BY term_data.weight';

$result_terms = db_query($sql_terms, $user->uid);

$displayed_terms = array();
$output = '';
while ($row = db_fetch_object($result_terms)) {
    // If tag is top-level, just display and put in array
    if ($row->parent == 0 && in_array($row->term_id, $displayed_terms) == FALSE){
        $output .= '
term_id.'">'.$row->name.'
';
        $displayed_terms[] = $row->term_id;
    }
    // Test if we've already displayed the tags parent, if not, retrieve it
    else if (in_array($row->parent, $displayed_terms) == FALSE){
        $sql_parent = '
        SELECT *
        FROM term_data
        WHERE tid = %d';

        $result_parent = db_query($sql_parent, $row->parent);
        $row_parent = db_fetch_object($result_parent);

        $output .= '
tid.'">'.$row_parent->name.'
';
        $displayed_terms[] = $row_parent->tid;
    }
}

return $output;
}


Full Calendar How to add Events I'm using the Full Calendar module.It's all working fine, but I can't figure how to add events to it. I've read the docs, I can see you can set up a feed to a Google Calendar which is cool,but I want to enable the user to add events right there.

After reading the documentation of the module it looks like you need create a custom content type with at least one date field and then create your view to use that content type.


Place custom content field only on sidebar i have created a custom content type "My_Content" with some custom fields. One of the fields in "My_field". Now, when the user is creating a content of type My_content, he/she is asked for the fields like title, body, picture, My_field etc...What i need is that the My_field always displays on the right sidebar. Is there a way to achieve this?

You can do this with the Panels module.  From the Page Manager configuration screen (Pages in the admin interface), enable the node edit page override.  Then edit this override.

Create a new variant.  Set the selection rule to be "content has type" -> "my custom content type".  Then, under Layout, choose an appropriate layout (one with a right sidebar).

Afterwards, under content, you will need to add all of the fields for the content type to be edited.  Just place My_field in the right sidebar and it will be displayed there.


How to bring custom block theme suggestions into the right hierachy? I have to create theme suggestions for my content block types (custom blocks - configured via admin/structure/block/block-content/types), because i didn't find them as default suggestions.

The default was:

FILE NAME SUGGESTIONS:
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
x block--block-content.html.twig
x block--block-content.html.twig
* block.html.twig

block--block-content.html.twig is not enough, because i need different custom block type templates. (Btw. 2 times block--block-content.html.twig?)

I need:

FILE NAME SUGGESTIONS:
x block--block-content--header-content-block.html.twig
* ...
* block.html.twig

So i tried in the theme file:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */

function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables)
{
    $block = $variables['elements'];
    $blockType = $block['#configuration']['provider'];
    if ($blockType == "block_content") {
        $bundle = $block['content']['#block_content']->bundle();
        $suggestions[] = 'block__' . $blockType . '__' . $bundle;
    }
}

This brings up:

FILE NAME SUGGESTIONS:
x block--block-content--header-content-block.html.twig
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
* block--block-content.html.twig
* block--block-content.html.twig
* block.html.twig

Nice - but my suggestion is higher then the id based ones for single blocks - not good ... so i added

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function oeb_theme_suggestions_block_alter(array &$suggestions, array $variables)
{
    $block = $variables['elements'];
    $blockType = $block['#configuration']['provider'];
    if ($blockType == "block_content") {
        $bundle = $block['content']['#block_content']->bundle();
        $blockUuid = $block['content']['#block_content']->uuid();
        $blockId = $block['#id'];
        $suggestions[] = 'block__' . $blockType . '__' . $bundle;
        $suggestions[] = 'block__' . $blockType . '__' . $bundle . '__' . $blockId;
        $suggestions[] = 'block__' . $blockType . '__' . $bundle . '__' . $blockUuid;
    }
}

Result

FILE NAME SUGGESTIONS:
* block--block-content--header-content-block--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
* block--block-content--header-content-block--registernowheaderblock.html.twig
x block--block-content--header-content-block.html.twig
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
* block--block-content.html.twig
* block--block-content.html.twig
* block.html.twig

This is not nice, because of the doubled id stuff - is it possible to get something like:

FILE NAME SUGGESTIONS:
* block--registernowheaderblock.html.twig
* block--block-content--7bd0dc95-f2ee-4e70-8a5a-90d718384712.html.twig
x block--block-content--header-content-block.html.twig
* block--block-content.html.twig
* block.html.twig

Means: Single blocks are the highest - but unique? Or should i live with this to keep the stuff simple?

What you need is simple array manipulation. Basically split of the original suggestions add the the suggestions and merge the suggestions again.

Some like this should work (untested).

function oeb_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  ...
  $first_sugestions = array_slice($suggestions, 0, 2);
  $last_sugestions = array_slice($suggestions, 0, 2);
  $first_sugestions[] = 'block__' . $blockType . '__' . $bundle;
  $suggestion = array_merge($first_suggestions, $last_suggestions);
}


How to get last X contents I want to write a function inside a module that will return last 20 contents of type X . is there any drupal ready function ? or shall i use queries ?

THanks

You can use views to get that.

Make sure you sort items descending and limit the result number to be 20.


Importing multiple images from Dropbox with Feeds As part of a product import, I am trying to import images from a link contained in a column of an Excel file.  Each link points to a Dropbox folder with 2 image sub-folders (named PRINT and WEB).  Is it possible to import multiple image files from a Dropbox folder using Feeds?

I hope you can read the images's urls inside the Excel table – or actually let your D7 install read them? Once you have that and can actually also access the files on dropbox, it should be possible to load them into your D7 install.

I had a similar, though probably more trivial problem. I had the images' urls and all related info nicely wrapped in a simgle xml file. Looking for a way to actually import the images I came across the Media Feeds module which basically let's you 'import' media files into as an image or file field into an entity (e.g. a node).

The module's project page (https://www.drupal.org/project/media_feeds) has also a link to a screencast – should not be too complicated once you can read the Excel table / get access to the images' urls.


Content region not visible in blocks setup page in Sky Adaptive Theme I checked the 'content' region, being one of the prerequisite regions and it is present and referenced in the sky.info file as well as in the page.tpl.php.

That is:
(in sky.info file)

regions[content] = Main content

(in page.tpl.php file)

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

However, when I go into the 'block' setup GUI page, from the regions dropdown, I can not see the 'content' region option.

Any idea as to why its not visible would be great. Cheers

Which version of Sky theme are you using? In 7.x-2.3, I can see the "Main content" region in the drop down list. If you have made custom changes to theme, try clearing the cache.


I can create content type fields pragmatically, but I set het widget options too? Im using field_create_instance to create all my defined fields, and use the correct field types and widget types and such, but Im not sure how to set the widget options.

In my use case, Im using the colorfield module and am trying to save the default options for the widget so the content type automagically uses farbtastic but I'm not the greatest drupal dev yet and am not sure how to do that.

Right now, my instance looks like:

'fill_color' => array(
    'field_name' => $fields['field_map_fill_color']['field_name'],
    'label' => 'The inactive state colors',
    'bundle' => 'nji_map',
    'entity_type' => 'node',
    'widget'      => array(
        'type'    => 'colorfield_unified_textfield'
    ),
    'description' => 'This is the color of the inactive color of the state.',

),

So that sets the field to use the colorfield field widget alright, but I need to set it up so it also uses the farbtastic option. I took a look at the module and theres a hook called hook_field_info with this option:

    'instance_settings' => array(
        'colorfield_enable_colorpicker' => TRUE,
        'colorfield_colorpicker_type' => 'farbtastic',
    ),

I looked at the drupal field_create_instance hook and i feel like it needs to go into widget->type right? Well I cant seem to get it to work.

Ive also tried:

    'background_color' => array(
        'field_name' => $fields['field_map_background_color']['field_name'],
        'label' => 'The background color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'description' => 'The background color is the color between.',
        'widget'      => array(
            'type'    => 'colorfield_unified_textfield',
        ),

        'instance_settings' => array(
            'colorfield_enable_colorpicker' => TRUE,
            'colorfield_colorpicker_type' => 'farbtastic',
        ),

    ),

I think it should look like this :

    'field_instance' => array(
  'bundle' => 'fo',
  'default_formatter' => 'text_default',
  'default_value' => NULL,
  'default_widget' => 'text_textfield',
  'deleted' => '0',
  'description' => 'blah blah blah.',
  'display' => array(
    'default' => array(
      'label' => 'above',
      'module' => 'text',
      'settings' => array(),
      'type' => 'text_default',
      'weight' => 0,
    ),
  ),
  'entity_type' => 'taxonomy_term',
  'field_name' => 'test',
  'instance_settings' => array(
    'text_processing' => 0,
  ),
  'label' => ' test',
  'required' => FALSE,
  'settings' => array(
    'max_length' => 255,
    'text_processing' => 0,
    'user_register_form' => FALSE,
  ),
  'title' => 'test',
  'widget' => array(
    'module' => 'text',
    'settings' => array(
      'size' => 60,
    ),
    'type' => 'text_textfield',
    'weight' => 31,
  ),
),


How to make a form that captures a value from $_REQUEST[] Update: This question now has a clone: https://stackoverflow.com/questions/13184335/drupal-how-to-make-a-form-that-captures-a-value-from-request

I have been trying to make a form that captures a value passed in from $_REQUEST.

A field is displayed only if a $_REQUEST variable exists (done)
The user can modify the field
The field is validated in whatever way
The (modified) value gets used

In this specific case, I am using a hook_user function, but I hope that the solution is applicable to any Drupal form.

Here's a simplified version of my code where the user would have an extra field to specify that they have a favorite fruit if they were to register using the following URL:

http://example.com/user/register?fruit=pineapple

function fruity_user($op, &$edit, &$user, $category = NULL){
    switch($op) {
        // Add extra fields if $_REQUEST contains values for them
        case 'register':
            if($_REQUEST['fruit'] == 'pineapple'){
                $fields['user_reg_info']['profile_fruit'] = array(
                     '#type' => 'textfield'
                    ,'#description' => 'Your favorite fruit (if applicable)'
                    ,'#locked' => 0
                    ,'#value' => $_REQUEST['fruit']
                );
            }
            return $fields;
            break;

        // check registration for mistakes
        case 'validate':
            if ($edit['form_id'] == 'user_register') {
                if ($edit['profile_fruit']){
                    verify_fruit($edit['profile_fruit']);
                }
            }
            break;

        // runs after the new user is inserted
        case 'insert':
            if($_REQUEST['fruit']){
                db_query('INSERT INTO user_fruits SET `uid`=%d `fruit`="%s"',array($user->uid, $edit['profile_fruit']));
            }

            // record information
            watchdog('user', t('user %user picked out a fruit',array('%user' => $user->name)));
            break;
    }
}

With the above code, the field does make itself visible only when $_REQUEST['fruit']  is present but if you change your fruit to "watermelon" on the form, insert still uses "pineapple".

The answer was to use #default_value instead of #value.

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/6#default_value


Print exposed filter in different postion I have created a view with exposed filter, i need to print it in different position, for example filter will be in next to many & view will be in the content container. Gone through some forum, nothing seems to be working from my end. With the code below i got view array but no sure how to print the exposed filter.

$view = views_get_view('watchlist');
$view->set_display('default');
print_r($view);

Are you trying to display it in a different region? Views has an option for that. When you have one or more exposed filters, you'll find an EXPOSED FORM option in the advanced tab that will allow you to detach the form and display it in a block.

From there you can place it anywhere just like a regular block.


Site structure taxonomy configuration I am looking forward to use Drupal in order to create a knowledge-base website having a structure as shown below. Therefore, each time a knowledge area is selected, Drupal should automatically filter the related sublevels and display them as a list.

Q1 : Could anyone please help me in knowing what taxonomy/terms configuration i should use to solve my issue ?
Q2 : Are (many-to-many) relationships represented by red lines supported by Drupal ? If Yes, how could that be done?

Below is a blueprint of how I'd implement what you're looking for. It can work for both D7 and D8 ...

Sub-level 1

You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources:

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Sub-level 2

Option 1

You could use one or more taxonomies to implement "Subject". E.g. 1 taxonomy for each area, each of them with 3 terms. As a variation, a single taxonomy (used by all areas) with up to 9 (different) terms could also work.

Option 2

As an alternative to using taxonomies/terms, you could also use the Entity Reference module (included in D8 core). Here is a possible solution to do so:

create a content type (say) "Subject", and add any "field" to it you might need (now or in the future).
create 9 nodes of type "Subject".
for the content type you use for your "nodes" (in your picture), add a field that implements an entity reference to your "Subject" nodes.

Nodes

That's pretty forward, just pick an appropriate content type for those nodes you want to create. One could argue if you yes or no want to use the same content type for the nodes of the various areas. But unless you have a need for different fields of those nodes for the various areas, I don't see any reason to have like a different content type for each area. Also because if you want to impose access rules for those nodes in the various areas, you'd do so using the Group module.

Bonus

Everything above is based on using entities. With that you also have all sorts of bonus options to further refine your implementation using out-of-the-box facilities with modules such as:

Views.
Rules.
Flag.
Message.


How to specify a Rules condition like 'Before creating new content'? I need to show an "Add content" link to users but I need to consider user field values to give access to the node form. For example, is the boolean field "Subscription fee paid" is True.

I thought the Rules module could help me. But I can not find any event "Before creating new content", only "Before saving content". Indeed, I do not want users to fill the form before conditions are verified. Because after 5 or 10 minutes of completing a form, it would not be user-friendly to get a warning message like "*you are not allowed to do that!" ...

So I tried Rules link to create a sort of button, with conditions and reactions. For example, in a block, I show the Rules link. When accessed, if conditions are true, I redirect the user to the form. Unfortunately, Drupal uses the Rules link path by default (for example, submit-the-form) and not the redirection page url included in my rule (for example: node/add/article) and finally the page is not found, since nothing is behind the default path.

Well, I guess I am close but still stuck. Any suggestions?

EDIT :
I have tried to create a rule, as suggested by @Pierre.Vriens. Here is the short code.

{ "rules_subscription_check" : {
    "LABEL" : "Subscription check",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "path_has_alias" : { "source" : "[site:url]\/node\/add\/manuscript-submission" } },
      { "data_is" : { "data" : [ "site:current-user:field-subscribed" ], "value" : "0" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, subscription is needed to add that type of content.",
          "type" : "warning",
          "repeat" : "0"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Unfortunately, an unsubscribed but authentified user can still add content when he clicks on the form link.

Try using Rules (System) event "Drupal is initializing" (= init), which is actually BEFORE your form is shown. If you still can't get it to work, you may have to add an extra condition (like the URL of such form?).

You may also want to look at my answer to the question "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?". The sample there also includes such "Drupal is initializing".

However using a condition like path_has_alias will most likely NOT work either. Instead try replacing such condition with something similar to this Rules condition (in export format here):

{ "text_matches" : {
    "text" : [ "site:current-page:url" ],
    "match" : "node\/\\d+$",
    "operation" : "regex"
  }
}

In the above example, adapt the regular expression (= node\/\\d+$) to fit your URL naming for that form. In your case that regular expression should be something similar to node\/add\/manuscript-submission ...

To double check my own answer here (regex-stuff can be complicated ...), I created this prototype rule to get you going:

{ "rules_limit_access_url_node_add_something" : {
    "LABEL" : "Limit access URL node\/add\/*",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "OR" : [
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "node\/add\/book" } },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/add\/article",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Adding content for selected content types (such as for \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022) triggers some extra (Rules) logic, as you can see here.",
          "type" : "warning"
        }
      }
    ]
  }
}

Some more details to understand this proto-type (and make it work for your case also):

my 1st condition was just to have "some other condition" (in my case: applies for admins only), that's like the "data_is"-condition in your question (ignore my condition here for the rest).
my rules action in my prototype is just for (easy) debugging, and as a proof that my rule works as I expect it to work (use whatever action you see fit in your case).
the text_matches Rules condition is the most important part for you to look at. Actually, you'll need 1 such condition for each of your content type you want your rule to apply to. In my prototype I decided to have it apply to these 2 content types (whereas I used 2 different techniques you can pick from):

article : just using an exact text match
book: using an (extremely basic) regular expression (which you may want to take advantage of if you have multiple content types that you can group together in a single regular expression.

in case you didn't notice: be aware of the or part of the Rule condition also ...

I suggest you replace the path_has_alias condition with the applicable parts of my prototype rule above (i.e. the text_matches Rules conditions). Together with the "Drupal is initializing" (as in your edited version already), it should work.


locally host a working website I'm trying to locally host an already working/hosted website using wampp to try and edit it without messing up the site. But every time I try to open the site using localhost/example, it automatically redirects to the hosted domain(https://www.example.com). Can someone help me solve this issue?

You have an .htaccess rewrite rule / PHP redirect moving all traffic to https://www.example.com when the domain/protocol doesn't match.

If it's in .htaccess look for these lines and comment them out:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If there's an http -> https redirect that will have been set up manually (the above is included in the core .htaccess), so you'll need to locate and remove that separately.

If it's in PHP, it typically happens in settings.php. You should be able to see what's doing it fairly easily and comment out/remove for your local environment.

Failing that, you'll probably need to trawl the code to find out what's responsible for the redirect.


Drupal and long-polling/sockets I'm looking for some ideas of how best to cater for the following scenario: I have a facebook-style feed on the front of a site that is updated with user content regularly, and just like facebook I want the page to update as nodes are submitted to the site.

So it looks to me like a classic use case for a bit of long-polling, or even using some of those new fang-dangled web sockets. But how am I going to integrate this with drupal?

There's no way I can have 20 let alone several hundred users long polling drupal directly - it would lock up every php process my system could provide.

I've been considering writing a tiny wee node.js program which would would handle all the long-polling connections and would watch the drupal node table directly. When updated, node would query drupal and proxy the request back to the clients. But this seems like a pretty awful solution to me.

Another idea I had was to load the current maximum node nid number along with the intial request, and then somehow also advertise this number via long-polling - if the advertised number changes, it would trigger the client to make a request. But I'm not sure how to implement this advertising.

So what other options are there?

Yes, implementing comet/long polling in Drupal is a bad idea.

There already is a node.js project that you could use: Drupal node.js integration.

The design principle of that module is that node.js does not contain any logic (to avoid duplication of logic in PHP and JS) but is only reponsible for keeping a connection open to your users. You then send notifications to node.js in the usual hooks (like hook_node_save()) which forwards it to your users.


Autocomplete field - fill the selected id into another form element (eg. hidden field) this was already asked here
Handling id from autocomplete field

but still without answer: I have an autocomplete field which uses geonames query to search cities. After value is selected I want the city name and admin area to fill into the autocomplete field, and to fill geoname_id of selected value into another (hidden) field. I don't want the geoname_id to be visible - it looks kind of ugly...

I've tried to hack the autocomplete.js and added following line

$("#search-geoname-id").val($(this.selected).data('autocompleteValue'));

into Drupal.jsAC.prototype.hidePopup function

then also tried

$("input[id=search-geoname-id]").val($(this.selected).data('autocompleteValue'));

but both without effect :/

Thanks for your help, Tomas

I've found solution, so I'll share it with others:

Both options in the question were correct. I just expected that the new value of hidden field will be visible through "see source code" which it's not. When I check the $form_state['values']['geonameid'] it is filled correctly.

The complete solution:

1) In Drupal.jsAC.prototype.found I've filled the 'autocompleteValue' with value instead of key, and added new data 'autocompleteKey' which I've filled with key, surprisingly :)

2) In Drupal.jsAC.prototype.hidePopup just added $('input[id="search-geoname-id"]').val($(this.selected).data('autocompleteKey'));

Hope this helps to someone in future.

P.S. I know modifying core functions is not the cleanest way to do things, but it works.


Limit the number of uploads per image field depending of role I need a hook (or something similar) where I can set the number of image uploads depending of the role of the user.

In the settings of the field there is no way to set the maximum number of values users can enter, just one value for all roles. For example, for role #1 I want the users can upload just 3 images, for role #2 just 5 images.

I tried several ways but none worked. I tried using #element_validate but the validation never worked.

Is there some way to do that? I forgot to mention is for Drupal 7.

Solution1 Limit on the form:

function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    global $user;
    // Only allow to upload 2 images for role = staff
    if (in_array('staff', $user->roles)) {
      $center_image_limit = 2;
      $form['#field_info']['field_center_image']['multiple'] = $center_image_limit;
      $i = 1;
      foreach ($form['field_center_image'] as $key => $value) {
        if (is_numeric($key)) {
          if ($i > $center_image_limit) {
            unset($form['field_center_image'][$key]);
          }
          $i++;
        }
      }
    }
  }
}

Source: DRUPAL – LIMIT THE NUMBER OF VALUES OF A CONTENT TYPE FIELD BY ROLE @ 1

Solution2 Limit in validation:

function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    // Add the extra validation
    array_unshift($form['#validate'], '<module>_addtional_validate');
  }
}

function <module>_addtional_validate($form, $form_state) {
  $count = 0;
  foreach($form_state['values']['field_center_video'] as $video) {
    if (!empty($video['value'])) {
      $count++;
    }
  }

  global $user;
  // Only allow to upload 2 videos for role = staff
  if (in_array('staff', $user->roles)) {
    if ($count > 2) {
      form_set_error('field_center_video', t('You cannot upload more than 2 videos'));
    }
  }
}

Source: DRUPAL – LIMIT THE NUMBER OF VALUES OF A CONTENT TYPE FIELD BY ROLE @ 2


Need to convert datetime to date during D8 migration from non-drupal source I'm working on a migration where I have

2012-05-07 00:00:00.000000

in my timedate field, but I need to convert it to:

2012-05-07

I realize that I should put this in the prepareRow function, but I'm not sure what it should look like.

public function prepareRow(Row $row) {

   $date = $row->getSourceProperty('database_date_field');
   $date = strtotime($date); // -> 1336341600 unix timestamp
   $date = date('Y-m-d', $date); // -> "2012-05-07"

   // Here you 'rewrite' the field with the new value before it gets saved
   $row->setSourceProperty('database_date_field', $date);
   return parent::prepareRow($row);
}


How do I get the category links as I had them in Drupal 6, before migrating the site to Drupal 7? I am migrating my Drupal 6 site to Drupal 7. I have vocabulary/category links like http://www.megaleecher.net/category/12.

How do I replicate this with Drupal 7? I exported the below view to Drupal 7, but it does not work.

$view = new view;
$view->name = 'vocabulary';
$view->description = '';
$view->tag = '';
$view->base_table = 'node';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'time';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Node: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Argument: Taxonomy: Vocabulary ID */
$handler->display->display_options['arguments']['vid']['id'] = 'vid';
$handler->display->display_options['arguments']['vid']['table'] = 'vocabulary';
$handler->display->display_options['arguments']['vid']['field'] = 'vid';
$handler->display->display_options['arguments']['vid']['style_plugin'] = 'default_summary';
$handler->display->display_options['arguments']['vid']['default_argument_type'] = 'fixed';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['query'] = FALSE;
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['path'] = 'category/%';

check this migrate and migrate_extras module, it is very handy framework to migrate content, you can easily migrate

node
taxonomy/categories
users

Edited:

Let me clarify with your scenario,
while migrating from source(D6) to destination(D7),

you have to define source field and destination fields as shown in below code sample.

first you have to migrate Taxonomy terms from D6 to D7.
later on you have to migrate node entity, while preparing node migrate class, you have to migrate term reference field as it is. so that in prepareRow function we can replace with old term_id with new term_id which is already migrated.

For example see sample code.

abstract class JiveBlogMigration extends Migration {

public function __construct() {
// Always call the parent constructor first for basic setup
parent::__construct();

// With migrate_ui enabled, migration pages will indicate people involved in
// the particular migration, with their role and contact info. We default the
// list in the shared class; it can be overridden for specific migrations.

  }

}

/**
 *
 * Jive Blog Post Information Migration class.
 *
 */
class JiveBlogPostMigration extends JiveBlogMigration {

  public function __construct() {
  // The basic setup is similar to BeerTermMigraiton
  parent::__construct();
  $this->description = t('Jive Blog Post Data Migration.');
  $this->map = new MigrateSQLMap($this->machineName,
                array('jive_blog_post_id' => array(
                        'type' => 'int',
                        'not null' => TRUE,
                        'description' => 'Jive Blog Post ID.'
                    )
                ),
                MigrateDestinationNode::getKeySchema()
   );

// Added ContainerType field for mapping
$query = db_select('migrate_jive_blog_post', 'mjbp')
        ->fields('mjbp', array('jive_blog_post_id', 'jive_user_id', 'jive_group_id', 'jive_container_type', 'subject', 'body', 'permalink', 'minorEdit', 'creationDate', 'modificationDate', 'status', 'displayName', 'blogstatus', 'feedEnabled', 'feedFullContent', 'pingOverride', 'pingServices', 'trackbacksEnabled', 'trackbacksModeration', 'trackbacksNotification')); //SELECT the fields from node
//generate the count for the number of records to be imported
$count_query = db_select('migrate_jive_blog_post', 'b');
$count_query->addExpression('COUNT(jive_blog_post_id)', 'cnt');
$source_fields = array(
    'jive_blog_post_id' => t('The id of a particular document in the jive system'),
    'term_data' => t("The taxonomy terms associated with the node"),
    'jive_container_id' => t("The social group or space id associated to the node decided in prepareRow()."),
);
$this->source = new MigrateSourceSQL($query, $source_fields, $count_query);

// Set up our destination - nodes of type blog
$this->destination = new MigrateDestinationNode('blog');

// Mapped fields
$this->addFieldMapping('title', 'subject')
        ->description(t('Mapping beer name in source to node title'));

// References to related objects (such as the author of the content) are
// most likely going to be identifiers from the source data, not Drupal
// identifiers (such as uids). You can use the mapping from the relevant
// migration to translate from the old ID to the Drupal identifier.
// Note that we also provide a default value of 1 - if the lookup fails to
// find a corresponding uid for the aid, the owner will be the administrative
// account.
$this->addFieldMapping('uid', 'jive_user_id')
        ->sourceMigration('JiveUserAccount')
        ->defaultValue(1);
// Mapping for Tags
$this->addFieldMapping('Tags', 'term_data');

// Additional mapping fields
$this->addFieldMapping('field_displayname', 'displayname');
$this->addFieldMapping('field_pingoverride', 'pingoverride');
$this->addFieldMapping('field_pingservices', 'pingservices');
$this->addFieldMapping('field_feedenabled', 'feedenabled');
$this->addFieldMapping('field_feedfullcontent', 'feedfullcontent');
$this->addFieldMapping('field_status', 'blogstatus');
$this->addFieldMapping('field_tbmoderation', 'trackbacksmoderation');
$this->addFieldMapping('field_tbnotification', 'trackbacksnotification');
$this->addFieldMapping('field_minoredit', 'minoredit');
$this->addFieldMapping('field_trackbacksenabled', 'trackbacksenabled');

//This is for path
$this->addFieldMapping('path', 'permalink');
$this->addFieldMapping('pathauto_perform_alias')
        ->defaultValue(0);

// Group mapping for space, personal, group associated Blog posts
$this->addFieldMapping('og_groups', 'jive_container_id');

$this->addFieldMapping('body', 'body');
$this->addFieldMapping('created', 'creationdate');
$this->addFieldMapping('changed', 'modificationdate');
$this->addFieldMapping('status', 'status');

// Unmapped destination fields
$this->addUnmigratedDestinations(array('revision_uid', 'teaser', 'revision', 'language', 'promote', 'sticky',
    'field_group_sticky', 'field_content_images', 'field_featured_content',));

//specify the unmapped source fields.
$this->addUnmigratedSources(array('jive_group_id', 'jive_container_type'));
}

public function prepareRow($current_row) {

 $source_id = $current_row->jive_blog_post_id;

 //populate all the tags associated with a particular node using the getDrupalTags() method
 //that returns an array of all the tags associated with a particular node.
 $term_data = JiveMigrationUtilities::getDrupalTags($source_id, 38); //38 is the object type for the blogpost in jive.
 if ($term_data) {
  $current_row->term_data = $term_data;
 }
 if ($current_row->jive_group_id != 'NULL') {
  $current_row->jive_container_id = JiveMigrationUtilities::getDrupalContainerNid($current_row->jive_container_type, $current_row->jive_group_id);
  }
 return TRUE;
}

}

Usual flow of migration module, it will create a mapping table for each migration class like migrate_map_jiveblogmigration, it contains sourceid1 and destid1 columns. for example D6 nid is as sourceid1 and D7 nid is as destid1.

in prepareRow function you can write a logic to replace old term_id with new term_id for each row of node migration.


Redirecting to a page based on the sub-domain How can I redirect visitors to a specific page based on the sub-domain? For example:

www.site.com goes to frontpage
checklist.site.com goes to checklist.site.com/checklist

My server is set to work with a wildcard (*.site.com). All sub-domains point to the same Drupal site.

I found Redirect based on query string about redirecting in Drupal 8, but I am not able to achieve what I want following what reported there.

The linked post points in the right directions, but contains a lot of code you don't need. Use this change record https://www.drupal.org/node/2013014 instead and check $request->getHost():

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->getHost() == '...') {
      $event->setResponse(new RedirectResponse('http://example.com/foo/'));
    }
  }

For a non-coding solution you can try Redirect Domain, a submodule of Redirect.


Display rendered node in view mode X in self node in View mode Y How can I render a node in itself in a different view mode?

If you  want to do this job the one way is achieve  in node.tpl.php (and sub tpls like yourcontenttype--node.tpl.php ), and according to  variables in node tpl
 you can use both  teaser or full mode of node .also you can add your desire variable in theme preprocess ... , there is another  ways to do this with more developing solution


Download a node (and its associated files as a zip archive) Looking to create a system whereby users can upload print quality images, have them resized for web, but allow admin users to download the contents of a particular node and download the highres images and field texts as a zip archive... what would be a good starting point for this?  A particular module?  Build a custom module?

I put together a proof of concept module real quick, which exports files based on assumptions about field_type (image, file and media).

To test it out, put the following code in a custom module, then go to /export-entity/node/nid to export a node.

<?php

/**
 * Implements hook_menu().
 */
function export_entity_menu() {
  $items['export-entity/%/%entity_object'] = array(
    'page callback' => 'export_entity_page_callback',
    'page arguments' => array(2, 1),
    'load arguments' => array(1),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

/**
 * Export entity page callback.
 *
 * @param object $entity
 * @param string $entity_type
 *
 * @throws EntityMalformedException
 * @throws EntityMetadataWrapperException
 * @throws Exception
 */
function export_entity_page_callback($entity, $entity_type) {

  $wrapper = entity_metadata_wrapper($entity_type, $entity);
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

  $file_fields = field_read_fields(array(
    'entity_type' => $entity_type,
    'bundle' => $bundle,
    'type' => array('image', 'file', 'media'),
  ));

  $field_files = array();
  foreach ($file_fields as $field_name => $field_config) {
    $files = $wrapper->{$field_name}->value();
    if ((int) $field_config['cardinality'] === 1) {
      $files = array($files);
    }
    foreach ($files as $file) {
      $field_files[$file['fid']][] = $field_name;
    }
  }

  $export_filename = drupal_tempnam(file_directory_temp(), 'entityexport_');

  $zip = new ZipArchive();
  if (!($zip->open($export_filename, ZipArchive::CREATE))) {
    throw new Exception(t('Unable to create zip archive'));
  }

  $entity_data = entity_var_json_export($wrapper->raw());
  $zip->addFromString(sprintf('%s_%d.json', $entity_type, $id), entity_var_json_export($entity_data));

  // Load and attach all files/file entities
  $files = file_load_multiple(array_keys($field_files));
  foreach ($files as $file) {
    $folder = reset($field_files[$file->fid]);
    $file_path = drupal_realpath($file->uri);
    $zip->addFile($file_path, $folder . '/' . $file->filename);
    $zip->addFromString($folder . '/' . $file->filename . '_entity.json', entity_var_json_export($file));
  }
  $zip->close();

  // Copy archive to public storage and redirect to its URL.
  $public_uri = file_default_scheme() . '://entity-export/' . $entity_type;
  file_prepare_directory($public_uri, FILE_CREATE_DIRECTORY);
  $public_uri .= '/' . basename($export_filename) . '.zip';

  $public_path = file_unmanaged_move($export_filename, $public_uri);
  $public_url = file_create_url($public_path);

  drupal_goto($public_url);
}

Note that this should be done using a batch callback and/or a cron-job, especially if you expect to get alot of data - which may cause the script to time out and/or run out of memory (although it really shouldn't).


Custom teaser text in Drupal 7 I have a custom field named "field_blurb." Is it possible to make this the text shown in a teaser instead of the default which is from the body field?

Certainly, just go to the content types display settings, and pick the teaser build mode.
Drag the body to hidden, and set the blurb to be displayed. Done.


Styling Menu Mini panels I'm having an issue with styling my menu mini panel hover.

Here's the site with the megamenu I'm working on:
http://drupal.scienceworld.ca

As I'm rather new to JS, I was wondering what the best way to center the foldout menu in the browser would be?

This isn't exactly a Drupal question but if you add the following to your CSS this will accomplish I think what you want.

div.qtip {
  top: 170px !important;
  left: 370px !important;
}

Adjust the values to suite your needs.

Edit: You may want to qualify that block of CSS further by prepending with it's wrapper or something, just to give it context and not break these qtip menus in other places


How to show both currencies at once in the node page for price field I am using Drupal commerce kickstart, Here I have two types of currencies like $ and INR. In the node page I am showing INR currency by default. Using Curreny Selector Module I am showing Dropdown to select the currency. If currency selected by user then calculated $ currency is showing fine. But here I need to show both prices at once. For example, "Rs.1205 & $20" at once without selecting the currency from dropdown. I am loading this node page programmatically. So I want to load the currency programmatically which is converting through European Bank. Any Suggestions please.

Commerce Multicurrency does exactly that.

  This module enhances some of the multi-currency capabilities of Drupal
  Commerce.

  Current features:

  UI for fine granular definition of exchange rates.
  (Every currency combination can be defined separately if needed)
  Synchronization of currency exchange rates directly from the European Central Bank (ECB).
  UI to specify which rates shall be synchronized and which are handled manually.
  Generation of currency specific price fields inclusive generation of rule-set to handle them.
  hooks for easy integration of custom currency exchange rate sources.


Which table should I query? On the parent term page, I want to get all the nodes belonging to the parent term page and its children term. I need to output the node title, a field I created, and the node summary.

Which tables should I query? Which condition should I use?

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product')
  ->propertyCondition('status', 1)
  // field_fenlei is the category field name.
  ->fieldCondition('field_fenlei', 'tid', arg(2))
  ->range(0, 10);

$result = $query->execute();

if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
  echo $nodes->title;
}

You want to specify that you searching for nodes first (and optionally by your content type), and then filter by term:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'YOUR_CONTENT_TYPE_HERE')
->fieldCondition('field_game', 'tid', 5);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = entity_load('node', $nids);

How to use EntityFieldQuery


How to filter Views records by day-of-week, including multiples I have a need to filter many records by the day of the week derived from a date-only field in those records (i.e. not today's dow).

I would like a solution that works with views filters, as the wider context is that the view itself is being manipulated in code to supply which days should be included -- note plural. Basically, a paragraph is configured with List(text) fields for the weekdays and during preprocess the view is loaded and the field values 'poked' into the view's value instead of the fixed original value. Several other fields are updated likewise.

If I was doing this in plain SQL I might use DATE_FORMAT(fieldname, "%a") IN ("Wed", "Fri") or something similar. I have looked at various existing modules - views_dates and views_date_format_sql in depth - and have noted D7-only views_dow. However I can't quite see a way forward using those (even as a base), partly because I'm not very familiar with views internals.

I have managed to create a usable filter, though there is still a portability issue. This is the filter class I ended up with:

/**
 * Filter to handle dates stored as a timestamp.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("views_dates_day_of_week")
 */
class DayOfWeek extends InOperator {

  /**
   * {@inheritdoc}
   */
  protected function opSimple() {
    if (empty($this->value)) {
      return;
    }
    $this->ensureMyTable();

    /** @var \Drupal\views\Plugin\views\query\Sql $query */
    $query = $this->query;

    $placeholder = $this->placeholder().'[]';
    $fieldexpr = $this->getDateField();
    // For PostgreSQL use EXTRACT (DOW FROM field), result is numeric.
    // For SQLite use strftime("%w", field), result is numeric.
    // BUT : How to tell if these are needed!!
    $lhs = "DATE_FORMAT({$fieldexpr}, '%w')";
    $snippet = $lhs . ' IN (' . $placeholder . ')';
    // Keys are 0..6, to match %w format.
    $possibles = array_keys($this->value);

    $query->addWhereExpression(
      $this->options['group'],
      $snippet,
      [$placeholder => $possibles]
    );
  }

  /**
   * Return an array of day names, keyed by the value of the %w date format.
   *
   * If the 'options callback' is defined, use it to return values, otherwise
   * use the predefined (translatable) versions.
   *
   * Cache the return value in $this->valueOptions for speed.
   *
   * @return array|null
   *   The array of names, keyed by integer 0..6 representing Sunday - Saturday.
   */
  public function getValueOptions() {
    if (isset($this->valueOptions)) {
      return $this->valueOptions;
    }

    if (isset($this->definition['options callback']) && is_callable($this->definition['options callback'])) {
      if (isset($this->definition['options arguments']) && is_array($this->definition['options arguments'])) {
        $this->valueOptions = call_user_func_array($this->definition['options callback'], $this->definition['options arguments']);
      }
      else {
        $this->valueOptions = call_user_func($this->definition['options callback']);
      }
    }
    else {
      // Keys are 0..6 and starting Sunday, to match %w format.
      $this->valueOptions = [
        '0' => $this->t('Sunday'),
        '1' => $this->t('Monday'),
        '2' => $this->t('Tuesday'),
        '3' => $this->t('Wednesday'),
        '4' => $this->t('Thursday'),
        '5' => $this->t('Friday'),
        '6' => $this->t('Saturday'),
      ];
    }

    return $this->valueOptions;
  }
}

Note that the implementation of opSimple has hard-coded use of MySQL. I was unable to find out which DB type this operation is using and therefore adapt to the SQL used by that DB. The builtin 'dateSQL' member of $this is protected and marked views-internal, preventing it being used to identify the db type. I also used the array placeholder feature of Drupal (the ".'[]'" on the placeholder variable) to avoid having to separately quote all the IN values. I also cannot see a way to avoid this operation requiring a sequential search of the db table :(

I switched to using numbers (2) rather than abbrev-names (Tue) because that was more portable between db types and possibly faster. The rest of the code I have inherited/adapted from the drupal.org/project/views_dates:

Add to views_dates.filter.schema.yml:

views.filter.views_dates_day_of_week:
  type: views.filter.in_operator
  label: 'DoW'
  mapping:
    type:
      type: string
      label: 'Type'

Add an entry in views_dates_views_data_alter(), which is :

$data[$table_name][$base_field_id . '_dow'] = [
  'title' => t( '@label as day name', ['@label' => $base_field_label]),
  'help' => t( '@label as day name 0 - 6, representing Sunday (0) to Saturday (6).', ['@label' => $base_field_label]),
  'argument' => [
    'field' => $base_field_id,
    'id' => 'date_dow',
  ],
  'filter' => [
    'field' => $base_field_id,
    'id' => 'views_dates_day_of_week',
  ],
];

Note that, in views_dates.module, entity type 'node' is skipped from adding these new filters - you may wish to change this!


How can I run a jQuery script in the admin overlay? I'd like to modify the interaction with one (or more) of my admin overlay pages, but it doesn't seem like the scripts that works on the site are directly functional in the back-end? How do I run a jQuery script within the Drupal admin overlay?

As you might tell, I'm quite new to Drupal.

You'll need to go in and do a form_alter on the admin overlay pages that you are wanting to modify. You will need to add an item to the ['#attached'] attribute on the form to attach your JS. You can read more about attaching JS to forms in the Drupal Form API documentation.


How do I add a view between display fields of a node? I have a view that displays a table at the bottom of every node. It's part of the content of the node so I want to have the "comments" section below the view.
However, the comments are a display field, which means they have to be in the same block as the node content. Since the view is a separate block I can't place the view between the node content and the comment section.
Is there a workaround for this?
Note that my content is created by the website community, so I can't use any solution that involves changing the contents of the nodes manually.

This can be done with Drupal 8's Layout Builder.
Layout Builder is a module in Drupal 8 core that does much of what Panels did in Drupal 7 and before-- it allows you to create arbitrary layouts consisting of fields and blocks for content types and even individual pieces of content.
Since its part of core, this should be a safe long-term solution to rely on.
In this case, the rough steps would be:

Enable Layout Builder.
Go to Structure -> Content types -> MY CONTENT TYPE -> Manage Display.
Under Layout options, check Use Layout Builder and save.
Click the new Manage layout button that appears.
Your fields will be arranged as before.  Now, though, you can click Add block to add any block you want, including Views blocks.  You can then put the Views block between your page body and your comments.

This is just scratching the surface of what you can do but it should get you started.


Hide option Generate automatic URL alias for all languages on user register form? Do I need to write a hook or may be I can hide this using amdin interface?
I am using Pathauto i18n, LoggingToBoggan.
The option "Generate automatic URL alias for all languages" is displaying on user register form, and my users can't understand why. I want to hide it only on register form
this code is not correct and does not work:

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

  /* hide Generate URL alias for all languages */
  if (isset($form['pathauto_i18n_status'])) $form['pathauto_i18n_status']['und']['#access'] = FALSE;
}

You can use CSS to hide it or set the option's #access value to false using a custom module.  The first will hide it but leave it available to be ticked, the second will completely remove it from the page.


Create a view from one result of another view and link to it I need to set up a contextual filter that will pass the information from a single row of a view into a new view that only shows that one row, using maybe a link that opens it into a new page or a PDF.

When a user clicks "Print" I would like the resulting page to just show the information from that one line...

Background

I have a view that lists a row of things in a table. It's data imported into MySQL that's not associated with a node. I need to build a view page certificate to use instead of Certificate.

The data is quiz scores and the fields are QID, Date, Course, Score and Print Certificate. The "Print Certificate" column is a Global: Math Expression field that basically compares the score (score) with the global passing score variable (pass_rate) and prints a link if the expression is not zero, otherwise the field is left blank. The expression I am using to accomplish this is: abs(([score]+1)-[pass_rate])+(([score]+1)-[pass_rate]).

Course is a custom content type that is connected to the quiz that was taken. The quiz also links to the course so that it comes up in this view and Quiz is using the Quiz module.

What I've Tried

I created another view as a page that is similar to the view that shows all the scores, except I limited it to one item, excluding all fields from showing and I arranged it as an unordered list instead of a table. Using Global Text field which is not excluded, add back all the other fields using replacement patterns in order to control how the data is rendered so that it reads more like a certificate about one specific quiz score or QID. What needs to be done in order that the information displayed on this view page is the same as the row that linked to it, or just one QID?

Notes

So why not just use certificate? Biggest issues are that there is no token for when the certificate was earned or when the quiz was passed. See my SE post. The other reason is because the quiz scores were imported as values from another site. See my other SE post on this.

Ideas
Can I use a contextual filter in the parent view with some php using the fetchfield() function such as something like:

db_query_range('SELECT 1 FROM {quiz_node_results} WHERE qid = :qid', 0, 1, array(':qid' => $[something]->qid))->fetchField();

With much help from an answer in this post I was able to solve my issue.
Here are the steps in case it is helpful to anyone else:

create a view (in my case, to show information from the quiz_node_results table, using quiz result ID or result_id)
create a PDF view containing the same fields as in the first view; use the views PDF module
in the first view, add a Global PHP field (use the Views PHP module) and add some PHP to print a link to the data in the row of the table from the PDF view if the score is at least the score threshold (pass_rate) for getting a certificate:

<?php
if ($row->score>=$row->pass_rate) {
print l('Print','/data/'.$row->result_id);
}
?>

in the PDF view, make sure the URL to the view is /data/% and add a contextual link; in my case, for the quiz result ID, set to show all if validation is provided and to show basic validation to show all if not provided


updates page shows an error for a mystery module 'standard 8.6.12' on the updates page /admin/reports/updates under Modules there is a module called standard 8.6.12 as and it is highlighted with a warning No available releases found (Warning)

this module does not appear when running $ composer outdated

is there any idea where this module is coming from, if it is in fact needing an update, or if this is just a typo in one of the site's config files somewhere?

this is what I see:

I have recently updated to Drupal 8.6.12 (using $ composer update)

going to mark this as answered so I can close it...

I removed a contrib module that we are no longer using and the mystery module "standard 8.6.12" no longer appears.

I cannot say for certain which module it was - but I am 99.78% certain it was from a contrib module, not from a core one.


Ubercart Numerical Attributes Not Respecting List Position Settings I have an attribute option select box field that has numerical options, like this:

LENGTH
1
1.5
2
10
100

However, this is how the options are displaying on the front-end view of the product:

LENGTH
1
1.5
10
100
2

As you can see, it is sorting anything that starts with a "1" before anything that starts with a "2". I need it to be in literal numerical format.

Any ideas on how I can make this work the way I need it to?

Thanks!

Ubercart manages options twice. First in the overall (global) attributes, which may be applied to any individual product, then in the realm of the individual product. Since the product may have only a subset of the global options selection, once you have applied an attribute to a product, you are able to select which options apply, and re-order the sort order for that product. The default sort in Drupal is alphabetical.

Edit your product, go to the options tab, and set the options order the way you want to see it. The select list will respect the order you set. (And yes, this will require you to repeat the process for every product.)

EDIT:

One possible way to brute force the ordering is with direct access to the database.

First go to /admin/store/products/attributes and open the options list(s) for your attribute(s). Drag and drop to get the options in the correct order, then save.

Then run the following query (after backing up your database in case it blows up):

UPDATE uc_product_options p JOIN uc_attribute_options a ON p.oid=a.oid SET p.ordering = a.ordering;

Just be aware that if you ever edit the attributes on a product, they will re-order with the selected options at the top, and the unselected options at the end of the list. You WILL have to double check the order before saving, as the selected attributes will probably be in alphabetical order.


How to make an existing website responsive using zengrids? i'm creating a website using drupal 7, zen theme with some other modules, like superfish menu for example, for now the website is empty, i'm wondering how to make the website responsive from now ? Can i just (from my starterkit theme) access to the css (or create my own) that contains some media queries and it will work ? or zengrids is a best solution ?

I have found the Superfish module plays well with the Zen theme. By default, it will toggle wide dropdown menus to accordion style menus at 768px.

The superfish library includes sass and css template files you can drop into your theme's scss or css folders.

I am using a custom theme based on Zen 7x-6x starterkit.


How to implement a multiple (AJAX) field collection with the FAPI Background: I have a field colleciton containing two fields. This field collection is attached to a profile entity and its number set to unlimited.

I am currently retrieving this field from the profile form to use it a custom form.

I get the form array and it is displayed correctly, but when I click on the button to add another element, I got a popup displaying this error:

  EntityMalformedException : Missing bundle property on entity of
  typefield_collection_item dans entity_extract_ids() (ligne 7663 dans
  /drupal_project/includes/common.inc).

Anyone have a clue or hint of what is going on behing the scene ? Maybe a solution to solve this issue ?

Update: the form I am making is a ctools multistep form. I am opened to alternatives such as Dave Reid's multifield.

So, I followed the answer in the other thread Clive linked and this did the trick:

  $profile = new stdclass();
  $profile->type = 'some_profile_type';
  field_attach_form('profile2', $profile, $form, $form_state, LANGUAGE_NONE);

EDIT: Well, this is fixing the issue because it enables the form to use its widgets. But it remains a problem, the button part of the array is passed in form_state as a value, and I have to delete it manually...


How can i select taxonomy terms applying filters on its fields? I'm building a project where i've decided to heavily use Drupal items (nodes, taxonomy, views) but i find hard to retrieve data in a simple way.

I've defined a taxonomy vocabulary with custom fields that are references to other vocabulary terms.

For example i have a book_author vocabulary and books vocabulary and need to get all the books written by a certain author tid.

Are there apis that i can use with a single call or do i have to use Sql queries on taxonomy_* field_data_* tables?

The EntityFieldQuery class is the normal tool fot this sort of task. Have a look at the docs for more information, but this is a basic example based around what you've mentioned in your question:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vocab_id_of_terms_you_want_to_select)
  ->fieldCondition('field_author', 'tid', $the_author_tid);

$results = $query->execute();

$found_terms = taxonomy_term_load_multiple(array_keys($results['taxonomy_term']));


Disable specific view display in drupal 8 via database or programmatically I was modifying a display mode in my view and must have added a criteria which doesn't exist and when I saved my changes, I was immediately thrown to a wsod.  After checking the logs, here is the error that I've found:

Exception: No entity type for field vid on view newsletters in Drupal\views\Plugin\views\HandlerBase->getEntityType() (line 697 of /home/admin/domains/zend8.sitesbycoop.com/public_html/core/modules/views/src/Plugin/views/HandlerBase.php).

Does anyone know of a way to disable this view mode via the database or programmatically so I'm not locked out of my view anymore?

Much appreciated!

In D8 views are configuration.

If you can use the admin ui, go to /admin/config/development/configuration/single/export, choose Configuration Type View and the view you want to change, modify it and paste in the single import section.

If you can't access the admin ui, you can use drush:

drush cedit views.view.newsletters


How to translate taxonomy breadcrumbs? My breadcrumbs only show in the original language.
When I change the language, only the heading of the breadcrumb which is in a t() function changes language. I can't put the $breadcrumb variable in the function, the string translation interface is also not the right place for it.
I am using taxonomy menu and taxonomy breadcrumbs modules.
How can I get the breadcrumbs to use either the translated terms or at least work through string translation?

Taxonomy Breadcrumb module has maintenance status: Unsupported. It means it's author's answer to all problems with it is simply "stop using it". There is a bug report 2 years 41 weeks old about your problem and I don't really expect it will be fixed any time soon.


Drupal 7 Members Directory Problem I created a member directory using view and it works well but I tried enable "Exposed form". I changed "Exposed form in block" to Yes & also  "Use AJAX" to Yes.
I defined "Contextual filters" to " User: Name ". then I went to Blocks and Enabled the new block and edited Only the listed pages and put the path but nothing shows up there.
here's my View :
here's my block:
final demo:

ok, I created that with Filter Criteria, now the search fields show up at the top of the view, how can i put them in sidebar of this view?
final result:

You do not have any exposed filters. Under "Filter criteria" you need to define a filter which is exposed to the user. The block will then show up

EDIT
You already set the exposed filters to be shown in a block in your views administration on the right side. Now you find a block with the exposed filters in your block administration page. Here you can set the visibility of the block - maybe just show the block under the path of this view.


Display 2 content type in front page I am learning Drupal 8, i have 2 content type (Notices, Plan), i want my front page look like this:

List entries of Notices

item 1
item 2
item n

Pager of list Notices

List entries of Plan

item 1
item 2
item n

Pager of list Plan

Can i do this in some way?

The fastest possible way is to create a Views page and a Views block.
Then change the front page path with the one you used for the View (Configuration > Basic site settings > FRONT PAGE)
Then create the block instance in the Content region (Structure > Block layout)

Also, make sure you are using 2 different Pager ids in your view (in your view, under Pager > Settings > Pager ID) You may just use 1 for one of the views and 2 for the other one.


Implement a custom PHP library into a custom block module? I have a PHP class and it's files in the folder:

/var/www/include_php/**the_folder**

How should I include this into Drupal?

ln -sf /var/www/include_php/the_folder /var/www/drupalSite/sites/all/libraries/the_folder

and then do drupal_add_library('the_folder') or something else in my block module?

drupal_add_library() is for Javascript/CSS libraries; Drupal doesn't have a similar registry for PHP libraries/classes.

To include a file inside a module in your installation, use module_load_include() e.g.

module_load_include('inc', 'mymodule', 'mymodule.pages');

For all others just defer to the standard PHP functions (include/require, etc.)


Module with block plugin not using custom template I am struggling to get my custom module template to get use by by block plugin.

I have followed the solution given at: Twig Template for a Custom Block Plugin but continually get this error:

  The website encountered an unexpected error. Please try again later.
  Twig_Error_Loader: Template
  "modules/custom/lrg_osm/templates/block--osmnhd.html.twig" is not
  defined in Twig_Loader_Chain->getCacheKey() (line 64 of
  themes/contrib/bootstrap/templates/block/block.html.twig).
  Drupal\Core\Template\TwigEnvironment-->getTemplateClass("modules/custom/lrg_osm/templates/block--osmnhd.html.twig")
  (Line: 424)

I have tried to also fiddle the name of the twig file in various ways to not avail.

My module file structure is shown below with relevant code if anyone is able to point out the error of my ways please:

src/Plugin/Block/osmnhdblock.php

<?php
declare(strict_types=1);

namespace Drupal\lrg_osm\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;

/**
 * Provides a 'OSM Block for Home development Landing page' block.
 *
 * @Block(
 *   id = "osmnhdblock",
 *   admin_label = @Translation("OSM New Homes Development (NHD) block"),
 *   category = @Translation("LRG")
 * )
 */
class OsmNhdBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     *
     */
    public function build()
    {
        return array(
            '#theme' => 'osmtheme',
            '#jsonDataLocations' => 'nhd some data',
            '#title' => 'nhd some title',
        );

        /*
         '#attach' => [
                'css' => '/css/openstreetmap.css',
                'js' => '/js/openstreetmap.js',
            ],
         */
    }
}

lrg_osm.module

<?php
declare(strict_types=1);

function lrg_osm_theme($existing, $type, $theme, $path) {

    return array('osmtheme' =>
        array(
            'variables' => array(
                'title' => null,
                'jsonDataLocations' => null
            ),
            'template' => 'block--osmnhd'
        )
    );
}

templates/block--osmnhd.html.twig

{#
/**
 * @file
 * Some description
 */
#}

{{ title }}

{{ jsonDataLocations }}

The templates directory must always be a direct descendent of the module or theme root directory, in your case /modules/custom/lrg_osm/templates/ (not modules/custom/lrg_osm/src/templates/).


How to select files from /sites/default/files with IMCE filebrowser? Somehow the settings of directories in the configuration of IMCE (7.x-1.7) is pointing to <root>/. which lets met start in the private_files directory but not in the (public) files directory.

I couldn't figure it out where to change this. I tried to set a path to the public files directory with <root>/.. but Drupal would not allow me.

The settings under Home>Administration>Configuration>Media is set  to:
Public file system path:  sites/default/files
Private file system patch: sites/default/files/private_files

Anybody having a clue ?

Create a new IMCE profile from

  admin/config/media/imce/profile

Don't forget to add the Permitted file extensions and Directories while creating the IMCE profile.


Views: how to remove ending zeros from decimal field Suppose, we have a view with a decimal field:

It is output like this:

5 000.000

Is it possible to remove the ending zeros, so it looked like this:

5 000

But if there are meaningful values in the field, it should output all of them. For example:

5.100 -> 5.1
5.010 -> 5.01
5.001 -> 5.001

I created a file /theme/bartik/templates/views-view-field--open-events--page--field-coefficient.tpl.php:

<?php
print (float) $row->_field_data['id']['entity']->field_coefficient[LANGUAGE_NONE][0]['value'];

And it worked.


Setting up a staging server workflow (for a relative beginner) I'm working on a Drupal 6 project and would like to set up a simple staging/live server workflow.

I know Drupal pretty well, including the Features module, and am relatively familiar with Git; as for the server itself, I've only got FTP access. I'd be interested in hearing possible ssh-based solutions too, though.

Can anyone recommend a suitable workflow, or suggest what I should consider if I have to develop my own workflow?

If I understand what you are asking for, that being your production server being remote, you might want to consider installing a devdesktop from acquia.com if you're using a Windoze or mac development system.  Then you can use features and/or deploy to move you changes to the production system via ftp.

If you're using a *nix development box I'd install Drupal directly and still use features and/or deploy to move things.

Worth a try -


Get user list according to node field value I have created one content type named "Project". I have added one field in it named "Skills". Skills is a multiple select field. And I have added one submit button. Which I want to use to get records of users. I have created an Ajax form submit, but my issue now is that I can't alter the form after the Ajax submit.

This is the code I'm currently using:

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

  if ($form_id == 'project_node_form') {

    $form['field_user_lists']['#access'] = FALSE;

    // Provide a submit button.
    $form['submit'] = [
      '#type'   => 'submit',
      '#value'  => 'Get Employee',
      '#weight' => '4',
      '#ajax'   => [
        'callback' => 'MYMODULE_form_ajax_submit',
        'wrapper'  => 'project_node_form',
        'method'   => 'replace',
        'effect'   => 'fade',
      ],
    ];

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

function MYMODULE_form_ajax_submit($form, &$form_state) {

  if (!empty($form_state['input']['field_skills']['und'])) {

    //print_r($form_state['input']['field_skills']['und']); die();
    $query = db_select('field_revision_field_skillss', 'n');

    $query->join('users', 'u', 'n.entity_id = u.uid'); //JOIN node with users
    $query->groupBy('u.uid');//GROUP BY user ID
    $query->fields('u', ['uid', 'name'])//SELECT the fields from node
    ->condition('n.field_skillss_tid', $form_state['input']['field_skills']['und'], 'IN');

    $result = $query->execute();

    $form['field_user_lists']['#access'] = TRUE;

    while ($record = $result->fetchAssoc()) {
      print_r($record['name']);
    }
  }
  else {
    $output = 'Enter a value';
  }
}

I think you are getting close. When you use ajax in Drupal, you have to return a render array with commands. In your case it looks like you would want ajax_command_replace.

Two additional steps should get you up and running.

First, built an html string instead of using print_r to try and send content back to the client.

    $return_html = '
';
    while ($record = $result->fetchAssoc()) {
              $return_html.='
' . $record['name'] . '
';
            }
    $return_html .= '
';

Then create the ajax object and render array to send back to the client

 $commands[] = ajax_command_replace('#my_selector', 'some html here');
 return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );

In this example, you would need to have a div on your page with an id of 'my_selector' that would receive the new html.


How do I intercept a press on "Save" and get the nid? I want to get hold of the nid of the newly created node whenever a new node or comment is created by a user by pressing "Save" (and only when the user press "Save" - not when the node is created or saved by other means).

I've tried to create a custom submit handler to intercept the save by means of a custom submit handler:

$form['#submit'][] = 'mymodule_node_submit';

This handler intercepts the press on the "Save" button, but it is invoked too early. The nid of the node it is not yet available inside the submit handler.

What is the correct way of getting the nid whenever a new node is created by an interactive user?

I know there is a similar question here: Get node id of saved node - but the accepted solution (use hook_node_update()) is not correct.  hook_node_update() will also intercept calls when nodes are created programatically (for instance by the Feeds module), when there is no real user involved.

If you read through node_form() you will see that the Submit button has its own submit handler:

$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);

so you need to add your own submit handler to this

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] = 'MYMODULE_node_form_submit';
}

Then inside that $form_state['nid'] or $form_state['node'] should have what you need.


How do I escape a string in a query? I received the following error using my module:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '%m-%d') =
DATE_FORMAT(NOW(), '%Y-%m-%d') AND is_logout = 0' at line 1: SELECT id FROM
ap_visits WHERE`current_ip` = '192.168.1.1' AND `url` =
'http://www.mysite.com/php/4220/how-build-shopping-cart-w-checkout-php.html''
AND DATE_FORMAT(date_start, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d') AND
is_logout = 0; Array ( ) in test_module_check()
(line 164 of /var/www/clients/client1/web2/web/sites/all/modules/test_module/test_module.module).

The error here is in the value of url column. It has an apostrophe at the end. So my question is on how can I escape this value so the apostrophe will not be an issue?

I am using db_query. This is my code:

$sql = "SELECT id FROM ap_visits WHERE`current_ip` = '$current_ip' AND `url` = '$url' AND DATE_FORMAT(date_start, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d')  AND is_logout = 0";

$result = db_query($sql);

You should do

$sql = "SELECT id FROM {ap_visits}  WHERE current_ip = ':current_ip' AND url = ':url' AND DATE_FORMAT(date_start, '%%Y-%%m-%%d') = DATE_FORMAT(NOW(), '%%Y-%%m-%%d')  AND is_logout = 0";

$result = db_query($sql, array(':current_ip'=>$current_ip, ':url'=>$url));


Trigger an event when file is upload on managed_file field I'm trying to trigger an javascript function when a user select an image for a managed_file field and click on the upload button, not the submit one.Except that in Drupal 7, managed_filr field do not accept ajax argument, I don't have any idea on how to solve my problem.
Thanks you in advance.

Finally I found a solution. I decide to use the '#upload_validators' parameter on my form and to declare my own function:

'#upload_validators' => array(
  'myOwnFunction' => array(parameters)
),
.
.
.

function myOwnFunction(parameters){
do stuff();
}


how to pull data from view to file and attach to email I have a particular use case where I want to be able to convert an existing list of Flags into a file and attach this to an email sent to the admin and user.

I currently have a working Flags list set up. What I would like to do is to covert this view to a file and be able to email it to my user and myself (admin) on the forms submission.

I envision implementing this through 1) creating the Flag list 2) converting to file 3) emailing this as an attachment to an email through the webform.

I've found modules that deal with data export, but I need some guidance on how to implement this. I suspect I may have to build my own module, but I'm only starting to dive into how to do this. Any advice on where to jump off would be greatly appreciated.

I imagine this will take the following steps: 1) check that flag list is populated 2) if flag list is populated write it to file 3) upon form submit, email a copy to user/admin

You have to use Views PDF module to output of views as PDF.
Use Mime Mail module to send email with attachment.

Write own custom logic to action performed or any rules.

Custom function to send mail as attachment visit here.

You may also check this