How can I set “This block (override)” programmatically on a view's display I need help about a specific implementation in Drupal 8.

I have been trying for two days to create a view programmatically, or more precisely to create a new display of an existing view.

The objective is to create (at the same time as creating new content) a duplicate display of a view, which is almost the same than the original, with just the title and a condition in filter criteria (a node id) changed, in order that the final user never needs to add display or modify the view.

The issue that I am coming up against is that the generated view's display lost an important property, the “This block (override)” parameter is replaced by the default state “All displays (excepts overridden)” so once I have generated the second view’s display programmatically, the first view’s display has its properties (title, filter criteria) replaced inevitably by the values of the second.

So I would like to programmatically set the parameter “All displays (excepts overridden)” at “This block (override)” but I haven’t found anything of relevance in the D8 API.

Thank you in advance for any ideas or suggestions.

function HOOK_node_insert(Drupal\Core\Entity\EntityInterface $node) {

if ($node->type->target_id == "SPECIFIC_CONTENT_TYPE") {

    $node_title = $node->getTitle();
    $node_id = $node->id();
    $machine_title = strtolower(str_replace(" ","_",$node_title));
    $block_id = 'block_'.$machine_title;

    $view = Views::getView("api_domain");//"api_domain" is the view's machine name
    if (empty($view)) {
        return;
    }
    $display_id = 'default';
    if (!$view->access($display_id)) {
        return;
    }

    $view->newDisplay('block',$node_title, $block_id);
    $options_array = array(
        'id' => 'field_api_domain_target_id',
        'table' => 'node__field_api_domain',
        'field' => 'field_api_domain_target_id',
        'relationship' => 'none',
        'group_type' => 'group',
        'admin_label' => '',
        'operator' => '=', 'value' =>  array('value' => $node_id));

    $view->setHandler($display_id, 'filter', 'field_api_domain_target_id', $options_array);//works
    //$view->setTitle($node_title);//doesn't works
    $view->display_handler->setOption('title', $node_title);// works
    //$view->display_handler->overrideOption('title', $node_title);// works too, but the "override" problem still persists
    $view->save();
}

}

If you can't find a way to do this with the methods of Views API, you can try another approach by using the view entity (storage), which provides a more direct access to the display settings in an array.

Example

$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
// add a new display
$storage->addDisplay('block', $new_title, $block_id);
// get the new display by reference
$new_display = &$storage->getDisplay($block_id);
// copy the configuration and change the filter settings
$old_display = $storage->getDisplay($old_display_id);
$new_display = array_replace_recursive($old_display, $new_display);
$new_display['display_options']['filters']['nid']['value']['value'] = 123;

$storage->save();


Media Youtube/Vimeo is being saved (or rendered) incorrectly as application/octet-stream In Drupal 7, I am using panels/panelizer, media & media_youtube.

I have correctly set up my view mode for the Video file type, and have selected that view mode using 'Rendered entity' in my pane settings.

The video is rendering as a link to sites/default/files/[file youtube title].

The above problem is arising with a file field on a node, that is being rendered with panelizer.  When I add a video using a fieldable panel pane, it renders correctly (using the same view mode).

Any help you could provide would be much appreciated.

      F 16 Fighter Pilots.F 16 Fighter Pilots over

I was having the same problem. The YouTube video was added correctly using the Media browser, the thumbnail was generated and it was even saved in the database correctly prior to saving the node.

After the node was saved, the entry in the database changed to application/octet-stream with a filename of the description twice, as well as a URI of public://

Something was altering the file details when the node was being saved. There weren't many options I could think of, and a quick review of the field settings revealed filefield_paths was enabled for the field, which was altering the filename.

I disabled fielfield_paths for the field and saved the node again, which resulted in the video displaying properly.

If you have filefield_paths installed, try disabling it for the YouTube field only.

Update: This is resolved in the latest version of filefield_paths. See: https://www.drupal.org/node/2576547


How can I hide the user profile from users? I'm using IP-based login to give visitors in a private network access to some parts of my Drupal 6 site. This means that all users from this private network are logged in as the same user.

Theoretically, anyone accessing the site that way could change the user password, which is something I don't really want to allow. I tried the User Protect module, but that just doesn't work at all on my site. I suspect that it is just incompatible with the IP login module.

Ideally, I'd like to hide the /user page entirely from certain users. They shouldn't be able to access it and shouldn't be able to change their password or any other profile information.

How can I prevent access to the user profile?

You can do this with hook_menu_alter changing the access callback and access arguments for the relevant user menu items.

e.g

/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Change user view and edit callbacks to be "administer users" access only.
  $items['user/%user/view']['access callback'] = 'user_access';
  $items['user/%user/view']['access arguments'] = array('administer users');
  $items['user/%user_uid_optional']['access callback'] = 'user_access';
  $items['user/%user_uid_optional']['access arguments'] = array('administer users');
  $items['user/%user_category/edit']['access callback'] = 'user_access';
  $items['user/%user_category/edit']['access arguments'] = array('administer users');
}

Clear menu cache to apply.


How to put links in a menu programmatically? I'm using Drupal 7, and modules such as Service links and Flag.

I would like to put the links proposed by these modules (share or flag) in a menu (main menu or other).

Anybody know the way to follow?

Your question is relatively vague, but to answer the title, here's the code you need to use:

$link = array(
  'link_title' => t('Your link'),
  'link_path' => 'your-path',
  // Enter the name of the menu where you want this link to appear.
  'menu_name' => 'main-menu',
  'weight' => 0,
);
menu_link_save($link);


Using a node editing form on a page that not a node edit page I have created a menu item, as reported below. I have taken the form ID from the page source (form id=listorious-list-power-100-node-form) but when I go to the specified URL, I get the following error:

  call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 771 of /var/www/drm6/drm001/site/includes/form.inc).

The form is the standard node form found on node/add/listorious-list-power-100.

$items['admin/config/listorious/settings/add'] = array(
  'title' => 'add Listorious List item',
  'description' => 'Add list item information.',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('listorious_list_power_100_node_form'),
  'access arguments' => array('administer site configuration'),
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

'file path' => drupal_get_path('module','node'),
      'file' => 'node.pages.inc',

needs to be added to the array.


Create/Select file from select field I have a content type video. It has some fileds for file meta data and a file upload field. Upload and display works fine.

Now I want to add a second video file to this content type. This file can either be uploaded or selected from a select field.

So you can select a previously uploaded file or add a new one. The select box should show all files that where added for any post with content type video.

Any ideas how to do this? I am using drupal 6.

FileField Sources module you are looking for, it is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser


How to validate a value against an existing field I'm doing some custom stuff with programmatically saving fields with EMW:

$wrapper->my_field->set('my_value');

Problem is, this doesn't validate before trying to save the field. How can I validate the value against the field before trying to save it?

install entity_validator module .

  Unlike Drupal 8, Drupal 7 has not validation for entity objects what
  so ever. One of your modules can create a node object without any
  title or a language and you don't want that.

for drupal 8 Use Entity Validation before save your fields.

as a example

 $violations = $typed_data->validate();
    $definition = DataDefinition::create('integer')
      ->addConstraint('Range', ['min' => 5]);
    $typed_data = \Drupal::typedDataManager()->create($definition, 10);
  if ($violations->count() == 0) { // this means there is not any validation error
     // save Entity
  }


How to pass an argument to a view? I have a a view with Taxonomy terms on the front page.I want when I click on a taxonomy term,this taxonomy term to be passed to a second view as an argument to an exposed filter.The second view is on another page.How can I accomplish that?Is there any module for this?
Thanks in advance

SOLUTION
I finally found a solution.I have rewritten the ouput of the taxonomy term to something like that second_view/[tid] .So when I click on a taxonomy term I am redirected to the second view which is filtered by the tid.That's it!

There is another solution for that. Try to use the FacetAPI module: http://drupal.org/project/facetapi

Then you can create a view and integrate the taxonomy terms with the drupal search as explained in the following link:

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/


Duplicates b/c of Node References, Views "Group By" not helping I have a view that displays all 'parent' nodes referenced from 'child' nodes. I just want to list the titles of the referenced nodes, but because there can be multiple 'child' nodes referencing the parent nodes, my view displays the 'parent' node titles multiple times (depending on how many child nodes refer to the parent).

I was trying to use Views 3.x's new 'Grouping' feature to group all nodes by nid, but that didn't seem to make a difference. I tried using an nid that was grouped in the filters section, and an nid that was grouped in the fields section, but it didn't matter.

I could do a views_pre_render and just remove the duplicates manually, but that's messy, and would also screw up the pager. (See here for something along those lines: http://capellic.com/blog/cure-duplicate-nodes-in-a-view).

Is there a better way to do this, or something I'm overlooking?

I also tried using the following hook_views_query_alter() hook:

/**
 * Implements hook_views_query_alter().
 */
function custom_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_subscriptions' && $view->current_display == 'my_networks') {
    $query->groupby[] = 'node_field_data_field_list_network_nid';
  }
}

But still no dice...

Here's the query being generated by views:

SELECT DISTINCT node_field_data_field_list_network.nid AS node_field_data_field_list_network_nid, node_field_data_field_list_network.title AS node_field_data_field_list_network_title, node.title AS node_title, node.nid AS nid
FROM
{node} node
INNER JOIN {flag_content} flag_content_node ON node.nid = flag_content_node.content_id AND (flag_content_node.fid = :views_join_condition_0 AND flag_content_node.uid = :views_join_condition_1)
LEFT JOIN {field_data_field_list_network} field_data_field_list_network ON node.nid = field_data_field_list_network.entity_id AND (field_data_field_list_network.entity_type = :views_join_condition_2 AND field_data_field_list_network.deleted = :views_join_condition_3)
INNER JOIN {node} node_field_data_field_list_network ON field_data_field_list_network.field_list_network_nid = node_field_data_field_list_network.nid
INNER JOIN {users} users ON node.uid = users.uid
WHERE (( (node.status = '1') AND (node_field_data_field_list_network.type IN  ('network')) AND (users.uid = '1' ) ))
ORDER BY node_title DESC
LIMIT 3 OFFSET 0

Well, as it turns out, I avoided this issue by adding another filter, on the 'list' nodes (the children), and I'm lucky that I have one child 'list' node per network that has a unique flag (a 'master' checkbox field that can only be checked on one child per parent 'network' node).

I filtered to only child 'list' nodes that contain that flag, and this means that my parent 'network' nodes only show once.

I still wish I didn't have to do it this way, though. If anyone else can think of a way to actually get a distinct set of nids/titles without my having to use the 'master' flag on the child nodes, I'll definitely mark that answer correct.


Assign file to entity image field (Programmatically) //class:Drupal\file\Entity\File
$file=file_save_data($image_data,$save_path,FILE_EXISTS_REPLACE);

//field_someimage = entity 'image' field
//field class:FileFieldItemList
//It contains objects with class FieldType\ImageItem
$field_someimage=$entity->get('field_someimage');

How can i add $file to the field_someimage of $entity? (entity already exists).
Do i need to construct new ImageItem somehow?

You add an image to the field by assigning the file id to target_id:

$entity->field_someimage[] = [
  'target_id' => $file->id(),
  'alt' => 'Alt text',
  'title' => 'Title',
];
$entity-save();

You can add other properties at the same time. An image usually needs a title and an alt text.


Any way to add more than one text entry to select fields In a form that a site user (i.e. not an administrator) fills out I want to have a section like this (the "[ ]" represents a checkbox in the form):

Certifications

[ ] Type 1 Certification

[ ] Type 2 Certification

[ ] Type 3 Certification

[ ] Other Type 3 Certifications [text box entry]

[ ] Type 4 Certification

[ ] Type 5 Certifications

[ ] Other Certifications [text box entry]

So the user would check as many of these as apply to them, and if they had a different Type 3 Certification than the one that was listed, they would check the "Other Type 3 Certification" checkbox AND fill out the text box with the type of Certification that wasn't listed.

And they would also have the option of checking the last text box and typing in other types of certifications in that text field.

I found Select or Other (https://www.drupal.org/project/select_or_other), but it doesn't appear to allow for two text options.

Perhaps I should simply do the list of options with Select or Other, put the Type 3 option last in the list, and add Other Certifications as a separate field?

In my opinion, the Select Or Other module works with field groups or something. It should allow one "other" value per group. You can do like this:

GROUP GENERAL

[ ] Type 1 Certification

[ ] Type 2 Certification

  GROUP CERTIF 3

  [ ] Type 3 Certification

  [ ] Other Type 3 Certifications [text box entry]

[ ] Type 4 Certification

[ ] Type 5 Certifications

[ ] Other Certifications [text box entry]


Email multiple user selected pages I need a way where someone can visit multiple nodes, add them to a list, and email them in a batch / list to a person.  I've looked at ShareThis and AddToAny, and each would seem to do a fine job for a single page, but I need to be able to collect an arbitrary number of pages and then forward them via email when the client is done creating the list.

The "use case" is that a salesman will visit a store, select 3 or 4 items on an iPhone / iPad that they would like to send more information on, and use Drupal to create the list and send the email.

I'm trying to avoid custom coding a solution because my skills are not quite up to the task, and as with everything, deadlines are tight.

Sounds like a job for Nodequeue or Flag and the Printer, e-mail and PDF versions Modules


After using unset($form['author']); for comment module drupal returns errors As I would like to allow users print their names with comments I added a new field called comment_name. To not have 2 fileds with name I used the code to unset filed "name" from comment.module

function user_add_node_form_comment_form_alter(&$form, &$form_state) {
unset($form['author']);
return $form;
}

But after adding a comment I receive an error message

Notice: Undefined index: name in function comment_form_validate() (line 2127 in file D:\sites\theme\www\modules\comment\comment.module).
Notice: Undefined index: mail in function comment_form_validate() (line 2140 in file D:\sites\theme\www\modules\comment\comment.module).
Notice: Undefined index: homepage in function comment_form_validate() (line 2143 in file D:\sites\theme\www\modules\comment\comment.module).

I guess it because I unset a form that has to validate if user logged in or not but don't know how to solve it.

P.S. Also I use the Ajax Comments Module

You should try this if you just want to hide the comment default name field !

function user_add_node_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['name']['#access'] = FALSE;
}


White screen of Death after clearing cache, can't find a way to get the site back up My problem is that I keep getting the white screen of Death ever since I cleared the cache of my Drupal website.

The error is the following :

PHP Fatal error:  Call to undefined function uc_address_property_info() in
sites/all/modules/ubercart/shipping/uc_shipping/uc_shipping.rules.inc on line 12

It happened after I cleared all the cache using the button from the Drupal configuration page. I'm pretty sure the Ubercart Store module is enabled, and I tried clearing the cache from the database already. Before clearing the cache, the site was working fine. The only thing I did is trying to hide some profile2 fields that I created and since they were still there, I thought that clearing the cache would do the trick.

If you have Drush, I would try doing another cache-clear. If that doesn't work, I would also try a registry rebuild.

Other than that, just make sure that file exists and that function exists.


How can I find out a list of available $string values for user_access($string) function? user_access($string, $account = NULL)

  $string: The permission, such as "administer nodes", being checked for.

How can I find out a list of available $string values for user_access() function?

As @Berdir said, the easiest way to see which permissions are available is to go to the permissions admin/people/permissions in Drupal 7.

The problem I kept running into is that I could never figure out what string I needed to supply as an 'access argument' to actually make use of the permission.  Well, here is how you find the string name for the permissions you want to use (This example uses Google Chrome.)

Step one. Go to admin/people/permissions find the permission you would like to use and right click on a check box to the right of the permission you would like to use.  Select 'Inspect Element' or just go look at the source.

Next look for the value of the check box and note the value. (In this case the string is 'create coupon content')

This is the string you need to supply as an access argument in hook_menu()

Example Code: (non-relevant items removed, don't forget title, callback, etc. in hook_menu())

function fsrsys_menu() {
    $items = array();
    $items['my-custom-url'] = array(
        'access callback' => 'user_access',
        'access arguments' => array('create coupon content'),
    );
    return $items;
}


Anonymous user can view unpublished content Is there any way anonymous users can access unpublished pages using view?

I have a REST api for a custom content type that has setting of unpublished content and I want anonymous users can access it.

Yes, You can enable module Workflows which is currently packed in core since 8.3 and check for permission for anonymous user

  View any unpublished content

in /admin/people/permissions

Note: Not to confuse about the permission when enable only Workflows. You need to enable module Content Moderation(Core module) to make Workflows work. Once go to /admin/config/workflow/workflows you will see the the default workflow. Here is the permission after enable Content Moderation.


conditional fields in node creation Well Im trying to use some conditional fields while creating some type of nodes. for example

I have a content type called "organization" this content type has

name, logo, and some other stuff

also has a select box field where the user selects the type of organization, depending of what the user selects I need to show other fields that depends of the type of the organization.

There is a module for this?

Thank you

You should look at Conditional Fields Module. Does exactly what you need.

You can also find nice tutorial here: CFM Tutorial


Pull data into a list for custom content type? Hopefully this is a quick question!  I'm working on a custom content type for users to create something similar to blog posts.  We'll have different authors who will be credited, so I need a drop down list so when a user writes the post, they can select the author.

The trouble is, I need to list to be auto populated from the data that is stored in a different field.  We have a content type called (you guessed it) authors.  It allows us to fill out name, field of expertise, etc.

So, how can I add an AUTHOR NAME list to my BLOG custom content type?

Thanks!
-JB

You can use the Entity Reference module to create your 'author name' field, which will reference your authors content type.


Allow anonymous users to post content but require login/register before it is saved I have a website with a node form displayed as a block on the frontpage. This is done to make sure users get down to posting content easily and quickly.

However I'm interested in saving details of the poster so they can later be notified of comments, etc to their node. I would like for the user to then be required to login or register before their content is posted.

So from nodeform block, they click Save and then they are asked to login or register..After that content is saved.

Is there any module that does this, or what approach can I take to code my own?

Thanks

This module might be worth looking at as well: Create and Register. Below are some more details about this module, and how it works (summary from the module's project page).

  This module allows an anonymous user to create the content. After
  doing so the user must login (or registers to the site). Here are some
  more details about the process to do so:

  anonymous user creates a content.
  the user will be redirected to the login page (if you set it on the settings form) after the user finished the node creation.
  the user registers or logs in.
  the created node(s) will be assigned to the user after logging in.


Calendar Module Shows Two Month Links So I have a view of a calendar with some events listed on it.  I also have this calendar setup to be a block on a page.

The block is on www.example.com/subsite

When I click the block it takes me to the month view of the calendar at
www.example.com/subsite/month

Now, on this view, there are tabs at the top of the calendar in the following order with their respective links:

Month - www.example.com/subsite/month
Month - www.example.com/subsite
Week - www.example.com/subsite/week
Day - www.example.com/subsite/day
Year - www.example.com/subsite/year

So... That second Month link is obviously wrong.  How do I get rid of it and/or change the title to Home?  If I make the Month view not show on the settings page, it removes the Month link that actually goes to the Month view.

Any help would be awesome, thank you.

Two tabs of Month came up in the first place don't make sense. It never happened to me. I would suggest to recreate this Calendar view, it's actually pretty easy if you "add view from template". (Consider you've installed the Calendar Module)

Make sure to select “A calendar view of the 'field_date' field in the 'node' base table.” on the list of views/add-template


extracting data from webform and parsing it I looked into this question, but it was irrelevant.

I have data entries on my webform... obviously each field has its own key field. Let's say it has key1, key2, key 3

What I want to do is to create an email draft as such:

Hi "key1"

I wanted to say "key2"

SUBMIT BUTTON

After pressing the submit button it will be emailed to "key3"

If there isn't any module that does do this, then can anyone tell me the steps( doesn't have to be very detailed) needed to do this?

You can use token for that purpose. Webform do have a facility to add token in mail template. But this would be default mail template using dynamic value of submitted form.

There you can find all field component available in webform.


How to onclick-trigger a non-native jQuery plugin's action? I've installed a 3rd-party jQuery plugin (it's an accordion).  It displays on my page, and works as expected.

I want to trigger one of the plugin's actions (open a particular slide) when I click on an image on my page.

I can't seem to get the  code &/or syntax for doing that right.

The plugin I've installed is "EasyAccordion" (http://www.madeincima.eu/blog/jquery-plugin-easy-accordion/).  It's .js source is posted here: http://pastebin.com/55JB4pr2.

I'm using the plugin on a Drupal7 page.

I don't think that the specific plugin, or the fact that it's been used in Drupal, is relevant to the proper jQuery usage.

jQuery's bundled with Drupal.  I init the plugin on my page with:

    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
            }
        };
    })(jQuery);

In my markup, I have

    ...

     ... EASYACCORDION MARKUP ...

    ...

Again, with this init & markup, the accordion appears/works as expected.

On the same page, in another  I've added an image-link, i.e.,

    ...

     ...  EASYACCORDION MARKUP ...

    ...

I want to click on the image in the "myImg" div, and have the EasyAccordion snap to a specific open 'pane'.  The activation of a particular pane is addressed, I think, by the

    line #127                jQuery.fn.activateSlide = function() {

function, as seen at the pastebin-link I provided above.

Iiuc, I need to add code to the init function above, to tie the image-click to an action execution in the EasyAccordion.

My question is -- how?

I think I need to fire off (e.g., for slide #3),

    jQuery(this).activateSlide(3);

adding some variation of,

    $('#myImg').click(function () {
      ...
    });

to the init, attaching it to the EasyAccordion init's function().  Something like?

    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
 ---->          $('#myImg',context).easyAccordion({ ...
 ---->          ?????????
 ---->          });
            }
        };
    })(jQuery);

So far the right syntax has eluded me.  At least, I can't get the click-on-image to actually cause the specified item to 'activate' in the EasyAccordion.

These two posts,

http://stackoverflow.com/questions/5492258/easyacordion-jump-to-desired-slidenum-jquery-plugin
http://stackoverflow.com/questions/6243870/easyaccordion-jquery-plugin-callbacks

I think are close.  But I'm still not getting the syntax to crowbar into my Drupal.behaviors... stanza right.

Any guidance?

This works.

Adding a targetable class to each slide, so that markup's:

    ...

         ...

         ...

    ...

then, in the init,

    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
                $('#myImg',context).click(function() {
                    $("dt.slide_1").activateSlide();
                });
            }
        };
    })(jQuery);

Now, a click on the img in the #myImg div opens the target slide ... here, 'slide_1', as intended.


Custom function doesn't get triggered by hook_cron() I have set up some FeedImporters and I've linked some custom batch imports to these FeedImporters. But for some reason, the function isn't triggered when running the cron... I'm wondering why. Anyone who can help me out on this one?

I've linked some custom functions to be triggered after the import:

/*
 *  Initialize hook_feeds_after_import()
 */
function my_module_feeds_after_import(FeedsSource $source) {
    _my_custom_function();
}

function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');

    // Trigger Batch for import
    batch_set(_start_my_batch('myfile', 'mytable', $fields));
}

And then my custom batch import:

function _start_my_batch($file, $table, $fields) {
    $batch = array(
      'operations'        => array(
        array('_import_csv_to_database_batch', array($file, $table, $fields)),
      ),
      'finished'          => '_import_csv_to_database_finish',
      'title'             => t("Import data in the $table-table"),
      'init_message'      => t("Feed is starting ($table)."),
      'progress_message'  => t('Processed @current out of @total.'),
      'error_message'     => t('Feed has encountered an error.'),
      'file'              => drupal_get_path('module', 'batch_example') . '/batch_example.inc',
    );

    batch_set($batch);
}

the _import_csv_to_database_batch is a custom batch import by the book. But for some reason, when I run following cron function, the _my_custom_function() isn't even triggered...

function my_module_cron() {
    _my_custom_function();
    watchdog('my_module', 'feed cron');
}

So why is that and how can I configure my cron to trigger this?

Can you change:

function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');
    // Trigger Batch for import
    batch_set(_start_my_batch('myfile', 'mytable', $fields));
}

Into

function _my_custom_function() {
    // Define fields
    $fields  = array('field1', 'field2', 'field3');
    $function = '_start_my_batch';
    $batch = $function('myfile', 'mytable', $fields);
    // Trigger Batch for import
    batch_set($batch);
}

I think you should check every functions separately (hook_cron, batch function..) and make sure they work. After that put on the same place and play. The Example Module also is the very good place for doing this kind of stuff.


How to create dependent dropdown in drupal 7 content type? I have created a 2 custome content type in drupal 7 one is tourname and another one is location. Once I added a tour name in tour content type like tour1,tour2 and so on. In location content type I added location1, location 2 and so on for each tour name. Now I created third content type name it as details in that I need two drop down one is list of tour I have added and another one is list of location I have inserted. Whenever i changed the tour drop down value, the second drop down value will get automatically updated  based on the tour name.

Thanks in advance.

you need to create a tour and location used Node reference module. And automatically change the drop down  option value of location based on tour option value that you can use ajax .  following url help to u

Dynamic select list in the form (dependent dropdown)

https://api.drupal.org/api/examples/ajax_example!ajax_example.module/function/ajax_example_dependent_dropdown/7


create url with destination parameter and additional query string to views page with exposed filters I have a views page with several exposed filters.
I have created a link using a view php field as per below:

$url = '/admin/dashboard/applications/create/' . $row->nid . '?destination=' . current_path() . '&' . $_SERVER['QUERY_STRING'];
$link = 'App+';

This leads to a form page with a confirmation 'Submit' or 'Cancel' button.  The resulting URL on that page being something like this:

http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries&nid=&field_enquiry_fname_value=&field_enquiry_email_value=&field_enquiry_country_tid=&field_enquiry_campaign_id_value=&field_enquiry_emailed_value=0&field_enquiry_stage_1_tid=All&field_enquiry_enabled_value=1

When the redirect is done, the querystring after ?destination=admin/dashboard/enquiries is removed. I think this happens because it is not URL encoded.

I then tried url encoding the link as per below:

$query_string = array('destination' => current_path() . '&' . $_SERVER['QUERY_STRING']);
$url = url('admin/dashboard/applications/create/' . $row->nid, array('query' => $query_string));
$link = 'App+';

This creates the following url:

http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries%26nid%3D%26field_enquiry_fname_value%3D%26field_enquiry_email_value%3D%26field_enquiry_country_tid%3D%26field_enquiry_campaign_id_value%3D%26field_enquiry_emailed_value%3D0%26field_enquiry_stage_1_tid%3DAll%26field_enquiry_enabled_value%3D1

The issue now is that when the redirect is done back to the views page, views does not recognize the URL query and does not load the view, and falls back to the parent menu callback.

Instead of Trying to generate destination manually, can use drupal_get_destination(). So your above code would be like this:

$url = url('admin/dashboard/applications/create/' . $row->nid, array('query' => drupal_get_destination()));
$link = 'App+';

drupal_get_destination() gets the current path + encode the query strings and make them as destination. this will generate below URL:

http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries%3Fnid%3D%26field_enquiry_fname_value%3D%26field_enquiry_email_value%3D%26field_enquiry_country_tid%3D%26field_enquiry_campaign_id_value%3D%26field_enquiry_emailed_value%3D0%26field_enquiry_stage_1_tid%3DAll%26field_enquiry_enabled_value%3D1

instead of your URL.

http://www.site.com/admin/dashboard/applications/create/154575?destination=admin/dashboard/enquiries%26nid%3D%26field_enquiry_fname_value%3D%26field_enquiry_email_value%3D%26field_enquiry_country_tid%3D%26field_enquiry_campaign_id_value%3D%26field_enquiry_emailed_value%3D0%26field_enquiry_stage_1_tid%3DAll%26field_enquiry_enabled_value%3D1

The difference is the encode of '?'. I have tested it in  local D7 installation.


how to add link to null path in menu in drupal 7 I have added superfish menu in menu bar in that one of the link have sub-link. How to add a sub-link with null path.

Please help me.

Thanks

You can use the Special menu items module.

  Features:

  User can create a new menu item and place either "<nolink>" or "<separator>" to the Path field, without quotes.
  "<nolink>" item will be rendered similar to a normal menu link item but there will be no link just the title.
  You can change HTML tag used for menu item
  "<separator>" item will be rendered to an item which is no link and by default title will be "-------".
  Breadcrumb of "<nolink>" will be rendered same as "<nolink>" menu item.
  CSS class "nolink" is added to "nolink" menu item.
  CSS class "separator" is added to "separator" menu item.


How to display elements responsively side by side using Bartik theme, similar to bootstrap grid? I am developing a module for Drupal 8, currently using the default Bartik theme. My module defines some pages through twig templates. As I am displaying several sections of a dashboard, I would like to show two DIVs next to each other side by side.

I am looking for something similar to the Bootstrap Grid. I am even thinking to just try to use Bootstrap inside my module regardless of the Drupal theme, as I used Bootstrap before but I am new to Drupal theming.

Is there some way the Bartik theme (or different Drupal 8 theme) provides to display elements responsively side by side?

I ended up working around it by extracting the relevant css classes of bootstrap into my custom css file. Now I can use the bootstrap grid without disturbing the normal Drupal theme:

.row {
  margin-right: -15px;
  margin-left: -15px;
  box-sizing: border-box;
}
.row:before, .row:after {
  display: table;
  content: " ";
}
.row:after {
  clear: both;
}

.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
  float: left;
  box-sizing: border-box;
}

.col-md-12 {
  width: 100%;
}
.col-md-11 {
  width: 91.66666667%;
}
.col-md-10 {
  width: 83.33333333%;
}
.col-md-9 {
  width: 75%;
}
.col-md-8 {
  width: 66.66666667%;
}
.col-md-7 {
  width: 58.33333333%;
}
.col-md-6 {
  width: 50%;
}
.col-md-5 {
  width: 41.66666667%;
}
.col-md-4 {
  width: 33.33333333%;
}
.col-md-3 {
  width: 25%;
}
.col-md-2 {
  width: 16.66666667%;
}
.col-md-1 {
  width: 8.33333333%;
}


Views 3 remove exposed filter programmatically I've got several node types each of them referenced to different taxonomy term vocabulary.
For category showing i use taxonomy_display module.

For example, we've got two categories: cues and billiard balls.

Cues has price from, price to and wood type filters.
But balls has no wood type filter.

So i need to remove wood type filter if taxonomy_term tid referenced to billiard balls vocabulary.

Thus, I need to remove one of many exposed filters programmatically.

function modulename_views_pre_view(&$view, &$display_id, &$args) {
  // Some custom logic wich field_info_instances checking ...
  $filter_field = 'filter_id';
  // Removes from everywhere where i can find filter or filters properties
  unset($view->display[$view->current_display]->display_options['filters'][$filter_field]);
  unset($view->display[$view->current_display]->handler->options['filters'][$filter_field]);
  unset($view->display_handler->display->display_options['filters'][$filter_field]);
  unset($view->display_handler->options['filters'][$filter_field]);
}

Filter field removes successfully, but I've got php notice:

  Notice: Undefined index: field_wood_reference_tid in function views_handler_filter_term_node_tid->exposed_validate()

Also i try to remove field in hook_pre_execute(), but with the same result:

function modulename_views_pre_execute(&$view) {
  $filter_field = 'filter_id';
  unset($view->display_handler->handlers['filter'][$filter_field]);
  unset($view->filter[$filter_field]);
}

Also try with override_option() method like here - http://groups.drupal.org/node/82219, but no result at all.

Any suggestions?
Pls help =)

Thanks to everybody for reply but I still has no answer.
Maybe something is not clear? =(

I would use hook_form_alter using unset on the form object as you are in your example for the element that you want to remove.


In drupal website how to create multiple sitemap for each content types? In Drupal how can I create multiple sitemaps for each content type?
Suppose I have a content type basic page. I want an sitemap.xml only for this content type. Is it possible?

There's now the module to do that: XML Sitemap per node type

The XML Sitemap Per Node Type module provides the additional context for XML sitemap module that allows creating sitemaps per content type.


The results within the page results do not lead to the nodes I do not know how to treat this problem with Drupal. I hope you can help me.

Suppose this. We have a glossary (Views), which shows the items of the content type called "Glossary".

I created a search engine Views, following these instructions.

Now, I open my website and try to find one of the words of my glossary site.

Result: Well, the results page returns the title of one of the nodes of content type "Glossary", good! If I click on that word, then word node (which belongs to the glossary) is displayed.

But I do not want the node is displayed. I want that word is displayed within the glossary. Glossary nodes should not be viewed independently.

Is it possible that the word shown in the results page glossary is leading the glossary, and not their respective node?

Thanks in advance.

Yes, you can change the link settings from within the field settings on the view (or, if you are rendering nodes, you will have to change it in the display settings or template files if you are showing teasers using default templates).

Once you've edited your view, you might consider using the Rabbit Hole module to further deal with unwanted Node views.


During installation, the 'set up database' phase was skipped. Is that normal? This isn't the first time I install Drupal 7 locally, but it is the first time that during installation the 'verify requirments' and 'set up database' phases were skipped.

I did have databases set up with the same name as the sites (testsite.localhost and testsite2.localhost). Is that why those steps were skipped?

I did look though the databases in phpmyadmin and it looks as though both installations were populated properly.

Did you perhaps already have a settings.php file in place with the database information already in it? If Drupal can find that, it will use that information instead of prompting you and creating a new settings.php file itself.


When can I, and when I can't rely on other module's classes to be loaded? I'm writing pluggable system. For a given name, I want to test if there is defined class pluginActionName. If it is, I want to create an instance of it. If it's not, I want to create an instance of pluginAction (parent class for all pluginAction* classes). That's the easy part, and Drupal unrelated.

Difficult about Drupal is to know when classes are defined. Can I rely on class_exists

in my .inc code outside actual class? no?
in initializers for static properties? no?
in static methods of my class? sometimes?
in dynamic methods of my class? yes?
in helper functions that will be called by methods? only if it would be OK in method?

In italics is what I figured out so far, but I'm not sure about this and I cannot figure out exact loading order to tell why it's the way it is reliably.

Drupal 7 introduces a code registry - an inventory of all classes and
  interfaces for all enabled modules and Drupal's core files. The
  registry stores the path to the file a given class or interface is
  defined in, and loads the the file when necessary. The registry loads
  classes and interfaces on demand, via php's built in class autoloading
  mechanism. Modules can now move all code for classes that are not
  regularly used into an include file, and Drupal will only load it on
  demand. This will cut down on the amount of code loaded per request,
  and reduce Drupal's memory footprint.

more info:

http://api.drupal.org/api/drupal/includes%21registry.inc/group/registry/7
http://drupal.org/node/350780
http://drupal.org/node/542202#files
http://php.net/manual/en/language.oop5.autoload.php


How to fix the useless 'favicon.ico page not found' log message? Why is Drupal looking for it in the root dir in first place? The favicon is always placed inside theme at sites/all/themes/mytheme/, but it's looking for favicon.ico inside home / dir.

When browsing website it spams the log error message in the Recent log messages page.

It's not really a Drupal bug, but a browser bug (I think Firefox might be a culprit)

The best way I found to fix it is to put:

<Location /favicon.ico>
  ErrorDocument 404 "No favicon"
</Location>

This code should work in your vhost file or should also work in the .htaccess file, see http://httpd.apache.org/docs/2.4/sections.html for more details


drush update - php.ini problem I am trying to update drupal using drush from Version 7.36 to 7.38 with >drush up drupal
the process finishes in 2-3 seconds stating update has successfully finished and a backup has been created.

As a result, drupal is still on 7.36 - no updates have been made.

but there is also an error stating  no php.ini found - and the created backup directory (where drush is looking for the php.ini) is empty:

(uiserver):xxxxx:~/kochlounge > drush up drupal
Update information last refreshed: Sa, 07/11/2015 - 16:07
 Name    Installed Version  Proposed version  Message
 Drupal  7.36               7.38              SECURITY UPDATE available

///some update-warnings snipped for readability

Do you really want to continue? (y/n): y

Source directory                      HERE COMES THE ERROR  [error]
/htdocs/drush-backups/db570947934/20150712144116/drupal/profiles/php.ini
is not readable or does not exist.

Project drupal was updated successfully. Installed version is now 7.38.
Backups were saved into the directory                                [ok]
/htdocs/drush-backups/db570947934/20150712144116/drupal.
Backups were restored successfully.

my drush status (snipped):

 PHP executable                  :  /usr/bin/php5.5-cli
 PHP configuration               :  /usr/lib/php5.5/php.ini /usr/bin/php5.5-cli
 PHP OS                          :  Linux
 Drush script                    :  /htdocs/.composer/vendor/drush/drush/drush.php
 Drush version                   :  7.0-dev

my .profile:

alias php="/usr/local/bin/php5.5"
alias php-cli="/usr/bin/php5.5-cli"
alias composer="php-cli ~/composer.phar"

export DRUSH_PHP="/usr/bin/php5.5-cli"
export DRUSH_INI="/usr/bin/php5.5-cli"
alias drush="~/.composer/vendor/bin/drush"

Has anyone got a clue as to why the update is not working, what may be wrong with the php.ini... ?
when trying to do updates for modules from drupal-backend, the site throws an error and goes in maintainance-mode.

Thank you!

Turned out that after a complete wipe and restore of my site the upgrade worked without that error.

Sorry, no idea what caused this in the first place!


Update issue of Drupal 8.34 Currently, there is a security issue of Drupal CMS, I'm using Drupal version 8.3.4, does the version 8.3.9 can solve the security issue released on March 28th, 2018 PSA-2018-001 (core highly critical release)?

I tried to update to version 8.5.5, but some of the modules did not work after an update. I got the error message "the website encountered an unexpected error. please try again later".

As you can read on https://www.drupal.org/project/drupal/releases/8.3.9 Drupal 8.3.9 fixes SA-CORE-2018-002 (and hence probably also SA-CORE-2018-001). However, there has been several later issues - see https://www.drupal.org/security - and only Drupal 8.5 is supported. Quote from the latest 8.5.6 release:

  Versions of Drupal 8 prior to 8.5.x are end-of-life and do not receive
  security coverage

In other words, you better upgrade to Drupal 8.5.6 and fix/upgrade the modules that no longer works.


Auto submit the user registration form I am customizing the user registration in the template file. I want to auto submit the registration form using Drupal code, or JavaScript code.

Does anyone know how I should achieve this?

Based on your question, I would recommend you use the devel module to auto-generate random users.

OR if you really want to auto-submit the user form (or any form) then attach JavaScript to the page that does so via #attached in a hook_form_alter or via drupal_add_js() or simply in your theme via a .js file included in your .info file.

The javascript would be as Eugene Fidelin has posted above – $('#user-register-form').submit();or potentially by extending the Drupal.behaviors object, which is recommended for a number of reasons I won't get into here:

(function ($) {

  Drupal.behaviors.myModule = {
    attach: function (context) {
      $('#user-register-form').submit();
    }
  };

})(jQuery);


Manage User Access by IP I am building an "Extranet" (Company Intranet, available both inside and outside our network).

What I want is three levels of authorization... Authorized (via LDAP AD), guest inside network and guest outside network.

Guest inside and Guest outside is where I'm getting hung up.

For users inside the network, I want "Public" stuff accessible (along with departmental stuff, depending on user signed in). For users outside the network I want a blank screen to show up until the user logs in (with proper AD credentials).

So a "Guest" inside the network should have access to stuff without logging in... a "guest" outside the network needs to log in before anything shows up.

I've seen some stuff that will "Ban" or "Whitelist" based on IP (since all the "inside" computers will be 192.168 or 10.10), but they don't seem to grant the ability to "greylist" (ban until logged in?).

I'm thinking maybe Themekey, with a separate theme for outside-unauthorized? Or would it be better to roll something up myself?

Rules might be what your looking for. you have to find a module that plugs into rules that can check ip.


Is it possible to display a Boolean field in a block using views? Using views,

I created a block that displays users that are online.
In order to allow users choose to appear online or offline, I added a Boolean field to the user account, which I subsequently used as a filter for the online users. All this works fine.

Now I need to find a way to have a form - (with the Boolean field as its only field) appear as an 'attachment' to the original block? In this way users can choose to appear offline without having to go to their user account page.

Please, is this possible using views,thanks.

Would a button do?

To do this you have to create a custom module, or add to an existing custom module.

First define your form. All you need is a submit button, and the value can be any label you want on the button.

function modulename_onlinevisibility_form( $form, &$form_state) {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Change my on-line visibility'),
  )
}

Then you need a submit handler for the form:

function modulename_onlinevisibility_form_submit(&$form_state) {
  global $user;
  $account = user_load($user->uid);
  $account->field_optout[LANGUAGE_NONE][0]['value'] =
    (isset($account->field_optout[LANGUAGE_NONE][0]['value'])
      && ($account->field_optout[LANGUAGE_NONE][0]['value'] == 1))
      ? 0 : 1;
  user_save($account);
}

This will switch the value of the boolean field turning it off if on and visa versa, for the logged in user. (Profile fields may not be included in the $user variable, so a full user object is loaded using user_load.)

Then in your view, add a footer using the Global: PHP type, and add the code:

<?php
print render(drupal_get_form('modulename_onlinevisibility_form'));
?>

This will place a button at the bottom of your view which will toggle the user's on-line visibility.

EDIT.

If you are using the Profile2 module, then the code for the submit handler should be changed to:

function modulename_onlinevisibility_form_submit(&$form_state) {
  global $user;
  $profile_type = 'main'; // substitute the machine name of the profile if you are not using the default
  $profile = profile2_load_by_user( $user, $profile_type);

  $profile->field_optout[LANGUAGE_NONE][0]['value'] =
    (isset($profile->field_optout[LANGUAGE_NONE][0]['value'])
      && ($profile->field_optout[LANGUAGE_NONE][0]['value'] == 1))
      ? 0 : 1;
  profile2_save($profile);
}

Profile2 profiles are not loaded by user_load.


Where is the file selection widget in Drupal code? If a content type has an image field then when the user creates new content, he is present with an image section on the form with a widget to "Browse" for a file.  Clicking it provides a pop-up window standard dialog box for selecting a file.  I would like to examine how this works to use it in a custom module, but cannot locate the code in the core modules.

The code to generate a field upload form element is in theme_file(). The code is very simple because all it does is to output an HTML file select form element. As explained in other answers, the files browsing dialog is provided by the web browser and, most of the time, re-uses the operating system native one.


Different 404 behaviour on custom URL For a client's website I have these URLs:

library
library/{category}

I have a ParamConverter to verify that {category} is correct and return the taxonomy term. And each URL requires a "view library" permission which anonymous doesn't have.

The client's requirements are that 404 errors redirect the user to the  login page if not logged in.

I created a RedirectOn404Subscriber event subscriber to handle the 404 and redirect as needed. (I have tested it with a logged-in user and can redirect using this.)

When not logged in the redirection works fine for any obvious URL error:

example.com/xxxxx

And works for these:

example.com/library
example.com/library/valid-category

But this does not redirect:

example.com/library/invalid-category

It generates the 404 error but does not hit the redirect code.

It's as if it's not executing the ParamConverter when it's wrong - but it can't know that until it's executed the code...

Clearing caches just prior to a test does not alter the behaviour.

UPDATED TO INCLUDE CODE

404 redirect...

  /**
   * Prevents this being called when it's not an HTML request.
   *
   * @return array
   */
  protected function getHandledFormats() {
    return ['html'];
  }

  /**
   * Specifies the priority of all listeners in this class.
   *
   * The default priority is 1, which is very low. To have listeners that have
   * a "first attempt" at handling exceptions return a higher priority.
   *
   * @return int
   *   The event priority of this subscriber.
   */
  protected static function getPriority() {
    return 750;
  }

  /**
   *
   *
   * @param GetResponseForExceptionEvent $event
   */
  public function on404(GetResponseForExceptionEvent $event) {
    if ($this->currentUser->isAnonymous()) {
      // Any 404 when not logged in, return to front page.
      $route_name = '<front>';
    }
    else {
      // Any 404 when logged in, return to base page for user.
      #$route_name = 'user.page';
      return;
    }

    $query = $event->getRequest()->query->all();
    $redirect_uri = Url::fromRoute($route_name, [], ['query' => $query]);

    $returnResponse = new RedirectResponse($redirect_uri->toString());
    $event->setResponse($returnResponse);
  }

403 redirect...

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    $is_anonymous = $this->currentUser->isAnonymous();
    $route_name = $request->attributes->get('_route');
    $is_not_login = $route_name != 'user.login';
    if ($is_anonymous) {
      if ($is_not_login) {
        $query = $request->query->all();
        $redirect_uri = Url::fromRoute('<front>', [], ['query' => $query])->toString();
      }
      else {
        // Do not redirect, this is an anonymous login.
        $redirect_uri = NULL;
      }
    }
    else {
      // Any 403 when logged in, return to base page for user.
      #$redirect_uri = Url::fromRoute('user.page')->toString();
      return;
    }

    if (!empty($redirect_uri)) {
      $returnResponse = new RedirectResponse($redirect_uri);
      $event->setResponse($returnResponse);
    }
  }

Pasting the code made me think about the problem in more detail.

It's a question of which gets sent first: 403 (Access Denied) or 404 (Page Not Found).

If it's a legal URL ("library" or "library/valid-category") but the user doesn't have access, they get a 403 and redirected.

If it's not a legal URL ("library/invalid-category") it gets reported as a 404 ... even though they don't have access anyway.

Makes sense.


I need to have my site visitors post comments even if they are not logged in as a member I need to have my site visitors post comments even if they are not logged in as a member in my drupal 7 site. How do I do that? or is it better to have them sign up so they can post comments?

You need to give the "anonymous user" role permissions to post comments. Go to admin/people/permissions and look for the Comment section. Check the box for "Post comments" for the Anonymous user role, then save the settings.

I would not suggest this unless you have good anti-spam measures in place. You can search drupal.org for modules in the Spam Prevention category to help with that. Otherwise, I would require users to sign in before posting comments.

Note that even when requiring users to sign in to post comments, you'll still likely run into spam. Couldn't hurt to look into the list of modules linked to above.


Drupal 6 administration menu like the one on Drupal 7 I build a lot of sites, mostly on Drupal 7, so when I have to use Drupal 6 I am totally lost on the admin options, (even using the administrative menu bar).

Since I can't find any module for this issue, I am wondering if I should give it a try to build a module myself to rename and rearrange the admin menu items, but I am not sure, if this is even possible or if that will cause any path issues in modules later.

Why not building your own menu with the most used functions and show it only for you? I do this all the time for D6 and D7.


How to define a custom menu and show it like an admin menu in Drupal 8? Question: How to define a custom menu and show it like an admin menu in Drupal 8 ?
Goal:
First of all, we have a custom administration theme where we are looking for a custom toolbar solution that stays visible for an "simple" user on the front and backend when logged in.
There is a need for a toolbar at top of page similar like the toolbar module in Drupal 8 core.
We want the following links shows to a user :

Back to site
User with possibility to view and edit their profile
Logout
The Edit option for edit content from the front of the site

Screenshot of the goal :

Research:
I have found there are several solutions for Drupal 7 with modules like Admin menu source, Webmaster menu and with Block Class styles module. But none of them is compatible for using in Drupal 8.
Expected solution:
This custom toolbar should only be for specific user roles("user") showed.
I will do this by creating an custom module but I'm not really sure if I need to inherit from the toolbar core module in Drupal 8.

A complete new toolbar
OR

I can work further on the default toolbar module in Drupal 8 but
there is a need for 2 things: add item "boutique" as example that is
decribed as an answer but also remove an item from the default
toolbar like Devel or Manage tab included the sub links from these items.
Are the two things together not possible then I prefer for creating a
completely new toolbar module from scratch for Drupal 8.

Recap:

Not hide or show items based on permissions
Not just adding items to the default drupal 8 toolbar module

Is that possible ? Are they better/other methods for achieving this goal ?

This is how i add custom menu :

In a custom module :

  xxxx.module :

/**
 * Implements hook_toolbar().
 */
function xxxx_toolbar() {
    $items = [];

    $items['Boutique'] = [
        '#cache' => [
            'contexts' => ['user.permissions'],
        ],
    ];

    if (!\Drupal::currentUser()->hasPermission('Access the Commande overview page')) {
        return $items;
    }

    $items['Boutique'] += [
        '#type' => 'toolbar_item',
        '#weight' => 1,
        'tab' => [
            '#type' => 'link',
            '#title' => 'Boutique',
            '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/commandes"),
            '#attributes' => [
                'title' => 'Boutique menu',
                'class' => ['toolbar-icon', 'toolbar-icon-boutique'],
            ],
        ],
        'tray' => [

            'configuration' => [
                '#type' => 'link',
                '#title' => 'Commandes',
                '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/commandes"),

            ],[
                '#type' => 'link',
                '#title' => 'Livraison',
                '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/livraison"),

            ],
            [
                '#type' => 'link',
                '#title' => 'Configuration',
                '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/configuration"),

            ],

        ],
        '#attached' => array(
            'library' => array(
                'boutique/admin',
            ),
        ),

    ];
    return $items;
}

And the result :

You can manage access with :

  if (!\Drupal::currentUser()->hasPermission('Access the Commande
  overview page')) {
          return $items;
      }

in the xxxx.module like me.


convert to db_query and addExpression Is there a way convert this static query in a dynamic query?

$sql = "SELECT n.nid, n.title, n.created, n.type, n.status, IF((SELECT nid FROM `newsletter_lists` WHERE cid=$cid AND nid=n.nid), TRUE, FALSE) AS included FROM `node` AS n
  LEFT JOIN `newsletter_lists` AS nl ON n.nid = nl.nid";

This is what I have, but it throws errors.

$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'created', 'type', 'status'))
  ->extend('PagerDefault')
  ->limit(5);

$subquery = db_select('newsletter_lists', 'snl')
  ->fields('snl', array('nid'))
  ->condition('cid', $cid)->condition('nid', `n.nid`)
  ->execute();

$query->addExpression($subquery, 'included');

return $query->execute();

The problem is that addExpression() doesn't take a SelectQueryInterface as a parameter, but only a string:

  $expression: The expression string. May contain placeholders.

So the best you're going to be able to do is add the expression as a manual string. As the argument description suggests placeholders are fine so you can at least keep a bit of structure.

$query = db_select('node', 'n')
    ->fields('n', array('nid', 'title', 'created', 'type', 'status'))
    ->extend('PagerDefault')
    ->limit(5);

$expression = 'IF((SELECT nid FROM `newsletter_lists` WHERE cid= :cid AND nid = n.nid), TRUE, FALSE)';

$query->addExpression($expression, 'included', array(':cid' => $cid));

return $query->execute();


Role specific dashboard block I created a set of Views based blocks which will be displayed in the Dashboard's Main Content Region.But those all of them are not for the site admins. Some of them are for other roles. So I have configured those blocks' visibility settings. Added those specific roles to the "Show block for specific roles" tab. But the problem is those are being displayed in the admin dashboard as well but with no content, actually it says "empty".

Is there any way to get rid of this?

A possible duplicate but no answers in that post as well.
Dashboard - empty blocks are shown

One way to hide the blocks completely without doing any coding is to set up your own custom dashboard using the Panels module.  With Panels, you can override pages (such as the admin dashboard) and then add the blocks using Panels.  The advantage of this approach is that you can use the Visibility conditions feature of Panels to only show the block for certain roles, which will completely hide the block rather than showing an empty version.

The disadvantage of this approach is that this might be overkill if this is all you need to do.


How to call a controller of custom module when a node is published? I am planning to make a module whose controller is called or method in that controller executes when a node is published. The module should be able to get the title and other properties of article that is set to published. Here is controller:

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class myController extends ControllerBase
{
    //Function that should be executed when a specific node is published
    public function publish()
    {
     //here I should get title and other properties of the published node
    }
}

I am new to drupal, I have looked into web and found that the solution is related to hooks but I don't know how to use them. Any help regarding the issue will be appreciated.

The purpose of controllers is just providing output for a route, not implementing hooks. If you need to write code that is invoked when a node is published, you need to implement one of the following hooks:

hook_ENTITY_TYPE_presave(), invoked right before the entity is saved
hook_ENTITY_TYPE_update() (invoked after an entity is updated and saved in the database) and hook_ENTITY_TYPE_insert() (invoked after an entity is created and saved in the database)

hook_node_presave(), hook_node_update(), and hook_node_insert() get a Node object as parameter, so obtaining the body value is pretty easy.

use Drupal\node\Entity\Node;

function mymodule_node_presave(Node $node) {
  $body = $node->get('body')->value;
  $summary = $node->get('body')->summary;
}

Getting the taxonomy term from a reference field of a node can be achieved with code similar to the following one.

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

function mymodule_node_presave(Node $node) {
  $term = Term::load($node->get('field_tags')->target_id);
}

To that, you need to add the code to verify the node has been published.

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

function mymodule_node_presave(Node $node) {
  if ($node->status()) {
    // The node has been published.
    $body = $node->get('body')->value;
    $summary = $node->get('body')->summary;
    $term = Term::load($node->get('field_tags')->target_id);
    $term_name = $term->getName();
  }
}

If the taxonomy reference field is not field_tags, replace field_tags with the right machine name of the field.


How to edit Commerce to display more than 3 products in a row I'm using Commerce Kickstart, I am not able to figure out how to display more than 3 products in a row. Even if I created a new View mode using Entity View Mode it still behaves the same.

How shall I go about changing this? Is there a setting somewhere in the View UI that's controlling this?

Thanks very much!

Think I found a way to resolve this simply via CSS.

There is this styles in global.css:

  .page-products .view-display-products li:nth-child(3n+4) {
      clear: left;
      /* LTR */
      float: left;
      /** LTR */ }

so we can overwrite it with a sub-theme CSS with "clear:none".

By re-sizing browser window, looks like it still works well when window get smaller.

Earlier on didn't quite look close enough into this, partly due to meddling too  much in Views Format settings. So assuming reverting to default Views setting, the above CSS change should work fine. Will update again if otherwise.

BK :)


Rss Feed Page Customization? I added a views adn feed type display for news. I want to customize the rss page. Currently it displaying like this :

<channel>
    <title> </title>
    <link> </link>
    <description></description>
    <language> </language>
          <item>
    <title> </title>
    <link> </link>
    <description> </description>
     <pubDate> </pubDate>
 <dc:creator> </dc:creator>
 <guid isPermaLink="false"> </guid>
  </item>
</channel>
</rss>

When i check it in firebug it includes in <pre> tag. But i want to customize it by css how to do that? How to remove <pre> tag?

There's a few issues confused into here based on the original question. I'll try to take these one at a time:

1 Is RSS the same as HTML?

No, these are different markup languages. RSS is a dialect of XML designed for syndicating content from podcasts, blogs, etc, etc. HTML is a web page specific markup format. In your question you mentioned that firebug is showing a <pre> tag in RSS feed, but this is impossible because <pre> is HTML only, and will never appear as RSS.

2 How can I style an RSS feed?

Typically, you don't need (or want) to do this. RSS Readers typically apply formatting to your RSS content, and if you change the formatting this could get confusing and ugly for your end users. Just as there are many browsers for HTML, there are many RSS REaders for RSS including iTunes, online services, Mozilla Thunderbird and hundreds of others. So, I recommend NOT styling your RSS feed.

However, if you need to style an RSS feed you can do using regular CSS by adding this tag to beginning of your RSS feed:

<?xml-stylesheet type="text/css" href="http://example.com/rss.css" ?>

Then you would need to create a css file called rss.css in the appropriate place on your server. Here's a great article that goes more in depth on this:
http://www.petefreitag.com/item/208.cfm

3 How do I get Drupal to modify my RSS feed to include CSS?

This is really a great question, and a lot of people struggle with this. What makes this hard is that in Drupal 6 and 7 only HTML can be "themed", so many of the normal hooks that work on nodes which appear as HTML do not work on RSS feeds. What's also really anooying is that Drupal will escape all your HTML markup and put it inside your RSS feed, making your RSS feed nearly unreadable.

If it doesn't exist already, create a new folder called template inside your theme folder. Add a new file inside that folder called views-view-rss.tpl.php. This file will affect all your RSS feeds. Add this code inside views-view-rss.tpl.php:

<?php
/**
 * @file
 * Default template for feed displays that use the RSS style.
 *
 * @ingroup views_templates
 */
?>
<?php print "<?xml"; ?> version="1.0" encoding="utf-8" <?php print "?>"; ?>
<?php print "<?xml"; ?> type="text/css" href="http://example.com/rss.css" <?php print "?>"; ?>
<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?>>
  <channel>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $node->body['und'][0]['value']?></description>
    <language><?php print $langcode; ?></language>
    <?php print $channel_elements; ?>
    <?php print $items; ?>
  </channel>
</rss>

For more details on this: https://drupal.org/node/1884558

4 How do I remove a specific tag from my RSS feed?

It depends on where the tag is appearing in your view. I assume it's showing up inside <item> tag somewhere. In the file you created earlier, change:

    <?php print $items; ?>

to:

    <?php print str_ireplace(array('<pre>','</pre>'), '', $items); ?>

Make sure to clear the cache.


SelectQuery, db_query() and pager I have a long query with sub-queries using db_query().
So far I know SelectQuery of D7 comes with Extenders. Example extenders are PagerDefault (replaces Drupal 6 pager_query()).

I need my query with pager. Can I use PagerDefault with db_query()?
If I have to use db_select() for pager, how can I implement my query with sub-queries using db_select()?

$result = db_query("SELECT leg.*,
    ( SELECT COUNT(*)
    FROM {field_data_field_leg}
    WHERE field_leg_nid = leg.nid AND bundle = :bundle ) AS reviews
FROM
    ( SELECT
        n.nid, n.created, title, field_from_value origin, field_to_value destination,
        field_price_value price, term.name transport
    FROM {node} n
        JOIN {field_data_field_leg} l ON n.nid = l.field_leg_nid
        JOIN {field_data_field_from} ff ON n.nid = ff.entity_id
        JOIN {field_data_field_to} ft ON n.nid = ft.entity_id
        JOIN {field_data_field_transport} t ON l.entity_id = t.field_transport_nid
        JOIN {field_data_field_price} p ON t.entity_id = p.entity_id
        JOIN {field_data_field_transport_type} ttype
            ON t.field_transport_nid = ttype.entity_id
        JOIN {taxonomy_term_data term} ON ttype.field_transport_type_tid = term.tid
    WHERE n.type = :type
    ORDER BY n.created DESC, field_price_value ASC
) AS leg
GROUP BY nid
ORDER BY created DESC",
array(':bundle'=>'review', ':type' => 'leg'));

The short answer is that subqueries is not possible with db_select(), and pagers are only created through the query builder, either SelectQuery or EntityFieldQuery.

So you can't the above query and utilize Drupal's pager system, you would have to manage the pager yourself if you want the above query, or rewrite the query into several queries.


Why does the core search module not index node titles? The search results only show terms in the body if that. Take the example of a product site. There is a product called Funkywidget with a description that has Funckywidget written twice in it. However, the core search module does not show any results for Funkywidget. It has a record in the search_index table but doesn't show when typed into the search form.

What is the best way to enable people to find a Funkywidget?

There is a product called Funkywidget

If the title of the node is "Funkywidget" it's searchable by that term. If you want to incorporate search terms that aren't in the node's fields, you should look at more complex search solutions like Apache Solr.

See here: http://api.drupal.org/api/drupal/modules--node--node.module/function/_node_index_node/6
The title is added to the search string that's going in the db.

$text = '<h1>' . check_plain($node->title) . '</h1>' . $node->body;


How to trim body text (field_body)? I've created a view for a node which shows the content as rendered entity. Among others, I output the body field in the twig template:

{{ content.field_body }}

Now, I'd like to limit the text to 200 characters and put three dots. I've tested three different ways to do that, but nothing has worked. The problem is, that each way counts and trims the HTML characters too.

1: I've added the format "Trimmed" in "Manage display" => The text is limited but not correct. And I do not have the three dots.

2: I've trimmed the text in the twig template. But to count the text I have to render it first. Thereby, twig outputs the text as HTML (I see HTML tags on my page!)

{% set text = content.field_body|render %}
{{ text|length > 200 ? text|slice(0, 200) ~ '...' : text }}

3: I've tried to solve the problem in template_preprocess_node(). Here I have the same problem with counting the HTML markup too.

$body_text = $node->get('field_body')->getValue()[0]['value'];
$trimmed_text = substr($body_text, 0, 200) . '...';

How can I trim my text right?

Thank you very much for your help!

There's a few solutions you can try but take note truncating strings with html is generally a bad idea due to having potential unclosed or malformed tags.

1. Use |raw to output the html as html, may produce malformed tags:

{% set text = content.field_body|render %}
{{ text|length > 200 ? text|slice(0, 200)|raw ~ '...' : text|raw }}

2. Strip html first, cleaner:

{% set text = content.field_body|render|striptags %}
{{ text|length > 200 ? text|slice(0, 200) ~ '...' : text }}

3. Register a twig extension (untested):

https://gist.github.com/leon/2857883

Another helpful extension you can check out is the Text extension, which helps you prevent chopping up words:

http://twig.sensiolabs.org/doc/extensions/text.html


Create a link in hook_mail_alter() I am using hook_mail_alter to modify the email that the user gets when an administrator creates an account. What I am trying to do is create a link in the email body, the link gets created but it adds a [1] to the link text and after the email text is done. There is the [1] again with the actual link. Is there anyway to actually have the link created in the text instead of having it render at the end? Here is my code:

function my_module_mail_alter(&$message) {
if ($message['id'] = 'user_register_admin_created') {

    $url = Url::fromUri('https://www.google.com');
    $external_link = \Drupal::l(t('Google'), $url);
    $message['body'][] = t("Go to: ");
    $message['body'][] = $external_link;
}
}

That happens because the class normally handling the email sending (PhpMail) uses the following code, in PhpMail::format().

  // Convert any HTML to plain-text.
  $message['body'] = MailFormatHelper::htmlToText($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = MailFormatHelper::wrapMail($message['body']);

In particular, this is the code handling the links. (See the comment before the code.)

  // Replace inline  tags with the text of link and a footnote.
  // 'See the Drupal site' becomes
  // 'See the Drupal site [1]' with the URL included as a footnote.
  static::htmlToMailUrls(NULL, TRUE);
  $pattern = '@(]+?href="([^"]*)"[^>]*?>(.+?))@i';
  $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  $urls = static::htmlToMailUrls();

To send HTML emails, you need a different class implementing MailInterface. The Swift Mailer module implements it, for example, and allows to send HTML emails; it also allows to select in which way to send a message (server SMTP, MTA agent, mail() function).
The Mail System module provide a UI that allows to select the mail plugin used to send emails, so you don't need to mess with the configuration to do it.


Redirect on returning to site In my site when a user logs in he is redirected to the profile page(profile2 module). But when returns to the site(and is already logged in), he is taken to the user account page. How do I override this redirect and see to that he is take to profile page?

UPDATE:
The user must be redirected from the site frontpage which contains the user login form

You can use Rules module, force user to redirect to whatever page after login. It's very easy to get it done via the Rules UI, try it out. http://drupal.org/project/rules


LDAP authentication module not working in xampp When i enabled LDAP module for drupal 7 then always shows error
No LDAP PHP Extension is loaded for PHP, so LDAP will not work properly.
even  after un comment extension=php_ldap.dll from my php.ini, it is not working.i restart apache and php_ldap.dll is also in php extensions.

Yes i have sorted out this issue.
In the \xampp\php folder you will find this file:libsasl.dll
Copy it into the \xampp\apache\bin folder.
Now try and start Apache again.It should now start.Now it is working.


Is it possible to change the layout of the registration form using display suite? My registration form contains the following fields
-Name
-City
-Mobile
-Email
-Password
-Confirm Password
-Terms and Conditions (using legal module)

Is there some way to change the layout? I want it to appear something like this

************** ***************
*   TERMS    * *   Name      *
*     &      * *   City      *
*   COND.    * *   Mobile    *
* ************ *   Email     *
*   Submit   * *   Password  *
************** ***************

Sorry, I don't think it is possible with display suite on its own but you may find this link helpful Changing the layout of user profile edit page. Display suite appears to only get you some of the way there.


Feeds importer. Only imports a certain amount then stops I have been attempting to import 5,000+ pieces of content from a CSV file using the feeds module. I have it set up to import 130 items every cron run and i have cron running every hour.

All is good for the first few hours. I go to sleep and then wake up, and it is no longer running.

I have my cache clearing every 6 hours. is it possible that clearing cache kills the communication with feeds and stops the import record?

Is it a simple setting change within feeds?

I cannot monitor it completely to see when this issue stops exactly since my imports are suppose to be spread over 48 hours on each hour.

Update: If I run cron manually over and over again, it will reach 100%.

you can check your php config php_memory_limit must be at least 128M and max_execution_time 120

also check the error logs go to admin/reports/dblog and check for the errors logged by the server, maybe you can find the problem there

Also make sure you are getting all the errors so you can make a better debug in your issue

Change settings in your site

You can show all errors by adding a few lines to your local testing site's settings.php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
//Note:  Do not include the opening and closing PHP tags when you copy this code

In addition, navigate to Administration→ Configuration→ Development → logging and errors and select "All messages". (This sets $conf['error_level'] = 2; .)


How to create multi select within select box in views expose filter in Drupal? I have created a view with exposed filter. It's working correct. But I need to use select box in exposed filter with multiselect.

User Better Exposed Filter, this module will give exact thing.

ok then in  Exposed form style -> BEF Settings ->


Ckeditor link text to file I'm creating a content type on Drupal 8, which will contain a text that's linked to PDF file.

In Drupal 7, it was just easy with some useful modules. Is it possible to link a text to a PDF file using CKEditor in Drupal 8?

This Drupal 8 module does exactly that, in a tightly integrated way: https://www.drupal.org/project/editor_file


How to access all of the properties related to Commerce Line Item entity in a rule? I wonder how I can access all of the line item properties in Rules?

For example in a Rules event "Before saving a line item" I can show a debug message of the line item.
It has different properties such as commerce_display_path and data->context->entity which however aren't available in Rules ie. I cannot set them as variable for later processing.

How could I make these properties available to Rules? I've tried to add different conditions to make sure the "whole entity" is loaded to Rules but still I cannot access these properties.

EDIT 1

I've now tried to develop a solution to provide this data to Rules.
Following enables only entity(field collection item) id and entity revision and nothing else. I thought that it would provide the whole entity and it's properties (or at least so I understood from documentation that all that entity__property_info returns).

EDIT 2

Now I can set a message on site that presents host entity properties. However, I cannot use those properties in any other rules functionality eg. I cannot create variable from field regarding field collection item i.e. I still cannot make use of them. Why the properties are available for message but not for anything else?

function mymodule_entity_property_info_alter(&$info)
{
  if (isset($info['commerce_line_item'])) {
    $info['commerce_line_item']['properties']['host_entity'] = array(
      'label' => 'Host entity',
      'type' => 'field_collection_item',
      'description' => t('Host entity of a line item.'),
      'getter callback' => 'mymodule_get_host_entity_callback',
      'setter callback' => 'entity_property_verbatim_set',
      'computed' => true,

    );

 $bundles['field_collection_item'] = array('label'=>'Field collection item', 'properties'=>entity_get_all_property_info('field_collection_item'));
    dpm($info['commerce_line_item'], 'line item in entity info alter');
  }
}

function mymodule_get_host_entity_callback($entity, array $options, $name, $entity_type)
{
  dpm($entity, 'line item entity in Rules callback');
  $wrapper = entity_metadata_wrapper($entity_type, $entity);

  $host_entity_id = $wrapper->data->context->entity->entity_id->value();
  $host_entity_type = $wrapper->data->context->entity->entity_type->value();

  $host_wrapper = entity_metadata_wrapper($host_entity_type, $host_entity_id);
  $host = $host_wrapper->value();

  return $host;
}

function mymodule_set_host_entity_callback($entity, array $options, $name, $entity_type)
{
  $wrapper = entity_metadata_wrapper($entity_type, $entity);

  return $wrapper->host_entity->value();
}

Below is a possible approach you can use to solve your question. It provides the details about how I was able to have a set of Drupal messages being shown at checkout time, which look similar to this testcase I used (for a cart with 3 line items):

Current line item has label 'USB-BLU-08' and id '17'
Current line item has label 'TSH4-BLK-MD' and id '18'
Current line item has label 'MES1-BLU-OS' and id '19'

To get this to work, I created a custom rule, which looks like so (use the Rules UI to import it in your own site):

{ "rules_access_line_items_at_checkout" : {
    "LABEL" : "Access line items at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } }
          ]
        }
      }
    ]
  }
}

Some details about it:

Rules Event: After completing the checkout process.
Rules Condition: none.
Rules Action: Create a loop, to iterate over each line item. And for each line item, show a Drupal message, starting with "Current line item has ...". Obviously, at this point you could display any of the properties related to a line item.

Easy, no?

PS: I'm assuming this question is about D7 ...


How to add Span before my <a tag only for main menu 1st level items I need to add a span tag before mt

if i add like

function mytheme_link($variables) {
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

it will add for all the menus

and if i use

function mytheme_menu_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }

  $link['localized_options']['html'] = TRUE; //let l function know that our link title includes html
  return ''.l($link['title'], $link['href'], $link['localized_options']).'';
}

it does not add at all.

you have forgotten the '#' before localized_options, title & href.

function mytheme_menu_link($link) {
  if (empty($link['#localized_options'])) {
    $link['#localized_options'] = array();
  }

  $link['#localized_options']['html'] = TRUE; //let l function know that our link title includes html
  return '<span>'.l($link['#title'], $link['#href'], $link['#localized_options']).'</span>';
}

for main menue only use theme_menu_link__main_menu($var)


How to correctly add meta tags to custom menu items? I want to be able to use the meta tag module for everything my site, but currently I have no idea how to add meta tags to custom pages. For example, I have this page:

function mymodule_menu()
{
    $items = array();
    $items['home'] = array(
      'title' => 'Home',
      'page callback' => 'mymodule_home_page',
      'access callback' => TRUE,
    );
    return $items;
}

function mymodule()
{
    $o = '';
    $o .= 'hello world';
    return $o;
}

Such a page doesn't get meta tags as it is a custom page. What is the best way to get meta tags on the page in this case? Or what is wrong with my strategy?

You can do this manually by using drupal_add_html_head(); in your menu's callback function

<?php

function mymodule_home_page() {

  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'custom meta info',
      'content' => 'test content',
      'attributes' => 'D7',
    ),
  );
  drupal_add_html_head($element, 'Test');

  return 'hello';
}
?>

or some modules will allow you to add custom paths.


how to change widget type of title field in content type Drupal 7 I am trying to change the widget type for title field in content type (currently it's a text field as default). Now I want to change to node reference.

i think, it is better to remove the original field 'title' and create new field for node reference type, use:

<?php
    function your_module_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'your_node_form'){
            $form['title']['#access'] = FALSE;
        }
    }

?>


How do I specify the custom template for a theme? Instead of page.tpl.php, How can I use a custom template in theme? I am using the Zen theme.

In Drupal 6, we will specify it in the theme_preprocess_page(), using the $vars['template_files'][] array. I don't know what to use in Drupal 7.

The equivalent in Drupal 7 is $variables['theme_hook_suggestions'], which is initialized in template_preprocess_page() using the following code:

  if ($suggestions = theme_get_suggestions(arg(), 'page')) {
    $variables['theme_hook_suggestions'] = $suggestions;
  }

If you want to add suggestions for the template files to use, you should append new suggestions using code similarly to the following one ($variables is the parameter passed to the preprocess functions):

$variables['theme_hook_suggestions'][] = "page__new_suggestion";

You can also add your suggestions before the existing ones, to be sure the template file you are suggesting is used whenever other template files exist.

array_unshift($variables['theme_hook_suggestions'], "page__new_suggestion");

Clearly if the template file your code suggests doesn't exist, one of the other template files will be used.
It is also suggested to prepend the template filename with the type of the template, in this case with "page__"; the underscores used in the suggested filename are converted in hyphens before to check if that file exists.


How to add only unrefered node of a content type in an entity reference field of another content type There are 2(two) Node types

A
B

A has a node reference field to node type B.

If a node x of A type used a node y of B type as a node-reference then next time node z of A type will not use the node y of B type as a node-reference because x is already used as node-reference.

The Entityreference unique sounds what you're looking:

  This modules adds a checkbox to an entity reference instance to enable a check for unique multiple entity reference fields. With this option enabled it is not possible to add one and the same entity to a multiple entity reference field.


Alter view plugin form in custom module files I'm looking for the right method to modify an especific plugin views ui inside a custom module. The views plugin to alter is created by the module https://www.drupal.org/project/views_json_source
I want to hide the "json file" field, in the query options. And when the view is executed i want prefill this field with config data from my custom module.
Later i will need to create my custom exposed form using the json fields, but this is another story.
I think the right way is using the hook_views_plugin_option_definition_alter, but i've tested it in my module and it dont make nothing (drupal messages are not displayed).
The views json source have an plugin/views/query/ViewsJsonQuery with this code:
public function buildOptionsForm(&$form, FormStateInterface $form_state) {

  $form['json_file'] = [
    '#type' => 'textfield',
    '#title' => $this->t('JSON File'),
    '#default_value' => $this->options['json_file'],
    '#description' => $this->t("The URL or path to the JSON file."),
    '#maxlength' => 1024,
  ];

}

Somebody can help to the right way?
Thanks in advance.
PD.: I'm using Drupal 9.

Finally i've created an customized views_json_source module adapted to my requirement. Anyway, it would be interesting if somebody can ask the question.


Embedding Javascript in Content or Block Causes Misalignment of Regions / Overflow When embedding Javascript, the content area seems to "overflow" past its container. I am pasting an example of how embedding Tweets can cause this problem. The content shouldn't be extending into the dark green area.

I am new to Drupal, but have basic web programming experience. Should I be looking at CSS rules for this? Could it be a quirk with a theme setting? Many thanks for any leads!

For reference, right now Tweets are being embedded by pasting this code block into the content (with Full HTML enabled):

TEXT & SUCH FROM TWITTER

Note that I intentionally pasted the same tweet twice so that it would better illustrate the problem.

Edit: Interestingly, the problem seems to resolve itself if I press "alt" while in Chrome or Firefox. The page seems to re-render slightly, filling in white space on the right. Perhaps this is because CSS is usually executed before JavaScript when rendering pages? I noticed this after bring up the inspector tool, which seemed to fix the problem.

Yes, CSS is the way to go with this. I had a similar problem with a twitter feed in a block. Using Chrome developer tools, I just targeted the twitter content without making adjustments to the block.

You definitely don't want to mess with the JavaScript if there isn't an option in your script tag.


Hook for module activation and deactivation I am trying to execute a function in my module when the module is activated or deactivated by the user. It seems that there is a hook for this in Drupal 7, but not in Drupal 6. It is possible to do this with a workaround in Drupal 6?

The docs say that hook_enable() and hook_disable() are for versions 5-7.


How to create a renewal request from the subscription page? I have 2 content types: a subscription and a renewal_request.

I would like to have the possibility for the user to create a renewal request from the subscription page (or from a view of subscriptions using VBO).

The renewal needs to be a content type, as there is a workflow associated to it (manual verification of user details).

What would be the best solution?
Create a link passing the nid of the subscription and use the Entityreference Prepopulate module? Or overriding the form?

If I understand your question correctly, you are using the Entity reference module on you subscription content type to point to a (new) node of the type renewal_request.

The Entity connect module extends the Entity reference field by providing an add and edit button:

  The "add a new" button will enable you to add / create a new entity. The first  form will be cached then the new form will be generated. Once the new form is  completed and saved the user will return to the original form.

  The "edit" button will take the user to the edit form of the referenced entity. Once the user is done editing, he is sent back to the previous form.

You could also use the Inline Entity Form module:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.


Programmatically adding fields to specific vocabularies Is it possible to add fields to vocabulary terms programmatically in a custom module?

I know it can be done at admin/structure/taxonomy/news_client_sites/fields in the UI, but I'd like to add the fields during the module install process.

I have specific vocabularies I've created during hook_install, but I'd like to be able to add fields to them as well.

It turns out that with taxonomies, vocabularies are bundles of taxonomy_term entities.

So, it turned out to be something like this:

Assuming a taxonomy machine name of example_taxonomy

  $field_example = array(
    'field_name' => 'field_example',
    'cardinality' => 1,
    'type' => 'text',
  );
  field_create_field($field_example);

  $field_example_instance = array(
    'field_name' => 'field_example',
    'label' => st('Example Text Field'),
    'bundle' => 'example_taxonomy',
    'entity_type' => 'taxonomy_term',
    'widget' => array(
      'type' => 'text_textfield',
    ),
  );
  field_create_instance($field_example_instance);

So, yeah, it turns out that taxonomy_terms are the entities and vocabularies are the bundles...


Display value not key of list after loading of node I've created a controller and I'm loading a node.

$variables['contest'] = Node::load(12);

return [
    '#theme' => 'theme_contest',
    '#variables' => $variables,
];

In this node there is a field "field_contest_things" of type list (text):

0|Dance
1|Read
2|Playing

In the twig file if I'm doing

{{ variables['contest'].field_contest_things.value }}

this will display the key and not the "value".

Is there any way that I can display the value and not the key in the twig ? Or should I change something in my controller ?

Thanks

If your field allows only 1 value, you can do it in both ways, i.e Controller or Twig :

Controller

$node->field_contest_things->getFieldDefinition()->getSetting('allowed_values')[$node>field_contest_things->value];

Twig

{{ node.field_contest_things.fieldDefinition.settings['allowed_values'][node.field_contest_things.value] }}

Update

You can now skip the usage of fieldDefinition on the latests Drupal 8 updates:

{{ node.field_contest_things.setting('allowed_values')[node.field_contest_things.value] }}

By experience, I suggest you to move for a taxonomy if you need to query your node by this field value on the future. It's more maintainable & scalable.

Hope it helps you !


How to get a field value of multiple nodes? I have some node ids from entityfieldquery. I would like to get the values of a field from all of these nodes. Should I use db_query, or should do a node_load_multiple, and get the field value with a foreach? db_query seems more efficient.

You can use field_attach_load() which will load the fields for a group of entities. You can also pass in the field_id value so it doesn't load unnecessary fields. I benchmarked field_attach_load() against entity_load() (which is what node_load_multiple will call) and the former was approximately ten times faster.

Here is an example:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'post')
  ->propertyCondition('status', 1);
$result = $query->execute();

if (isset($result['node'])) {
  // field_attach_load() requires entities to be passed on it with the bundle
  // and the ID instead of just IDs. We need to add these values to the result
  // of EntityFieldQuery()
  foreach ($result['node'] as &$node) {
    $node->bundle = $node->type;
    $node->id = $node->nid;
  }
  field_attach_load('node', $result['node'], FIELD_LOAD_CURRENT, array('field_id' => 'body'));
}


Redirect .com domain to .dk/en I have a site; www.example.net. If you type www.example.com it redirects to www.example.net which is okay.

On my site i have to different language prefixes /da and /en that you can switch between.

My question: is it possible to redirect all who try to visit the site via www.example.com to www.example.net/en?

In your .htaccess,

RewriteCond %{HTTP_HOST} www.example.com
RewriteRule ^ http://www.example.net/en [R,L]

Where www.example.com is your old domain and www.example.netis the new one.