Views - Add a wrapper around fields or rows Example:

I have a view with fields:

[field_name]    == Field collection item: Name
[field_title]   == Field collection item: Title
[field_text]    == Field collection item: Text

I can wrap these fields by excluding from display first two of them, and rewriting the output of the third field with tokens, for example:

[field_text]

[field_name] // [field_title]

It seems a bit tricky, so here is my first question:

Is there any module or just another way to wrap fields in views?

I know Semantic Views module which solve the problem, but there is no recommended releases for Drupal 7.

Question #2

All my fields are wrapped in their div like in above mentioned example, but this is only the one row, and I have several rows. I need wrap all of them in another div.

Do I have to create a view template file only for that? which contain for example:

<?php if($rows): ?>

        <?php print $rows; ?>

<?php endif; ?>

I have a feeling like I miss something when I have to create a special template file only for one wrapper.

I think it's pretty safe to say that most people tackle both of your questions using the Cascading features of CSS.

For example, a typical view's HTML looks somewhat like this:

So, to your 1st question, Views already creates a div that wraps each row, that's the
 one.  You can style it per view by doing something like this:

.view-NAME .views-row {
  /* styles for the rows div goes here */
}

And to your 2nd question, Views also already creates a
 that wraps all the rows, that's the
 one.  To style it for a particular view you can do something like this:

.view-NAME .view-content {
  /* styles for the div wrapping your rows goes here */
}

Now, somewhat obviously, this is all dependent upon your theme.  I am aware that some out there dislike all the markup Drupal by default creates and has overridden a lot of the standard templates to create leaner markup.

If that's the case in your instance, you should still be to instruct Views to add a class to each row if you want.  This is accessed via the overall Style Settings (where you can also look at each Views template that is used for the particular view).

You could also instruct Views to add a class to each field wrapper.  This is accessed from the config widget by each field.

ADDITION based upon commentary:

The Views template that creates the output of the view-content div is views-view.tpl.php and the code in question is:

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

so without changing this up, you're right, Views doesn't allow quick and easy preprocessing of the View to insert any other variables into that div's classes.

You could however use Views' preprocessing hooks to create an additional variable so you don't need to create lots of additional templates but rather just one more.

For example, copy views-view.tpl.php to your theme (easiest) or module (requires special Views theme incantations :) and modify it along these lines:

<?php if ($rows): ?>
  <div class="view-content <?php print $my_special_content_class; ?>">
    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

and then create a views preprocess hook along these lines:

function YOURTHEMEORMODULE_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['my_special_content_class']='FOO';
  } else {
    $vars['my_special_content_class']=''; // so we don't have to isset() or !empty() it in our template :)
  }

}

Save everything and clear your theme cache and now you should be on your way.

SECOND ADDITION:

Upon further thought, and a 'doh!' moment, you can do this without a template at all in preprocess like this:

function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['rows']='
' . $vars['rows'] . '
';
  }

}

if you don't mind another wrapped div in there.  And, I think you will need to/should do this in your theme instead of a module so you make sure this happens in the right order, eg, you want this to happen after Views is all said and done with things, and the theme hooks always run after the module hooks.

You can use  Drupal 7 Field Formatter CSS Class Module.

  The Field formatter CSS class module allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.


How to run a rule for a specific user? I want to redirect a specific user when he logs in.

There are 4 users.

Each one must go to a different url.

Under the rule I have

What do I need to put in for the conditions?

There are many other methods to do it, but I prefer this method,

Try this on your Rules module.

  Events: User has logged in.

  Condition: User has role

  Actions: Page redirect

using "Text comparison" for the condition worked.

So I created a rule for each specific user.

But rather look to the other answer


Download all files from webform I need to download a zip with all attached files from a webform.

Is it possible?

Webform stores all these files in sites/default/files/webform you can download them with FTP.


Custom drupal module does not appear on the extend page I have created a custom module, yet it does not appear on the extend page.
I have my_new_block.info.yml file in modules/custom/my_new_block/:

name: My New Block
description: Create own blocks.
package: Garage

type: module
core: 8.x

dependencies:
  - block

In addition, when I try to install any drupal module with composer, it also is not recognised in the extend page.
What can be wrong?

There was a preceding issue with installation, I had several drupal projects under Projects folder, the newer project tried to access modules in the directory of the older one. Probably, the paths have somehow mixed, leading to the problems with modules installation and database connection(it was not described in a settings.php file). After the disabling of the previous projects and reinstallation of the current one, everything has been working properly.

You can use this example Hello World Module and then change it for your case and do not forget to delete a Drupal cache.


Reference View in Entity Reference field I have a content type that has an entity reference field allowing you to link to other pages and add a custom image, for nice big CTAs.

However, it's come to light that some of the links may need to be to Views that show content as a list or map.

The ER field has autocomplete enabled and it can't find the view by its URL e.g /my-view

Is there a plugin that would allow the field to find Views? Or do I have to change the content type and add a Link field instead?

Views are config entities so you can target them to be referenced (see screenshots) and check this post.

The caveat is you can only point to a given entity type when using ER fields so you cannot have an ER field targeting content and config alike.

On the other hand almost any market solution referencing views aim to render it not just displaying a link pointing the view.

As you suggest using a link field can work around with your use case but the link form element only autocompletes content entities, you cannot type your views' display title and wait for it to get the proper URL for you. For that I'm afraid you need to provide your own widget/form element (and controller). Check this and this about how to build your own autocomplete widget/form element for a text field and this post from Drupal.org docs on how to build your own field formatter.

Also worth noticing that Views URL's are used on limited display types (Page, Feeds, possibly 2 more but I'm not quite sure) and is considered a route, not a path or link like when building a menu link item.

Hope this points you in the right direction.

One way to handle this is to make the view page into a block, then create a node with no content that contains this block (block placement in main content with limited view to /node/.  Then use this in the entity reference field.

An alternative might be to have a content type that uses one of the views fields like view reference.  Then just create a view node with the desired view and use it.


How can I reduce the file sizes of the original versions of uploaded image files? I have a Drupal 7 site that allows users to upload pictures of themselves.  While the pictures aren't using much space on the server's filesystem now, I am worried that if my membership grows substantially I will have to add more space to cover all the images.

Right now, I allow users to upload images up to 10 MB in size.  I want to leave this limit high if possible because many of my users are not technically skilled and they do not know how to resize their images.

At the same time, the largest resolution that will be used on the site is 1024x1024.  So, I have configured the core image field to automatically scale down the images to 1024x1024.  This significantly reduces the file size.

Are there any other ways to automatically reduce the size of uploaded images?  Please note that I am talking about the original files, not image styles.

Interesting question - this should be a standard option on community distributions to avoid the space issue you raised but you're right that the focus seems to be on image styles as a solution..

Two ways to handle this

More custom way would be to add a hook_form_alter to your form that would add a submit handler to resize the image file after uploaded to the correct size -- if you are able to do image styles than your server already has the image libraries needed to do this.
An easier way would be to use an uploader that can be configured to do this work for you on the upload. One example is the plupload module / widget which has a clientside resize option during the upload (also saving bandwidth)

resize

Enables plupload to resize the images to clientside to the
specified width, height and quality. Set this to an object with those
parameters.

you could hook in to "theme_image_style()"  and do a check on every image for size every time it loads.

if I was doing it though, since it's just a one time thing, you may be better off doing a bootstrap and writing your own script to resize.


How to manage text on my site that's not node content? I have text on my site that isn't node content, such as:

footer legal text
"Subscribe to our newsletter"
"Browse our categories"
etc.

I need to save my development work as a Feature but I also need content editors to be able to edit the text. But I don't want to give them permission to edit all blocks. In the not too distant future, the site will be extended to another region so this content will also need to be translated.

Is there a technique / solution designed for housing this data?

I could create a new content type and create a new field for each piece of text. I could easily print the field in TPL files but it might be a little harder to print it in blocks. I also don't know if its performance inefficient to do this, does the whole node object get loaded when you print a single field?

I've heard about (but not used) the Nodeblock module. It looks like this would work but I don't know how easy it will be to work with the Features module (I don't think you can feature nodes).

One nice thing about the first method is that the field label could be descriptive eg "Footer legal text" which would make the translation side of things easier.

Consider using the Bean module for this. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

If you'd grant content editors the appropriate Bean permissions, it appears to me that you might be close to a possible solution to what you're looking for.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

PS: This module only started as of D7, and is already integrated in core in D8 ...

The NodeBlock module is very easy to use and easy to implement.
So, content editor can easily edit the block same way as any other page.

You can apply Nodeblock in you content type which you wanted to make it as a block like showing in a picture.

NodeBlock Setting in Content Type

NodeBlock in a page

If you want to give editing access for just one page then you can use "Nodeaccess" module.


url of custom theme not showing up with page.tpl I've a custom theme. page.tpl has the html markup for my template. And I created some paths like 'about-us', 'terms' via my custom module.

Now, my problem is when I access the above defined paths. They are just showing up the contents defined in the callback function.

What I've to do if I want to show the contents in the content region of my page.tpl

Please help me.

----- THIS IS FIXED NOW :: THANKS FOR YOUR HELP -------

Thanks everyone for helping. I changed the contents of the callback function, print to return. It solved the problem.


Can a batch process be stopped Is there a way to force a batch process to stop if some kind of error occurs?  In particular, I have a batch that starts with saving a record to a database. Each subsequent batch operation depends on the database insert working correctly.  I'd like to force the batch to stop if the first batch fails.

The batch is called like this

$batch = array(
    'operations' => $operations,
    'finished' => 'mymodule_batch_finished',
    'title' => t('Merging records'),
    'init_message' => t('Starting processing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Processing has encountered an error'),
    'file' => drupal_get_path('module', 'mymodule') . '/forms/mymodule.inc'
);

where $operations is the array of functions to call.

Each function uses PDO to update the database.  I'm trying to figure out how to stop the subsequent $operations from being called if the query in the current operation fails.

try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results']['[] = $sth->rowCount();
  }
  else {
    // TODO: stop processing due to an error
  }
}
catch(PDOException $e) {
  // TODO: stop processing due to an error
}

If an error occurs, I want to bypass the remaining operations and go straight to mymodule_batch_finished

Inside your batch callback, where you do the batch work, you should be able to set $context['finished'] to 1, and that will signal to Drupal that the batch is complete.

So, in your case:

$error = FALSE;
try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results'][] = $sth->rowCount();
  }
  else {
    $error = TRUE;
  }
}
catch (PDOException $e) {
  $error = TRUE;
}
// If there was an error, immediately complete the batch process.
if ($error) {
  $context['finished'] = 1;
}

And, even better, you can pass in an error message in the $context as well, which you can check for in your finished callback, then display to the end user in case of failure.

If you want to immediately stop processing anything in other callbacks in the $operations list, you might also need to check for a static variable at the beginning of each callback, and skip the callback if it's in an error condition. You could try using variable_get/variable_set, or some other mechanism that persists between page requests. This would definitely be a hackish/last-resort solution, though!

See also:

How does the batch API work internally?
Batch operations API documentation

Can you try below code ?

$result = array('status' => FALSE, 'data' => $message);
die(json_encode($result));


Connecting 3 content types together entity reference/field collection - adding references in reverse? I have 3 content types:

1. Client
Fields: business name, description, contact name (all standard text fields)

Field collection (called 'client campaign'): Fields: Entity reference field to campaign content type - so I can select campaign to tie this client to.

2. Campaign
Fields: Campaign brief, campaign duration, campaign budget, campaign monthly hours (all standard text fields)

Field collection (called 'collection publishers'): fields, publisher status (paid, live, dead, pending) [select list], publisher live date [pop up date], publisher payment amount [integer], Entity reference field to publisher field - so I can select publisher from drop down

3. Publishers

Fields: website url, name, contact email, payment method (all standard text fields)

If I now:

1) add a client (create one client node)
2) add a campaign (create one campaign node)

I now can add publishers to my campaigns via the field collection added to this content type (collection publishers) This is set to unlimited to I can add as many as I want, in each one I can add in details for each publisher such as 'payment amount' 'live date' and all the other fields that are within this collection.

This all works fine but I need to be able to see all my publishers in one view with details of them and 'reverse' add them to a campaign all at once, perhaps via checkboxes. This will save loads of time. I tried an editable view but cannot seem to get this to work. I am not sure why. It is almost like I need to somehow write to the database without opening up the publisher node..

Was wondering it anyone out there can give me some pointers here or just tell me I am doing it all wrong! I don't mind which.

(the end goal here is to track publishers working across multiple campaigns and then I can see what's gong on at all times through views I'll create)

ADDED A SCREEN SHOT OF THE 'LOGIC' BEHIND THIS!

Thanks for any help in advance.

Screengrab 2 shows how the current campaign node edit form looks - the field collection is showing the publisher nodes.

Screengrab 3 shows how I would probably like this to look, an editable view of publishers that I can assign a campaign to then save. However, this may not work as publishers can work over many campaigns...

It looks like you need Corresponding Entity References:

  It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.

I do all that you want with the following modules:

entityconnect - edit entityreference in content
entityreference - call node is an nother content into creatting content
field_collection - call entityreference in ones
field_collection_table - option view display table in another necessary views (when u want display untimited entityreference field in views)
field_collection_views - diplay all content of field collection to views into node


Multiple/Bulk Image Upload Tutorial? Plupload etc I want my users to be able to upload multiple images at once. They need to be able to upload 60 images for one gallery and doing that one at a time is just not feasible. I've been reading other posts here and doing a ton of searches. I'm told that using the Media module and plupload (I have the javascript library and the drupal integration module installed) that I can do it, but I can't figure out how to actually make it work.

Would anyone be willing to explain it below? I've seen at least one video on youtube that shows the person clicking the Select Media button which pops up a little window, and that window has a drag and drop plupload area where they drop their images. I don't see anything like that.

Install Multiupload Filefield Widget and, if you're so inclined, Multiupload Imagefield Widget.

Make sure your PHP upload limit will allow all the files to upload.

In Drupal 7 You can't add a bulk upload field to content types because it does not support CCK.   According to this post others want to do this too.  There are several side projects but nothing official.

Bulk upload only works as a stand alone tool that creates individual nodes under "create content."


How to add a JS confirmation popup when clicking an #ajax button I have a basic FAPI button input that is #ajax enabled and that's working fine, but I want to add a JS "Are you sure?" confirmation popup when clicking the button before the code actually runs, and I'm not sure how to do that because FAPI's JS seems to be eating the click before I can get to it no matter what I do.

I've tried adding an inline onclick handler, like so:

$form['search_filters']['channels']['channel_delete_' . $channel->nid] = array(
  '#type' => 'button',
  '#name' => 'channel_delete_' . $channel->nid,
  '#value' => 'Delete',
  '#attributes' => array(
    'class' => array('confirm'),
    'onclick' => "return confirm('Are you sure you want to delete that?')"
  ),
  '#button_type' => 'no-submit',
  '#ajax' => array(
    'callback' => 'delete_channel_callback',
    'wrapper' => 'channel_container_' . $channel->nid
  ),
);

...which doesn't help, and I've also tried adding:

$('.confirm').click(function(e) {
  e.preventDefault();
  alert('Is this recognized')? // never runs
});

in my module's JS which is also ignored.

Any other ideas? Is there a way to add a submit handler to the top of the stack which Drupal #ajax will recognize?

Drupal is a PHP framework, and it's amazing how much fancy AJAX stuff you can get using that and the FAPI. But it has it limits and for a use case like this, I would suggest that you use custom JavaScript. Also instead of using the usually JavaScript dialog, you could use jQuery UI to create a themable dialog instead.

Anyways the problem that you're facing is probably caused because you use AJAX on the submit button. Since you are using AJAX for the actual delete call, preventDefault and the like won't work.

What you would have to do is something like this. (This is not widely tested but should work.)

Drupal.behaviors.module = {
  attach: function() {

    var events = $('.confirm').data('events'); // Get the jQuery events.
    $('.confirm').unbind('click'); // Remove the click events.
    $('.confirm').click(function () {
      if (confirm('Are you sure you want to delete that?')) {
        $.each(events.click, function() {
          this.handler(); // Invoke the click handlers that was removed.
        });
      }
      // Prevent default action.
      return false;
    });
  }
}

I have fixed this by modified the drupal misc/ajax.jx file.

Create a copy of ajax.js file and put it any custom module and modified the Drupal.ajax = function (base, element, element_settings) {     function in  beforeSend:

beforeSend: function (xmlhttprequest, options) {

    if( ajax.url =='/?q=field_collection/ajax'){ // condition for when click on the Remove button
      if (confirm('Are you sure you want to remove this?')) {
       ajax.ajaxing = true;
       return ajax.beforeSend(xmlhttprequest, options);
      }
      xmlhttprequest.abort();
    } else{
        ajax.ajaxing = true;
        return ajax.beforeSend(`xmlhttprequest`, options);
     }
},

Its working fine for me.


How to delete a large amount of nodes effeciently during cron? I implemented hook_cron() to delete nodes older than 30 days using node_delete function. Tracing the performance displays this:

  2015-07-06 21:28:49 Drupal watchdog
  ApCleanup::node_delete|/fpe/article||0||Node ID 423466 has been
  deleted [1.1173 secs]
  request_id="v-b8288e7a-2415-11e5-b14b-22000aeb06a5"

A single node deletion takes 1.1 sec. What is the most efficient way to delete the (2075546) nodes using hook_cron() and the node_delete_multiple function?

I would not recommend using Cron for this task.Since you have so many nodes it would always time out. Your better off using Drush and the Delete All module.
Or if you're fully purging all your nodes for instance I have written an SQL script before I can invoke with Drush which uses the sql truncate command to remove all data from Fields of a content type and then does a delete all from node and node_revisions for the given content type, and url aliases -- etc. Using SQL makes such a task take very little time for hundreds of thousands of nodes.
EDIT:
The Delete All admin UI has options for a quick delete that uses sql JOINs and not node_delete. See the admin form code: http://cgit.drupalcode.org/delete_all/tree/delete_all.module#n71
I suggest you install and try using the module.


Unblock an automated blocked user I used Login Security module to block users after some login failures. It works fine however I need to unblock such users after certain time like after 1 hour/day. How would I do that as it has configurations to delete attempt from database but user isn't unblocked and it has to be active manually.

Please see below attached screen shot of module configuration.

I just developed a small module named as Auto Unblock Users to unblock users.

This will only work if the user is blocked by Login Security module.

What about unblocking the blocked user after an hour using Rules module?

Edited:

Use Rules module.

Create custom event for your particular module event (for example, "User Blocked after login failure"

Unblock users after one hour.


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

You can upload file separately and after that add the link to this file.
Or you can use module IMCE to upload files in WYSIWYG and add link on them easily.


Hide node created messages programmatically I'm trying to the node created messages for a certain content type, but I can't use Disable Messages because it has a conflict the Commerce Add to Cart Confirmation module.

All the other methods (like the ones here) I've found either hide all status messages, or hide all status messages after a content type is created, which are inappropriate for me since I'm using rules to show a messages after a node is created, but I need to hide the default "__________ has been created" message, and I appreciate any help you can offer me.

drupal_set_message is not hookable. But the message you want removed comes from node_form_submit, so you can get rid of it using hook_form_FORM_ID_alter on node_form. Either replace node_form_submit as form's submit handler with it's clone, sans messages, or set second handler that will remove what you want removed from $_SESSION['messages'][$type].

http://xandeadx.ru/blog/drupal/729

Change

$_SESSION['messages']['status'][$old_message_key] = 'Текст нового сообщения';

to

unset($_SESSION['messages']['status'][$old_message_key]);


How to add javascript to theme_preprocess_user_login I have working code in my theme's template.php file that adds "autofocus" to my modal login form, but Firefox ignores ajax autofocus fields (only applies autofocus on pageload). So I'm trying to add some js to set focus when the modal login form is called. I currently add autofocus via:

function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['rendered'] = drupal_render_children($variables['form']);
}

And I'm trying to add js to set focus as a fallback this way:

function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['form']['#attached'][js][] = path_to_theme() . "/js/focus.js";
  $variables['rendered'] = drupal_render_children($variables['form']);
}

but this doesn't seem to add the js as expected. How can I add either inline or external javascript to my modal login form?

A preferred solution I would use for adding/editing forms would be to use a module hook.

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

  $form['#attached']['js'] = array(
    drupal_get_path('theme', 'THEME') . '/js/focus.js',
    '/* inline js here */' => array( 'type' => 'inline')
  );
}

Use the standard drupal_add_js https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7

drupal_add_js(drupal_get_path('theme', 'THEME') .'/js/focus.js', 'file');
drupal_add_js('(function ($) { ... })(jQuery);', array('type' => 'inline', 'group' => JS_THEME));


Permit only one role to download files I'm trying to set up a new D8 site. It needs to include some "subscriber only" type functionality. There is one content type which is little more than a title, a file, and one extra field for sorting purposes. There is also a View to make this visible to the end user. What I'm trying to do is let the unauthenticated site visitors see the list, but not download anything while the authenticated users in a specific Role are allowed to download those files. The site's owner will be taking care of adding people to it manually. It isn't too frequent of an event, apparently.
I see how to make the View itself only available to people in that Role. I see how to make content as a whole unavailable to the unauthenticated (Anonymous Users) in /admin/people/permissions. Am I going to have to disable Anonymous Users' access to all content and then enable it one content type at a time?  Or is there a better way to achieve the goal?
I'm open to scraping the approach I've taken (Content Type, File field, and a View) and doing something else entirely if it would be better.
Note: We're currently using private files as the default storage location.

It's good you're using Private file system. That is one level of control you need to prevent the files from being freely downloaded.
Other levels of control are the Page (Views list), Node, and File fields.
You could create two different Views, one without the file field, and one with it, and use Role permissions on those pages. In this case you'd have to make nodes not accessible to all, which isn't fortunate if you want to control other types differently. There are modules, though, that you can use to set up different node type permissions.
But in your case I think it makes the most sense to have different File permissions. This way you don't have to duplicate Views or control node access.
You can do this with the Field Permissions module.
All can see the nodes and Views pages, but only special Roles will see the File field that has those special permissions.

You can create a field formatter for a file field.
When you extend the FormatterBase class you can implement method inapplicable or just prevent rendering by adding return false in a view method.
So add a check if currently logged in use has a correct role - render the file field, else don't display it.


Using jquery mmenu, how to close one submenu when I open another submenu? I'm building a (Drupal 7.5) site where I use mmenu (Mobile Sliding Menu) module to create the menu. When I click the trigger, the main menu items appears. Some of the main items have a submenu. When I click the trigger for those submenus, the submenu opens, so far so good.

When I then click another submenu trigger, that submenu opens, but the previously opened submenu stays open as well. What do I need to change to have only ever one submenu open at any one time (i.e. triggering a new submenu closes one that was opened before)? There is no setting for this in the mmenu configuration (drupal module), and no instructions on this on the mmenu website (http://mmenu.frebsite.nl).

Many thanks for any help on this.

The easiest method I can think of is to use JS or jQuery to trap the click for every sub-menu item then, onclick, cache a reference to the clicked item, then programmatically close all of the open sub-menus with a loop, skipping the clicked item.

Try something like this:

(function ($, undefined) {

  // Execute once the DOM is loaded.
  $(document).ready(function () {
    // List of expandable sub-menu items.
    var subs = $('.mm-subopen');

    // Iterate through each sub-menu item...
    $(subs).each(function () {

      // Set up onclick handler...
      $(this).click(function () {

        // Cache reference to clicked item.
        var clicked = this;

        // Iterate through list of sub-menu items...
        for(i=0,c=subs.length;i<c;i++) {

          // If current item is not the clicked item...
          if (subs[i] !== clicked) {

            // Get reference to parent <li>, then remove the mm-opened class.
            var parent = $(subs[i]).closest('li');
            $(parent).removeClass('mm-opened');
          }
        }
      });
    });
  });
})(jQuery);

You might need to modify for nested sub-menus, but I hope this helps!

HTML

CSS

.sub-menu
{
  display: none;
}

JQUERY

$("ul > li > a").click(function () {
   var _parent      = $(this).parents("ul");
   var _children    = $(".sub-menu", _parent);
   var _nextElement = $(this).next();

   _children.css({ "display":"none" });
   _nextElement.css({ "display":"block" });

});


How to abort the ajax request and redirect in the ajax callback of form element I want to redirect the page in the ajax callback function, and nothing (like "header", "drupal_goto" etc.) works for redirect in the ajax callback function.

If you've got ctools installed (nearly all Drupal sites do), you can make use of ctools_ajax_command_redirect() in your AJAX callback, e.g.

ctools_include('ajax');
$commands[] = ctools_ajax_command_redirect('path/to/redirect');
return array('#type' => 'ajax', '#commands' => $commands);

in your drupal callback function add javascript
window.location.href = "path";

ex: if your callback is ajax_call_back() then,

 `function ajax_call_back($form, $form_state){

return 'window.location.href = "http://www.google.com";'exit;

}
`
note: you should add SCRIPT tag in rerutn before window.location.href = "http://www.google.com";


Using Simple jQuery click() events in Drupal 7 I've been able to get jQuery to load and work for some basic things such as:

(function ($) {
  console.log('jquery called');

  $(document).click(function() {
    var h1 = $('h1').text();
    console.log(h1);
  });
}(jQuery));

However, when I try to do the following, nothing happens.

(function ($) {
  $("h1").click(function() {
    alert('clicked!');
  });
}(jQuery));

I'm wondering if this has something to do with when the .js file gets called. I suspect that the document element already exists, so having a click event on it is no problem. However, I think that the h1 elements don't exist by the time the click event is loaded. I've tried the .bind() and .on() functions as well, with no luck.

Any ideas?

I call my .js file from my theme's info file, not sure if that matters.

(function ($) {
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.ss2 = {
  attach: function(context, settings) {

  $("h1").click(function() {
    alert('clicked!');
  });
}}

})(jQuery);

be careful with braces at the end, and rename ss2 as you want, it's just for example...

So figured out that having your jQuery called in the footer after all the dom elements load works much better for things like click events. Here is how I got it to work:

Open your theme's template.php file
In the ThemeName_preprocess_html(&$variables) function add the
following:

    drupal_add_js(drupal_get_path('theme', '**ThemeName**') . '/js/**FileName**.js', array(
      'scope' => 'footer',
      'weight' => '15'
    ));

Have your FileName.js file look something like this:

  (function ($) {
  //insert your jquery here
  $('h1').click(function() {
      $(this).hide('slow');
      console.log('h1 clicked!');
  });
  }(jQuery));


Stop caching for a specific node type Drupal 7 I'm working with a node type that has several custom fields. The values of these fields need to refresh on each page load, but because of Drupal's caching feature, they don't. What is the best way (simplest way) to stop this content type from caching?

See if http://drupal.org/project/cacheexclude can do it for you. If not you need to create a module that will implement hook_init. Inside of that hook you need to load the node from arg() from there see if the node is of a certian type; if it is disable the page cache.

<?php
  // Get the current active node object if present.
  $node = menu_get_object();
  if (!empty($node) && !empty($node->type) && $node->type == 'page') {
    drupal_page_is_cacheable(FALSE);
  }
?>

For Drupal 8:

// Mark this page as being uncacheable.
\Drupal::service('page_cache_kill_switch')->trigger();


Redirecting after login for specific roles I want to redirect specific users after a succesful login but I can't make it work.
Here's my code:

function concessionaire_login_user_login(&$edit, $account) {
foreach ($account->roles as $role){
    if($role == "administrator"){
    } else if ($role=="concessionnaire"){
        global $language;
        unset($_REQUEST['destination']);
        unset($_REQUEST['edit']['destination']);
        $url = "http://www.my-site.com/myfile.php";
        $options = array(
        'query' => 'id_rub=14&lg='.$language->language
        );
        drupal_goto($url,$options)

    }
}

}

I tried also with header('location: $url'), but it doesn't work either. Login_destination module was my first guess but I can't use variables..

Also is it possible to redirect to an external URL and passing POST parameters at the same time ?

Thanks in advance.

Some things to look at:

'query' itself needs to be an array, not a string, eg...

array('id_rub' => '14', 'lg' => $language->language)

and if you want to call header() directly, you need some more parameters:

header('Location: ' . $url, TRUE, $http_response_code);
drupal_exit($url);

(and an exit for good measure...btw, that's all drupal_goto() is really doing anyway)

You can use the Login Destination module.


How do I re-name my zone--content.tpl.php file for a separate front page layout? I am using Omega 3.x along with Delta and contexts for creating a drupal theme for my site. I have experience with using D6 themes like Zen but I am still learning my way around Omega.

I want to know how I can create and name a separate template for my zone called content for the front page. I wouldn't mind a hard coded or a Delta+context solution or for that matter any other method to achieve my goal as long as Omega is used.

This was too much for a comment so I put it in an answer. newdwardss's answer contains the right methodology, but it doesn't address the Omega theme.

You can use the same logic as in that answer, but customise it for the zone template:

function MYTHEME_preprocess_zone(&$vars) {
  if ($vars['zone'] == 'content' && drupal_is_front_page()) {
    $vars['theme_hook_suggestions'][] = 'zone__content__front';
  }
}

That will allow you to use a template file called zone--content--front.tpl.php which will only be used for that zone, and only when on the front page.

For use with the region content template (region--content--front.tpl.php) use this instead:

function YOUR_THEME_NAME_preprocess_region(&$vars) {
  if ($vars['elements']['#region'] == 'content' && drupal_is_front_page()) {
    $vars['theme_hook_suggestions'][] = 'region__content__front';
  }
}


OG + Exposed Filters + Views What would be the smartest way to approach filtering content by the groups that it is posted in?

I will almost certainly need custom code to do this (I think a Handler, but I need someone to point me in the right direction), especially because I want to be able to filter by content posted in "All" groups, posted in a set of groups (i.e. a user's "core groups," determined by a taxonomy term reference on all users and groups -- if they are equal, that group is a user's "Core Group"), and also by each individual group that the user belongs to (but I don't want groups that the user isn't a member of showing up in the filter).

The docs for Views aren't very good, and I just know that there's an elegant, Drupal way to do this, and I need someone to point me in the correct direction (i.e what hooks, etc.)

Thanks in advance for help!

I think you can do what you want using OG and Views with nothing custom. This is a good place to get started: https://modulesunraveled.com/organic-groups-7x-2x.


How can I change the user login tabs labels? I am pretty new to Drupal and wonder if there's any possibility to change the text of the user login / create an account and reset tab? I'd like to rename them to something like "sign in", "sign up" and "reset account".
I found no way through the backend UI. Neither in Tabs Block Content nor Menu structure.
Do I need to write a theme hook or a module to achieve that, or is there any functionality in the backend I've overlooked?

As shown in the answer to the duplicate question you can use template_preprocess_menu_local_task from a custom theme or hook_preprocess_HOOK from a custom module to override the tabs.
If you want to do it right, you also set the page title and the HTML title to display the same strings. Maybe keep things DRY and get the $target_routes array from a small helper function.
First the tabs:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_menu_local_task(&$variables) {

  $target_routes = [
    'user.login' => t('sign in'),
    'user.register' => t('sign up'),
    'user.pass' => t('reset account'),
  ];
  $current_route = \Drupal::routeMatch()->getRouteName();

  if (isset($target_routes[$current_route])) {
    /** @var \Drupal\Core\Url $url */
    $url = $variables['link']['#url'];
    $route_name = $url->getRouteName();
    $variables['link']['#title'] = $target_routes[$route_name];
  }
}

Then the page title:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

  $target_routes = [
    'user.login' => t('sign in'),
    'user.register' => t('sign up'),
    'user.pass' => t('reset account'),
  ];
  $current_route = \Drupal::routeMatch()->getRouteName();

  if (isset($target_routes[$current_route])) {
    $variables['title'] = $target_routes[$current_route];
  }
}

And finally the HTML title:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_html(&$variables) {

  $target_routes = [
    'user.login' => t('sign in'),
    'user.register' => t('sign up'),
    'user.pass' => t('reset account'),
  ];
  $current_route = \Drupal::routeMatch()->getRouteName();

  if (isset($target_routes[$current_route])) {
    $variables['head_title']['title'] = $target_routes[$current_route];
  }
}

You could also make use of the Hook regarding the menu alter depending on your needs.
A sample of it could be something like :
function MYMODULE_menu_alter(&$items) {
    $items['user/%user/track/navigation']['title'] = "Track Your Posts";
    $items['user/%user/view']['title'] = "View Profile";
    $items['user/%user_category/edit']['title'] = "Edit Profile";
}


How do I display an error message on a basic page when the user does not have permissions to see the nested view inside the basic page? I have a basic page, and inside of that basic page I have a view "newsletters". The view "newsletters" has permissions set on it based on role, so only admin and subscribers can see it. How can I display "You must be a subscriber to view this content" on the basic page when the user does not have permissions to view "newsletters".

Currently, if the user cant see "newsletters" my basic page just shows an empty page. I want it to display "You bust be a subscriber to see this content".

I tried creating another view "redirected page" that is only visible to anonymous users but it is not showing up for some reason.

The reason I made a basic page with a view nested inside it is because I wanted users who don't have permission to view the page to still see the link in the menu bar.

You can create a basic Block with your text message and set up Visibility to only Anonymous users, and to show on your basic page.

This way anonymous will see the Block, authenticated will see the Views block.

Not a very elegant solution but a quick solution for your situation. You could add a basic block just below your view block with your "You must be a subscriber to view this content" text

Then in css do:

.myviewblock + .mynewbasicblock {
  display: none;
}

So that means if your view block is coming out on the page (Which only would if they have permission) then hide your basic block.

But this relies on you keeping those blocks next to each other. And also means the "You must be a subscriber to view this content" content is always on the page but just hidden.

Your alternative could be to instead use a node access module that restricts access to the nodes rather than the view so that the view wouldnt have permissions but the nodes would


How to make a Feature available only to certain Spaces? For a Drupal 6 Open Atrium site (i.e., Features, Spaces, Organic Groups) I'm running, I've created some custom Features that only really apply to a handful of the hundreds of groups on the site.

As it stands, the "Customize Features" config screen shows all the Features, including those I'd like to intentionally restrict to just a couple of special groups.

What's the best way to prevent these special Features from being offered to every group, while retaining those Features on the special groups?

The features for each space are configured via the spaces_features_form() function. You could implement hook_form_alter() to selectively and conditionally remove features from specific groups.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'spaces_features_form') {
    $space = spaces_get_space();
    // Populate the array with hard-coded NIDs, or whatever logic
    // needed to determine if these features should be allowed.
    if ($space->type == 'og' && !in_array($space->group->nid, array(...))) {
      // Hide features foo and bar.
      foreach (array('feature_foo', 'feature_bar') as $feature) {
        $form['spaces_features'][$feature]['#access'] = FALSE;
      }
    }
  }
}

Could you enable all of the features from the start, but handle their display via Context?  I haven't had a chance to try Context myself yet, but it sounds like a fit.


Is it possible to create a view of Nodequeues I'm trying to create a list of all my nodequeues using Views, To be clear I'm not trying to create a view that showing the content within a Nodequeues, but rather create a views that lists the Nodequeues themselves is this possible? if so how do do it?

Excerpt from the Community Documentation of Nodequeue (about "Automatic Creation of Views"):

When configuring Nodequeue, you can opt to "Automatically create one view per queue" (you may wish to leave this off if you plan to create the views yourself).
The views created automatically cannot be deleted from the Views interface because they are implemented "in code". However, if you disable the auto-creation, then clear caches, these views will be removed.
It is highly recommended that you use the Views module to display your subqueues. However, if you choose not to, you can alternatively use a small PHP snippet.
To use nodequeue from Views (D7), add a 'relationship' to the queue, and typically set to 'require this relationship'. Optionally add 'nodequeue: Position' to match the preset queue order.

Steps to make a view from node queue:

Create a node queue and add some article(content) to it.
Create a view and select fields in format section show (fields).
Click on Add relationship in advance section.
search for Node-queue and add the relationship.
check the Require this relationship checkbox,
check the Limit to one or more queues (recommended) checkbox and Select the node-queue name which you have created earlier and hit apply button.
Now in fields section just add the field you want from you node queue content and Only the article(content) added to the node queue content will get appear in display of view.


Correct way to append value to serialized array in key_value table I have a serialized array in the value field of key_value, to which I constantly what to append values. An easy way to do this is to get the array, append the new value, and reinsert it. However, with a large enough array it's quite inefficient and in theory it can be done on an SQL level.

What's the correct way to do this in Drupal 8? Is there a way that does not involve getting and then setting the array?

The best way to go about doing this is by using config API. If somehow this option is not suitable for your use case. You can also use the DB API to update the desired congratulation table records. In both cases, you will need to unserialize the blob then change the data and serialize it back before inserting it into the database.

https://www.drupal.org/docs/8/api/configuration-api/configuration-api-overview


How can i configure the core search module to also show results for incomplete words? I see that the results page only shows results if the "keys" parameter matches a complete word. how Can i configure the core search engine to also show results for incomplete words?

I am using core search module .

Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. No need for Solr.

Enable both the modules and go to the Search API configuration page
(admin/config/search/search_api)Add a server and give it a recognizable name (such as "MySQL"), make sure it's enabled.

Choose the following service class: Database service (normally the only option. If you don't see it, make sure that the "Search API Database Search" module is enabled).

Selecting this service class will provide you the option Search on parts of a word (make sure you enable it). Now hit "Create server".

Next, go back to the Search API configuration page, and add an index. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled.
Select the server you recently created (in this example "MySQL").
Datasource options: check the content types you want to index (the description of this field may be a bit confusing, but make no mistake: you should check the content types you want to index, not the ones you want to leave out).

You could check "Index items immediately", but that depends on the size of your content. This option is alright for smaller websites. In the other case: let cron take care of it. Hit "Create index".

Next, you want to enable the fields (in the fields tab) to that very index, e.g.: content type, title, status and author - and hit "Save changes" (we'll take care of the related fields later).

Then you want to configure the filters (in the filter tab). Here you can enable the bundle filter, if you want to finetune the content types once again (probably won't need to).
Down below you'll find the highlight filter, to highlight the search word in the results.
Now return to the fields tab and unfold the "Add related fields" tab. Add all the fields of which you want to get the content indexed, and hit Save.

Finally go to the "view" tab of the index, and index now all the items.
The last step is to create search results page and search block in Views, which only takes a few minutes.

Make sure the submodule Search Views is enabled and create a view page which will show "Contentindex" (select the name you gave to your index configuration instead of "content" which is selected by default.

Add all the fields (make sure your format is "fields") that every search result should consist of (title [link to content], body, …).

You'll notice that these fields look like this Indexed Node: Title
Add an exposed filter: Search: Fulltext search; and select the following in its settings: Contains any of these words, and use as: Search keys.

You're done!


Render block programmatically in Drupal 8 returns 0 I create a block at /admin/structure/block/block-content and I want programmatically render it in our custom template files. What I did is

function hook_preprocess_page(&$vars) {

    $block = \Drupal\block_content\Entity\BlockContent::load(2);
    $vars['contact-us-info-block']= \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    //kint( ($vars['contact-us-info-block']));
    //kint( drupal_render($vars['contact-us-info-block']));
}

and in page template file I try

<p>{{ contact-us-info-block }} </p>

but I only see a "0" in output.

if I use

$vars['contact-us-info-block'] = drupal_render($vars['contact-us-info-block']);

everything is Ok but I find out drupal_render is deprecated in Drupal 8.
Where is problem and how can I render a block at page template programmatically?

For display only your block in your templates with preprocess the best way is

$block = Block::load('my_block_id');
$variables['My_region'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

And in your page.html.twig or node.html.twig or xxx.html.twig use your variable My_region like this :

{% if page.My_region %}
    {{ page.My_region }}
{% endif %}

And in rendable array (custom module) by exemple into an controller custom in content():

public function content() {
    $block = Block::load('my_block_id');
    $block_content = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

          return array(
            '#type' => 'container',
            '#attributes' => array(
            'class' => array("Myclass"),
          ),
           "element-content" => $block_content,
           '#weight' => 0,
  );
}

drupal_render is not usefull drupal already assume the render in D8 and this is deprecated (https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_render/8)

it's a bit heavy, it is better to use the maximum area system and does not add load block from the preprocess. In the case of using a controller in your modules this seems a justified use.

function hook_preprocess_page(&$vars) {
  $block = \Drupal\block_content\Entity\BlockContent::load(2);
  $blockview = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
  $vars['contact-us-info-block'] = render($blockview);
}


Database query with notExists I can't figure out how to select all aid's from the areas table that do not exist in the field_data_field_area_parent table.

It almost works, except it returns Windy Ridge with an "aid" of "11".   I am guessing that this is because "IN" is the same as "ANY", and the number "1" is in the subquery results.

How can I use NOT EXISTS instead of NOT IN?

function verb_get_parent_areas () {
  $query = db_select('areas', 'a');
  $query->distinct();
  $query->fields('a',array('name','aid','parent','latitude','longitude','description'));
  $subquery = db_select('field_data_field_area_parent', 'p');
  $subquery->fields('p', array('entity_id'));
  $query->condition('a.aid', $subquery, 'NOT IN');

  $result = $query->execute();
  while ($record = $result->fetchAll()) {
    $areas = drupal_json_encode($record);
  }

  return $areas;
  exit;
}

I've thought of trying this, but it returns nothing.

function verb_get_parent_areas () {
  $query = db_select('areas', 'a');
  $query->distinct();
  $query->fields('a',array('name','aid','parent','latitude','longitude','description'));
  $subquery = db_select('field_data_field_area_parent', 'p');
  $subquery->fields('p', array('entity_id'));
  $query->notExists($subquery);

  $result = $query->execute();
  while ($record = $result->fetchAll()) {
    $areas = drupal_json_encode($record);
  }

  return $areas;
  exit;
}

Here is another approach to write Dynamic queries. We generally write queries in phpmyadmin or mysql command prompt and then convert them to D7 style or dynamic queries using Query coder module.

For example, as per your question, you want to find out all those records in child table which don't exist in parent table.

So D6 style query,

db_query("SELECT c.* FROM {child} c LEFT JOIN {parent} p ON c.p_id = p.p_id WHERE p.p_id IS NULL");

after converting to D7 style query using query coder module would look like,

$query = db_select('child', 'c');
$query->fields('c', array('*'));
$query->leftJoin('parent', 'p', 'c.p_id = p.p_id');
$query->isNull('p.p_id');
$result = $query->execute();

Have you tried out drupal_write_record() function? if no then see below link,

https://stackoverflow.com/questions/5825337/help-with-db-query-in-drupal-if-exists-update-else-insert

This may helpful to you.

Thanks.


Credit card type in drupal commerce I need to find out what credit card type was used when someone purchased something from my website.

Is it possible to find this out? I was looking through the database tables and couldn't find anything in there. I also looked in the orders payment tab and still couldn't find anything.

Thanks

Drupal commerce does not provide anything for this. Actually it must not do it since payment companies require (and often make it completely impossible) to know the credit card properties.

Your only hope is what might be stored in the commerce_payment_transaction table by the payment gateway. Often additional data is stored as a serialized PHP object in the payload filed.

If you don't find anything there, you might have to dive into the specification of the payment getway company and check whether they provide this information via the API. If you are lucky this might be integrated into the appropriate drupal commerce payment getway.

Credit card info can be found out by the first two digits (out of 16) on the CC. That will itself tell you whether its AMMEX, MASTERCARD, VISA or else


Use part of the user_profile_form on another page My users enter a phone number on registration. The amount of values that can be entered is set to unlimited. Setting this changes the field so that you can add another field below to add additional phone numbers.
I would like the users to be able to add more numbers after registration without having to go to /user/%user/edit

I am trying to return just the phone number field on another page.
However I cannot seem to get any of that form displayed on another page.
When I have been displaying other forms I have called them like this:

drupal_render(drupal_get_form('user_profile_form'));

This does return part of the form, First Name, Last Name, Country (all custom fields) but not the phone number field. I also get quite a few errors
Undefined index: user_profile_form in drupal_retrieve_form()
Undefined index: #user_category in block_form_user_profile_form_alter
Undefined index: #user_category in overlay_form_user_profile_form_alter()
Undefined index: #user_category in system_form_user_profile_form_alter()
Undefined offset: 0 in uc_roles_form_user_profile_form_alter()

Obviously I am doing something very wrong...

I made this work based on the work by Erik. I guess you could do ['#access']=false for all the values you don't want.

//Provide a custom page at /custom-profile to access our custom profile form
function mymodule_menu() {
  $items['custom-profile'] = array(
   'title' => 'Custom Profile!',
   'page callback' => 'mymodule_custom_profile',
   'access callback' => TRUE,
   'type' => MENU_NORMAL_ITEM,
 );
}

//displays the custom form at /custom-profile
function mymodule_custom_profile() {
  module_load_include('inc', 'user', 'user.pages');

  global $user;
  $user = user_load($user->uid);

  $form = drupal_get_form('user_profile_form', $user, 'account', 'custom');

  return $form;
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state){
  //modifies the form_user_profile DO CUSTOM STUFF BELOW!
  if(isset($form_state['build_info']['args'][2]) &&
           $form_state['build_info']['args'][2] = 'custom'){

   //rename submit button
   $form['actions']['submit']['#value'] = t("dooo it!");

   //remove a few account things from this page
   $form['account']['#access']=FALSE;

   //needs to be there for the picture to work
   form_load_include($form_state, 'inc', 'user', 'user.pages');
  }
}

Trying to fetch a single field from a form doesn't make sense IMHO.

If you want to update a single value in the database for this field, you'd better code your own form and manage the submit and validate functions to update the database yourself.


How to add / remove tabs from user profile? By clicking on the "My account" link that on the secondary menu on the site, the user is redirecting to the user's profile page.

In this page there are many tabs. Some tabs are there originally, and some tabs created by some modules. I understood how to add tabs to this menu (by simply create view and give it path of /user/%user/XXX).

Is there another way?
How can I remove tabs from the user's profile menu?

Why this user profile menu is not under the menus section of Drupal?

My goal is to remove the following tabs (see screenshot below): "HybridAuth", "Your Questions" and the "Points" tab.

If you don't want to use a contrib module like TabTamer then, In Drupal 7,   you can use hook_menu_alter to disable the MENU TAB by using access callback

    /**
     * Implementing hook_menu_alter
     * Restrict MENU TABS access
     */
    function MODULE_NAME_menu_alter(&$items) {
        if(/* check your conditions */) {
            $items['user/%user/hybridauth']['access callback'] = FALSE;//Change the MENU PATH as per your requirement.
        }
    }

Note

Get the MENU PATH by printing $items variable.

function hook_menu_alter(&$items){
   $items['user/%node/subuser']['type'] = MENU_CALLBACK;
}

Where hook is your custom module name.


Add javascript to a content type form in Drupal 7 I'm trying to add a custom javascript file to my article content type forms (add/edit).

I've tried mythemename_preprocess_page, hook_form_alter and  theme_content_type_node_form to no avail. They both seem to pick up the page i'm on, not the form in Drupal's Overlay with the form in it.

Obviously I want the Javascript to fire only when I'm actually on the form. So just putting the Javascript in a onReady function in a sitewide js file won't suffice.

My current setup in template.php:

function zeilschepen_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'node-accommodation-form':
      $form['#after_build'][] = 'zeilschepen_after_build';
      break;

    case 'views_exposed_form':
      if (isset($form['field_country_value'])) {
        $form['field_country_value']['#attributes'] = array('placeholder' => array(t('Land...')));
      }
      break;
  }

}

function zeilschepen_after_build($form, &$form_state) {
  $theme_path = drupal_get_path('theme', variable_get('theme_default', NULL));
  drupal_add_js ("$theme_path/js/test.js");
  return $form;
}

And test.js:

(function ($, Drupal, window, document, undefined) {

    Drupal.behaviors.test = {
        alert('test');
    }
})(jQuery, Drupal, this, this.document);

This:

node-accommodation-form

Is the HTML ID of the form, found in $form['#id'] (confusing I know). You need the internal ID, which is

node_accommodation_form

As in:

function zeilschepen_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'node_accommodation_form':

Using #attached, as mentioned in comments, is far preferable to drupal_add_js() when you get to that part.

As an aside, you may find coming back to your code later on a bit easier if you separate out your form alters like so:

function MYMODULE_form_node_accommodation_form_alter(&$form, &$form_state, $form_id) {
  // Logic specific to the accommodation node form, no need to check form ID.
}

Also, as noted in another answer, theme hooks are only run when the theme is actually in use. So if you're using the admin theme for your node edit forms, your code will never run. If that's the case, you need to move the logic to a module.

I think hook_form_alter() will help you. Try this:

   function yourmodule_form_alter(&$form, &$form_state, $form_id){
     if($form_id == "your form id") {
       drupal_add_js('your js file');
     }
    }


Can two nodes have same URL using Pathauto? I know that Drupal allows same url for multiple nodes.
But I've a scenario: a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title.
At the same time another user creates an article with same title in unpublished form. Will it too have same url?

I'll not "publish" those nodes anytime. I'll (as an admin) simply create a new node and copy paste contents.

a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title. At the same time another user creates an article with same title in unpublished form. Will it too have same url?

No. pathauto by default will append a number to the end of the URL to differentiate between them.

Sorry, but Drupal does not allow same URL for multiple nodes.


How can I add a field in Entityform / hook_form_alter I'm trying to add a field to the form in hook_form_alter. What's the proper way of adding fields in this hook in case of entityform?

I tried to add it this way:

$form['leadname'] = array(
    '#type' => 'hidden',
    '#value' => 'abc'
);

but I have the impression that this is not the way it should be done...

That is the way it should be done.

For example using

MODULE_form_ENTITYFORM_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {}

You have to use the following API's

field_create_field : Creates a field.
field_create_instance : Creates an instance of a field, binding it to a bundle.
field_delete_field : Marks a field and its instances and data for deletion.
field_delete_instance : Marks a field instance and its data for deletion.

Reference

Programmatically create a field in Drupal 7


In Drupal 7, where is the code for the "powered by Drupal" block? The "powered by Drupal" block used to be a module in Drupal 6.  I can not find this module in Drupal 7.  Where do I find this module/block? So I can duplicate it, or modify it.

The contents is provided by theme_system_powered_by(), which is turned into a block by system_block_info() and system_block_view().

The block itself is located in admin/structure/block, where you can disable for the footer if you'd like.

I would say if you want to duplicate/modify it then you can just create a new block with whatever content you'd like


Creating a bootstrap sub-theme with the SASS starter kit I am attempting to create a bootstrap sub-theme using the SASS starter kit in the the bootstrap base theme. I'm using bootstrap version 7-3.16.

I followed the directions here: How to create bootstrap subtheme using sass? as best as I could.

I copied the SASS starter kit into a new directory in the sites/all/themes directory and named it "bootsub". Then I changed the sass.starterkit file to "bootsub.info" and edited the file to reflect the name "bootsub".

Then I copied the bootstrap framework files into a file in the subtheme named "bootstrap". I had previously installed compass and sass.

I then ran the command "compass init" from the command line (in the subtheme root directory). This created the config.rb file. I then ran the command "compass compile" in the subtheme root directory.

I am still not able to see any styling on the site. I have flushed the cache and I have double checked to make sure that the subtheme is enabled and set as default and the bootstrap base theme is enabled.

I am including an images of the directory structure and a copy of the config.rb file

require 'compass/import-once/activate'
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/sites/all/themes/bootsub"
css_dir = "stylesheets"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"

# You can select your preferred output style here (can be overridden
via the command line):
# output_style = :expanded or :nested or :compact or :compressed

# To enable relative paths to assets via compass helper functions.
Uncomment:
# relative_assets = true

# To disable debugging comments that display the original location of
your selectors. Uncomment:
# line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv
scss sass

Try using Radix Theme. Check how the compiler gulp is setup and try to replicate it to bootstrap sass.


How to embed javascript into content region I am trying to embed javascript into the content page of my page. I decided to use php filter and the following is my code:

<?php
$scripty = "http://blah.com/plugins/embedvanilla/remote.js";
drupal_add_js($scripty, array(
'type' => 'external',
'scope' => 'content',
'group' => JS_LIBRARY,
'every_page' => FALSE,
'weight' => -1,
)
);
?>

The script shows on this page if scope is not set (which means it defaults to header).

How can I get it to display in the content region?

Never use php filter, it's one of the worst inventions in Drupal.

You can create a region in your info theme.  Then, use the preprocess hook like that:

function hook_preprocess_region(&$vars) {
  // Region names of (header|footer) collide with drupal_add_js()'s
  // (header|footer) labels.
  $scope_theme = 'your_region';
  if (!empty($scope_theme) && $scope_theme != 'footer' && $scope_theme != 'header'
    && $vars['region'] == $scope_theme) {

    // Inject javascript into page.
    $javascript = drupal_get_js($vars['region']);
    $vars['content'] = $javascript . $vars['content'];
  }

}

And finally, fire your drupal_add_js using the region you defined wherever you prefer... But never in php filter

If you're using php filter on your page, couldn't you just add the script tag into the node body?

<script type="text/javascript" src="http://blah.com/plugins/embedvanilla/remote.js"></script>


How to sort the content types/bundles on /node/create page I want to reorder the list of available content types on the create content page.
I have node-add-list.html.twig and entity-add-list.html.twig inside my custom theme template folder.
Twig then outputs the array of all types or bundles/content types in alphabetical order. How can I sort this a different way? And can I hard code the links I want in this file or can I output each content type individually?

You can do this in preprocess by overriding this code from node.module:

function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = array();
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = array(
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

Or you can replace the foreach loop in the twig template

node-add-list.html.twig

    {% for type in types %}

{{ type.add_link }}

{{ type.description }}

    {% endfor %}

with a hard-coded list:

{{ types.article.add_link }}

{{ types.article.description }}

{{ types.page.add_link }}

{{ types.page.description }}

Unfortunately not so easy.
Please take a look,
I've already answered that in a previous question.

How to modify the page at admin/structure/types?


Group nodes by terms How do you group a list of nodes by the taxonomy term?

e.g.

Term 1
--- Node 1
--- Node 3
--- Node 7

Term 2
--- Node 6
--- Node 9
--- Node 12

I have tried creating a view with "Node" and "Taxonomy Term" as fields. I then enabled grouping, and grouped by the taxonomy term. Doing this outputs the following:

Term 1
--- Node 1
Term 1
--- Node 3
Term 1
--- Node 7
Term 2
--- Node 6
Term 2
--- Node 9
Term 2
--- Node 12

There is a Drupal 6 tutorial here that explains how to fix it, but it doesn't work under Drupal 7.

It seems like such a simple task, yet after many days of trying, I can't get it to work! I've found many threads of people asking the question, but no solutions (at lease a solution which doesn't involve installing taxonews).

In your view add two fields:
- Node title
- Taxonomy Term

You are right up to here.

Now:

Set the "Taxonomy Term" field to "Exclude from display"
Select your views' format as unformatted list; use "Edit settings" for the format
Set "Grouping Field" as "Taxonomy Term"

For details, view my views' export data in pastebin.

I resolved the problem of duplicated grouping fields :D

So, for people who have the same problem, just disable your module Themer and it's done !

Hope it helps.


Way to prevent drush from eating custom profiles when updating core? I use drush make with a stub .make file to download a custom profile via git.

that profile has all of the modules I want all of my sites to start out with.

If I then go into that site, and run "drush up drupal", it will update core, and remove my custom profile.

This is not good, since all of the modules I downloaded with my install profile's make file get stuck into the profiles/myprofile/modules folder. This basically removes all of my installed contrib modules, and drush doesn't give me a way to put them any where else, so basically, I can't update core with drush.

Consider to use Aegir. It supports this usecase.


Adding a new content type programmatically in .install file or .module file? There are 2 different ways to create a new content type programmatically.

First one, which I also use, is to create it in your custom module's .install file in hook_install() using node_type_save() and attaching the fields also in hook_install() with field_create_field() and field_create_instance() .
The second one, which in Node Example module is used, is to create it in your custom module's .module file using hook_node_info() and creating and attaching the field instances in hook_node_type_insert()

I am preferring the first method, since my feelings say that is better to maintain (i.e. adding/updating new fields via hook_update_N()) and it suits better in .install file. But, I keep myself asking why it is done other way in Node Example module.

Does anyone know the CONs and PROs of using both methods to create a new content type in code?

Some hooks, like hook_delete are only called on the module that defines the node's content type. If you save content type to a database using node_type_save(), it might not be recognized as "defined by module" - it acts as content types created by user. Unless, of course, you will set $info['module'] to point at your module - in that case created entries should work the same way.

There will be no issue with that...with update method you can create the new content types...


What is required to get a custom module to appear in uninstall list? Solution: Ayesh K provides the correct answer below.

What is required to get a custom module to appear in uninstall list?  I thought all you had to do was specify a database schema in hook_schema(), but I've done so and my module does not appear in the uninstall list.  Currently my module consists of the following code in the .install file:

<?php

/**
 * Table schema definition for the Events Sponsors module.
 */
function event_sponsors_schema() {
    $schema['event_sponsors_sponsors'] = array(
        'description' => 'A collection of event sponsors.',
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => "Unique ID for the sponsor.",
            ),
            'name' => array(
                'type' => 'varchar',
                'length' => '255',
                'not null' => TRUE,
                'description' => 'The name of the sponsor.',
            ),
        ),
        'primary key' => array('id'),
        'unique keys' => array(
            'id' => array('id'),
        ),
    );

    $schema['event_sponsors_sponsor_relations'] = array(
        'description' => 'Maintains sponsor and node relations.',
        'fields' => array(
            'sid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The sponsor ID, as can be found in the sponsors table.',
            ),
            'nid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The node ID as can be found in the node table.',
            ),
            'ordinal' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The order this sponsor appears alongside the node.',
            ),
        ),
        'primary keys' => array('sid','nid'),
        'unique keys' => array(
            'sid' => array('sid'),
            'nid' => array('nid'),
        ),
    );

    return $schema;
}

Any insight is appreciated.

For Drupal 6, you needed to install/uninstall schema using hook_install and hook_uninstall.

This is not necessary for Drupal 7.

Module will appear in uninstall list if both of these conditions are met:

module implements hook_schema OR hook_uninstall in its .install file.
module was enabled once and now is in disabled status.

If the only purpose of hook_uninstall is to uninstall the schema, you do not need a hook_uninstall function. For variable_del(), etc: you need.
If you have any of these and module has data in the site already, you will see the uninstall check box.

A very simple solution for newbies like me in drupal 7.

You can't uninstall a module when it's running or active. So try, to disable your module first and it should appear to uninstall list afterwards.


Make certain pages available to logged-in users only I need some help and here is the issue:

I am building a site using Drupal 7.

I need to make certain pages only visible to logged-in users (each having their own username/password), other users should be simply redirected or shown an error message. Is this functionality maybe included in Drupal 7 itself or is there a module that does this (something simpler than Organic Groups)?

You need to use Content Access module for fine grained node view permissions.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

There is pretty simple programatic solution, you can read user role (and also if it is anonymous or registered) like this:

$roles=$GLOBALS['user']->roles;

you will get an array with roles of current user in $roles.

You can redirect that user depending on role with some logic using

drupal_goto ('url-of-the/page');


Custom module with custom node type, error Trying to get property of non-object en comment_node_type_delete() I'm quite new with Drupal 7 development, after researching and following some tutorials I was able to create my custom module that defines a new node type with some fields, but now I have a problem when I uninstall it, the hook_uninstall runs almost fine(the node type, the contents from my custom node, and the node fields), except that display this error after the uninstall:

  Notice: Trying to get property of non-object en
  comment_node_type_delete() (línea 344 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module).

This is from mymodule.install:

function mynode_uninstall() {

    $ournewtype = 'mynode';
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => $ournewtype));
    $nodeids = array();
    foreach ($result as $row) {
        $nodeids[] = $row->nid;
    }
    node_delete_multiple($nodeids);
    node_type_delete($ournewtype);
    field_purge_batch(500);
    drupal_flush_all_caches();
}

I believe the problem is that it's expecting an object, and you are passing a string. Try changing this:

node_type_delete($ournewtype);

To this:

$node_type = node_type_load($ournewtype);
node_type_delete($node_type);

One other thing, instead of this:

$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
    $nodeids[] = $row->nid;
}

You can simplify it by using this:

$nodeids = db_query($sql, array(':type' => $ournewtype))->fetchCol();

It's a caching thing.  Type this line of code at the start of your hook and the problem goes away:

drupal_flush_all_caches();

For example:

function mynode_uninstall() {
    drupal_flush_all_caches();
    $ournewtype = 'mynode';
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => $ournewtype));
    $nodeids = array();
    foreach ($result as $row) {
        $nodeids[] = $row->nid;
    }
    node_delete_multiple($nodeids);
    node_type_delete($ournewtype);
    field_purge_batch(500);
    drupal_flush_all_caches();
}


Retrieve value from an array I have an array, that I want to retrieve the values from.
When I test the array with a print_r, it says that it has the right values. But when I want to show them  in their right places, it says that it has no values.

function employees_items($nodeid, $language)
{
  $query  = db_query(//SOME QUERY);
  $rows   = array();

   foreach ($query as $row) {
    $rows[] = array(
        $row->nid,
        $row->title,
        $row->field_service_nummer_value,
        $row->field_support_email_value,
        $row->uri,
    );
}

    return $rows;

}

Here I want to retrieve the values...I want the value in $row->uri. The errormessage: Trying to get property of non-object i employees_block_view()

  function employees_block_view($delta = '')
 {
 if (array_key_exists($brandpage_id_page, $medarbejder_brandpages))
    {
     switch ($delta)
    {

        case 'employees':

        $employees = employees_items($brandpage_id_page, $lang_name);

        foreach ($employees as $row)
            {

              $block['content'] .= '
';
              $block['content'] .= 'uri). '" alt="Vores support medarbejder" />';
   }
  return $block;
 }

Try $row['uri'] instead.  As 'uri'  is merely the key and not another object.

In this line of code:

$block['content'] .= '<img style="width: auto; height: 100px;" src="'.file_create_url($row->uri). '" alt="Vores support medarbejder" />';

you refer to another object, the uri ($row->uri). Within the $row array, that you printed with print_r, there is the key 'uri'. To get the value of that key you should use $row['uri'].


Create a view block that shows list of nodes that references same node as current node I have two content types. "Article" and "Collection". Any article can be placed into collection. Also when you create collection, you can select articles to be placed into collection. So I have created "collection" as node reference field in "Article" content type, and "article" as node reference field in "Collection" datatype.

Now when I am on any article page, I want to create view that shows other articles from the same collection. I have tried adding "collection" as relationship and contextual filter as "NId" with relationship with "collection", but it is listing all articles that is having any collection(may reference to other collection) and not the articles that belongs to collection of current article.

Am I doing something wrong?

Please suggest.

-- Thanks for your time.

Let us assume the the filed in collection that referes to article is field_entity_article

Then you would do the following.

With in your view first you would add a relationship called Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_entity_article)
The you would add another relationship Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_node_article) While you are here select the previous relationship you created from the dropdown Relationship
Add a contextual filter of the type content: nid and provide default argument and select node id from url form the dropdown.
Add the required field and give the second relationship we created for this.

That should do it.

millionleaves, did you succeed?
In my approach i have "other answers" for the same question, but on the all answers pages the block is the same.

The reletionships are:
Entity Reference: Question
(Content entity referenced from field_question) Entity Reference: Referencing entity


It's possible to pass a variable on attach_library in a template on Drupal 8? I need to pass a variable to a library called on a Twig template, is this possible?

{{ attach_library('theme/some-library') }}

.module

/**
 * Implements hook_ENTITY_TYPE_load()
 */

function my_module_node_load($nodes) {
    foreach ($nodes as $node) {
      if ($node->getType() == 'article') { // is of article content type
        $data_passer = &drupal_static('my_module_node_field_name');
        // use &drupal_static to pass value between hooks.
        $data_passer = $node->field_name->value;
      }
    }
}

/**
 * Implements hook_page_attachments()
 */
function my_module_page_attachments(array &$attachments) {
    if (!empty(&drupal_static('my_module_node_field_name'))) {
      $data_passer = &drupal_static('my_module_node_field_name');
      $node_field_name = $data_passer;
      $attachments['#attached']['drupalSettings']['my_variable'] = $node_field_name;
    }
  }
}

.js

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_behaviour = {
    attach: function (context, settings) {

      alert(drupalSettings.my_variable); //alerts passed in node field_name

    }
  };
})(jQuery, Drupal, drupalSettings);

I have passed my variable in twig like this:
{{ attach_library('theme/library' ~ variable ) }}


How do I change a field with hook_node_presave()? In Drupal 7, I was using hook_node_presave() to update some hidden fields in a node.

function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->field_fieldname['und'][0]['value'] = importantfunction();
    }
}

In Drupal 8 I cannot do the same thing. Looking into the object I tried this:

function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->values['field_fieldname'][0]['value'];
    }
}

It won't work though. I am aware that a lot have changed in Drupal 8 and I am studying it, but I did not find an answer to this yet.

A bit outdated but still a great resource:

http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

Also the documentation on drupal.org: https://www.drupal.org/node/1795854

In short, fields are lists of objects that use property and array access magic methods to simplify reading and writing values to them:

// Set a value, the field class will decide what to do with it, usually write to the primary property...
$entity->field_fieldname = importantfunction();

// The default property is often called value, but for reference fields, it is target_id, text fields also have a format for example
$entity->field_fieldname->format = 'full_html';

// By default, you access delta 0, you can also set other deltas.
$entity->field_fieldname[1] = importantfunction();

// You can also append a new item, without hardcoding the delta.
$entity->field_fieldname->appendItem(importantfunction());

// Note that when accessing fields, you must always specify the property:
print $entity->field_fieldname->value;
print $entity->field_fieldname[1]->value;

// What basically happens internally for the above is:
$entity->get('field_fieldname')->get(0)->get('value')->getValue();

This is a very late answer.

With \Drupal\node\NodeInterface interface, I'm using that snippet to achieve your needs :

/**
 * Implements hook_node_presave();
 *
 * @param \Drupal\node\NodeInterface $node
 */

function module_name_node_presave(\Drupal\node\NodeInterface $node) {
    if($node->get('field_name')->getString() != 'search') {
        $node->set('field_name', 'new field value');
    }
}


presidency of drupal template file I am new to drupal themeing, I have tried to find the presidency of template files(.tpl.php).. So my question is for a particular scenario if I have html.tpl.php, page.tpl.php, block.tpl.php, node.tpl.php, taxonomy-term.tpl.php, template.php,

which file going to run first?
if I want to make change some variable's value for page.tpl.php/html.tpl.php then I need to write a function XXX_preprocess_page()/XXX_preprocess_html() according to this listed presidency (https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7) ?

Answer 1:-template.php file will runs first.you can check it by using die() on top of all files.

answer2 :-For changing some variable's value for page.tpl.php/html.tpl.php use function function XXX_preprocess_page().

html.tpl.php -> Handles meta info, body classes

page.tpl.php -> Handles content body display

node.tpl.php -> Handles content display

field.tpl.php ->Handles per field display

Template.php provide display alteration  for all these files.

html.tpl.php will always be used before page.tpl.php (unless you hack core in some way).  typically, variables available in html.tpl.php are not the same as variables available in page.tpl.php, so you shouldn't have an issue with conflicts.  What exactly are you trying to do?


Cant get desired results for multiple sort criteria in a view I have created a points table for a race event and would like to sort the results in a specific order.

I am working with a table view that contains 3 sort criteria:

the race event (working fine done via table settings)
class of a car A, B , C and
the points each driver receives.

I would like the order to be A then points B then points C then points regardless of what class has the highest points.

Problem:

If for example a C class car has points higher than any B class car then the stacking order is ACB. As soon as any B class car gets higher points than the C class car then the order is ABC (how I would like it). This can be seen in class A where Driver 2 has the lowest points of all.

I have tried re arranging the sort order but that does nothing.

Can i suggest removing the grouping and getting the single table to display as you would like it and then once you have done that apply the grouping. It sounds as if youre sorting by points not by car class - can you change the sort to car class then add the group.

Or group by event and then sort by car class and points.

You can use hierarchical select module which has good option for customizing the hierarchical points


Constraint on paragraph field not working Here is a very simple code:
1-My constraint plugin (MyConstraint.php)
/**
 * @Constraint(
 *   id = "MyConstraint",
 *   label = @Translation("Never Validated", context = "Validation"),
 *   type = "string"
 * )
 */
class MyConstraint extends Constraint {
  public $message = "error %value";
}

2-My constraint validator (MyConstraintValidator.php) [=>addViolation in all cases]
class MyConstraintValidator extends ConstraintValidator {

  public function validate($items, Constraint $constraint) {
    dpm("I am displayed");
    $this->context->addViolation($constraint->message, [
              '%value' => 10
            ]);
    return;
}

3-My constraint added to my bundle
function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if($bundle=='my_bundle'){
      $fields['my_paragraph_field']->addConstraint('MyConstraint', []);
    }
}

Result:
1-The dpm message 'I am displayed' is displayed
2-The entity is saved without any validation error
Notes:
-I have other constraints which are working well, If I test one of them (on my_bundle), the violation of this working constraint will be displayed but not the one with the code detailled here.
-The problematic constraint is added to a paragraph field... I suspect the problem is coming from there
-Nothing in the error logs.
I am looking for a hint to where to look.

On your addConstraint() your second parameter is an empty array - if you do not want to add any options leave that empty or use NULL

You need to add
namespace Drupal\my_module\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the MyConstraint .
 */
class MyConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {

    if (!$item = $items->first()) {
      return;
    }

    $field_name = $items->getFieldDefinition()->getName();

    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();

    if ($entity->hasField('my_paragraph_field')) {

      $value = $entity->my_paragraph_field->value;

      // Check if the value matches or not.
      if ($value != 10) {

        $this->context->addViolation($constraint->message, [
          '%value' => 10
        ]);
      }

    }

  }

}

For reference : Adding Constraint to entity referenced Paragraph field


how to render a welcome page in page--front.tpl.php I have a template page--front.tpl.php. It contains all different stuffs and a welcome message, wrapped in a div container. Since, I want it to be editable, I created a new basic page called 'Welcome message'. It opens in a separate node 'welcome-message'.

Now I want this to be rendered in page--front.tpl.php in given div container. Any suggestions?

Login as admin to the site, visit "admin/config/system/site-information" , scroll down to find setting for for front page and then form "Default front page" set the node relative path to be used as default front page that looks like "welcome-message" in your case.

with the above process you have informed drupal to use the node you have created as front page.

Now remove the hard-coded page front template you have created before as "page--front.tpl.php" because it will be used over the node till its present there.

clear your caches.


Facets and Apache Solr in Drupal 7 - Clicking Facets results in no results being show I'm having a bit of an issue with Facets and Apache Solr, I'm not sure whether the fault lies with Solr or the Facets API.

I am using Solr as my search engine and I get results being shown when searches are performed, also shown are the amount of matches in specified fields/facets.

E.g. I search for 'content' - there are numerous values for 'content' within different categories such as 'category1', 'category2'

The search result shows as:

category1(5)
category2(7)

Implying there are 5 results in the facet category1, and 7 results in the facet category2, these are also links, however upon clicking these links the search shows as "no results found". Odd behaviour, has anyone experienced anything like this before? if so any pointers on where to look in order to resolve the issue?

I'm hoping this question is quite clear, if not just ask and I'll try provide some more details.

Thanks, Dan.

This is very odd behaviour, can you ensure you are:

running the latest version of apachesolr (3.6.1)
running the latest version of the apachesolr module (7.x-1.1) OR search_api module (7.x-1.3)
are running the latest schema.xml and solrconfig.xml (hopefully the 3.x version)

Also, try dropping and re-creating the entire index, this normally addresses more problems.

I would start by looking at how the url for the solr query is being built and testing it directly against the solr engine to see if it returns any results. I guess once you see the query built for the link you will understand why it returns 0 results. Happy hunting :)


Multiple upload image using managed_file I'm trying to do a very simple thing (seems not that simple at all) in my custom form, to add multiple files using the managed_file form api. Like in the admin, select a file, upload, then a new input file appears.

But I can't achieve that... do I need a callback ???

    'gallery' => array(
        '#type' => 'managed_file',
        '#name' => 'gallery[]',
        '#title' => t('Gallery'),
        '#upload_location' => 'public://',
        '#attributes' => array(
            'multiple' => 'multiple',
        ),
    ),

Thanks

In Drupal 8, add '#multiple' => TRUE

Example:

$form['images'] = array(
  '#type' => 'managed_file',
  '#upload_location' => 'private://images/',
  '#multiple' => TRUE,
  '#upload_validators' => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(25600000),
    'file_validate_image_resolution' => array('800x600', '400x300'),
  ),
);

More about form api: Introduction to Form API

Complete details of upload multiple images using from API

/**
 * our example system settings form
 */
function mf_settings_form($form,&$form_state) {
  $form = array();

  $form['managed_file_example'] = array(
    '#type' => 'managed_file',
    '#title' => t('Managed File Example'),
    '#default_value' => variable_get('managed_file_example',''),
    '#upload_location' => 'public://managed_file_example/',
  );

  $form = system_settings_form($form);
  $form['#submit'][] = 'mf_settings_submit';

  return $form;
}