Why do I get the following error? I need to implement hook_views_query_alter() to change the value of delta of the field that form a relationship.

As I posted in change delta value, the code is the following one.

   function supermama_misc_views_query_alter($view, $query) {
     $view->$query->table_queue['field']['join']->extra[2]['value'] = 1;
   }

It gives me the following error:

  Fatal error: Cannot access empty property

The same error appears if I use the following code.

    function supermama_misc_views_post_build($view) {
      if ($view->name == 'gallery_images') {
        $view->$query->table_queue['field']['join']->extra[2]['value'] = 1;
      }
    }

What's wrong with the code? How do I bypass the error?

Thanks a lot molot

the problem was a wrong implementation to the views hooks as this post

and hook_views_query_alter

This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified.


How to add a js script as type="module" How to add type="module" to script added in MODULENAME.libraries.yml when i do:
my-library:
  version: 1.x
  js:
    js/App.js: { }

I get
<script src="/modules/custom/MODULENAME/js/App.js?v=1.x"></script>

I need to add type="module" to script tag like:
<script type="module" src="/modules/custom/MODULENAME/js/App.js?v=1.x"></script>

I have tried:
my-library:
  version: 1.x
  js:
    js/App.js: { type: module }

But i doesn’t work.
Is this possible to add a script of type module?

Yes, it is possible, with the attributes property.
my-library:
  version: 1.x
  js:
    js/App.js: { attributes: { type: module } }

See Adding attributes to script elements and JS properties.


Show block for specific content type programmatically How can I show a block on a specific content type programmatically? I want in my image the 'basic page' selected.

I used the xxx_block_info() function, should it set in here?

If you look at the node_module file it controls the node type visibility using the hook_block_list_alter.

So basically it might looks something like this.
NOTE: This is a non tested version.

function hook_block_list_alter(&$blocks) {
  $node = menu_get_object();
  // list of all block deltas u want to apply this
  $block_delta = array('deltas');
  foreach ($blocks as $key => $block) {
     if (!empty($node) && $node->type == 'page' && in_array($key, $block_delta)) {
       unset($blocks[$key]);
       continue;
     }
  }
}


view slideshow not working I created a view block and a content type "slideshow image" with "title" and "image" specially for slideshow.
In this block only images of "slidshow image" content will appear.

And i added up five elements and i see effects on the slide show.

And even i created a directory named "jquery.cycle" in libraries
 \sites\all\sites\all\modules\libraries. Added the jquery.cycle.all.js file into that directory and but i didnt got any sliding of images...

Only the latest image is displaying but no effects.

If you are using the libraries API module, the correct place for the JS code is actually sites/all/libraries, not \sites\all\sites\all\modules\libraries (why do you have sites/all in the path twice?)

What slideshow module are you using, views_slideshow? I don't think you will actually need to add a jquery library if that is the module you are using, but that will depend on the actual module you are using. If you are trying to build a slideshow from scratch with jQuery cycle, here is info from the handbook on getting your js added to Drupal http://drupal.org/node/304255


How to translate the title, axis labels and legend of a chart? I have successfully created a grouped bar chart using the Forena module.
My application supports English, Portugese and Spanish.

But I am not able to translate my chart to Spanish and Portugese.
I need to translate the chart title, labels on each axis and the legend.

Here is the chart I created so far:

I wonder how I can translate the following strings in this chart:

Biological and chemical indicators
Average of indicators
Positive biological indicators
non responsive chemical indicators

Here are the steps to create a translated version of a chart (or more general: a report) using the Forena module:

Make sure (core) module locale is enabled.
Instead of using the "edit" icon to change the specs of a report, use the "translate" button next to edit. Then select the language to which you want the report (chart) to be translated.
On the next screen, enter the translated report (chart) title.
You should get some informational message as in this example (in which I created a 'nl' version of drupaladmin/active_users, for which I changed the tite from "Active users" to "Actieve Gebruikers"):

  Translation, Actieve Gebruikers has been created. Switch languages to translate.

  Your report, nl/drupaladmin/active_users has been saved.

After switching your active language to the language for which you want to create a translated version, you'll be able to change anything of the report (charts) specs to the specs of your additional language.
In your case here, you can now modify those 4 strings

Bottomline: tranlating Forena reports is similar to translating nodes.


How to output correctly an html_restricted textarea field in Twig? I don't know if that stupid question has already been asked...

But how should I output a field type "text_long" in Twig ?

Now what I do is to set myself an array with that :

$data = $journalist->field_bio->getValue();

$user['bio'] = [
                    '#type' => 'processed_text',
                    '#text' => $data[0]['value'],
                    '#format' => 'full_html'
               ];

Because I cannot find the filter to render a text_long in html.

In the twig I tried : {{ user.bio | raw }}, {{ user.bio | render }}...

=> What's the drupal 8 way to handle that ?

The Drupal 8 way would be to use a view mode and let the field formatter do its work.

If you want to do this in custom code you can build the render element for processed text like you did in the question, but use the text format stored in the field:

$user['bio'] = [
  '#type' => 'processed_text',
  '#text' => $data[0]['value'],
  '#format' => $data[0]['format'],
];

Then you are sure, that the text filters are applied configured in the format, that the user who filled in the text field had permission to use.

To output the variable in twig you don't need any filters, they are applied automatically by the render element:

{{ user.bio }}

Edit for the question in the comment, how to render a field without a view mode. There is a way to do this. You can view a field by providing the display options in an array:

$user['bio'] = $journalist->field_bio->view(['label' => 'hidden', 'type' => 'text_default']);

But this is as expensive as rendering the complete entity and is not optimized for caching. So use it only if you can't figure out a way how to render whole entities in view modes.


How to make a map black and white? I created a view (using Views) which shows node locations in a map using Location and Gmap modules.

How can I make map black and white?

Add a class name for node locations field, for example "nodeLocation"

and in style.css

.nodeLocation{
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
}


One contextual filter based on two entity reference fields I have two content types.

Doctor
Location

Doctor has two entity reference fields. Both reference Location nodes.

Primary Location
Secondary Location

I need to create a view that appears on a Location node and shows all Doctors that reference the Location node via the Primary Location or Secondary Location fields.

This has turned out to be incredibly difficult.

I've create a contextual filter for Content: Primary Location and set Provide default value to Content ID from URL. This successfully filters the view to Doctors that reference the Location via the Primary Location field.

I now create a contextual filter for Content: Secondary Location and set Provide default value to Content ID from URL. I now have no results.

I can then delete the Content: Primary Location contextual filter and this successfully filters the view to Doctors that reference the Location via the Secondary Location field.

It appears I can't have both at the same time. Thanks for any help!

Of course I solve this immediately after I post it after hours of trying. If you're in the same situation, it appears the only solution is to use https://www.drupal.org/project/views_contextual_filters_or .

Configure the view as described above. Then additionally, under Query settings, check Contextual filter OR.

The UI of this module leaves something to be desired but it works so long as all your contextual filters should relate to each other as OR.

The second missing piece was that I was testing this in the view UI using the preview. I was passing the NID of the Location as an argument. What I missed is that because I have two contextual filters I actually need to pass the NID twice like this: "2173/2173". When the view is actually used on the page, the NID is retrieved from the URL and the fact that there are two contextual filters becomes irrelevant.


Date Calender Starting Date of Field B should be equals to or advanced from the Ending Date of Field A I have created a form using webfrom module. The form contains Arrival Date and Leaving Date. I want Leaving date should either be same as Arrival date or higher than that.

Try out Webform Validation module

  This module adds an extra tab to each webform node, allowing you to
  specify validation rules for your webform components.

OR in other case, write custom code, Use hook_form_alter() to apply custom validation

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    print $form_id;

    if($form_id=='webform_client_form_1') //Change webform id according to you webformid
    {
        $form['#validate'][]='mymodule_form_validate';
        return $form;
    }
}

function mymodule_form_validate($form,&$form_state)
{
    $phoneval=$form_state['values']['submitted']['phone'];//where "phone" is field name of webform phone field
if($phoneval=='')
{
form_set_error('phone','Please fill the form field');
}
/** THEN USE REGULAR EXPreSSION TO VALIDATE IT
In above example i have check if phonefield is empty or not
**/

}


Ckeditor can not create new profile with input format I've already a profile with input types but I can not create another, even when I am cloning the profile with input types.

These are my text format, and I using administrator user.

This is the list of ckeditor profiles

In Test profile, the only text format allowed is PHP code.

What could it be?

It seems to be a problem when creating or cloning a ckeditor profile, the module doesn't insert registers into the table ckeditor_input_format, so we can do that by the following SQL queries

INSERT INTO `ckeditor_input_format` (name, format) VALUES ('<profile_name>','filtered_html')
INSERT INTO `ckeditor_input_format` (name, format) VALUES ('<profile_name>','full_html')
INSERT INTO `ckeditor_input_format` (name, format) VALUES ('<profile_name>','plain_text')

The name  must be replaced with the name of the profile you created with ckeditor.


Cron job stops when another one is running I have two cron jobs in my site (I'm using Elysia Cron).
They are set in my own module. One runs every minute and one every hour. Code below:

function mymodule_cronapi($op, $job = NULL) {
    $items['Import J Data'] = array(
        'description' => 'Import J Data',
        'rule' => '* * * * *',
        'callback' => 'mymodule_import_j_data_cron',
    );
    $items['Import Q Data'] = array(
        'description' => 'Import Q Data',
        'rule' => '0 * * * *',
        'callback' => 'mymodule_import_q_data_cron',
    );
    return $items;
}

function mymodule_import_j_data_cron($what) {
    mymodule_j_save_f_data();
    mymodule_j_save_c_data();
}

function mymodule_import_q_data_cron($what) {
    mymodule_q_save_data();
}

In my server (centOS), i have the following line in my crontab (with correct MYKEY and url):

* * * * * root wget -O - -q -t 1 http://.../cron.php?cron_key=[MYKEY] >/dev/null 2>&1

When the second job runs (the one set to run every hour), the other one stops and I get the following error in my site log:

  Attempting to re-run cron while it is already running.

The firs job runs for about 15-20 minute. After it ends, the other one starts again.

My question is, it's not possible to have both cron jobs running at the same time? Am I missing some settings in elysia cron?

It looks like ultimate cron can run parallel jobs.


Should I make a SOAP or a REST service to receive files from a .Net WCF Service? I need to implement a web service client in drupal 7 using the Web Service Client module,  which receives files from a .Net WCF Service.

Should I make a SOAP Service or REST service using WCF such that the web service client can easily implement the file receiving logic in Drupal/PHP?

I have implemented SOAP based web service. And for file transfer I have sent the file contents as an array of bytes and it was successfully received in PHP.


Migrated D8 site breaks when cache_discovery is truncated I was developing a site for a migration on Acquia's free tier, but it turned out there wasn't enough space for all of the files. Since I can no longer use local development/acquia for development, I decided to migrate it all over to another host that I use.

Did my normal process of installing a clean site on the new server, and then copying the modules, themes, and file folders from the old dev site to the new dev site, and then importing the full database dump from the old database into the new database.

Boom, site is up and running. I go to clear the caches on the new dev site to finalize the migration and am met with the angry error "The mysite.com page isn’t working. mysite.com is currently unable to handle this request. HTTP ERROR 500".

After re-importing a few times and clearing the cache tables one at a time, I've learned that the cache_discovery table in particular is the culprit. Clearing all of the other cache tables works fine, but when I clear this one the site throws that error.

Anybody know what might be happening here? I never encountered anything like this in D7 and this is my first D8 build, so I'm not sure how to proceed.

Did my normal process of installing a clean site on the new server,
  and then copying the modules, themes, and file folders from the old
  dev site to the new dev site,

In D8 all information from annotations and yaml files are newly discovered on a cache rebuild. And your mix from the clean site install and the copied files did not fit together. This could be one file, which is left over from an older core or module version and you get this problem. So the solution is, to copy complete site archives or when updating remove the old code completely before replacing it.


validation question for webform validate I need to validate that a field does not contain only numbers. in other words it can have some numbers but must have some letters as well. Can someone help me with the regex to do that?

I am using webforms 7.x-3.18+3 and webforms validation 7.x 1.1

thanks

Here are the steps you'll need to follow:

Go to your webform
Select the "form validation" button.
under the "Add a validation rule" select "Regular expression, case-sensitive"
For the regex, you can use ^\d*$ and check the negate rule box below

OR

Go to your webform
Select the "form validation" button.
under the "Add a validation rule" select "Regular expression, case-sensitive"
For the regex, you can use [^\d]+


Duplicate part of the main menu to a sidebar I am building a website like the one in the picture (here is the photoshop mockup :P) My question is the blue arrow!

I want to relate the main menu with the node as follows: When the visitor clicks on a parent item of the main menu (or a child of that parent menu) (let's say he clicks on "services" or on "Web dev" or "Web design" or "SEO") I want a submenu to be displayed, on the left sidebar, with "services" as the parent element highlighted and the sub elements also present (as shown in the photo).

If i use menu block and choose to display from a certain level and on, then I will have that level from the whole main menu depicted, and not just the active one, right? (for my example, in the left sidebar i only want to show the items shown, not "Home" or "About us" or "Contact us")

Which modules should I use? Can I do it with hook_page_alter, and if yes, how will I choose to only show the submenu of services and not the whole main menu? (Any directions are appreciated)

P.S. for what's worth, the main menu is a drop down Superfish menu with a depth of 2 levels.

in nice menu you can select parent menu item to render, also you can achieve this with views tough


How to block (or redirect) external image source? Users can add images to content. They're supposed to be uploading them to the site, but occasionally people will reference an image hosted elsewhere in the src='...'.

What is the best way to prevent these images from working (or even better, redirecting to a "This image is blocked" image)? I imagined using a hook of some sort to modify the content, or possibly a module that adds a filter to weed out these images. But it seems like a situation I could be overthinking.

Any suggestions?

I presume you are allowing the uploading and embedding of images via the WYSIWYG. That being the case you need to write a text filter and apply it to the text format the users are allowed to use (Filtered HTML for example).
http://local.example.com/admin/config/content/formats/filtered_html

Have a look at the Examples module for how to do that.

filter_example  Defining an input filter

If you're not allowing them to upload and embed via the WYSIWYG (but uploading via a field for example) you could simply remove img from the permitted tags in your Limit allowed HTML tags filter.


User Import: Possible to use other variables in the user notification email? We are using the User Import module to populate the User list, and having it send out a notification email with a temporary login URL. In the notification email section of User Import configuration, it is stated:

Customize the body of the welcome e-mail, which is sent to imported members. Available variables are: !username, !site, !password, !uri, !uri_brief, !mailto, !login_uri, !edit_uri, !login_url.

In this site we have some custom fields added to User which are being populated via User Import of .csv files. We would like to include a variable in the message body that picks up a numerical value from those fields. There is a set of fields of the name pattern "field_schools_owned_zone_1" which goes from 1 to 6; then in a View we have a math field that sums up those 6 field values for each user. It is that sum that we want to use.

Can this email form accept variables other than those listed? If so, how can we determine the replacement string for that math field value so it can work in the email message?

--Thanks--

Probably not easily an existing request in the issue queues shows people want to add fields from the Content Profile module on the 6.x branch of this module:
https://www.drupal.org/node/1060394

There is a small patch in that issue that adds custom profile fields into the allowed list. The tokens would be in the same format as the given !username examples, eg !field_schools_owned_zone_1 for 1 of your fields.

Until that patch is added to the version of the module you're using you'd have to apply or adapt that patch to your site.


How can I create a custom html tag in the CKeditor wysiwyg editor? I've created a custom HTML tag that pulls information from my database and displays it. Basically it uses preg_match_all to parse the body of articles for <profiletag>Person Name</profiletag> and replaces this tag with html of the person's profile.

Now what I want is to allow my writers to insert this HTML (<profiletag>Person Name</profiletag>) from the WYSIWYG editor rather than having to go into the source and insert a tag into the html. When they write <profiletag> etc. in the WYSIWYG editor obviously it gets all messed up. I'm looking for something like [profile]Person Name[/profile] markup for them to include these tags in the WYSIWYG side.

Is this possible, and if so how can I implement this functionality?

What you need is a custom filter. Filters are the check boxes you can set on input formats like 'Filtered HTML' and 'Full HTML'.

There is an example available in the examples module: https://www.drupal.org/project/examples

Basically, you need this:

1) You need to implement hook_filter_info() to let Drupal know there is a new filter
2) You need to a function to process the input. This is where you can use your regex.

I highly suggest looking at the examples module or any other modules that use filters.


Defining a new input format I need to define a new input format programmatically, probably as part of my module's hook_install().  I need to write code that duplicates the manual operations described on http://drupal.org/node/778976.

I have not been able to learn how to do this. Any pointers in the right direction will be appreciated.

Code from standard Drupal profile is your friend: http://drupalcode.org/project/drupal.git/blob/c5d6e6334fb7a71ecf1dbc7e06a7de8ad9547b27:/profiles/standard/standard.install#l14

  // Add text formats.
  $filtered_html_format = array(
    'format' => 'filtered_html',
    'name' => 'Filtered HTML',
    'weight' => 0,
    'filters' => array(
      // URL filter.
      'filter_url' => array(
        'weight' => 0,
        'status' => 1,
      ),
      // HTML filter.
      'filter_html' => array(
        'weight' => 1,
        'status' => 1,
      ),
      // Line break filter.
      'filter_autop' => array(
        'weight' => 2,
        'status' => 1,
      ),
      // HTML corrector filter.
      'filter_htmlcorrector' => array(
        'weight' => 10,
        'status' => 1,
      ),
    ),
  );
  $filtered_html_format = (object) $filtered_html_format;
  filter_format_save($filtered_html_format);

Enable permission for system roles (code):

// Enable default permissions for system roles.
$filtered_html_permission = filter_permission_name($filtered_html_format);
user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array($filtered_html_permission));
user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array($filtered_html_permission));
user_role_grant_permissions(variable_get('user_admin_role', 0), array($filtered_html_permission));


Using an entity wrapper to change node->body value (with localization) I try to programmatically modify the body of a node using an entity wrapper.
In my Drupal installation I also use Locale module (language for node is 'en', for body it is 'und') and Revisioning module.

Now, I've created a simple code to do this task:

<?php
// in database: field_data_body->body_value = 'old_value'
$node = node_load(1);

$wrapper = entity_metadata_wrapper('node', $node);

print_r($wrapper->body->value->value());   // prints 'old_value'
$wrapper->body->value = 'new_value';
print_r($wrapper->body->value->value());   // still prints 'old_value'

$wrapper->save();
node_save($node);
?>

yet it seems not to make any changes to the node.

Although, if I've tried to change the title:

$wrapper->title = 'ABC';

everyting worked fine.

I guess it's the problem related to using localization, but I can't find sufficient documentation on how to achieve what I want.

Could someone tell me how can I put it to work?

Documentation is up to date now.

Examples from drupal.org :

 $wrapper->author = 0;
 $wrapper->url = 'dummy';
 $wrapper->author->mail = 'foo';
 $wrapper->author = NULL;
 $wrapper->author->set($GLOBALS['user']->uid);
 $wrapper->author->set($GLOBALS['user']);

 // Localization Here
 $wrapper->body->set(array('value' => "The second body."));
 $wrapper->language('de');
 $wrapper->body->set(array('value' => "Der zweite Text."));
 $wrapper->language(LANGUAGE_NONE);
 $wrapper->set($node);

 $wrapper->reference->name->set('foo');
 $wrapper->reference->set($wrapper);
 $wrapper->save();
 $wrapper->delete();
 $wrapper->type->set('article');
 $wrapper->author = $user->uid;
 $wrapper->{$property}[0] = '2009-10-05';
 $wrapper->field_image = array('fid' => $file->fid);
 $wrapper->$name->value();
 $wrapper->parent[] = $term_parent2;
 $wrapper->field_tags[1] = $term_parent;
 $wrapper->field_tags->set(array(2));
 $wrapper->field_tags = NULL;
 $wrapper->$field_name->set(NULL);
 $wrapper->field_text[0] = 'the text';
 $wrapper->field_text[0]->set(array('value' => "The second body."));
 $wrapper->field_text2->summary = 'the summary';
 $wrapper->field_text2->value = 'the text';
 $wrapper->field_file[0] = array('fid' => $file->fid, 'display' => FALSE);
 $wrapper->field_file[0]->description = 'foo';
 $wrapper->field_file[0]->display = TRUE;
 $wrapper->field_file[1]->file = $file;
 $wrapper->field_file[] = array('description' => 'test');
 $wrapper->field_file = NULL;
 $wrapper->field_image = array('fid' => $file->fid);
 $wrapper->field_image->alt = 'foo';
 $wrapper->field_image->file = $file;
 $wrapper->field_image = array();

You can follow this link to see full documentation and examples about entity metadata wrappers and localization.

Documentation about entity metadata wrappers on Drupal.org


Make a relationship to last element of a Field Collection I have a View with a relationship to Field Collection (with unlimited cardinality). I need this relationship to connect only to the last element (having the largest delta). How can I do this?

In order to show only the Field Collection item having the largest delta, you can use the Field Collection Views module as your formatter (i.e., Views field-collection items) in your View (i.e., parent View). With this formatter you can select another View (i.e., sibling View) to display your field collection items (so you will get a View within a View).

In the parent View you simply specify in the 'Multiple field settings' to display only the last result (i.e., Display 1 value(s), starting from 0, reversed checked), see screenshot below:

Note: in order to output the results in the order that is specified on your node, you have to set a relationship in the sibling View <view_name_for_field_collection> to 'Field collection item: Entity with the {Field Collection field}' and mark it as required. See this issue for the Field Collection Views for an extended explanation.

Let me know if you need any help with this.


How do you get the current destination URL query parameter in Twig? Does anyone know to how to get the drupal destination in twig file?
At the moment I an getting the destination parameters in a preprocess function.
// Get destination params.
$variables['destination_params'] = \Drupal::destination()->getAsArray();

Then in the twig file:

You can try logging in to see if you have access.

Thanks!

You can use path() function with '<current>' pseudo URI to generate current page relative URL.
For example:
{# in hard-coded path (bad practice) #}
<a href="/user/login?destination={{ path('<current>') }}" class="btn btn-sm btn-primary icon-before"> Sign-In

{# more proper twig-like way #}

You can try <a href="{{ path('user.login', {}, {'query': {'destination': path('<current>') }}) }}">logging in to see if you have access.

More about Drupal's twig built-in functions here: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/functions-in-twig-templates


Link by internal path in *.links.menu.yml not visible in admin menu Based on the official documentation to create menu links I've tried to use an internal link on the administration menu. But the internal link is only visible for users with administrator rights.

In my my_module.links.menu.yml I use the following links for testing:

my_module.test_link:
  title: 'TEST LINK internal'
  url: internal:/node/add
  description: 'TEST internal'
  parent: system.admin_content
  weight: 99

my_module.test_link_2:
  title: 'TEST LINK external'
  url: https://www.stackoverflow.com
  description: 'TEST external'
  parent: system.admin_content
  weight: 100

Both links are visible for administrators, but an user with editor role does only see the external link.

I activate every permission for the editor role, the link remains invisible.

It seems to be necessary to use a route_name for this. Then you can control permissions and the internal link is visible for the editor role too:

1 – Change my_module.links.menu.yml to use a route_name instead of the url:

my_module.test_link:
  title: 'TEST LINK internal'
  route_name: my_module.test_route
  description: 'TEST internal'
  parent: system.admin_content
  weight: 99

2 – Add the route with  permission to my routing file my_module.routing.yml:

my_module.test_route:
  path: '/node/add'
  requirements:
    _permission: 'access content'


Entity reference field changes not shown in diff? I installed the Diff module so see the changes to node revisions. Works fine, but when I change an entity reference field the diff of that field is not shown. What could I be missing? From everything I've see the modules should integrate with each other. Diff 7.x-3.2 and Entityreference 7.x-1.1.

Problem was that the fields were set to hidden in Mange Display default display setting. Set to Label and it works.


Warning: Illegal offset type in drupal_add_js() (line 4184 of C:\EasyPHP-5.3.8.1\www\lfp\includes\common.inc) I am using D7. I am getting the above error when I created a js file with the code below and then included it in the .info file. What is wrong?

(function($) {
Drupal.behaviors.userLoginChanges = {
    attach: function(context) {
        $("#user-login-form").attr("placeholder", "Username");

    }
}
}) (jQuery);

I realized the issue - In the info file I was writing scripts[all][] = filename, the same way you do it with css files. The correct syntax is scripts[] = filename.


Some of my pictures and fonts are not loading after uploading to host I've just uploaded my website to my host.  There was a 500 Internal Server Error at first, I looked into my htaccess file and after a lot of struggling with it I commented this line: Options +FollowSymLinks and then it worked but still some of my pictures and fonts are not loading, also I have some errors in my pages like:

Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 702 of /home/simamedi/public_html/includes/bootstrap.inc

and

Warning: ini_set() has been disabled for security reasons in include_once() (line 290 of /home/simamedi/public_html/sites/default/settings.php

Sorry, I'm quite new with these things, there's a live version of my website at www.simamedia.com.

Seems like ini_set is disabled by your hosting provider.  There is a thread on drupal.org that may help.

Seems like your best option is to contact your hosting provider directly and see if there's anything they can do for you.

This might help as well.

  I had the exact same problem, and by reading the posts here and
  Googling around I found out that this error is caused by ini_set being
  disabled by the hosting provider.

  Unless you have root access, you cannot edit the php.ini file
  directly, but at least on my hosting the support gave me these
  instructions to circumvent the problem:

  Create a "php.ini" file in your public_html directory and put one line
  of code exactly:

  disabled_functions =


Create pagination in theme('table') when not using SQL query I would like to create a pager in the table when there is fix amount of rows.

The method suggested on internet creates table, and it fetches data by using sql query, but i want to create a table from the data from the array.

visitedgroups = array('1','2','3','4');//It is an array of node id which are group entity
$header = array(
                array('data' => t('Group Name')),
                array('data' => t('Group Since')),
                array('data' => t('Join')),
            );
            $rows = array();
            foreach ($visitedgroups as $groupid) {
                $groupnode = node_load($groupid);
                $createdtime = format_interval((time() - $groupnode->created) , 2) . t(' ago');
                $joinlink = l('Join Group', 'group/node/'. $groupnode->nid.'/subscribe');
                $rows[] = array( l($groupnode->title, 'node/'. $groupnode->nid),
                                                t($createdtime),
                                                $joinlink,
                                    );
            }
            $output .= t('Recently visited groups by you, in which you are not member.');
            $output .= theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('group-visited-table')))).theme('pager');

The above code generates the table and working fine. But i want to add pager in the table.
From the references on internet i found that people adds,

  $query =
  $query->extend('TableSort')->extend('PagerDefault')->limit(10);

ahead of $query->execute(), but i don't have query.

So how can i apply pager in this scenario..

Try the following function:

/**
 * An generic array pager for Drupal.
 * For Drupal 5 and 6, the default limit is 10. For Drupal 7 it is 9.
 */
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

$output = pager_array_splice($yourarray, 5);  // 5 is per page values

See Paging non-SQL data for more details.


How to use FilterProcessResult::createPlaceholder (#lazy_builder) in an input filter? The FilterProcessResult::createPlaceholder method suggests that I can set a PHP callable that will allow me to return a render array. However my callable is not being called when visiting a node using Drupal 8.0.x.

I do not see any error messages in watchdog or in the PHP log.

What should I be doing in order to get FilterProcessResult::createPlaceholder() to call my callable?

Code

  public function process($text, $langcode) {
    $matches = [];
    $result = new FilterProcessResult($text);

    $count = preg_match_all('/\[processing\](?P<code>.*)\[\/processing\]/is', $text, $matches);

    if ($count) {
      $i = 0;
      foreach ($matches['code'] as $i => $code) {
        $args = [$code, $this->settings['render_mode']];
        $markup = $result->createPlaceholder('\Drupal\processing\Plugin\Filter\FilterProcessing::build', $args);
        $text = preg_replace('/\[processing\](?P<code>.*)\[\/processing\]/is', $markup, $text);
      }
      $result
        ->setProcessedText($text)
        ->setAttachments(['library' => ['processing/drupalprocessing']])
        ->setCacheTags(['processing']);
    }

        return $result;
      }

  static public function build($script, $mode) {
    $id = uniqid('processing-');
    $canvas_classes = ['processing-js-canvas', 'processing__canvas'];
    $render = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['processing-wrapper']
      ],
      'canvas' => [
        '#theme' => 'processing_display',
        '#rendermode' => $mode,
        '#unique' => $id,
        '#code' => $script,
        '#attributes' => [
          'class' => $canvas_classes,
          'id' => $id,
        ],
        '#attached' => [
          'drupalSettings' => [
            'processing' => [
              'drupal.processing' => [
                'elementId' => $id,
                'renderMode' => $mode,
              ]
            ]
          ]
        ],
      ],
    ];
    return $render;
  }

See commit 9d84e9477515bce1b7dd15f9724da1c6c0bd0fc2

HTML Output

<drupal-filter-placeholder callback="\Drupal\processing\Plugin\Filter\FilterProcessing::build" arguments="0=%0A%20%20%20%20%20%20%20%20size%28200%2C%20200%29%3B%0A%20%20%20%20%20%20%20%20background%28200%29%3B%0A%20%20%20%20%20%20&amp;1=source" token="bd5dbeba"></drupal-filter-placeholder>

I am running a settings.local.php with cache disabled on a local VM, but I got the same result without it.

After several months, I looked at the code again and found the issue. The createPlaceholder method calls addAttachments, but then I call setAttachments, which removes the previous attachment.

I should always use addAttachments as that will merge instead of overwrite.

foreach ($matches['code'] as $i => $code) {
  $args = [$code, $this->settings['render_mode']];
  $markup = $result->createPlaceholder('\Drupal\processing\Plugin\Filter\FilterProcessing::build', $args);
  $text = preg_replace('/\[processing\](?P<code>.*)\[\/processing\]/is', $markup, $text);
}
$result
  ->setProcessedText($text)
  ->addAttachments(['library' => ['processing/drupalprocessing']])
  ->setCacheTags(['processing']);


Sanitization of the q parameter I'm using Drupal 7. My question regards the sanitization of the "q" parameter. We know about SQL injection, so I was wondering if this parameter may be a vector for this kind of security flaw. I've searched the Drupal core files for the $_GET['q'] string. It is used several times but I could't find any kind of sanitization. Perhaps I've missed something.
My opinion is that Drupal does not uses the $_GET['q'] inside any kind of query or if it does it will be sanitized by the database API itself.

The request sanitization is an important part of Drupal security. Probably you can find the most important code in the DrupalRequestSanitizer class.
Here you have the sanitize method:
 /**
   * Modifies the request to strip dangerous keys from user input.
   */
  public static function sanitize() {
    if (!self::$sanitized) {
      $whitelist = variable_get('sanitize_input_whitelist', array());
      $log_sanitized_keys = variable_get('sanitize_input_logging', FALSE);

      // Process query string parameters.
      $get_sanitized_keys = array();
      $_GET = self::stripDangerousValues($_GET, $whitelist, $get_sanitized_keys);
      if ($log_sanitized_keys && $get_sanitized_keys) {
        _drupal_trigger_error_with_delayed_logging(format_string('Potentially unsafe keys removed from query string parameters (GET): @keys', array('@keys' => implode(', ', $get_sanitized_keys))), E_USER_NOTICE);
      }

      // Process request body parameters.
      $post_sanitized_keys = array();
      $_POST = self::stripDangerousValues($_POST, $whitelist, $post_sanitized_keys);
      if ($log_sanitized_keys && $post_sanitized_keys) {
        _drupal_trigger_error_with_delayed_logging(format_string('Potentially unsafe keys removed from request body parameters (POST): @keys', array('@keys' => implode(', ', $post_sanitized_keys))), E_USER_NOTICE);
      }

      // Process cookie parameters.
      $cookie_sanitized_keys = array();
      $_COOKIE = self::stripDangerousValues($_COOKIE, $whitelist, $cookie_sanitized_keys);
      if ($log_sanitized_keys && $cookie_sanitized_keys) {
        _drupal_trigger_error_with_delayed_logging(format_string('Potentially unsafe keys removed from cookie parameters (COOKIE): @keys', array('@keys' => implode(', ', $cookie_sanitized_keys))), E_USER_NOTICE);
      }

      $request_sanitized_keys = array();
      $_REQUEST = self::stripDangerousValues($_REQUEST, $whitelist, $request_sanitized_keys);

      self::$sanitized = TRUE;
    }
  }

There a few more functions but this one is the most important.
As you think sanitizing request input is very important. One of the worst Drupal core issues were related to this (in fact, this file was patched, if I'm not wrong). See "Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002" security report.
Implications
Given Drupal has a Security Team you don't have to worry about request sanitization unless you develop your own code that deals directly with the request.


Relationships between nodes and display in a special order I have two content types: 1) Team member and 2) office

There are about 150 team member nodes that need to be associated with 50 offices. When a team member is added to the site, there should be an auto complete field, where the name of the office, the member is in, can be selected.

After saving, the team member information should show up at the office which she has just been associated with. (Name, title and photo should be displayed - which could be done with Display Suite's view modes.)

In addition, each team member is associated with a specific function (head, partner, principal, consultant). This is done with taxonomy. On the office page, however, the team members associated with that office should be ordered according to the team members' taxonomy function. Those team members with the taxonomy term "head" should be displayed first, those with taxonomy term "partner" second, "principal" third etc.

How can this best be achieved? I have taken Entity Reference and Nodereference modules into consideration. Can this be done with Display Suite only or do I need to create a Views block?

I solved this with the modules: entity reference and corresponding entity reference, setting up a relationship between the "team member" and "office" content type.

Then I created a view and added A Contextual Filter choosing the reference field from the "team member" content type as a contextual filter. Then I added: "Provide default value" "Content ID from URL" in the "When the filter value is no available" option.

After that I chose "Content: Function" field as a sort criteria so that the team members will be displayed according to the taxonomy order. Finally I added the block, which I created with the view, to the office page content type under manage display.


"Search Setting" missing from 'Search And MetaData' section on configuration page I have a problem. I have a project that uses Domain Access.
I recently installed the "Search API" module and attempted to set up an indexing configuration.  That all went well, but when I tried to index the items I tried going to Drupal 'configuration' page, and under "Search And MetaData" section, there should be a link called "Search Settings", but there is not.

In a different project that did not use Domain Access I set this up and it works fine. Here is an example of the project that has search api set up properly and "Search Settings" shows up under "Search and Metadata"

I can click on "Search Settings" and it takes me to the "Search Settings" page where I can index my nodes, as well as a few other configuration options.

For my new project that uses Domain Access the "Search Settings" section is missing from "Search and Metadata", behold:

I initially thought it might be a permissions problem, and went to permissions section and the both have 'administrator' set under permissions for "administer search api".

Does anyone have any idea why my new project that uses Domain Access might be missing this page?  I tried going to the "Search Settings" page by manually typing the url into my browser, but it said "Access Denied". (I also have Access Denied backtrace set up and no reports were being generated after it gave me the access denied.

The only reason I mention that my new site uses Domain Access is because that is the only major difference between the 2 projects that I can see.

I would really love some help with this, and would consider it my Xmas present.  :D

I found the answer out.
I thought that the "Search Setting" configuration section was created for the "Search API" module, but it is actually for the core "Search" module.
Re-enabling the core "Search" module caused the "Search Setting" configuration section to reappear.


Drupal 7 -Resize image from URL At present I am working on a demo site. I am pulling in sample images from from lorempixel for place holders. That is working great. In my content type I have an image field and it includes the url to the image like this: http://lorempixel.com/output/people-q-g-605-186-6.jpg

I will be creating views soon and I want to adjust the image size using image styles. How can I apply the image style to the text field that holding the url? Is this possible, if so, how? if not, is there another way to accomplish this?

I don't want to create various image size, just adjust them as they are being referenced.

Thank you in advance.

For this one - I am going to adjust the size via css in each of the views.  Would still like to know if the above is possible, but this will resolve my current issues


How to trim the beginning of a field (reverse trim)? In Views and several field formatting modules you are given the ability to trim the end of text fields to show for example only the first 100 characters. However what if I want to do the reverse. What if I want to trim a field to not show the first 100 characters but to show everything else, how could I do this?

The right way would be to write your own view field plugin.

The quick way is as follows:
I assume your text field is the main body field.
Install views_php. In your view hide the text field. Add a Global PHP field. Make sure it is after the text field. In its output code put the following:

<?php print substr($data->field_body[0]['rendered']['#markup'], 100);?>

In Rewrite Results strip out HTML tags. As you are truncating text you will run into problems with unmatched tags, so you have to do this. Also, this sanitises the text. If you do not do this you have to run check_markup in the php.

Also, this is not the preferred way to output a field. The correct way is to use field_view_field.

And if your field is anything other than the body, then install devel module, and include this PHP snippet in the output code of the PHP field.

<?php print dsm($data);?>

This will help with getting the right field.


How to remove mymodule configurations on uninstall I have created a custom module and created a yml file to create a menu

system.menu.custom_menu.yml

id: custom_menu
label: 'Custom menu'
description: 'Custom menu.'
langcode: en
locked: true
dependencies:
  - mymod

When I installed my module it creates the the custom menu.
But then When I uninstall the module and try to install it again I get the following exception

exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects (system.menu.custom_menu) provided by mymod already exist in active configuration' in
/var/www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70

What I am doing wrong? Is there any way to remove my configuration (system.menu.custom_menu) from the configurations when I uninstall my module?

The easiest way is to ensure that the config has a dependency on your module.

dependencies:
  module:
    - yourmodule
  enforced:
    module:
      - yourmodule

Then Drupal will automatically remove that configuration and also warn in the UI that it will be removed.

Note that this only works for new installations, it won't fix existing ones.

An alternative is to put the configuration in config/optional instead of config/install, then it will only be created if it doesn't exist yet and the dependencies are met.


What is the recommend process for migrating a Drupal 6 Ubercart site to Drupal 7 / Drupal Commerce? I'd like to migrate a client's site from Drupal 6 and Ubercart to Drupal 7 and Drupal Commerce. Is there an easy (i.e.: no manually munging data in the database) migration path? Do I need to go to Drupal 7 + Ubercart as an interim step?

There are new tools and resources for this:

http://drupal.org/project/commerce_migrate
http://drupal.org/sandbox/rfay/1233708
http://vimeo.com/26775252
http://www.commerceguys.com/resources/articles/215
http://www.commerceguys.com/resources/articles/ubercart-drupal-commerce-1
http://www.commerceguys.com/resources/articles/ubercart-drupal-commerce-2
http://dl.dropbox.com/u/7350603/Importing%20into%20Drupal%20Commerce.mp4


Modules installed with composer do not have a version number Recently we ran into an issue where the Focal Point module has a dependency on a specific version of the CropAPI module. Since composer is installing these modules directly from git, they dont have the version numbers that were added to the .info file by the drupal.org packaging scripts. This cause the focal point module to fail during enable.

Has anyone else solved this?

I am using https://packagist.drupal-composer.org/ as Packagist repository for Drupal modules, and I get the version information inside the .info.yml file of the modules I require with composer require.

I first added the new repository with composer config repositories.drupal composer https://packagist.drupal-composer.org/. After, I can add any modules, for example the Focal Point module with a command like the following.

composer require drupal/focal_point 8.1.*@dev

The command install the module and its dependencies, producing the following output.

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drupal/crop (8.1.0)
    Downloading: 100%

> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Installing drupal/focal_point (8.1.0-beta3)
    Downloading: 100%

> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
drupal/crop suggests installing drupal/media_entity (Required by drupal/crop_media_entity)
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

If then I check the content of modules/focal_point/focal_point.info.yml and modules/crop/crop.info.yml, I get the following output.

name: Focal Point
type: module
description: Allows users to specify the focal point of an image for use during cropping.
# core: 8.x
package: Images
# version: VERSION
test_dependencies:
  - crop
dependencies:
  - image
  - crop (>=8.x-1.0-alpha2)

# Information added by Drupal.org packaging script on 2016-09-01
version: '8.x-1.0-beta3'
core: '8.x'
project: 'focal_point'
datestamp: 1472695440

name: Crop API
description: 'Provides storage and API for image crops.'
# core: 8.x
package: Media
type: module
dependencies:
  - image
  - user

# Information added by Drupal.org packaging script on 2016-05-25
version: '8.x-1.0-rc1'
core: '8.x'
project: 'crop'
datestamp: 1464160143

In both the cases, the information added from the Drupal.org packaging script is present for both the modules (the one I directly required, and it's dependency). I am using this method for all the module I need in my site, and I have never had problems with the version strings.
To update the modules, I just run composer update, and Composer updates all the modules with a new version that respects the restriction I set for each module.


Stemmer processor not working I have configured Search api module in my Drupal 8 search. This is the first time I am configuring search api. I am using database search and not solr. My problem is stemmer processor is not working properly. I am not getting intended result for keywords due to stemmer processor issue. Stemmer processor is not stemming the words while indexing but is stemming while search query is executed. For example the word 'cars' is stored in the database as 'cars' itself while indexing but when a search query for 'cars' is executed it stem the word to 'car' and I am not getting the result. How can I fix this.

It seem to be a bug. I run into the same problem today, so I created an issue on the search api queue Stemmer is not working properly on indexing or on search. Please check that issue and elaborate if necessary.


UberCart product image won't scale The image in a product (full view not teaser) is coming in full size (and too big) and I can't figure out how to change it.
Looking at the Product content type I see the 'Preview image style' is 'Thumbnail (100x)'. I read in some doc the Preview image style should be 'uc_product' so I'm a bit surprised by that.
In an attempt to figure it out I went to >>Media>>Image styles and changed every image style to Scale 50x50. Images in the teaser responded to the change but on the product page the image is still coming in large (full size probably).
Also as a guess, I went to Configuration>>Media>>Colorbox and change Max width, Max height, Initial width & Initial height to very small values. This made no difference.

Any suggestions for solving this or tips for figuring it out?

Thanks

May be the css property for the image in the full page was written as width:100% and height:auto , so it will always makes an image in large full size. you can check by inspect element to see the correct path of image style is coming or not.

You can get the image path from there and paste that in new tab to see what size of image is coming without applying any css rules.

Hope this will help you.


How can I let a group of users edit anything in a specific section? Our content editor wants to let the various authors have rights to edit things in only specific sections, and it will often be multiple people assigned to a given section.  What's the best way to do this?   (And sections do NOT map neatly to content-types.  They're based on the menu/site structure.)

It's not clear to me what your rule for determining access control is. I'm going to guess it's menu paths.

I had a similar problem recently. I needed to ensure that users trying to access /somePathName/* were of a certain role. This is a bit of an odd scenario since any path in the system could be aliased under one of my UAC paths and it will automatically become access controlled whether it was a term, node, user, whatever.

I looked into existing solutions and found none. I wrote my own module that managed access control based on "arg(1)" and a user's roles.

Access control in Drupal is one of those pieces that you understand after a few hours of studying, do the work, then completely forget how you did it. Or maybe that's just me.

Documentation on Drupal.org is pretty good on this topic. Be sure to install the Devel module and enable the node access modules it provides. They are very useful.


I can't get my drupal_http_request to go to the correct function I am working with Drupal 7, I have a hook_services_resources() set up:

function Api_services_resources() {
  $api = array(
    'applicant' => array(
      'operations' => array(
        'retrieve' => array(
          'help' => 'Updates applicants',
          'callback' => '_Api_retrieve',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'gwf',
              'type' => 'text',
              'description' => 'GWF Number',
              'source' => array('path' => 0),
              'optional' => TRUE,
              'default' => '0',
            ),
          ),
        ),
        'create' => array(
          'help' => 'Creates applicants',
          'callback' => '_Api_create',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'data',
              'type' => 'array',
              'description' => 'User Account Info',
              'source' => 'data',
              'optional' => FALSE,
              'default' => '0',
            ),
          ),
        ),
        'test' => array(
          'help' => 'Tests API Connection',
          'callback' => '_Api_test',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'timestamp',
              'type' => 'text',
              'description' => 'Timestamp',
              'source' => array('path' => 0),
              'optional' => TRUE,
              'default' => '0',
            ),
          ),
        ),
      ),
    ),
  );

  return $api;
}

And am trying to post to it using:

$create_website_applicant_path = 'http://' . $website_url . '/api/applicant/create/';

      $applicant = array(

        'mail' => $user['applicant_email'],
        'pass' => user_password(8),
        'status' =>  1,
        'roles' =>  array(2 => 1, 3 => 0, 8 => 0, 7 => 0, 6 => 0, 9 => 0),
        'notify' => 0,
        'timezone' => drupal_get_user_timezone(),
        'field_given_name' => array('und' => array('0' => array('value' => $user['first_name']))),
        'field_family_name' => array('und' => array('0' => array('value' => $user['last_name']))),
        'field_gwf' => array('und' => array('0' => array('value' => $user['gwf']))),
        'field_vac_ip' => array('und' => array('0' => array('value' => $_SERVER['REMOTE_ADDR']))),
        'submit' => 'Create new account',
        'ldap_user_create_ldap_acct' => 0,
        'op' => 'Create new account',
        'signature_format' => 'filtered_html',
      );

      $create_website_applicant_params = array(
        'method' => 'POST',
        'data' => drupal_http_build_query($applicant),
        'timeout' => 15,
      );
      $create_website_applicant_result = drupal_http_request($create_website_applicant_path, $create_website_applicant_params);
      echo $create_website_applicant_path;
      print_r($create_website_applicant_result);

The only problem is that when I try to use POST I get an error saying 404:Not found: Could not find the controller.  I know the page is there, I can go to it in my browser.  If I try to use GET the function being called for /api/applicant/create is actually _Apt_retrieve().  I'm not sure why this is and can't get it to point to the other function.

The path that you are passing in drupal_http_request is incorrect. It should be $create_website_applicant_path = 'http://' . $website_url . '/api/applicant/';


Correct way of formatting dates for output in node theming I am theming a node where I need to show the created date. Since Drupal stores it as timestamp, what is the best method to retrieve it? I have found this post: http://drupal.org/node/101993. But the problem is that whe using this...

<?php
print date("D, j M, Y \a\\t G:i", $node->changed);
?>

... it delivers me the content in English. My portal default language is Portuguese. Is there a Drupal function that will deliver the timestamp as a regular date that takes into account the user's selected language? And  that maybe takes into account the preformatted dates set in the portal configuration? Thank you.

Instead of date(), try using format_date()

It has an otional last parameter $langcode that tells it what language code to use for the date.


How to add two registration form on single page? How can i add two registration form on single page

I had created two registration page using the Profile 2 module and given a custom path,eg:

http://localhost/dupal/member/register
http://localhost/dupal/non_member/register

How can I display that two form on single page
eg:http://localhost/dupal/user/register

Give a try to Profile2 Registration Path module:

Problem with Profile2 module: By default, the Profile2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

Solution:

  Profile2 Registration Path enables you to set a unique registration path for each Profile2 profile type. Users who register via that unique path will be presented with fields from the chosen profile type(s).

Alternatively another method to include multiple forms (e.g: FORM1 and FORM2) on same page is somewhat like below(however I am not sure where it will work with the profile2 forms):

$output = array();
$output['FORM1_DISPLAY'] = drupal_get_form('FORM_1_FORM_ID');
$output['FORM2_DISPLAY'] = drupal_get_form('FORM_2_FORM_ID');
return $output;


How to create a view of Users and use uid field with Display Suite view mode I have been able to create a view of Users with format of Fields. I added user fields, and and found the UID field as well which I can use to link a field to the user's profile page.

However, I prefer to output views with the Content format and create a view mode for the view. For users, there is no Content format, and I assume the equivalent is User format.

However, when I created my display mode on the user profile and set it to a display suite layout, I found that there is no UID field (I did see Username, but that wont help). Does display suite not provide us this field?

Just as it does not provide a nid field for nodes, so it does not provide a uid field for users.

For format in your view you can also show 'Display Suite' which will open up more ds-goodness.

To show the uid you need to add a ds code field. it is best used with the token module installed as well.

Add the token [user:uid] as the field value.

The field will now become available for display suite to use. You could also use html in the code field, and for instance use the [user:uid] token to create a link, as in:

[user:name]

Also note that you do not need to display the primary identifier of an entity (uid for users) in order to use it in views relationships. As users is the base table it will already be available.


How to hide time from the date display? In a view using Articles and Blog posts sorted by recent post date, I'm using [Content: Post date] and I would like to display (as a column on the display) as only the date and not the time, i.e. 2016/04/08.

I merely wish to alter what data Drupal is displaying, not the data it is collecting.

How can I apply this date format to the field in the view?

In Home>Administration>Date and Time, I can add new date type but all 19 of the options include displays of time.

There should also be a Formats tab at the top of that page. Here you can add additional formatting (like date or time only formats). After saving the format, go back to the first page and now you can select your newly created format as an option.


Why has this "details" accordion appeared in this view? I have a view that uses the table format and the "group by" setting.

I've just updated to the Drupal 8.9. Suddenly, each group has this empty Details accordion.

It wasn't there before.

Why did it appear? How can I get rid of it, other than removing it with CSS?

I ran into this issue with a View as well. Fortunately, this issue was reported to Drupal Core, fixed and released in Drupal 8.9.2 and Drupal 9.0.2 all in under a month which is quite commendable.
I just tested this issue by upgrading a test to Drupal 8.9.2 which resolved this issue.


Drupal Calendar mini String overrides I want to change !day-abbreviation S|M|T|W|T|F|S string in the calendar block view. I used String overrides for other elements (month, week) and they work, but in the calendar block, day letters are not changing.

In Views/Block view/Styles (gear icon) change Calendar day of week names to Abbreviated name.


Views, show block on nodes where the node author has specific role(s) I am trying to display a few views blocks on nodes of authors that have specific roles. So far I used contextual filter Content: Author uid with the following settings:

Provide default value: User id from url (Also look for a node and use the node author checked)
Specify validation criteria: validator user, Restrict user based on role checked and I checked the roles for which I want the block to show up.

Although it seems to work with some blocks, it does not with all.

A good example is this page. The Featured listings block has the same settings (contextual filter as described above) as the Similar listings one but it does not show up. I used the same filter for another page (diff role of the author) with exactly the same config except the role and seems to work fine as well.

Any idea anybody how this could work for all use cases? Is content author uid the correct filter and is the setup correct?

Any help will be much appreciated.

THanks

Change access settings from access:Permissions to access:Roles and select the desired roles you want.

And for users use the contextual filters.


setHandler into views_pre_render OR count results in views_pre_render I have a view that needs to have a custom views footer only if it get results. Otherwise the view needs to not be displayed

I can set up a view footer by using $view->setHandler with hook_views_pre_render and I can count results with hook_views_pre_render

How can I achieve both with a single function? Using $view->setHandler with hook_views_pre_render does not attach the footer

Found an alternative solution, by using hook_views_pre_render and $view->attachment_after

$view->attachment_after = array('#markup' => 'Button');


Use JSON instead HTML for access denied on some custom paths I create a small API for one project using Bathic Authentication. The API consists of some custom paths defined in routes in a custom module. Using JsonResponse() in the controller we send back a JSON object with data.

But in case the user does not have permissions to access the path the route gives back the 404 HTML page. How can I tell Drupal to return a JSON object for my API paths under every circumstances?

Another example: we defined just to accept GET in the route. Using POST will return a HTML error page - we want Drupal to send back JSON with error information.

Drupal returns the 404 in the format requested, so adding the query string ?_format=json to the request should return a JSON response under any circumstances. If Drupal doesn't detect the format it uses HTML by default. You could either help Drupal detecting the format in a request subscriber or implement an exception subscriber to return JSON exceptions similar to ExceptionJsonSubscriber::on4xx for your API paths.


losing CCK custom field when saving I have installed varnish load balancer on my pressflow 6.22 website.
i have some custom fields created by CCK.
the original server is X and i have added another server Y to make this load balancer.
now, when the editors try to create any node when they were directed to server Y, they lost all custom fields when they save. however, when they are directed to  original server (X), everything goes fine with them!!
anyone faced such case? any idea about the reason or how can i fix it?
** EDIT **
i have checked in the DB and found that the image path has been saved normally, but when i make node_load, it didn't show this field. also when view or edit this node, the image is not shown as well!!
any idea is highly appreciated
Thanks for your help

Thanks 32i for your suggestion, i have managed my problem already.
it was a result of cache. when i flush all caches i get the content normally.
finally i found out the memcache is the caching level behind this problem, simply i excluded authenticated users from being served by memcache and this fixed my problem


How can I programmatically add data to an address field? I'm trying to import user data from a json file. So far I managed to import most of the information, but now I'm stuck on the address field (created with Address module for Drupal 8).
In the json file (exported from a Drupal 7 website), there is city, country code and country name.
How can I import this data into the new field (the machine name is field_address)?
So far I tried using Drupal::entityTypeManager.
$values = array(
            'name' => $user["name"],
            'pass' => '',
            'status' => $user["status"],
            'mail' => $user["e_mail"],
            'field_first_name' => $user["first_name"],
            'field_last_name' => $user["last_name"],
            'field_address' => $city,
        );

        $userStorage = \Drupal::entityTypeManager()->getStorage('user');
        $userEntity = $userStorage->create($values);

It doesn't work: The address field stays empty.
Should I use the sub fields?

If you have a field with multiple properties then use an extra array:
$values = [
  'name' => $user["name"],
  'pass' => '',
  'status' => $user["status"],
  'mail' => $user["e_mail"],

  'field_address' => [
    'first_name' => $user["first_name"],
    'last_name' => $user["last_name"],
    'city' => $city,
  ],
];


How to link two content types from each other I have content type A and content type B. Users need to be able to link between them while creating either content type (A or B). When they link them up I would like it to be saved in one table. Currently using something like node reference would put it in two different tables.  Know of any module or functionality that can do that?

Clarifying
I want a user to be able to go into content A and save a reference to content B. We also need a user to go into content B and save a reference to content A. Ideally both references would be stored in one table as a many to many relationship.

You can save it to a single table by creating one entity reference field and invoking it on both content types.


Is there a way to know the view type from PHP code? Is there a way to know the view type (page or block) from PHP code?

if (views type is block) {
  echo "This is a block view.";
}
elseif (views type is page) {
  echo "This is a page view.";
}

The nomenclature for what you're talking about in Views is the display handler.

If you have the $view object (which you should in virtually all Views scopes), you can find the current object for the display handler at $view->display_handler. You can find the name by using get_class():

get_class($view->display_handler);

will return something like

views_plugin_display_page

which is the machine name of the display handler. But in conditionals, you can just use the instanceof type operator:

if ($view->display_handler instanceof views_plugin_display_page) {
  // ...
}


Limit which roles can view a node basing on its content type I'm using Drupal 7 and I created a new content type called "eBook," and I created a new role called "MonthlySubscriber." My intention is to allow only users with the "MonthlySubscriber" to view the "eBook" nodes. When I looked at the permission settings for a role, I saw the checkboxes that allows to create, edit and delete nodes of that content type, but there are no checkboxes for viewing nodes.

How do I limit the users who can view "eBook" nodes to just the users with the "MonthlySubscriber" role?

You need to install Content Access module to add this access control.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type.


Writing functional tests for a controller that makes call to external service? I'm working on the D8 version of the CAS module. To integrate with a single sign on CAS server, this module will have to redirect the user to the CAS server often, and occasionally make cURL requests to that server for validation of various tokens. I'm struggling to write functional tests because of this.

I have a Drupal controller that will redirect the user to a number of places and invoke actions on a number of services, some of which may make cURL requests to the CAS server.

When the controller redirects to the server, I can just tell my web test to NOT follow redirects by overriding the property maxiumRedirects and setting it 0, then inspecting the response to make sure it was a redirect.

But, Since this controller may invoke services that make cURL requests to the CAS server, how would I handle that in a functional test, where that external service does not exist? In a unit test, I can mock the response from Guzzle, but can I do that in a functional test? Is my only option to create a test "server" module (with all the routes defined that CAS client makes requests to) that is enabled only for testing and would be used for testing my CAS client module?

Depending on what exactly you want to do, what we've done multiple times is make the domain/URL to which you redirect to configurable, and then configure it to redirect back to your site.

Then implement dummy routes there in a test module, do whatever you want and redirect back.

This was already possible in 7.x and hasn't really changed. It is sometimes more complicated to set up, but has the advantage that you are testing much more of your actual code and integration.

if you use @larowlan's approach, you could also just write unit tests for your service but I like to have most code covered with functional tests (too). I've seen it in core already many times that unit tests and their mocks get out of sync with how things really work, and then they are testing something that no longer exists. The more you have to mock, the bigger that risk becomes.

Note that, no matter which approach you chose, moving as much logic as possible into a service or even multiple services makes sense anyway and allows you to use unit tests for things that they are good at. Testing all possible cases, error handling/conditions and so on.


How should I order custom blocks? I have two blocks in a custom module.

function THEME_block_info(){
    $blocks = array();

    $blocks['contact_info'] = array(
        'info' => t('Contact Info Block'),//admin ui block name
    );
    $blocks['contact_form'] = array(
        'info' => t('Contact Form Block'),//admin ui block name
    return $blocks;
}

function THEME_block_view($delta = ''){
    $block = array();

    switch($delta){
        case 'contact_form':{
            $block['subject'] = t('');
            $block['content'] = build_contact($delta);
            break;
        }
        case 'contact_info':{
            $block['subject'] = t('');
            $block['content'] = build_contact($delta);
            break;
        }

}

These blocks show up in the admin UI where we are able to order them. However, the order set in the admin UI doesn't work.

How should I set the order of these custom blocks to make it match the one sets in through the UI?

You can use 'weight' for every block.

$blocks['contact_info'] = array(
  'info' => t('Contact Info Block'),//admin ui block name
  'weight' => 0,
);

$blocks['contact_form'] = array(
  'info' => t('Contact Form Block'),
  'weight' => 1,
);

I hope this will work for you :)


How do I add fields to the sidebar menu when creating/editing nodes? I would like to add to the sidebar menu on the create/edit node pages. How would I do this?

I would like to do this in order to make the content creating/editing a little cleaner and easier to understand for content editors.

See attached pic...

Thank you.

The latest version of Field Group module supports putting fields into the sidebar (at least for nodes).

Field Group version >= 3.0-rc2, containing issue 2652642


Eliminate the "Upload" button in Webforms There is a way to eliminate the "Upload" button in Webforms, just adding an "attach" button that uploads the file automatically when you push "send", like in the image.

First, it's worth to remember that file will be uploaded when you push form's submit button, if user haven't uploaded it yet.
Second, you could use AutoUpload module:

AutoUpload is a user interface (UI) enhancement that initiates automatic upload of files minimizing the number of clicks required by a user.
Currently, users must select files, then press the "Upload" button. We found users often don't realize a button press is necessary and mistakenly think their image is uploaded when it's not.
This module removes the extra button press and hides the "Upload" button via JavaScript for a quicker, automatic file upload. When JavaScript is not enabled, it falls back to the "Upload" button.

I must admit that this module conflicted with my custom modules and themes, but as a code sample it was perfect. It's GPL, so tailoring it to your custom needs is perfectly legal.


Put menus into separate file for better handling caching with expires I am trying to clear the page cache of drupal as micro invasive as possible by using Cache Expires and custom logic.
On each page, the menu is shown down to Level 2 in a footer and a hover area.
Therefore I did only rebuild all menu trees and remove pages from cache if an item on the second or first menu level has been changes.

Now we have got an additional menu for mobile devices which is load with each page and shows down to four menu levels.
Changing a menu on the first to fourth level would no lead to a clear of almost any pages.

To avoid this, it would be great to put all that menu stuff out of the page html and put in a single file, containing just the menu information in e.g. json format.
So if a menu changes I would only need to update the menu file and the changed node.

Are there any smart hacks out there or even modules dealing with that?

There are several ways to achieve this - maybe more.

Ajax call and include the menu via jquery / javascript from drupal at runtime
Ajax call and iclude the menu via jquery / javascript from a static generated file by cron
SSI or ESI include at proxy level of a static file generated by cron

At the moment my favorite is 2. Option as the First option has a major performance drawback because the menu has to be generated for each page visit

Number 2. and 3. inlcude the menu within under 10 milliseconds
but 3. would be perfect as it makes the least problems with SEO.
As I do not yet have nginx as reverse proxy available in production I stick at 2. as I could not get to work SSI and PHP with apache and php virtual() is not cached by the drupal page cache (in fact it breaks it)

There is a module which helps with SSI and ESI called https://www.drupal.org/project/esi


How to have different URLs for microsites? First of all, thanks for anyone bearing with me with this issue. I know that I really should start looking into how Apache settings work etc., but first of all, I would like to get this working. (Plus points for anyone recommending good Apache learning material, right? ;) )

I'm working on a Drupal 6 site running on Apache where several users (around 120) will have content which will act as a microsite. I have defined a content type for this purpose, used ThemeKey to switch to another theme only on those nodes etc.

I would like to be able to serve any of those nodes on a different domain (e.g. microsite.com) than the main site (e.g. mainsite.com). What should I do to "redirect" (sorry if I'm using any wrong terms here) the new domains to the right place? I would like to keep the new URL for the new pages (so it would not occur as mainsite.com/microsites/microsite, but microsite.com in the address bar).

[I've heard that it would be a bad idea to serve the same microsite with two different URLs from a SEO viewpoint - so that's another issue I should consider, but I have no idea on how I should address this...]

This is what the Domain Access module is for.  Essentially, it allows you to run multiple Drupal sites out of the same database, and share content.

Sending particular pieces of content to different domains is rather easy; a new tab shows up on edit panels.

It integrates nicely with Panels, Views, and other modules that use cTools, as domain rules show up as selection criteria.

For the Apache side, you need to configure it so that your multiple domains point to the same DOCROOT.  How this is done depends on how you are running your sites.  If you are using virtual hosts, then you set up additional ServerAlias settings for your <VirtualHost>


I'm missing my core search module I'm running Drupal 7.12 and had to build a module that extends the search functions of the core Search Module. I made the module, installed it in my custom module folder and reloaded my Drupal site only to find that the search bar couldn't be found on the page...

I looked through the module selector on my dashboard and looked through the core modules. Surprisingly, there was no search module listed in the core module section, although my module did show up in my custom module section (which is irrelevant because the module I wrote needs the core search engine to work).

I checked through my Drupal on my FTP site and found that the files for the core search module are still there.

Why isn't it appearing in my dashboard core module list, and how do I get my Drupal site to recognize that the files are still there?

I'd guess that your custom module is called search, which would conflict with the core Search module, also named search.

There's no such thing as namespaces with regards to Drupal modules (at least out of the box, I'm not sure if there are any contrib modules that deal with this. My gut instinct is that there wouldn't be). Each module needs to be individually named, or the last module of the same name that Drupal comes across will be the one it uses.

Make sure your module is not called search; that includes making sure the folder name for the module, the name of the .info file, name of .module file, etc. are not called search.info etc. That should make sure that both modules are available in your module list.


Drupal Commons change theme I'm pretty new to Drupal, I installed Drupal Commons in order to build a website where users can register and create a custom profile. Users will be split in categories.

I'm not entirely sure Drupal Commons is the best choice for me.

Anyways, now I find myself in the following situation:
- I cannot find a way to change the Commons Origins default theme, let alone find a place where I can acquire such themes.

You can essentially download and upload a new theme to your site by following the instructions here:

https://drupal.org/getting-started/install-contrib/themes


Theming own field: how do I control the outer markup? I'm working on a custom field and formatter and right now I'm at the theming stage. My formatter should render a list of items as a run-in list of badges, much like the tags here on Drupal answers. Currently I am getting a top-to-bottom list, as the fields get the Drupal's default wrappers:

...

...

I thought it would be more appropriate if I had a control over the wrappers markup and delivered something like:

  Value 1Value 2etc.

I have already managed to control the span markup via a custom tpl, but I'm unsure how I am supposed to theme the field's outer markup to suppress the default wrappers.
Of course I know I could override div styling by setting display: inline-block, but I treat this as my first theming excercise hoping to learn.

The way to correctly theme what you are asking is shown here: theme_field()

In particular:

  This is the default theme implementation to display the value of a
  field. Theme developers who are comfortable with overriding theme
  functions may do so in order to customize this markup. This function
  can be overridden with varying levels of specificity. For example, for
  a field named 'body' displayed on the 'article' content type, any of
  the following functions will override this default implementation. The
  first of these functions that exists is used:

THEMENAME_field__body__article()
THEMENAME_field__article()
THEMENAME_field__body()
THEMENAME_field()

  Theme developers who prefer to customize templates instead of
  overriding functions may copy the "field.tpl.php" from the
  "modules/field/theme" folder of the Drupal installation to somewhere
  within the theme's folder and customize it, just like customizing
  other Drupal templates such as page.tpl.php or node.tpl.php. However,
  it takes longer for the server to process templates than to call a
  function, so for websites with many fields displayed on a page, this
  can result in a noticeable slowdown of the website. For these
  websites, developers are discouraged from placing a field.tpl.php file
  into the theme's folder, but may customize templates for specific
  fields. For example, for a field named 'body' displayed on the
  'article' content type, any of the following templates will override
  this default implementation. The first of these templates that exists
  is used:

field--body--article.tpl.php
field--article.tpl.php
field--body.tpl.php
field.tpl.php

  So, if the body field on the article content type needs customization,
  a field--body--article.tpl.php file can be added within the theme's
  folder. Because it's a template, it will result in slightly more time
  needed to display that field, but it will not impact other fields, and
  therefore, is unlikely to cause a noticeable change in website
  performance. A very rough guideline is that if a page is being
  displayed with more than 100 fields and they are all themed with a
  template instead of a function, it can add up to 5% to the time it
  takes to display that page. This is a guideline only and the exact
  performance impact depends on the server configuration and the details
  of the website.

Finding the right naming convention is somewhat a mess, so I suggest you to try the Theme developer module in order to find out all the possible names for your template file.

Here is the naming convention guide. Given your comment my best guess would then be: field--field-chemical-hazards.tpl.php


What is the best way to achieve this result? I've hit a bit of a stumbling block with how to tackle this design I'm working on in Drupal. The end result needs to be a block that sits on the home page and it updated weekly by anyone with the 'staff' user flag.

This is what it needs to be in the end: http://i.imgur.com/XUZugT4.png (Data being the focus of this question, design is irrelevant):

Whoever generated the list has their name and picture on the block.
There will always be 3 products.
The person who picked this week can include a personal comment on the picks.

I've been able to get it working so far by making a block that uses inline PHP to grab a view that contains 3 products that have the taxonomy term "Promote to Front Page", and then manually filling in the user information myself... But I'd like for this to be something a staff member can fill out themselves without needing any code knowledge.

Is this something achievable with a content type or something else i'm not thinking of?

An awesome bonus is if there's a way to do it so that each week a new pick is generated but the old ones are still stored for reference.

Thanks muchly!

I would do it with content type using entity reference to products.
Entity reference allows you to reference other nodes in your "deal of the week" node and use this relationship in your view. No PHP should be needed.
With this setup, you can do almost anything:

only Staff is allowed to create new content of this type
view can show author name (and picture)
custom comment? no problem, just a text field in content
old content is still available


How to support .dcm image format file for uploading in an article? I want to upload .dcm image format file into Drupal7 article, but it's not allowed.

Suggestions about how to get this to work?

Unfortunately, it is not possible to allow image extension that cannot commonly displayed by a browser. You would have to use a filefield instead.

This has been discussed at:

https://drupal.org/node/1081060

https://drupal.org/node/1014816

And for D6 at:

https://drupal.org/node/515152


How can I show parents after child term inside a Views exposed filter? I have a vocabulary with states and cities, where city are children of state:

I have an exposed filter with depth. How can I show parent term after child? For example, like this:

I'm confused because the array has no relation between parent and child. For example, this is the form array select box:

{
#type: "select",
#options: {
0: {
option: {
17: "Aragon"
}
},
1: {
option: {
21: "-Barbastro"
}
},
2: {
option: {
20: "-Calatayud"
}
},
3: {
option: {
19: "-Zaragoza"
}
},
4: {
option: {
16: "Cataluña"
}
},
5: {
option: {
22: "-Barcelona"
}
},
6: {
option: {
24: "-Girona"
}
},
7: {
option: {
23: "-Tarragona"
}
},
8: {
option: {
18: "Valencia"
}
},
9: {
option: {
26: "-Alicante"
}
},
10: {
option: {
27: "-Elche"
}
},
11: {
option: {
25: "-Valencia"
}
},
All: "- Any -"
},
#size: "",
#default_value: "All"
},

The exposed taxonomy filter select box form doesn't have any hierarchy built into the select form array (e.g. using subarray to present optgroup elements). Rather, its labels are indented to present the hierarchy on each select option.

To alter the labels, you can utilize hook_form_views_exposed_form_alter() to alter the selectbox array structure with some string manipulate logic. For example:

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $parent = '';
  $options = $form['tid']['#options'];
  foreach ($options as $index => $option) {
    if (is_object($option)) {
      $label = reset($option->option);
      $key = key($option->option);
      if (substr($label, 0, 1) != '-') {
        $parent = $label;
      }
      else {
        $options[$index]->option[$key] = $options[$index]->option[$key] . " ($parent)";
      }
    }
  }
}


Creating new content type (programmatically) with CCK fields as default Possible Duplicate:
  Module development - integrating custom content types

Is there any way to programmatically create a new content type with few CCK default fields?
I don't want to add those fields after I created the content type, but I want them to be delivered with my module instead
Luca

there are several suggestions about create CCK programatically (also can be seeking for CCK import content):

Programmatically Create, Insert, and Update CCK Nodes: http://civicactions.com/blog/cck_import_and_update
Creating Drupal CCK content programatically/ via API: https://stackoverflow.com/questions/772880/creating-drupal-cck-content-programatically-via-api
Programmatically add CCK field to content type: http://drupal.org/node/702156
Creating nodes with CCK-fields programmatically using drupal_execute() in D6: http://drupal.org/node/439090

I extract interesting comments from StackExchange:

  ...The Node Export module can generate sample code for creating a node
  (complete with CCK fields) programatically.
  There are a ton of modules that try to do the import thing right. Take
  a look at a comparison of them http://groups.drupal.org/node/21338 ...

I hope this information be useful


Form theming not working Please could someone advise what is wrong with the following? When the page loads it downloads an unknown file type. The form is displayed but not with the template/theming.

The form...

function test_form($form, &$form_submit) {
    $form['message'] = array(
            '#type' => 'textarea',
            '#title' => t('Message'),
            '#required' => TRUE,
    );
    $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Send')
    );

    // Get the path to the module
    $path = drupal_get_path('module', 'test');

    // Attach the CSS and JS to the form
    $form['#attached'] = array
    (
            'css' => array
            (
                    'type' => 'file',
                    'data' => $path . '/css/test.css',
            ),
            'js' => array
            (
                    'type' => 'file',
                    'data' => $path . '/js/test.js',
            ),
    );

    $form['#theme'] = 'test_form';
    return $form;
}

The theme...

function test_theme($existing, $type, $theme, $path) {
    return array(
            'test_form' => array(
        //'arguments' => array('form' => null),
        'path' => drupal_get_path('module', 'test') . '/templates',
        'template' => 'test',
        'render element' => 'form',
            ),
    );
}

The directory...

test
test/css/test.css
test/js/test.js
test/templates/test.tpl.php
test/test.info test/test.module

It sounds like there is just a problem with the loading of the attached files in your $form['#attached'] setting. Are you getting 404 errors from your debugger for the js and css files or is it not trying to load them?

You should try rewriting your form settings with the type as a settings array (if you need it) according to the API documentation

$form['#attached'] = array
(
        'css' => array
        (
                $path .'css/test.css' => array('type' => 'file',),
        ),
        'js' => array
        (
                $path .'js/test.js' => array('type' => 'file',),
        ),
);

or maybe more simply as:

$form['#attached']['css'] = array(
  drupal_get_path('module', 'test') . 'css/test.css',
);

$form['#attached']['js'] = array(
  drupal_get_path('module', 'test') . 'js/test.js',
);


Slider for Select List (Text, Numbers etc) in Views Exposed Filters I am trying to implement a vertical slider-like select list inside my views-exposed-filters as shown in the image below (on the left sidebar, vertical slider)

I am using Drupal 7 and Views 3. I have tried Better exposed filters module but I don't think it has such a feature. How can I achieve this? (See updates below)

Thanks

UPDATE: I have also tried Views Contextual Range Filter and Select with Style modules but couldn't get any of them working as desired.

UPDATE 2: One thing I have realized is, I am trying to show a an exposed filter for a term reference field, named 'Style' (based on a taxonomy term), so actually the field itself is not a multi-value field, hence it is not a select list. That is why Select with Style module doesn't work here. Is there a way to tweak my field/Views to make it work with one of mentioned modules?

There is another module called Views Contextual Range Filter

Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.


How to share menus and blocks across domains, but not users and content data? I'm trying to create multiple sites(maybe over 20 sites) using the same menu and some blocks, but not others.

I found these modules that have very similar features/functions:
- Domain Access.
- Domain Menu Access.
- Domain Blocks.

However, I don't want to share the users, content and other data.

Also, for each of the domain, I would like to have their own Drupal backend.

What is the easiest and effective solution?

There really is not "Easy" way but you are on the right track. From your description it sounds like you need to be using Domain Access. In order to share content all sites need to be using the same shared database. As for content/users, you will have to configure your data and users to not be shared across all domains. These are all permission settings that can be set from Domain Access. Set each user to only have access to a specific domain. And set each content type to be visible for the domain it was created under.

With domain access you can have a different theme set up for each domain, so that will help you have a different "backend" experience for your authenticated users. So to answer your question, Domain access is the most effective apporach for this type of scenario. Its all just a matter of configurations and permission settings.


What are the different types of hooks? In an old blog post, Larry Garfield refers to "registry-style" hooks and hook_nodeapi type hooks.

When it comes to breaking down the different types of hooks, there doesn't seem to be any documentation. There is the big list of hooks and Tim Plunkett found two defgroups dealing with hooks, but there doesn't seem to be a formal breakdown of what different types of hooks we have.

What would such a breakdown look like?

I would group them in three, four groups, but there is no technical/internal difference between them. All are just functions that are called because of naming conventions.

Info hooks. Hooks that provide information about something, typical examples are hook_entity_info(), hook_field_info(), hook_hook_info() but also hook_permission(), hook_menu(), hook_theme(), etc. Many of these have a _info suffix but don't necessarly need to. These hooks can be called any time and the returned information is often cached (static cache or persistent cache) or stored to specific tables (e.g. hook_menu()).
Reactive/Action hooks. I just invented that name, but these are hooks which are called when something specific happenend like hook_init(), hook_node_save(), hook_user_save(), hook_node_view() and so on.
Alter hooks. Hooks that can be used to change something provided by other modules, exist for almost any info hooks (e.g. hook_menu_alter() or hook_entity_info_alter()) and also some action hooks (e.g. hook_node_view_alter()).

There is also a forth group but those are actually not really hooks and they are one of the main reasons for the typical confusion about hooks. They are often referred to as "Callbacks". This are "Hooks" which are only called for a single module, which owns something. Typical examples include node type callbacks (hook_submit, hook_view, hook_form, ...), many field hooks (e.g. hook_field_load()) but also hook_block_view(). There are plans to remove these and replace with something else (oop based) or rename them to something else than hooks.

I assume there are also some hooks that can't be correctly put in any of these groups or are a mix of those groups. If so, that might be a sign that they should be redesigned. If someone knows any examples, I can add it here.

Disclaimer: This is not official but how I see it. Use with caution. ;)


How to export format settings (label, weight, etc) for body field, image field, and tags field I'm trying to export my layout settings that I did in Display Suite for my article content type full content view. All my settings for various fields (label and order) do take except the image, body, and tag fields. For example I change the label for the body field to hidden, export, and clear my db but when I go back to look it shows it as 'above'. I've tried to go into the exported code for display suite itself and insert in a 'label' => 'hidden' into the array also but that doesn't work either.

The order issue is where the tags field always show up before the body field. I've even checked the ds_layout_settings_info() function and the weight numbering of the array looks correct.

Why is it that only those three fields won't export correctly? Someone said that those specific settings are in core/field api fields but I can't find what to export in Features.

I figured what I was doing wrong. Since I was working with Features for some reason the Article Content Type originally got exported out into another module and was clashing with mine.