How to export paragraph bundles with features? According to paragraphs documentation, it's should be possible to export paragraph bundles with features module, but whatever I search, I can't find any option in the features component section for doing this.

Paragraphs documentation

  Features:
  This module has some overlapping function with field_collection, but this module has some advantages over field_collection.

  Different fields per paragraph bundle
  Using different paragraph bundles in a single paragraph field
  Displays per paragraph bundle
  Bundles are exportable with features.
  Entities, so: exportable field bases/instances, usable to show in Search API, used in Views

It seems that features not treated the same for every paragraph types because I can't see paragraph type in the features component section for some of the created paragraph types.

Paragraphs in D8 are entity types. So to create a feature with a paragraph bundle definition, you will need at least:

The paragraph type definition
The Entity form display
The Entity view display
The field instances you use.
Core override fields.
Optionally, you will need the field storage definitions.. but generally it is best to put these in a separate feature like core since fields can be used in multiple places.

The easiest way to get all these is to create a new feature and search for paragraph.[type-machine-name].  E.g. I have a paragraph type named banner, so I created a paragraph_banner feature by searching for paragraph.banner and adding the results.


How to configure the YouTube Field and Mediafront modules? I was told that the latest dev version of MediaFront has support for the YouTube field module. How do you configure the fields and the modules so that the embedded YouTube video is displayed using the MediaFront player?

What I'm trying to do: I have a content type that allows for YouTube URLs to be copied in it creates a list of all the YouTube videos that were entered in that node. I want MediaFront to use that list of YouTube URLs in the MediaFront player.

Also in the read it says this:

 7. Change the Manage Display settings for Media link.

    Set up the fields in this order and with these settings:

    Field           Label       Format
    Body            Hidden      Default
    Media URL       Hidden      MediaFront Player

    In the Media URL player settings, set the MediaFront preset to
    nodeplayer. Hit Update. Hit save.
            "

I cannot enable the MediaFront player for the textfield "Media URL".

Edit your textfield (admin/structure/types/manage/media/fields/[YOUR_TEXT_FIELD]).  Under the Mediafront settings Field type, set field type to 'Media' and Media Type to 'Media Content'.

You must create a mediafront preset (admin/structure/mediafront) before you can associate the textfield to mediafront player.

After your preset is setup, go to manage field of your content type (admin/structure/types/manage/[YOUR_CONTENT_TYPE]/display).  For the testfield that stores your media url, set the Format to Mediafrontplayer and set set the player settings to the Mediafront preset that you created.


Deprecated Dependency Warning not removing In my Drupal 8.9.6 (Installed with Lightning distribution) Status Admin Page, there are three warnings showing after updating several modules and core to the latest versions:

DEPRECATED DEPENDENCY: ENTITY EMBED Lightning Media 5.0 will not include the Entity Embed module. Please add it to your project directly: composer require drupal/entity_embed:^1.0
DEPRECATED DEPENDENCY: VIDEO EMBED MEDIA Lightning Media 5.0 will not include the Video Embed Media module. Please add it to your project directly: composer require drupal/video_embed_field:^2.0.
DEPRECATED DEPENDENCY: VIEWS INFINITE SCROLL Lightning Media 5.0 will not include the Views Infinite Scroll module. Please add it to your project directly: composer require drupal/views_infinite_scroll:^1.6.

I have installed the latest versions of these contributed modules through composer. But the warning not going away from the admin status page. How to remove these warning?

The Lighting Media modules have hard-wired checks to report this information if it finds Video Embed Media or Entity Embed & Views Infinite Scroll installed. It doesn't check the Composer requirements to see if the warning message is still applicable.
Either ignore the warning until the 5.x release is out or patch away checks in hook_requirements() if it bothers you that much.


How to enable Submit Button after filling out the required fields? I have created custom Content Type and I would like to disable the submit button, till the user has filled out all the required fields.

I should enable the submit button, once the user fills out the required fields, how do i achieve this?

check out #states visible #states invisible in drupal.

http://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_process_states/7


Unable to Install/Uninstall a custom module I am new to Drupal development and was working on a module. It has since gotten entirely screwed up. This is in Drupal 7. The module was adding a field type with a widget and some theming. It also created several new tables.

My module does not show up in the module list, and it does not show up in the uninstall list either. I see that it is still listed in the system table, and I had manually disabled it there (and did the clearing in the cache_bootstrap table). I removed the entire module folder at one point and have tried with it there and not there, clearing cache at each step.

Though I could live with the module still being "in the system", I would greatly prefer not to. I also have the major problem of I can not create a module with that name anymore as adding in a folder (even with a new, much simpler codebase for the module) does not make it show up in the list. To make matters worse this is a group project so it is not as if I could just start with a clean install of Drupal and start over.

So I am curious how I could remove the existing module so that I am able to "start over" with my own module?

Thanks!

You should pay close attention to the Module developer's guide on Drupal.org.

To appear in the lists, the module should be placed in its own sub-directory like modules/modulename, and it must have a properly configured modulename.info file in addition to a file named modulename.module.

If you have properly segregated the functions into the proper files, there should be no problem. Drupal will detect them automatically and will maintain an entry in the system table for the module. You should be able to activate or deactivate the module normally.

The installation routines (which are used to create or to remove the tables should be handled by functions in a modulename.install file. Drupal will look for the modulename.install file to see what tasks are required for installation or removal of the module.

My first advice would be to make sure that the module is correctly structured, and let Drupal handle the deactivation and uninstall, but you can do it manually if all else fails.

Deactivate the module and drop the tables using queries directly on the database. Start by looking for the definition in the system table.

UPDATE system SET status=0 WHERE type='module' AND name = 'modulename';

Then manually DROP any tables your module created and remove any variables it created.


drush cc all != "Flush all caches" If I try and clear my drupal site's cache using drush cc all command - the command completes successfully but when I pull up my drupal site in a browser its a mangled mess because there is no CSS.

Whereas if I sign into my site as an admin go to "Flush All Caches" my site works just fine.

This is discussed briefly here: http://dnotes.net/blog/dark-side-drop/david/why-all-my-css-gone-drush-cc

Although I don't really see a solution.

I think the underlying issue is that drush cc all isn't re-creating LESS CSS files but the "Flush All Caches" is? Is there some way I can make drush re-create the LESS files after a cache clear?

Thanks
Brad

Clearing cache via the UI and via drush both end up calling drupal_flush_all_caches(), but there is a subtle difference.

When you run from the UI, the PHP executes as Apache (or however you have your webserver configured).  When you run from drush, it runs as the user who executed the command.

The problem in your case is that the LESS module will run its cron functions, which clears out the less directories in sites/default/files and makes a new one.  When this happens, there is often a permission problem:  your drush user owns the less directory and Apache can't write to it.  Therefore, your CSS files don't get regenerated and your site end up unstyled.

My solution is to make sure my drush user is also in the Apache group on my server, and that my sites/default/files directory has 2775 permission on it and with ownership by apache:apache.  I also make sure that the umask of httpd makes things group writable.

This makes sure that any files and directories that get created always have group ownership by apache, and that Apache can write to any directories that get made, regardless of whether it was done by httpd or from the command line.

EDIT:

There is one more difference that is worth noting.  When you clear with drush, you just clear the caches.  When you clear from the UI, you clear the caches and then the page reloads.  When the page reloads from a cold cache, the parts used to rebuild that page get cached again.  This includes making CSS files from the LESS sources.


drupal #default_value not working for #type radios i am editing a form in drupal 7.1 and want to add a group of radios
    $form['yearofstudy']= array(
   '#title'=>'What is your year of study',
   '#type' => 'radios',
   '#options' => array(1=>'first year',2=>'second year',3=>'third year',4=>'fourth year',5=>'fifth year'),
   '#required' => true,
   '#default_value'=>array(1,0,0,0,0),
   );

The problem:
I intended the first option to be selected but this is what am getting

Please help.

A radio group can only have one radio selected. Did you try '1' as default value?


filter navigation, site content, etc I am really new to Drupal, so this is a beginners question.
I need to create a website with a dropdown within the header, where visitors can choose a region (not a language, just a region, like "Europe", "US", ...). The entire page should be filtered according to this selection, so if the visitor chose "US", some parts of the navigation or parts of the content should not be visible.

Is this possible with drupal?

And, more importantly: how would you go about this? The only thing I could think of is create a taxonomy for each "region" and assign content items and navigation items. Is that a good idea? Is there a better way to go?

I'd be thankful for any suggestion. Thank you.

I'd try this link. So install that then apply some classes to the menu items that you can use in JQuery to target the links and have the dropdown links trigger them to show/hide. I'm willing to provide further explanation if there's something you're unclear of. Sadly there is no current module or plugin to provide this functionality that I know of.


Media module and views I am using Media module on a Drupal 7 installation and have created a content type called Media. I then used the Multimedia asset of the Media module, so users can upload both images and videos.

I now want to create a view with the latest videos and also latest photos, but there is not anything on the filter to select a video (or photo). How can I add such a filter?

Try this:

Create a new taxonomy vocabulary called 'Media Type' with terms 'Image' and 'Video.'
Add a taxonomy field to your Media content type.
Add a taxonomy field to your view (hidden/exposed/however you'd like)

You'll then be able to filter by the value of the taxonomy field.


Add a hyperlink underneath the table of a Page View? I have a Page View that is being displayed as a table. Underneath that table I want to add a simple hyperlink.

I was looking into hook_views_pre_render but I do not see any way to do add this. I also tried hook_preprocess_node. In order to add an anchor tag underneath the table, I really don't know if I should be looking at view hooks or page hooks, or ?

Question:
How do I add a hyperlink underneath the table of a Page View?

There's a few ways to do that.

Edit View
Click "Footer > Add"
Add your footer HTML as "Global: Text Area"

Another way is to add a block on that page under the view.

admin/structure/block/add
Set page visibility to only your View page path
Set region to "Content" below "Main page content"

If you want more control or placement, you can theme the View page

Edit the View
Click "Advanced > Theme > Information"
You would override the page level "views-view.tpl.php" template renamed to match your View (e.g views-view--my-view.tpl.php ) in your theme dir.


Where should hooks go? Only in modules? I need to use 1 hook from webforms.  Where does this belong? Do I have to make a custom module just to implement 1 hook or is there a more appropriate place?

A custom module is the most appropriate, probably only, place for your hook(s).

Most hooks only get run for modules; there are exceptions such as hook_form_alter(), hook_theme() etc. which are also called for themes, but generally speaking you'll need to write a custom module for any hooks you want to implement.

In case you're not familiar with building modules take a look at the Module Developer's Guide.


How do I remind users to pick an avatar? I use the Avatar Selection Module to provide a list avatars my users can choose from. I don't want to make choosing an avatar required, but I'd like to have a persistent reminder for users who have not picked an avatar for themselves.

How can I identify users who have NOT chosen an avatar and use Context (or something else) to conditionally display a message in a block like, "Hey you haven't chosen an avatar yet. GO HERE (User Form) to choose one."?

Profile Complete Percent helps to guilt users into filling their profile details. This isn't avatar specific, but you can configure the PCP block to only use a single field for its percentage calculation.


How can I override a module's file via hook_menu_alter()? I have the following code in my hook_menu_alter().

<?php

function bonus_menu_alter(&$items) {

  if (!empty($items['things'])){

    $items['things']['title'] = t("New title");
    $items['things']['callback'] = 'new_callback';
    $items['things']['file path'] = drupal_get_path("module", "bonus")."/includes/";
    $items['things']['file'] = 'bonus.pages.inc';

  }

}

The problem is that the file path of the new file is including the original modules path and spitting this out:

/var/www/staging/sites/all/modules/things/sites/all/modules/bonus/includes/bonus.pages.inc

The original implementation of the parent hook_menu():

/**
 * Implements hook_menu().
 */
function things_menu() {
  $items['things'] = array(
    'title' => 'Things title',
    'page callback' => 'things_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/things.pages.inc',
  );
  return $items;
}

What could I be doing wrong?

I think this happens because your alter hook does not update the value for $items['bonus']['module'], which was automatically set to 'things' when menu_router_build processed things_menu(). Try this:

$items['bonus']['module'] = 'bonus';
$items['bonus']['file path'] = '/includes/';
$items['bonus']['file'] = 'bonus.pages.inc';

or simply this, more like the things module does:

$items['bonus']['module'] = 'bonus';
$items['bonus']['file'] = 'includes/bonus.pages.inc';


Printing date with custom format I want to print "event_info_date" Date (Unix timestamp) field with custom format in node.tpl.php.

I'm using this code:

<?php print date("Y/m/d h:i:s", $node->event_info_date['und'][0]['value']); ?>

And it prints: 1970/01/01 01:00:00, but it isn't value from my field.

I've also tried this:

<?php print format_date($node->event_info_date['und'][0]['value'], 'custom', 'Y/m/d h:i:s'); ?>

But it doesn't print anything. Any ideas?

Try this:

print date("Y/m/d h:i:s", strtotime($node->event_info_date['und'][0]['value']));

Hope this will help you.


MODULENAME_page_attachment_alter() Undefined I have a custom module named rsm_library.  I would like to use hook_page_attachment_alter() in rsm_library.module and called the hook as follows:

rsm_library_page_attachment_alter($attachments);

I then issued $ drush cr to clear the caches.

This resulted in:

  AH01071: Got error 'PHP message: Error: Call to undefined function
  rsm_library_page_attachments_alter().

First, there's a typo. It's not attachment, it's attachments.

Next, you can't simply call a function without defining it.

In Drupal hooks are used to modify existing code when it's being processed.

See hook_page_attachments_alter for an example of what you are supposed to do.

Using hooks, you simply define a new function prefixed with your module's machine name, put your code/alterations in there, and in the end it's automatically being hooked up for execution. No need to call it again.

function hook_page_attachments_alter(array &$attachments) {

  // Conditionally remove an asset.
  if (in_array('core/jquery', $attachments['#attached']['library'])) {
    $index = array_search('core/jquery', $attachments['#attached']['library']);
    unset($attachments['#attached']['library'][$index]);
  }
}


Ignoring unpublished/published as criteria for "Has new content" I have rudimentary Recycle Bin system based on Flags and unpublishing / republishing content. However, when republished, "Has new content" displays Updated.

I still want New and Updated for when there are new comments so I'm not sure of the best way to go about it.

Thanks.

You need custom code to achieve this. There's 2 things to know here:

Updated Status Logic

The logic for driving the New & Updated labels is based on the history table (which stores the last time a user viewed a node) & the node.changed column:

$changed = $this->get_value($values, 'changed');

$last_comment = module_exists('comment') && !empty($this->options['comments']) ? $this->get_value($values, 'last_comment') : 0;

if (!$last_read && $changed > NODE_NEW_LIMIT) {
  $mark = MARK_NEW;
}
elseif ($changed > $last_read && $changed > NODE_NEW_LIMIT) {
  $mark = MARK_UPDATED;
}
elseif ($last_comment > $last_read && $last_comment > NODE_NEW_LIMIT) {
  $mark = MARK_UPDATED;
}
return $this->render_link(theme('mark', array('type' => $mark)), $values);

Essentially, it's comparing when a user last viewed a node vs. when a node was last changed.

What isn't known, is what was changed (e.g. the publish status) so to implement some sort of exclusionary logic you're going to have to track the history of publishing/unpublishing to check if the last update was just a change in publish status (node.status).

Updated Status Display

Assuming you have that logic in place, it's possible to override the output a views field. Here you can extend the views_handler_field_history_user_timestamp class with your own custom class implementing a render() method that adds the logic to check whether the last change was only a publish status change. In the final step, you can use hook_views_data_alter to override the handler for the Has new content field.


how to get data in views templates I am trying to use the field data inside of a views template to modify its output. I looked at the available fields with devel, and, inside of a field template, I used the following code:

$row->field_field_twitter_screen_name[0]['rendered']['#markup']

and many more like this. It worked fine. The only issue is that the page was giving me a lot of notice message from this code:

*   Notice: Undefined offset: 0 in include() (line 28 of [path-to-file].tpl.php).

Is this not the correct way to get data? If so, what is it?

It shows you the Notice because somewhere in your data array you have missing data for a specific node. As for being correct, yes, it is a good way to alter the output. Try checking the data before printing it.

Something like

if(isset($row->field_field_twitter_screen_name[0]['rendered']['#markup'])) {
  //do custom action here
}

Edit: You can also make good use of $content variable here.


How to publish nodes 3 times a day? I have a list of unpublished nodes, created with the Views module. I would like a task to be run 3 times a day, at specified times. Every time the task  runs, only one of the nodes on the list should be published. How can I do this?
Steps I have tried
Scheduler
The Scheduler module requires you to specify the exact time you want the node to be published. This makes it complicated, as I would have to work out when each node is supposed to be published.
Views Bulk Operations + Rules + Rules Scheduler
With the Views Bulk Operations module, you can create a list of Nodes that are exposed to the Rules module. Rules can then act on the list and publish the node on the list. You can tell Rules to only publish a specific number of nodes.
This works perfectly. Except, it doesn't seem possible to schedule the Rule to run 3 times a day.
You can link the Rule to the main site Cron job, but this doesn't seem very precise as the Cron job could run more than 3 times.
There is a Rules Scheduler module (a sub-module of Rules), but it doesn't look like you can use this a Rules condition. There also doesn't seem to be a way to specify the running time.
Job Scheduler
This lets you set a time, but it doesn't seem to integrate with Rules or Views.

Using modules VBO, Rules and Rules Scheduler

About your approach using modules Views Bulk Operations (VBO), Rules and Rules scheduler (submodule of Rules), for which you wrote "it doesn't seem possible to schedule the Rule to run 3 times a day.": that appears to me "a" valid approach.

What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 8 hours (instead of just 1).

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

Using modules Rules and Rules Once per Day

There is a fairly new module related to rules, i.e. the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way I understand/Read this (haven't experimented with it yet though) is like so:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

So by creating 3 similar rules, you could have 1 of them run around (say) 6 pm, another one around 2 pm and the ast one at 10 pm.

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


Executing drupal file using shell_exec I wish know whether a drupal function/file can be executed using 'shell_exec()' from another drupal function.
Any help is appreciated.

Drupal imposes no limits on how you can use php. If it's possible to do what you need to do in php, it's possible in Drupal.

There are no Drupal-specific API methods to help execute code through the shell, so just approach this as you would if Drupal wasn't involved.

A simple method, depending on what you need to do, might be to install Drush and invoke commands using that. Then the bootstrap/file includes will be handled for you automatically and you'll need to write less boilerplate code.


How to display image preview right away for managed_file form element? I have managed_file for uploading an image in my form and I would like to display the image(thumbnail) right away when the user uploads it so he won' have to submit the form to see it(I am rendering it in the form if the image exists).

I think there might be an issue with the ajax wrapper/structure so I am not sure how exactly it should be achieved without too much customization/coding.

This is my solution:

<?php

namespace Drupal\foo\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Element\ManagedFile;

/**
 * @FormElement("managed_image")
 */
class ManagedImage extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $info = parent::getInfo();
    // @see \Drupal\image\Plugin\Field\FieldWidget\ImageWidget::formElement()
    $info['#accept'] = 'image/*';
    $info['#image_style'] = 'thumbnail';

    return $info;
  }

  /**
   * {@inheritdoc}
   */
  public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
    /** @var \Drupal\Core\Image\ImageFactory $image_factory */
    $image_factory = \Drupal::service('image.factory');
    $element['#upload_validators'] += [
      'file_validate_is_image' => [],
      'file_validate_extensions' => [implode(' ', $image_factory->getSupportedExtensions())]
    ];

    $element['#description'] = [
      '#theme' => 'file_upload_help',
      '#description' => isset($element['#description']) ? $element['#description'] : NULL,
      '#upload_validators' => $element['#upload_validators']
    ];

    return parent::processManagedFile($element, $form_state, $complete_form);
  }

  /**
   * {@inheritdoc}
   */
  public static function preRenderManagedFile($element) {
    $element = parent::preRenderManagedFile($element);

    if (!empty($element['#files'])) {
      foreach ($element['#files'] AS $delta => $file) {
        /** @var \Drupal\file\Entity\File $file */
        $element['file_' . $delta] = [
          'preview' => [
            '#type' => 'container',
            '#weight' => -10,
            '#attributes' => [
              'class' => [
                'image-preview'
              ]
            ],
            'image' => [
              '#theme' => 'image_style',
              '#style_name' => $element['#image_style'],
              '#uri' => $file->getFileUri()
            ]
          ]
        ] + $element['file_' . $delta];
      }
    }

    return $element;
  }

}


How do I run cron as an authenticated user? On my site, user profiles are not public; the anonymous user does not have permission to access them.  However, I want to send a view containing a list of member profiles in an email with Rules Scheduler.  I am attaching the view to the email with views_embed_view().  However, the view content is not displayed because Rules Scheduler use cron, which embeds the view as anonymous user.

So my first thought was to somehow run cron as an admininistrator, but the Drupal documentation states this:

  Running cron as an authenticated user (Drupal 6 and earlier only)

  If triggering cron.php via the methods above, cron tasks will run as
  the anonymous user. For most cases this should be fine, but if Drupal
  cron has been customized to include tasks that must run as a certain
  site user (e.g. custom logic has been implemented in hook_cron() that
  requires special user permissions), the following script may be
  useful. This script authenticates a user of your choosing before
  calling cron.php.

  Note that as of Drupal 7, cron always runs as an anonymous user, so
  this will not work in Drupal 7 and later versions!

It doesn't give the reason why, but I assume this is some kind of security issue, and there is no alternative listed.  Is it flat-out impossible to run cron as an admin in Drupal 7+?

I don't think this is possible w/o some shenanigans.  If you look at drupal_cron_run(), you will see that it changes the user to anonymous (around line 5337 in includes/common.inc):

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

The only way around this would be to implement a hook_cron() and alter its weight so that it gets called first, and have it swap in the user that you want (which can be a little tricky in some cases.  This may also cause problems with some cron hooks, like search_cron(), which assume the anonymous user, and end up with weird results (in this case, there may be a security problem where privileged information is revealed to the anonymous user).


How to delete taxonomy term? I would like to delete taxonomy term. Unfortunately on taxonomy -> list I can only see "edit" button next to each term (under "operations"):

How can I delete the term I added earlier?

When you click "edit":
 Drupal will take you to the page where you can delete that term; right beside the "save" button:
 For bulk deletion you may take a look at the taxonomy manager module.


DIV covering over the login buttons in commons-origins theme We're using Commons 3. It uses a sub-theme of Adaptive Themes (AT). There appears to be a DIV that is blocking users from clicking on the signup | login area.

Should I file a bug on this or work around it with CSS?

The following is a work around.

#block-search-form  .block-inner {
    height: 30px;
}


Warning: uasort(): Array was modified by the user comparison function in FacetapiWidget->applySorts() I'm trying to build my own sorting function implementing hook_facetapi_sort() and sorting the following data by weight.

name, weight
dog, -2
cat, 1
zebra, -5
dolphin, 3
bee, 5

The code I wrote so far is the following one.

function zoo_facetapi_sort_animal(array $a, array$b) {
  $a = db_query("select weight from {animal} where name = :a", array(':a' => $a['#markup']))->fetchAssoc();
  $b = db_query("select weight from {animal} where name = :b", array(':b' => $b['#markup']))->fetchAssoc();

  $a_value = (isset($a['weight'])) ? $a['weight'] : 0;
  $b_value = (isset($b['weight'])) ? $b['weight'] : 0;

  return strnatcmp($b_value, $a_value);
}

The result is what I expected.

zebra
dog
cat
dolphin
bee

I get the following error message.

  Warning: uasort(): Array was modified by the user comparison function in FacetapiWidget->applySorts() (line 230 of /var/www/zoo.dev/sites/all/modules/facetapi/plugins/facetapi/widget.inc)

How do I avoid getting that message?

Register your own function as FacetAPI sort callback. Then select it in the FacetAPI sort order.

http://example.com/admin/config/search/facetapi/search_api%40default_node_index/block/field_animal_type/edit

http://drupalcontrib.org/api/drupal/contributions%21facetapi%21facetapi.api.php/function/hook_facetapi_sort_info/7

NB: You also accidentally collapsed the space between array and $b

function zoo_facetapi_sort_animal(array $a, array$b) {...}

/**
 * Implements hook_facetapi_sort_info
 */
function zoo_facetapi_sort_info() {
  $sorts = array();

  $sorts['active'] = array(
    'label' => t('Animal ...'),
    'callback' => 'zoo_facetapi_sort_animal',
    'description' => t('Sort by whether the animal is ...'),
    'weight' => -50,
  );

  return $sorts;
}

function zoo_facetapi_sort_animal(array $a, array $b) {
  ...
}


Batch API timeout during initialization I'm creating a module to batch import/update nodes in Drupal 7 based on input files that can be XML or other formats. Worst case scenario is they are like ~10-20MB and can contain 10-20k entries.

Currently, the module works fine for small files (~2k entries), but I get timeouts during initialization (before the actual batch job) for bigger files. The input file parsing is not the problem, it works fine and this is an example table of parsing times:

ENTRIES  PARSING (s)  FORMAT
     63        0.056  xml
    544        0.144  xml
   1706        0.202  xml
   2741        0.940  xml  <- batch job doesn't start
   3398        0.419  txt  <- batch job doesn't start
   7916        8.726  xml  <- batch job doesn't start
   8607       29.734  xml  <- batch job doesn't start

This is the relevant part of my module's code:

function batch_import($ps_platform, $ps_input_file) {
    # I've tried to change timeout limit with no luck
    set_time_limit(500);

    # Parsing the input file to my own class. The time spent for
    # different size files can be in the table above.
    $o_dat = new DatContainer($ps_input_file);

    # [1/2] Preparing the batch job array we will output
    #---------------------------------------------------
    $a_batch_job = array(
        'title' => t('Importing dat file'),
        'init_message' => t('Beginning dat import process'),
        'operations' => array(),
        'finished' => 'batch_finished',
        );

    # [2/2] Populate the operations sub-array with all the jobs we want to do
    # -----------------------------------------------------------------------
    foreach ($o_dat as $o_entry) {
        $a_batch_job['operations'][] = array('process_entry', array($ps_platform, $o_entry));
    }

    batch_set($a_batch_job);
}

The actual function to process each individual task doesn't do anything by now, it simply prints the progress.

function process_entry($ps_platform, $po_entry, &$context) {
    $context['message'] = "Processing: {$po_entry->s_name}";
    $o_node = _get_entry_node_by_id($ps_platform, $po_entry->s_id);
    $_SESSION['http_request_count']++;
}

Does anybody see where is the problem? After checking many examples for batch api, I'm quite frustrated because my code seems to be correct.

Regards and thanks for your time.

The timeout happens because of large amount of operations within $a_batch_job['operations'] array. For every operation defined queue item is created and stored in the queue table of the database.

Check the _batch_populate_queue() method.

Workaround

Instead of defining Pre-set list of calls, you can take a route of Alterable list of calls. So in your case it could be like this:

function batch_import($ps_platform, $ps_input_file) {
  # Parsing the input file to my own class. The time spent for
  # different size files can be in the table above.
  $o_dat = new DatContainer($ps_input_file);

  # [1/2] Preparing the batch job array we will output
  #---------------------------------------------------
  $a_batch_job = array(
    'title' => t('Importing dat file'),
    'init_message' => t('Beginning dat import process'),
    // Pass our parsed file as a parameter to the batch operation callback.
    'operations' => array('process_entry', array($o_dat, $ps_platform)),
    'finished' => 'batch_finished',
  );

  batch_set($a_batch_job);
}

And your process_entry() would look like this:

function process_entry($o_dat, $ps_platform, &$context) {
  if (empty($context['sandbox'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_entry'] = 0;
    // Assuming you implemented method for DatContainer class, that can
    // return number of records in the file and it's named rowCount.
    $context['sandbox']['max'] = $o_dat->rowCount();

    // Store the source file in the context.
    $context['sandbox']['source_file'] = $o_dat;
  }
  // Process 5 entries per iteration.
  $limit = 5;

  // Assuming you have method getRows to get N number of entries starting from X entry.
  foreach ($o_dat->getRows($context['sandbox']['current_entry'], $limit) as $po_entry) {
    $context['message'] = "Processing: {$po_entry->s_name}";
    $o_node = _get_entry_node_by_id($ps_platform, $po_entry->s_id);
    $_SESSION['http_request_count']++;

    $context['sandbox']['progress']++;
    // Assuming you have number for entry within file.
    $context['sandbox']['current_entry'] = $po_entry->entry_number;
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }

}

So now instead of N queue items you would have only one item, that would get called recursively as long as $context['finished'] < 1.

For more information about $context variable please visit callback_batch_operation() page. It's preferable to use this variable to store information used across batch operation callbacks, rather than $_SESSION.


Building Custom Forms in Drupal 7 I'm new to Drupal 7 and installed it on my local machine to play around.

I'd like to build a basic Job Posting Form and wanted to ask about questions/best practices regarding Drupal.

This was the process I was going to follow:

Create a new content-type "job", add a title, description and pay - all text fields.
Create a new module, then within the module build out the custom form to create a new job listing.  How do I associate the new form with the content-type?  Should I build the form code in my custom theme folder (template.php) or in a new module?
When the form is submitted, how does the data get saved?  How do I associate the submitted form with the database?  Most of the examples using the Form API only mention building the form but not how to store the data (in my example, storing the "job" as new content).

I'm not asking for you to write code for me, but I'm having a difficult time understanding the workflow and best practices for working with Forms in Drupal 7.  Any good guides on how to accomplish what I need would also be appreciated.

Great to know you're exploring Drupal! :D

Create a new content-type "job", add a title, description and pay -
all text fields.

Since you want to ask data from users or something like a survey, Geek Alvaro J Hurtado V is right. The Entityform module is the way do go since it uses entities and fields which are future proof and used in Drupal 8.
Brings me to another module called Views, Entityform works well together with the Views module. This module helps to create data lists without any coding needed. This is one of the most used module in the Drupal world. Check it out if you have time. :)

How do I associate the new form with the content-type?
When the form is submitted, how does the data get saved? How do I associate the submitted form with the database?

The Entityform module already handles this for you out of the box.
So what you need to do is to create your survey form using the Entityform module and you're basically good to go. You would have:

A public form where your anonymous/not logged in users can fill-up.
A content type where it relates the data submitted by the user.
A page which lists all the user submitted data.


Can't install modules from UI when site placed in subdirectory I have Drupal 8 installed in a subfolder (www.example.com/drupal), and I have my root .htaccess configured to mask the subfolder (i.e. the URLs resolve to www.example.com; /drupal does not appear in the URLs).

Everything works great except when I try to install new modules I get a 403 error.  I see in the URL for authorize.php that /drupal now appears in the URL.  Where I would expect www.example.com/core/authorize.php/, I instead see www.example.com/drupal/core/authorize.php/.  I imagine this is the reason for the 403?

What additional modifications do I have to make to /drupal/.htaccess in order to get access to the /core files required to install new modules?

Here's what's in my document root .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_URI} !drupal/
RewriteRule (.*) /drupal/$1 [L]

And the only modification to /drupal/.htaccess is to uncomment the subdirectory per the instructions in the file:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /drupal

You have to uncomment this line.

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal

Another option is to update module using drush.

drush up


Fine-grained flag permissions Is it possible to control permissions relating to flags more closely, either in flag.module or by installing another module? I'd like to be able to control permissions for each flag, such as "Flag content with this flag", "unflag content with this flag", "view this flag" etc etc.

Are you looking for a 'local' flag? Flags are already separated into global and local flags. For example, a global flag might be 'report this comment' and once one person flags the comment it is flagged for everyone. Local flags on the other hand are unique for each user, so for example a 'bookmark this' flag would only be for the current user context and other users wouldn't be able to modify their flags. From the documentation:

  Flags may be per-user, meaning that each user can mark an item
  individually, or global, meaning that the item is either marked or it
  is not marked, and any user who changes that changes it for everyone.

You set whether a flag is global or local when you create it.


Has anyone used beta profiling module For most of my projects i am using Devel module. Recently i looked at other module Profiling - it also provide integration with views and Panels. I was thinking to use this, as mentioned here it is stable but still lacks the Views and Panels support. So not sure i should use it or not (i am using views and panels).

Is there anybody who used this module and found it working (without bugs) ?

OR

You would recommend other module?

Thanks in advance.

I have used profiling 7.x-1.0-alpha1, as it was alpha release there were some issues. I hope those have been fixed in the beta release, so maybe you can use it. I would recommend not to use the beta version either; it can break anything.

However, if you are willing to learn how to use this module, just use it; it is not too risky.


Does this look right for adding a terms of use checkbox to register form? And also, how can I get node/terms to open target="_blank"?

<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'user_register') {
  $form['legal'] = array(
      '#type' => 'fieldset',
      '#title' => t('legal'),
    );
  $form['legal']['select'] = array(
      '#type' => 'checkbox',
      '#required' => TRUE,
      '#title' => t('Terms of Use*'),
      '#default_value' => 0,
      '#description' => t('I certify that I am over the age of 18, and I have read and agree to the '.l('Terms of use.','node/terms').''),
    );
  $form['#validate'][] ='customfunctions_form_validate_custom';
  }

}

function MYMODULE_form_validate_custom($form, &$form_state) {
    $legal = $form_state['values']['select'];
    if ($legal == 0) {
        form_set_error('select', 'Please check the agreement.');
    }
}

?>

Yes, but I would change

$form['#validate'][] ='customfunctions_form_validate_custom';

to

$form['#validate'][] ='MYMODULE_user_registration_form_validate';

and

function MYMODULE_form_validate_custom($form, &$form_state) {

to

function MYMODULE_user_registration_form_validate($form, &$form_state) {

Nothing wrong with your code, but this just keep with the Drupal naming convention ie search_form_validate,  node_form_validate, etc

Also

'#title' => t('Terms of Use*'),

is bad

'#title' => t('Terms of Use') . "*",


One Page User Profile How do I make a one-page user profile? I want to include wishlist, cardonfile and addressbook from commerce, and render all the data already inserted into the profile, and edit/create forms on the individual user page.

Thanks!

To keep this convo going even though I do not have a definitive answer...

I feel that is a pretty big question with a fair bit of config and templating even... So my short answer would be Views and/or Blocks. Depending on your needs maybe you could do just a views page with filters and relationships as you need populated with commerce entities and content types. Maybe you need views blocks, blocks, and content types with template files to render everything on the same page. My gut just tells me that's the pace to start. Views is Drupal cores way of bringing many things together.


What is the purpose of aggregation in view? What is the purpose of aggregation in view?

And why is it important to enable him when you make charts?

Without aggregation, Views fetches data from the database and lists that data in individual "rows".

When you turn on Aggregation some mathematical functions can be applied to the existing results under certain conditions. That is how you might get the SUM of all the values of a field, or the AVERAGE etc.

Charts usually don't display individual "rows" of data, they display statistical data that you get from calculating some values from the entire results list. That is why charts need Aggregation - to get to the numbers that are shown on the chart.


References versus Entity Reference This question has been asked before, but a while ago, looking for a fresh opinion. Many more people seem to be using references (perhaps because it's a port from Drupal 6) but the functionality of entity reference seems pretty good. Opinions? Thoughts?

I think the only way you will find out is through testing this for yourself. I  speak from experience in using Entity Reference currently in a project with success. It comes down to your needs. For example I needed a way to reference commerce products - which are not node entities - so the references module is useless. Entity reference was perfect for this case and would work with any other entity type.

With the massive change in drupal 7.x moving from a common mindset of "everything can be a node" 7.x core has emphasized and shown us the benefits of "everything can be an entity". With the success of entities you can pretty much guarantee that entity reference has a strong future in d7.x

I am not sure if there is any advantage in using references since Entity Reference does all that references does, while being much more powerful.

From the project page;

  "Note :
  - As the past couple months showed, the current maintainers are not up to the task. This module accepts new maintainers.
  - References will most probably be deprecated in the near future in favor of Entity Reference, which should probably be considered first
  on fresh D7 projects."

I think this says it all.

For the extended future developers should look into Relation which is expected to replace entity reference.


Drupal 7 add ajax listener directly to node form I'm trying to register an ajax listener to a checkbox on one of my standard node forms. I want to display certain regions of the form only in case, the field is checked. I can get the drupal ajax ecosystem to work, when I use it in a custom form, but I'm unable to make it work on my node forms.

First I hook into form_alter to check if I'm with the node type I want to add the listener for:

function interceptor_form_alter(&$form, &$form_state, $form_id) {
  if($form_id === 'film_node_form') {
    interceptor_dvd_listener($form, $form_state);
  }
}

Then I try to attach the ajax stuff to my checkbox, which name is field_dvd:

function interceptor_dvd_listener(&$form, &$form_state) {
  $form['field_dvd'] = array(
    '#title' => t('You want to display DVD informations too?'),
    '#type' => 'checkbox',
    '#ajax' => array(
      'callback' => 'interceptor_dvd_listener_callback',
      'wrapper' => 'checkboxes-div',
      'effect' => 'slide',
      'progress' => array('type' => 'none'),
    ),
  );
  return $form;
}

The function interceptor_dvd_listener_callback is never called. I try to print some debug information there, but nothing happens...

function interceptor_dvd_listener_callback($form, $form_state) {
  data_service_log_object($form);
}

UPDATE

After passing $form as reference to interceptor_dvd_listener the ajax callback function got called like expected. I edited my code above.

This interceptor_dvd_listener_callback() should return value, in documentation:

  After form processing is complete, ajax_form_callback() calls the
  function named by #ajax['callback'], which returns the form element
  that has been updated and needs to be returned to the browser, or
  alternatively, an array of custom Ajax commands.

Why don't you use this:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states

It is drupal 7 standard feature to hide or show some fields when some elements has some states.


How to browse the server to upload files from there in Drupal 7 I need to upload the audios and videos on server in a specific folder via FTP and then let the content managers to select them when they want to upload any of them in add/content path (because it takes a long time to upload them via the Add Content user interface). Is there such a capability in Drupal 7?

****UPDATE****

Best option is to use https://drupal.org/project/imce_filefield
This is specially made to upload files to sites/default/files and add them.

Just configure imce and the field.

Uninstall file field sources, because it's not compatible to have them at the same time

Old anwser

You could use the FileField Sources module. To browse the server it looks like you need to use this with IMCE. From the FileField Sources project page:

The FileField Sources module expands on this ability by allowing you to
select new or existing files through additional means, including:

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

This question / answer was on another question:
Image Field Browser Option


Search query for node content join taxonomy term I am creating a form that searches the FAQ with the search term typed and the taxonommy term selected, i.e., the form will contain a search field and a select list of taxonomy terms associated with the FAQ. So I needed a sql query to achieve this.
I need some modifications on this  db_query("SELECT question, nid
  FROM {faq_questions}
  WHERE question LIKE :term
  ORDER BY question asc", array(':term' => '%%' . $term . '%%'));  so that taxonomy term associated with question is also searched. The above code just searches FAQ with keyword only, not combined with taxonomy term selected

Finally I managed to get results by using this code
db_query("SELECT faq_questions.question, faq_questions.nid,taxonomy_index.tid
FROM faq_questions
JOIN taxonomy_index ON faq_questions.nid = taxonomy_index.nid
JOIN taxonomy_term_data ON taxonomy_index.tid =taxonomy_term_data.tid
WHERE question LIKE '%$keys%' AND taxonomy_term_data.tid='$tid'");


Invoke a rule upon form validation Is it possible to to invoke a rule this way?

So far I have not had any luck?

/* Implementation of hook_form_alter*/

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

  if ($form_id == 'user_login') {

  $form['#validate'][] = 'ea_login';
  }
}

/* implementation of hook_form_validate */

function ea_login($form, &$form_state) {

  $response = rules_invoke('rules_my_rule', $args);
}

This works

/* Implementation of hook_form_alter*/

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

if ($form_id == 'user_login') {

        $form['#validate'][] = 'ea_login';
    }
}

/* implementation of hook_form_validate */
function ea_login($form, &$form_state) {

        $response = "SUCCESS message";

      rules_invoke_component('rules_display_a_message',$response);

}


To add Joins to your views using the Views UI you will need to open the Advanced settings and visit Relationships. (See graphic)

Assuming the user is the author ($node->uid) of the donation's and subscription's payment types you should be able to use the "Content: Author" field to accomplish this join.

This should allow you to build the second table from your question.  To see results displayed in a similar format to your first table you will need to use aggregation.  'Use Aggregation' can be found under the Advanced menu.

Once use aggregation is enabled you will see a new link below your fields called "Aggregation settings."

Select SUM on the field you want to display the totals for and you should see something similar to your first table.

Lastly, while you are getting aquanted with the Views module I recommend turning on the "Show the SQL query" feature in Views settings.  This can be found at admin/structure/views/settings

This will show you the SQL views is generating which can be useful while debugging or learning the Views UI.


Submitting disabled fields on content entry forms? I need to submit content entry forms that have default values set in disabled elements.  However, if I remember correctly, HTTP specifies that fields that are disabled do not have their values sent to the web server (or are dropped by the web server, I can't remember).

Specifically, I have a tag field (term reference) that is a select list, and it defaults to a particular value that is updated twice a year and it cannot be changed by users submitting the form.  I want this field to appear to the user, but at the same time I want it disabled so they can't change it.

How can I submit a disabled field in Drupal 7?

As long as security is not a concern, the following can be done:

Use hook_form_alter to create an additional hidden field in the form.
The name attribute of this hidden field should be equivalent to the name of the disabled field.  The value attribute of the hidden field should be equivalent to the currently selected value.
The hidden field needs to be placed at the very END of the HTML form, or at the very lease, immediately after the disabled field.  The reason for this is that, according to the HTTP specification, if you submit multiple fields with the same name, the last field in the flow of the HTML has it's value submitted above all other submissions.  Of course, disabled fields have their values dropped altogether, so the hidden field could technically appear anywhere in the form, but this would be "best practice".

Here's some code from my hook_form_alter:

function ccom_validations_form_challenges_node_form_alter(&$form, &$form_state, $form_id) {
  $form['my_field'] = array (
    '#type' => 'hidden',
    '#value' => 'schweet'
  );
  $defaultValue = $form['field_reporting_period']['und']['#default_value'][0];
  $form['my_field']['#attributes']['name'] = 'field_reporting_period[und]';
  $form['my_field']['#attributes']['value'] = $defaultValue;
  $form['my_field']['#weight'] = '4';
  $form['field_reporting_period']['#disabled'] = 'true';
  dpm($form);
}

So in the above code you can see how I've assigned the name and value to the field, adjusted the weight so it appears last in the list (using DPM I found that the the highest weight value was 3 in the form, so I used 4 so it was weighted the heaviest), and finally indicated that the original field I wanted disabled is in fact disabled.  Note that you disable form fields in Drupal using the meta attribute #disabled, rather than specifying the disabled attribute directly in the #attributes array.  Weird.

Now this obviously isn't secure, because anybody with any browser HTML manipulation tool like the Chrome Inspector can enable the field and move it to last in the list and then it's value would be used rather than the hidden fields.  I'll revisit this later if security really becomes a concern in this area.


Allow a node to have many dates attached to it I am stumped trying to figure out how to set up a node to have many dates attached to it without having to just add a lot of date fields to it.

The scenario is that we have a show, and that show occurs on multiple days at different or multiple times each day.

I'd like to be able to have a content type of 'Show' with a date field and then just add multiple dates to it. However, the Date field doesn't seem to support multiple values.

How do I make this work?

Just answering this myself so it doesn't count towards the unanswered total.

Turns out the answer is relatively simple - as long as you don't choose a Widget for the Date field that handles repeating dates, the 'Number of Values' field appears and you can choose 'Unlimited'.

So choosing either of the following Widget types:

Select List with Repeat options; or
Text Field with Date Pop-up and Repeat options

will not allow you to have multiple values. Any other options should be OK.


Hide menu backend side for different roles/users I'd like to hide some menu on the backend side /admin/structure/menu and make the hidden items to disappear of the navigation menu for a specific user/role.

I managed to hide the list of the menu visible in the page /admin/structure/menu but it's just the list which as been changed, meaning they can access by accessing to the url.

function module_menu_alter(&$items) {
    $items['admin/structure/menu/manage/devel']['page callback'] = 'module_change_devel';
    $items['admin/structure/menu']['page callback'] = 'module_change_menus';
}

function module_change_menus() {

    global $user;
    if(!in_array('administrator', $user->roles)){
        $result = db_query("SELECT * FROM {menu_custom}
            WHERE menu_name='menu-contact-us'
            OR menu_name='menu-1'
            OR menu_name = 'menu-3'
            OR menu_name = 'menu-2'
            ORDER BY title",
            array(),
            array('fetch' => PDO::FETCH_ASSOC));
    }
    else{
       $result = db_query("SELECT * FROM {menu_custom}
           ORDER BY title",
           array(),
           array('fetch' => PDO::FETCH_ASSOC));
    }
    $rows = array();
    $header = array(t('Title'), array('data' => t('Operations'), 'colspan' => '3'));
    foreach ($result as $menu) {
    $row = array(theme('menu_admin_overview', array('title' => $menu['title'], 'name' => $menu['menu_name'], 'description' => $menu['description'])));
    $row[] = array('data' => l(t('list links'), 'admin/structure/menu/manage/' . $menu['menu_name']));
    $row[] = array('data' => l(t('edit menu'), 'admin/structure/menu/manage/' . $menu['menu_name'] . '/edit'));
    $row[] = array('data' => l(t('add link'), 'admin/structure/menu/manage/' . $menu['menu_name'] . '/add'));
    $rows[] = $row;
    }
    return theme('table', array('header' => $header, 'rows' => $rows));

}

function menu_change_devel() {

    global $user;
    if(in_array('administrator', $user->roles) == 1){
        $items['admin/structure/menu/manage/devel']['access arguments'] =  array('aminister users');
        return $items;
    }
}

But the function menu_change_devel which is supposed to give the access to admin/structure/menu/manage/devel for the user having the permission to aminister users doesn't seem to work :(

Any idea ?

Cheers

EDIT :
I found the solution

function MODULE_menu_alter(&$items) {

    //deny the menu if they are not admin (if they don't have the acess right to adsminister users)
    $items['admin/structure/menu/manage/%menu']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu']['access arguments'] = array(4, 'administer menu');
    //edit
    $items['admin/structure/menu/manage/%menu/edit']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu/edit']['access arguments'] = array(4, 'administer menu');
    //add
    $items['admin/structure/menu/manage/%menu/add']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu/add']['access arguments'] = array(4, 'administer menu');
}

function MODULE_check_menus_access($menu, $permission){
    global $user;
    $account = $user;

    if (user_access($permission, $account)) {
        if(array_key_exists ($menu['menu_name'], $menuList)){
            return user_access('can manage '.$menu['menu_name'], $account);
        }
        else{
            return true;
        }
    }
}

/**
 * Implements hook_permission().
 */
function MODULE_permission() {
  return array(
    'can manage navigation' =>  array(
      'title' => t('Can manage navigation menu'),
      'description' => t('Limit access to the navigation menu'),
      ),
    );
}

You can use Menu item visibility module to hide the item for specific user role.

  This module exposes configurable and extendable visibility settings
  for menu links. For example, if you want to create a 'My account' link
  that points to /user, both anonymous and registered users have access
  to the /user path, so both will see the link, even if anonymous users
  do not technically have an account. Using this module will allow you
  to only have your 'My account' link visible to registered users, and
  hide it from anonymous users.


How can the items in a field collection view be restricted to those of its containing entity? I have an entity type with a field collection that I want to display as table within the main entity display. I have created the view as a block view and added it as a block field using Display Suite.

However items that don't belong the containing entity appear in the display. In effect the embedded view displays all the field collections items, instead of those added to the containing entity.

The Contextual filters and the Relationships in Views UI don't display a means of linking the collection items to the host node.

Is there a way of filtering the view by the node?

It is rather counterintuitive because the way the settings that need to be changed are labeled. The idea is to filter the view by the Node Id for the containing entity, but that doesn't show up immediately in any of the places you expect to see it..

The first step is to add a Relationships. When you click the Add button you get the option for applying to Add Displays or This block (override). In my case I am doing it for only that view so I chose This block (override).

The relationship I choose is Field collection item (Entity with theConfig Type (field_system_config_type).Config Typeandfield_system_config_type` are the friendly and machine names of the field collection.

The select list for choosing which category to filter on is redundant because Field collection item is the only one there.

The next stage is to choose the Contextual filter. This order has to be followed because unless the Relationship is chosen first, the right elements to select for the Contextual filter don't show up.

The element to select here is the node id for host entity - Content: Nid. It is easier to type it exactly as there are quite a number to choose from.

You then select it and click Apply (this display). After that there is a message This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'. You click on Provide default and in the 'Fixed value select Content Id from URL and click on Apply (this display)

This returns you back to the main Views UI screen and you can save it now.

If you know the node ids of some of the content types, you can test it by typing them in the Update preview box and see the list of field collections they match.


organic groups and private files Hi everyone I was wondering if it's possible to have directories of files attached to an organic group so that only group members and admins can access those files. If so whats the easiest way to accomplish this? I tried to use a htaccess file in files/private/groups (the directory I want to store these files in) but to no avail.

For anyone attempting something similar I ultimately modified the user files module
and used the hook_file_download to only allow group members to download protected content by using the built in is_og_group_member function.


How can I make my brand new module dependent on a minimal version of Drupal 7 that's required for it to work OK? I am developing a brand new module (there isn't any site using it yet). It requires a specific Drupal version, as it uses the hook_taxonomy_term_view() hook that was introduced in Drupal core version 7.17.

I want to avoid my module being enabled on a site using, for example, Drupal 7.16 or any earlier versions of Drupal core. Higher versions of Drupal, above 7.17, should be fine.

My Question: How can I make my module dependent on that Drupal 7.17 version, which is a minimum for my module?

Note: I don't need (have to worry about) a solution for sites where the module is already installed. So there is no need for it to be disabled somehow in such pre-7.17 Drupal versions.

The trick, apparently, is to use the system module like:

dependencies[] = system (>=7.17)


How to adjust price in Drupal Commerce based on quantity and attributes? I wonder how I can adjust the price in Drupal Commerce depending on quantity and attributes.

I found Commerce Price Table and Commerce Pricelist for quantity, and Commerce Pricing Attributes for attributes. Not sure which one is more matchable for that.

Any suggestions?

Attributes
Consider using the Commerce Pricing Attributes module. Here is an excerpt from its project page:

... provides some enhancements to the Commerce Product Option and Commerce Product Attributes handling by applying pricing rules to custom product attributes.
Features:

Dynamic price calculation based on selected operators.
Cart combination based on product attributes.
Support for multi currency.
Multilingual attributes.
Different attributes and settings per product.
Price adjustments either per item or per order.
Rules integration.
Easy UI for editing and reordering attributes.

This module depends on Commerce Product Option and Commerce Product Attributes.
Refer to the video about this module for a great introduction about it.
Quantity
From your question it's not realy clear to me what exactly you mean the quantity part of it.
Which is also why I'm not convinced (yet) that you should use the modules
Commerce Price Table or Commerce Pricelist.
However, you should probably consider the Rules module, using some custom Rules, something like so:

Events = Calculate Sell Price of Product.
Actions = calculate the price, and set the price to the calculated value.

Not sure (yet) ifff you'd need some extra 'Conditions' added to this.
Refer to Drupal commerce and rules: changing the product price dynamically for an example of dynamically changing product prices.


How to hide roles from user_profil_form while keeping value? After loading user_profil_form form, I tried to hide the roles fields.
It worked fine, however after submitting the form, my user roles are removed and it's only linked to "authenticated user".

Is there a way hide this field but keeping the value ? I would not like to user the alter hook in order to keep the full form in the admin pages.

Thank you

In my experience, unsetting the field works fine to disallow access to a field while keeping values on update. For example:

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

  if ($form_id == 'user_profile_form') {
    unset($form['account']['roles']);
  }
}


How do I rewrite a facet item label using facetAPI bonus? I am looking at the code example provided by Facet API Bonus module in the section Rewrite facet items via callback function

function HOOK_facet_items_alter(&$build, &$settings) {
                        if ($settings->facet == "YOUR_FACET_NAME") {
                          foreach($build as $key => $item) {
                            $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
                          }
                        }
                      }

How would I modify that to override the label of a specific facet item?

This snippet forces the output to be uppercase by using drupal_strtoupper($item["#markup"]);. And then sets $build[$key]["#markup"] to this new uppercased value.

If you need to check for a specific item, you could use:

function HOOK_facet_items_alter(&$build, &$settings) {
  if ($settings->facet == "YOUR_FACET_NAME") {
    foreach($build as $key => $item) {
      if ($item["#markup"] == 'my value') { // Check if this is the right item
        $build[$key]["#markup"] = 'my overridden value';
      }
    }
  }
}


How to make a callback funciton to a drupal behaviors funtion I have this Drupal behaviors function:

(function ($) {

    Drupal.behaviors.modulenameSwiper = {
        attach : function (context, settings) {
        if ( location.pathname != '/en/imce' ||              location.pathname != '/fr/imce' ||              location.pathname != '/it/imce'     ) {

        var mySwiper = new Array();
        var mySwiperIndex = 0;

        $('.swiper-container').each(function (){
          mySwiper[mySwiperIndex] = new Swiper ($(this)[0],{
              mode:'horizontal',
              loop: false,
              slidesPerView: 'auto'
              });
          });

          mySwiperIndex++;

    }
    }
  }
 }(jQuery));

I need to call mySwiper object out of the Behaviors callback. there is anyway to make it?

You could assign mySwiper to a property within the behavior.

(function ($) {
  Drupal.behaviors.modulenameSwiper = {
    attach : function (context, settings) {
      if ( location.pathname != '/en/imce' || location.pathname != '/fr/imce' ||              location.pathname != '/it/imce'     ) {
        mySwiper = this.get();
        $('.swiper-container').each(function (){
          mySwiper.instances[mySwiper.index] = new Swiper ($(this)[0],{
            mode:'horizontal',
            loop: false,
            slidesPerView: 'auto'
          });
        });
      }
    },
    /**
     * Returns an object with Swiper instances and highest index.
     */
    getSwipper : function () {
      if (this.mySwiper === 'undefined') {
        this.mySwiper.instances = new Array();
        this.mySwiper.index = 0;
      } else {
        this.mySwiper.index++;
      }
      return this.mySwiper;
    },
  };

  $(document).ready(function () {
    console.log(Drupal.behaviors.modulenameSwiper.getSwiper());
  });
}(jQuery));


How to store temporary metadata for the remainder of a request? I am looking for a way to store some additional metadata for the remainder of a request, that should be removed after the request has finished. Sessions or SharedTempStore store persistent data across requests, which is not desirable.

The main problem is that I am working on an inbound PathProcessor, which after some path modifications needs to check if a valid path remains by using  \Drupal::service('path.validator')->isValid($path). This in turn calls all PathProcessors again, leading to infinite processing. I wish to store some sort of metadata in the request, so that the PathProcessor is aware that it is ran for a second time and does nothing.

Obviously, for subsequent requests the metadata should initially be empty again so that the processing is done for each request.

Drupal introduced the Drupal\Core\Cache\MemoryCache\MemoryCache class to, as Added memory cache says, allow classes that would previously maintain state on a protected property (as a static cache to avoid persistent cache or database lookups) to inject a service to hold that state instead.

Drupal core implements two services that use that class, one of them is the entity.memory_cache service, which is defined from the following code.

entity.memory_cache:
  class: Drupal\Core\Cache\MemoryCache\MemoryCache

The other service using that class is the cache.jsonapi_memory service, which is defined from the following code.

cache.jsonapi_memory:
  class: Drupal\Core\Cache\MemoryCache\MemoryCache
  public: false

A module that needs to store data that is valid only for the current request can define a similar service. Setting the service as private is optional, but it avoids other modules uses it, making the stored data private for the module.


Standard way of getting a form inside block I'm using :

public function build() {

    $form = $this->formBuilder->getForm('Drupal\mymodule\Form\Myformclass');
    return $form;
  }

to get form inside block. But Drupal community doesn't find it as an appropriate way to get form inside a block.

According to Drupal community module reviewing team, Do not hard-code class names in strings. I tried calling class directly but that is not serving my purpose, giving 505 error.

What's the right way to get a form inside a block?

You can get the fully qualified class name by using ClassName::class:

use Drupal\mymodule\Form\Myformclass;

  public function build() {

    $form = $this->formBuilder->getForm(Myformclass::class);
    return $form;
  }

If you want to avoid the full classname in code.


Custom rules component execution I have created rules component with some custom fields fc_home_city,fc_pin, fc_loan. When I am trying to execute then asking to fill text box value of fc_home, fc_pin and fc_loan manually I have attached screen shot below. I want to pass all the variables value from my database and calculate user points according to what he had fill in my custom registration form . How I will do it with custom code? Is any idea?

Ex:

In screen attached below after rules execution asking HOME CITY value but I want to pass Home city value from our end with custom code.

Thanks

Thanks

When you say "what he had fill in my custom registration form" do you mean that fc_home_city, fc_pin and fc_loan have equivalent fields on the user entity (probably called something like field_fc_home_city, etc)?

If so then I don't see why  you are trying to populate those fields with code.  One of the main advantages of the Rules framework is that you can can use the token selector system to pass in values nested into the objects you have to hand without having to write a line of code.

For example if you wanted to pass in the field_fc_home_city value of the current logged in user to the "Home city" field then you'd enter "account:field-fc-home-city" into that field and then every time it executes, that token will be replaced with the correct value for the current logged in user.

If it's not the logged in user you want to work with then so long as the component receives the user account as a parameter then you will be able to use the system to get the values from that user entity.

The javascript drilldown mechanism on the fields should help you get to the right token, otherwise you can press "Switch to direct input mode" and find the token in the "Replacement patterns" fieldset.

A good overview of how it works can be found here.


Can users disable email notifications sent to them by Rules? One of my Drupal sites has a bunch of Rules set up to send email notifications to various roles when certain things happen on the site (new content added, etc.)

Is it possible for one of the site users to change a setting in their profile so that they won't get sent these notification emails?

I know that in the user account profile, you can uncheck the box for the personal contact form - but does that have any effect on getting emails sent by the System or by Rules processes?

Clarification: I actually don't want users to be able to opt out. I'm trying to investigate if they have a way to do that because I don't want them to.

Unchecking the box for the contact form only affects the personal contact form provided by the Contact module (part of Core).

I added a similar feature (allow users to opt out to e-mails sent via rules) to a Drupal 7 site in the following manner.

First, I added a field (Boolean single on/off checkbox) labeled "Send me notifications" to the user account page.

Then, I made a couple rules to award a role nomsg upon checking the box and to remove the role upon unchecking the box.

After that, I created a rules component of type condition that checked to ensure that the user did NOT have the nomsg role.  I then added that component to all rules that sent e-mails.  This was a bit of a pain, because some of the rules that sent e-mails also did other things, so I had to break out the part about sending the e-mail (as another component) so that the other actions would be performed but the e-mail would not be sent if the user had the nomsg role.


Using menu tokens (or similar?) to create "invite user link" on OG Group page I am new to tokens but was planning to use the menu to token to create a simple menu allowing group administrators to easily invite users without going to the Group administration menu.

The default Organic Groups (7.2x) link for inviting members is: http://www.example.org/group/node/GID/admin/people/invite-users

As the Group ID (GID) is the same as the Node ID (NID) I thought that the [current-page:url:args] would work well. so I created a menu link with the path

group/node/[current-page:url:args]/admin/people/invite-users

Which crashes all group pages and also makes it impossible to delete the link in the menu as "the website suffered a temporary issues". Uninstalling the Menu token modules solves the issue but I am wondering how to make the menu link work as I intended.

For anyone interested in the bug this seem to be a known issue (see: https://www.drupal.org/node/1205086).

I was having similar trouble as you, due to the bug in menu-token.

The way I would go about is, as a work-around, is to create a views-block relative to your groups, adding your node id or gid as a field that is not displayed (you'll have to move this to the top of your fields list in views for it to work).

Then you add a "global text" -field with a value like "Invite", re-writing the output as a link that includes the node id/gid as a token in the URL. This must be located below the node id/gid in the field order(!).

Finally, you will have to set your views filter to restrict the output to the page a user is currently on, this way the Node id/gid field will return only the correct value. Also set your pager to a single result as measure of ensuring only one value is passed through.

Hope this helped!


File upload error. Could not move uploaded file I am getting this error while changing the logo of my site,

i  have tried changing the permission through hosting provider, added php_value safe mode 0 in .htaccess file and even added one file in drupal folder named php.ini with

safe_mode = Off
file_uploads = On
upload_max_filesize = 256M

but still i am unable to change the logo and getting the error

  File upload error. Could not move uploaded file.

Had a same problem. The best way to fix it is to:

Update the folder permissions on /sites/default to 777
Remove /sites/default/files folder
Go to /admin/config/media/file-system and click save so drupal re-creates the files folder.
Update the folder permissions back to 755 on /sites/default.

On my server when website creates a file or folder, the owner is set to nobody.nobody and since I already had a lot of files in my /sites/default/files folder all I had to do is update the ownership and permissions:

chown -R nobody.nobody ./sites/default/files
chmod -R 755 ./sites/default/files

Good luck!


Image Captcha Refresh not displaying refresh link I want to add button/link for refreshing Image Captcha, therefore I've installed and enabled Image Captcha Refresh module. But this module is doing nothing, no refresh button is added, no options are added to Image Captcha settings page, no javascript is loaded from this module.

My captcha is in custom form:

$form['captcha'] = array(
    '#title' => 'Code',
    '#type' => 'captcha',
    '#captcha_type' => 'image_captcha/Image',

What could be wrong?

I have tried recreating your problem and i saw that after you enable the refresh module for the image recaptcha, a link is added below the image in all the forms where captcha is enabled.

But there is no configuration page specific to this refresh module. The link works fine in reloading the image.

I suggest that you add your form via configuration page of the captcha module instead of adding it in the code.

just include your form machine name and captcha in the captcha module configuration page.


Annoying general behavior: the width of the text-input-fields, when editing a node, can be up to 2X your screen's width / decentered I was just wondering whether anyone else is annoyed by the curious & sporadic behavior of Drupal of making the widths of the text-input-fields very large, when starting to edit a node.

The widths of the text-input-fields (by default: "Body" & "Summary") get as much as 2 times the width of my computer screen.

Would anyone know how to get under the hood, to try and come up with a fix?

I am also not sure about the origin of the behavior, which sometimes does show up; and at other times don't.

Thanks.

With the help of the adept question by @J.Reynolds

Might solve this issue: (did so for me)

Just change the administration theme a couple of times

This can be changed at Appearance >> Administration

To which you can navigate manually using the administrative overlay
Or to which you can arrive directly, by default, via www.Your-Website-Domain/#overlay=admin/appearance


Sales Tax Exemption for an Authorized User? I have my Drupal Commerce store set up to apply my state sales tax on appropriate purchases. I also have an authorized user who has a state-approved sales tax exemption. I'm trying to configure my tax type such that no sales tax will be applied on their orders, but I'm not having much luck.
I've installed the Commerce Product Tax Conditions module, which appears to support a customer role condition. The module documentation doesn't identify that condition as "apply sales tax for this role" or "exempt this role from sales tax", though, and I haven't been able to apply an exemption.
How can I make this work?

After looking at the code I figured out that this module isn't about conditions to provide exemptions, it's about conditions to apply the tax. So yes, to make it work you have to check all of the roles for which you want the tax applied while leaving out the role(s) for which tax should not be applied. It might also be necessary to apply a patch and add a setting.


Adding a field to a content type for Apache Solr search and Facets I've got a content type of Journal, and another content type of Article. All of the data associated with the Journal itself is stored on that content type, and not duplicated in the Article; the Article just has an entity reference to the Journal. So, for instance, Journal has a Year field, but Article has no Year field. (Conceptually, a Journal is a collection of Articles.)

For the most part, this entity reference relationship works great (and avoids duplicate information.) However, when doing things like searching, it can have some side effects. For example, if someone searches for a keyword, gets back a list of Articles with that keyword, they're then not able to filter that down by Year using facets, since that content type doesn't technically have a year associated with it, just a reference to a different content type that does. I'm hoping to find a way around that, but I'm not sure how to get it working.

I'm still pretty confused on the relationship between the Solr server we have and the Drupal site. It was my idea that once all was indexed, the Solr server takes the search string, and just ships back nodes/entities/etc. that match. If that's wrong or right, I'm still not sure if my problem has to do with Solr or FacetAPI.

What I've done so far is below, but it seems to have no effect on the search results. (In other words, if I search for a year, the articles aren't being returned as results; I'm not even worrying about Facets yet, even though those are the ultimate goal.)

function issue_archive_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id){
  if($node->type == "article") {
    // Load the journal this article is associated with, and get it's year
    // The is_ prefix is to denote a single (instead of multi-value) integer
    $journal = node_load($node->field_journal['und'][0]['target_id']);
    $document->setField('is_article_year', intval($journal->field_year['und'][0]['value']));
  }
}

function issue_archive_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // Make the indexed fields available for search results
  $query->addParam('fl', 'is_article_year');
  // Filter where 'index_field_name' = 'indexed_value'
  $query->addFilter('is_article_year', 'indexed_value');
}

Figured it out. Adding the answer in case anyone else needs it. Code below...

function issue_archive_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id) {
  if($node->type == "article") {
    $node = node_load($node->nid);
    $journal = node_load($node->field_journal['und'][0]['target_id']);
    $document->addField('its_field_year', $journal->field_year['und'][0]['value'] + 0);
    $document->addField('itm_field_year', $journal->field_year['und'][0]['value'] + 0);
  }
}

function issue_archive_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  $query->addParam('qf', 'its_field_year');
  $query->addParam('qf', 'itm_field_year');
}

Using the solr_devel module, I saw that the journal type had two fields listed in the entity/document for year, one with the its_ prefix, and the other with the itm_prefix. I added both of those, and added the query field (I think that's what it stands for?) parameters to the query.

This got me the exact results I was looking for.


convert a cck field from integer to string (text) How do I convert an existing integer field to text without having to copy paste manualy each value on each node and then delete the old integer field
I´m using Drupal 7.9

I tried altering the database.. on the definition of the field and the value type
I'm still getting errors

Notice: Undefined property: stdClass::$field_ubi_gps_x_format en field_sql_storage_field_storage_load() (línea 360 de /modules/field/modules/field_sql_storage/field_sql_storage.module).

Notice: Undefined variable: regexp en number_field_widget_validate() (línea 389 de /modules/field/modules/number/number.module).
Warning: preg_replace() [function.preg-replace]: Empty regular expression en number_field_widget_validate() (línea 389 de /modules/field/modules/number/number.module)

that is because the validation and presentation of the field has remained as integer..
I can't find in the DB where it stores that to copy if from another text field

I've so far altered field_data_field_FIELDNAME_THAT_WAS_INT changing field_FIELDNAME_value
from int to varchar and paradores_field_config . copying the blob data field from a text to ID of the FIELDNAME and using text on type and module fields

You would have to change the type in field data and field revision tables and add the FIELD_NAME_format column in both the tables.
Change the type and module columns in field_config to 'text'. And change the data column in field_config and field_config_instance tables.

For more info on this you can visit this link.


User reference (Profile2) with Views I have a D7 site where users are linked to other users (by References). User profiles are extended using the Profile 2 module and by so, containing some additional fields (phone, email,...).

I want to create a landing page where logged in users can see the info of the connected profile. So a logged in user should see the name, phone and email of the linked account.

I've been trying around for a while, but not able to close this issue.
It's not a matter of permissions, since the direct URL (/profile-representative/16) is accessible by the logged in user. On that page, he can see all the info. It's that info (phone, email,...) I want to get into Views.
But for some reason, it cannot be done by using relationships. At least not by me.

Is there anyone with experience concerning this matter?

I managed to fix this issue with a combinations of a relationship and a custom formatter.

First, in a (User) view, I created a contextual filter with User: Uid. Of course, no contextual filter will be given at the page, so I provided the default value User ID from logged in user.

Then, I created two relationships. The first one User: Profileand the second one Profile: [your custom name]. The second relationship is created with the first one as relationship.

Next, in my Fields section of my view, I added a Profile field and gave it a custom formatter. By using this custom formatter, I was able to display all the needed data.

If someone is interested in more code, please let me know!


How do I consume REST as a client? I need to import on node save information from a third party REST server and map that data to an entity that references the node saved. There will be a field in the node that the user can input an id that is passed in the url of the REST call. The REST call will return an XML object that needs to be mapped to a new entity that is referenced to the node.

How is this done? Are there an examples of Drupal 7 modules that do this?

Normally, I just roll my own.

I use a combo of drupal_http_build_query and drupal_http_request to make the request.  I then use drupal_json_decode to parse JSON results, or
simplexml_load_string to parse XML results.

When possible, I try to abstract out all of this into a PHP class as a singleton, which also includes static caching and/or caching via cache_set/cache_get for the actual requests.  I will then wrap up everything as a normal Drupal module.

Invariably, the service I am consuming will have something odd about it that precludes using a generic solution.  Also, I don't find the generic solutions any simpler than a custom one.


Buttons get longer when pressed if using AJAX I'm using Ajax Commerce Cart Cart with a custom Drupal 7 theme that I made with Artisteer, but the issue does not seem to just be related to the one module. Whenever AJAX is attached to a button, when the button is click it pretty much doubles in width while the AJAX process is taking place and then returns to it's original size.

I wasn't sure what code or information you'd need so please do ask if you need me to upload anything or provide further details. Does anyone know of any solutions to this problem?

Thanks in advance

I suspect it's the trobber, you know the little .gif image showing an ajax loading.

You can fix it via css, but to find out the class/id to edit, i had to break the ajax and force it to never complete the load, so i had time to inspect the markup with firebug.

check this discussion:

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


how to select different colorbox styles for different content types in drupal 7? i tried to select different colorbox styles for different content types but i couln't. because we can select only one colorbox style for all using.

if onybody know how can select different colorbox style for different content type please help me

There is no way to do it from admin UI.
Formatter settings also has no option to select style for current image display.

But you can try the following:

function [themename]_preprocess_node(&$vars) {
  if ($vars['type'] == 'node_type' && $vars['view_mode'] == 'full') {
    variable_set('colorbox_style', 'stockholmsyndrome');
  } else {
    variable_set('colorbox_style', 'default');
  }
}

Yep, it's dirty hack, but it can helps... maybe... =)


Associate one item of content with one taxonomy term I have a view of type 'term' that displays in a grid, all the terms in a vocabulary. I need to display 2 images per term, but this is not possible I believe. (E.g. the taxonomy Image module only allows you to add one image per term).

So I thought maybe a solution to this would be to create another content type with one piece of content per term. And then associated each one with one of the vocabulary terms. And then create relationship in the view to link them. However I cant figure out how to get the view to do this. Is this possible?

It's possible, but not terribly easy in D6.

In Drupal 6 (unlike 7 and 8) vocabularies were not fieldable, so the approach you took is a reasonable one.  You probably do not need a relationship in the view, just adjust the filter to include content types of the new type, and then use sorting to move the to the start or end of the result set. You could sort by content type or use the usually ignored "sticky" field on the nodes if its not in use (set all your new images to be sticky and then sort the list to place them where you want).

You could also create a block that uses the same filter pattern as the original view, but limit to the new content type and the only 2 results. Then place that block on the page that's displaying the grid.

Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.


how to apply tag functionality on drupal 7 nodes? I want to show tag in my news content type and want to show these tag for specific node in front end with the help of views.

You must add a term reference field to the content type, and choose your vocabulary.

See the below screenshot of a view to see how to show tags for nodes in a view.


How can I reference two field without nid or uid? I have two content types: 1.- Equipment and 2.- Configuration

The First CT has the following fields:

Title : is equipment id with autocomplete module serial and hide for not capture.
model : Text
Serial : Text

The Second CT has the following fields:

Title : is conf id with autocomplete module serial and hide for not capture.
installed os : Check box (Yes|No)
App Installed : Check box (Yes|No)
Network Access : Check box (Yes|No)
Serial : Text

I need make a relationship with field serial and then create a view that shows all properties of CT two.

Regards Advanced.

enable  entity reference module.
In the second CT , add an entity reference field.
In the field settings of the entity reference field select the first CT from a list of CT .
Create a view of second CT with all its related field.
Add relationship under the advanced options  ,  add an entity reference relationship referencing first CT.
Then add all the fields of first CT.
use the module link -
https://drupal.org/project/views_dependent_filters
for equating the serial text field.


Alter list of blocks on admin page I'm using Drupal 8.

I need to hide blocks of certain type from blocks UI because I'm managing them from my custom module and I'm not using them as a regular blocks.

Is there any way of altering block list generated on blocks administrative page?

You could try using hook_block_access to restrict access to block operations.

  Control access to a block instance.

  Modules may implement this hook if they want to have a say in whether
  or not a given user has access to perform a given operation on a block
  instance.

  string $operation: The operation to be performed; for instance,
  'view', 'create', 'delete', or 'update'.


How to change the order in which Views SQL joins are executed? Views creates certain JOINs behind the scenes, e.g. for fields or filders added via the UI.

I have a view with such an implicit join based on an entityreference field. In order to get the desired results I need this join to be the first one, but Views happens to place it as the last JOIN (other joins in the query come from other fields and Views relationships).

Can I change the order of the joins, while keeping all fields and filters configured via the Views UI?

As a workaround I can explicitly add a relationship based on the entityreference field in question and order it as the first one. This works, but it adds an extra join that I don't need, which has a performance impact.

You are looking for the following:
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
It will work roughly as follows:
You will find that there is a clauses array in your query object among others that will contains your restraints. Remove the particular element, and insert it into the correct order in the array. They will be executed 0 through N


How add/update a record conditionally based on existence of primary key? I have a table with structure:

Table
(
record_1 int,
record_2 int,
PRIMARY KEY (record_1)
);

I want to write/update a record based on its existence.

I was told to use drupal_write_record(), but for that I must know if the record already exists or not.

In my case I am not aware of its existence.

How can I do this?

No, you do not "must know if the record already exists or not". If you will look at drupal_write_record source code, you will see these lines:

 if (empty($primary_keys)) {
    // We are doing an insert.

On else, this function will update instead of insert. The only problem with this is that Drupal's record system expects you will leave key management to Drupal. No saving at arbitrary key, because it breaks autoincrement.

If you need to manage keys on your own, use lower level db_merge function instead.


Drupal accounts with dead addresses: how to de-activate? on my drupal website, there are a lot of users with an invalid email address. I know because, either they have never logged in or their mails bounce. But I have to check manually, which is not good.

When a user signs up with an email address, they receive a confirmation email. Is there a way to automatically disable an account if the user does not log in within the first day after receiving this confirmation mail?

Alternatively, it would be OK to keep the accounts disabled until the user clicks a link on the confirmation mail.

Are there plugins or settings in Drupal to do this?

Drupal's LoginToboggan module does this. In the settings, there is an option to "Delete unvalidated users after:" and then you select a time period. It runs with cron so you can "set it and forget it."


Are there any acceptable uses for $_COOKIE['has_js'] outside of core? Drupal 7 has a cookie called has_js.  drupal.js sets this cookie, and it is used by the Batch API and the authorize.php script.

There is a rather old issue about this cookie, backport "$_COOKIE['has_js'] must die" patch to 7.x, but this cookie still remains in drupal-7.x.

Are there any acceptable uses for this cookie, outside these two cases in core?

I don't think so, for many separate reasons.

Given the comment made to 8.x change records Removed has_js cookie:

  Only Batch API used it as a workaround. A clean solution has been reached avoiding the need for the cookie.

I would extrapolate that any solution that uses it should be considered unclean.
There is no page for it on api.drupal.org so it appears it wasn't designed to be used outside and it's not guaranteed to stay unchanged. It's a common in IT to assume one uses undocumented features at his own risk.
It can be unset if JavaScript is on, but Cookies are off, so it cannot have a clear meaning.
It can be unset if some module will successfully try to make site EU Cookie Law compliant (and user didn't agreed yet)
If you read it from PHP, it will be unset if your page is first one loaded after "open in private window" or "clear cookies" click, no matter what are client's JS and Cookie settings.

Reasons in no particular order.