Rendering a simple PHP array into an HTML table I am trying to render a simple PHP array witch isn't a drupal render array, basicly it s something like this:

array(
  array(
    'Some Index:',
    ' Some value',
  ),
  array(
    'Some Index:',
    'Some value',
  )
);

I would like to render it as an HTML table, is there any out of the box API to do that ?

Thank all for the help,

Cheers

Assume you have code similar to this:

$table_data = array(
  array( 'Some Index', 'Some value'),
  array( 'Some Index', 'Some value'),
);

In this case, just call theme('table', array('header' => array(), 'rows' => $table_data));.

This will call theme_table(), unless your theme overrides that particular theming function. Any override, however, should expect the array to be structured in the same way as described for theme_table(), so look there about the specifics. In particular, you might want to replace 'Some Index' with array('data' => 'Some Index', 'header' => TRUE) to indicate that this cell is a table header cell.


Drupal views UI, is it possible for the user to limit the number of row of the result? I created a view that display some content. I would like to allow the user to change the number of result (row).

By example, the view display ten row. The user can set (in text field?) 5, and the view display only the first five result.

Is it possible via view ui ? I didn't find...
If not, I guess that I must create a custom module with view alter..

Thanks for help =)

Go To view .Set pager options and do the change given in above screen shot


How can I display the value of a variable inside a condition? I have created a rule using the Rules UI. My rule is not working, and I need to debug it, displaying the values of my variables inside a condition where I make a comparison.

I see within Rules Actions that I can add a system message, but in condition how could I debug variable values?

Rules debug log doesn't show value of variables.

How can I do so?

Try cloning the rule, and adjust the clone, remove your condition & add a system message action that shows the two variable values you are trying to debug.

BTW, Eventually you may want to install a debugging environment like xdebug. This is likely a longer process than you'd want to tackle for a quick fix. However, if you are planning to keep working in the field, it's incredibly helpful.

You'll find a good start here:
https://stackoverflow.com/questions/7303912/setting-up-xdebug-for-drupal-site


Why does node/%node/random/stuff work? I just noticed this, and I can't find an explanation.

I can go to node/1/45645645/klzkelfkzlef/47z4e5fz56e4f/etc and it'll just show node/1 instead of a 404 page.

The same happens with taxonomy/term/%term/stuff

Somehow, if it doesn't match a valid path (/edit for example) it falls back to just a view of the entity. How? Like, where does this happen?

Is this normal hook_menu behavior? node/%node exists and node/%node/edit exists, so node/%node/random may not exist but it'll use the callback for node/%node anyway?

Ah, just found it in pretty much the first few lines of menu.inc. It does indeed look one level higher until it finds a match.


Field in Custom Content Type Stripping out  tags Drupal6: I have a custom content type, with a custom field, set to textarea. The content type's instance filter is set to Full HTML.

When I add an image tag to the custom field, the image renders in the WYSIWIG in edit mode. When I save the node, the  tag doesn't show up at all. When I view source, the  tag simply isn't there.

I returned immediately out of my module's hook_nodeapi, and disabled all custom filters in the full html input format, to no avail.

If I put the same image tag in the body field of this content type, the image renders when viewing the node. Any ideas?

A custom field doesn't have the same attributes as the standard body area.

Another approach would be to add a second field for the image and separate the two types at the content entry stage. You can combine them using Views. You could hide the first field and then rewrite the second field to display them together. A possible problem here is that the image will appear at the beginning or end of the copy -- float the image to have the text wrap around it -- but you won't have an option to place anywhere else.


How to change password via REST when validating email address (first login link) Is there a REST api way to allow the user to set a new password on email confirmation / first time login?

I tried the same code as for changing the password when you're already logged in and adding the pass-reset-token as a GET param but without any luck. Server always returns the following message:

{"message":"Users can only update their own account, unless they have the \u0027administer users\u0027 permission."}

Does anyone have any idea? If not, I will write some custom code inspired from the core module but I hoped that the rest api should handle such things.

I'm not sure there is a pure Drupal core way of doing this, but there are contrib modules which can help. These modules involve resetting the password when it has been forgotten but may help with understanding the process.

Password reset REST allows resetting the password via REST.

  Small module to help with resetting password through rest.

  This attempts to provide the same logic present with a
  pass-reset-token as you'd do with the normal interface.

REST Password Request provides an alternative method which involves generating a temporary password so the user can change their password via rest, and then log in as normal.

REST Register User with Email Verification supports email validation, but may not be exactly what you're after.

It is also worth reviewing this issue regarding anonymous REST and user entities: A REST resource's "auth" configuration MUST be non-empty, which prevents configuring it for anon access only


Validate date selection in date picker I am using a javascript datepicker to allow users to select a date (which I have functioning in my form). What I don't know how to do is limit the dates that can be selected. Is there a way to do this using the datepicker instead of validating the form on submission?

Here is the code I am using to create the date selector:

drupal_add_library('system', 'ui.datepicker');
drupal_add_js($path . '/providers/support/js/datepicker.js');
drupal_add_js(array('dateselector' => array('date_format' => $date_picker_format)), 'setting');
return array(
  '#type' => 'textfield',
  '#default_value' => $current_value,
  '#attributes' => array('class' => array('datefield')),
);

Am I missing an option somewhere?

I don't see, how you initialize the datepicker (probably in */providers/support/js/datepicker.js file), but for this functionality you should use maxDate and minDate options of datepicker library.


How to render only field label Is it possible to render only the field label from $view->result ,
like render the field value only

$display['label']='hidden';

print render(field_view_field('node',$node,'field_date',$display));

found it here
 $view->field['field_description']->options['label'];


Admin Toolbar not working I downloaded the Admin_toolbar module, installed and enabled it with Drush (drush en admin_toolbar -y).

If I look in admin, it's enabled. But it's not working; it's not hovering.

Notes:

I have a Git workflow. But for now I just installed it locally. I had some issues with the $config_directories. For the configuration files. Could this may have to do with this? Now I returned to default settings in settings.php and in admin/reports/status I get no errors.
I installed with Acquia Dev Desktop and have Mac OSX. Shall I trie de-install and install again maybe?

I used drush cache-rebuild and now it works!


$body variable not working I am in a custom tpl.php file [node--netrunner-card--Operation--full.tpl.php].
This is for a custom content type [netrunner_card].

I am trying to output the contents of the $body variable and unable to do so via the prescribed avenue. I copied node.tpl.php into my theme and renamed it. I can output the contents of body but I have to do this like so:

print render($body[0]['value']);

I should be able to do it like so:

print render($body);

But the second option renders nothing.

Any ideas?

Actually, the documentation for node.tpl.php says, in the description for the $content variable.

  An array of node items. Use render($content) to print them all, or print a subset such as render($content['field_example']). Use hide($content['field_example']) to temporarily suppress the printing of a given element.

The node body is a field, and you should use render($content['body']) to render it.

The note about field variables is the following one:

  Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node->body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node->body['en'], thus overriding any language negotiation rule that was previously applied.

You should use $body only when you need to access the field's raw values, not to render the field.


How to display featured or new products on main Ubercart catalog page? I'm having a little difficulty setting up Ubercart that may be related to the particular way I am wanting to use it. I'm sure I've just missed a setting somewhere or something.

I have the front page of my website at mysite.com, and the store located at mysite.com/store. I have added categories to the catalog taxonomy (mysite.com/store/category1). So the store is secondary to the front page.

When I go to mysite.com/store Ubercart only displays a list of the categories, and not any products (as expected, they are all within their categories). My issue though, is I would like to display some "new" or "featured" products on the mysite.com/store page instead of just the list of categories. If my store was located at mysite.com I could just use the "promoted to front page" option, but it is not.

How can I display products on mysite.com/store?
Thanks

Create a view and make a block in that and then expose that on the /store page above your content or what you see fit. that should do it.


How do I trigger an AJAX submit button on page load? I am attempting to trigger a form (to get live data) on a page load. So far, I have this code I have found from bits and pieces and digging around the net, but unfortunately not a lot of people actually appear to have needed to do this.

jQuery(document).ready(function($) {
  var element_settings = {};
  var element = {};
  element_settings.progress = { 'type' : 'throbber' };
  element_settings.submit = { js: true };
  var ajax = new Drupal.ajax($('#edit-ratessubmit'), element, element_settings);
  element.form.clk = element;

  ajax.form.ajaxSubmit(ajax.options);
});

This currently complains that element_settings doesn't contain a URL, but when it does contain a URL, I get some random "b is undefined" error.

This was a simple case of targeting the correct element using the code below.

$(document).ready(function() {
    $('#edit-submit').trigger('click');
}


Automatic Node Reference my task is, to create a forum-like behaviour which resembles StackExchange's platform with the only difference that only the question's poster will be able to comment on the replies.

My thought is to create a Content Type that describes the initial post/question, and then add a "Reply to this" button that should somehow create a new node of type "Reply" or something (ideally in the front-end, but that's another story - feel free to comment on it though) that should get automatically referenced to the initial post/question.

The "Reply" Content Type should maybe support Drupal's core comment functionality but restricted somehow to the initial post/question's creator.

The basic question is the automatic referencing. Other than that if you got any idea about the front-end content creation and/or the limitation of comments to the afforementioned role and CT, I'd be glad to get some extra input :)

EDIT: using Entity Reference module, not Node Reference module, fyi.

For the automatic referencing you could use entityreference_prepopulate. So your button to answer from the question node would link to something like node/add/answer/27 where 27 is the question node nid. The module supports to hide the field once the value is in the URL so the user dont have to see the field.


Module always returns the default language in hook_theme() I am developing a custom block that shows a different image URLs for different languages. Currently, I enabled English and French.

The code I am using is the following one.

function MODULENAME_theme($existing, $type, $theme, $path) {
    $currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
    $imageUrl = "";
    # If current language code is english
    if ($currentLangCode == "en") {
        $imageUrl = "English image url"
    } elseif ($currentLangCode == "fr") {
        $imageUrl = "French image url"
    }
    return [
       "modulename_block_template" => [
            "variables" => [
               "description" => [],
               "image" => $imageUrl,
               "current_language" => $currentLangCode
            ],
       ],
    ];
}

The problem is that the value for $currentLangCode is always 'en'.

What can I do to get the current language?

Data from hook_theme is cached, any logic decisions you make in it will only apply when the theme registry is rebuilt.

The point of variables is that they're passed in at the time the theme is called, not when the theme hook is declared.

For example hook_theme() should look like this:

MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'modulename_block_template' => [
      'variables' = [
        'description' => '',
        'image' => '',
        'current_language' => '',
      ],
    ],
  ];
}

And you pass the variables in when you use it:

$currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
$imageUrl = '';
# If current language code is english
if ($currentLangCode == "en") {
    $imageUrl = "English image url"
} elseif ($currentLangCode == "fr") {
    $imageUrl = "French image url"
}

$build = [
  '#theme' => 'modulename_block_template',
  '#description' => '...',
  '#image' => $imageUrl,
  '#current_language' => $currentLangCode,
];


Problem with node revisions and taxonomy terms I have a content type with a number of fields including a checkbox which allows you to select one or more taxonomy terms.  If I create a new version of a node, all the previous taxonomy terms are automatically included in the new node version.  I can see this in the database table "field_revision_field_catagories" (catagories is my checkbox field).

If I update the checkbox field with fewer terms checked, Drupal will not remove the existing ones.  For example:

Node Version 1 has taxonomy terms 1,3,5 7 checked and 4 corresponding records in the database table.

I use node_load() to get Version one from the database.
I update the node using a Form API form and change the checkbox to select 2 (uncheck    1,3,5,7)
save the node with node_save().

The database now has Version 2 with taxonomy records 2,3,5,7.  It updated the first record, changing it from 1 to 2.  The other 3 records are still there, however and need to be removed for my logic to work.

I guess I can use SQL to delete the records (or just delete them all after node_load()), but will that create other problems?  Is there a Drupal function I can use instead of SQL?

Thanks.

I figured it out.  unset() is the answer.  Here is my code:

        $loop = 0;

    $termarr = $form_state['values']['catagories'];
    // drupal_set_message('Termarray '. print_r($termarr,1) .'');
    foreach ($termarr as $term) {
      if ($term > 0) {
        $node->field_catagories['und'][$loop] = array('tid' => $term);
      } else {
        unset($node->field_catagories['und'][$loop]);
      }
      $loop++;
    }

This took way longer than it should have.  I wish Drupal had better documentation although trial and error for days does have some benefits... :-(


How I do I remove the User menu from the top right corner? How would I go about removing the "User menu" from being displayed in the top right corner of the site when logged in? It is set to display "None" in the block, yet it seems to be up there by default.

Other than using CSS to hide it, what is the recommended way to remove these links? I've got the login/logout links in my footer instead.

In admin/structure/menu/settings, you select which is the source for the Main links, and the Secondary links.

By default, the source for the Secondary links is the User menu; if you set it to No Secondary links, or another menu, the user links will disappear from the page.


Create a node Programmatically having Composed Field I have a content type having composed filed (used Composed Field module for this).

How can I create a node programmatically with composed field values?

Consider with this example
you created a field as contact with two subfields as mobile(textfield) and home(textfield).

so while creating the node pro grammatically you just have to assign the array of your input to the field,something like below

$contact = array("mobile"=>"1234565","home"=>"789");
$node->field_contact[$node->language][0]['composed'] = $contact;

I have not shared the node_save() as you have mentioned you are able to make it.


Taxonomy Term description in views when "no results" (Haven't associated nodes) need help with Taxonomy Term description when no results in views.
I'm using Drupal 7.44 / Views 3.14 and render content from node teaser template without using fields, and for showing description used Header area / Global:Text area / Php Filter and this code

<?php
$view = views_get_current_view();
if (is_numeric($view->args[0])){
$term = taxonomy_term_load($view->args[0]);
return $term->description;
}?>

But it's work only when term have associated node, but some terms doesn't have nodes and description not showing.

Maybe some one knows how can I fix it?

Forgot about "Empty Results". insert code in "Global:Text area" and It's works. Thanks me for helping)))


How do I put the user registration form on my front page? I'm using Panels and have a panel page for my front page.  I found a discussion for Drupal 6 but the code doesn't work for Drupal 7:
http://drupal.org/node/257721

I would like to show the user registration form on the front page to make it extremely easy for new users to sign up.

You just need to add a "New custom content" to a panel pane and add the following code to the body (you need to have PHP format selected):

<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

It works :)


Group by taxonomy headers Not sure why I can't do this as it sounds simple, I have:

A content type called 'RSS FEEDS'

A vocabulary called 'Publications' within this I have 3 terms which are 1) NY Times 2) BBC 3) National Geographic

I now have a bunch of nodes that are tagged with these 3 terms.

What I want to do is have an accordion with 3 headers:

NY Times,
BBC,
National Geographic

So when I click a header I see all the nodes of that particular type underneath. I have tried an number of things including aggregation, taxonomy views etc but cannot seem to work this out. For clarity I have mocked up how I want this to look.

Any help greatly appreciated.

I had the same problem. You're almost done, but missed some settings ;). You just need to do some Format settings for Views Accordion in your View.

Here are the steps to make your grouping field as the "header" or "trigger" of the accordion action.

Go to  Format: Views Accordion Settings and select Grouping field.
Check "Use the group header as the Accordion header"

Save View. That's it. Now your Grouping field will act as Views Accordion Header and avoids duplicate headers too.

Hope this helps.


Using print render($content['taxonomy']); in node.tpl.php I am having trouble getting my taxonomy terms printed into the containing  of my node.tpl.php file. I have named my taxonomy terms for a custom block (books) as     field_tags and I want them to get printed after the $classes array as plain text CSS classes.

Here is the offending line:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?><?php print $content['field_tags']; ?> clearfix"<?php print $attributes; ?>>

The goal here is to have a menu on top of this view of books that can select individual titles based on their individual taxonomy terms. Open to suggestions about that as well if you think this plan is stupid.

I think the proper way to do this would be to implement THEME_preprocess_HOOK() in your theme's template.php.

In that function, just add each taxonomy term name into the classes array.  You'll probably also want to cleanse the term names as you put them into the classes array, dig around Pathauto or Transliteration modules to find a function to do the dirty work.

function mytheme_preprocess_node(&$vars) {
    foreach ($vars['node']->field_my_taxonomy_field[LANGUAGE_NONE] as $term) {
        $vars['classes_array'][] = pathauto_cleanstring($term->name);
    }
}


Notifications vs Subscriptions? I have enabled both modules for D6 but I'm going to disable one to tidy up my Drupal stack. So wondering what are exactly the differences between the two modules, in terms of  functionality. Are they interchangeable for basic task of allowing users to subscribe to posts and send notification updates? If so, which one is preferred?

P.S. there is relevant thread here some other people may find useful.

Thanks

I have successfully used notifications on 2 Drupal 6 sites. I like it. Subscriptions had a good reputation but Notifications looked to be more modular and extensible; however, what tipped me towards notifications was the fact that it seemed that the Organic Groups developers were keen to support it and I was looking at putting OG onto my sites (which I subsequently did)

I have the 6.x.2 version of notifications, which seems stable and does what I want.  Very limited experience of the 6.x.4 version suggested it was not stable so I did not persist with that and it remains in beta after 2 years.

Now I have recently been involved in the development of a Drupal 7 site. Although it is over 18 months since D7 was released there is no full Notifications version yet and the module is flagged as Seeking new developer and has been for a significant length of time.  Apparently a quick upgrade was done when Dr7 was released with some limited functionality (what though?) and there is an Alpha2 version which seems to have been receiving some considerable attention (but last updated June).

On this basis, you might be safer to go with Subscriptions which now has a full Dr7 release if you have any thoughts of migrating to Dr7 or developing other sites that might use Dr7. That is mainly to avoid the difficulties in mastering two admin UIs and to protect you in case Notifications really is moribund.

Subscriptions is in the hands of a very experienced developer who has been maintaining it for a long time.

Please note that I have not done a systematic comparison of Subscriptions and Notifications for Dr6 though I did spend quite a while investigating the two at one time several years ago.  See my contribution here:
http://groups.drupal.org/node/12645
(This contains contributions by many others and is useful for an insight into the position in 2008! But Subscriptions and Notifications will both have been enhanced since those posts were written).


Building a non-config, programmatically-created, semi-dynamic, semi-manual menu We have a custom entity called "Topic". With this entity, users can build topics and reference other content to "belong" to the topic. We also have a requirement where, whenever a user creates a topic, a menu is also created for it. When content is added to the topic, a link is automatically added to the menu pointing to that content.

The workflow is like:

User creates a topic.
User references a bunch of arbitrary content to the topic.
User saves topic.
Menu associated with topic automatically adds links to added content.
(optional) User adds more links to menu, not necessarily for topic content.

Now this menu currently couldn't be a custom-built block, as we also have a requirement where users should be able to to add menu links like a regular menu. But the downside to using menus is that they're config - they need to be exported. Otherwise, a deploy without the config would wipe out all the created menus.

Is there a way to create a menu without making them config? Is there a better approach to this problem?

Without delving too much into the specifics of your complex configuration management, I'd venture to say that you should use Drupal 8's built-in configuration sync to export config to YAML and commit it to your version control repository (git or what-have-you) so that you can deploy your config along with your code.

Then, you can use the Config Filter, Config Split, and Config Ignore contrib modules to split off certain configuration from the sync directory into separate directories that can be used or ignored in different environments.

NOTE: If your users are all adding content in the production environment, you'll need to make sure your lower environments always have the latest config before deploying to a higher environment. This would be the case even if you didn't use config sync; it will just be a different workflow (i.e., you'll need to drush cex the latest config from Prod and drush cim it into your Dev environment, rather than grabbing a fresh sqldump from Prod.)

More info:
https://www.o8.agency/blog/tips-dev-team-using-config-split-and-config-ignore-fine-tune-your-configuration-management

There's work underway to integrate some of the functionality provided by Config Filter and Config Split into Drupal 8 core. This is the way things are headed, so there's really no downside to config export anymore if you do it correctly.

Admittedly, setting it up can be a pain, but it's a different pain (and, I think, a less painful pain) than keeping all your config in the database and trying to keep that in sync across your local, dev, stage, and prod environments.


Change the rendered output of a Message entity I'm using the Message module to create messages on certain events, for example, on forum node creation:

"X has posted a new thread in the Y forum."

I've got a view that spits all of these out.

I now want to create a new view that shows the same messages, but in this view, I want to change the output of the above message to:

"You have posted a new thread in the Y forum."

Every time the node's author matches the currently authed user.

Now my thoughts would be that I could somehow intercept the output of either the token (X) or override the whole message entity template, but I'm not entirely sure how to go about this.

Another thing I tried was to create a new user token, called "Username or you", which would output "you" if the associated message node matched the authed user, or the username if not. However, I'm not sure how I could get the message object. It's worth noting that I have the token:

[message:field-forum-post:author:username_or_you]

So if I could follow the trail back to "message" and get the message id, I'd be all set.

Any pointers?

See the Messaging documentation, specifically this overview on new features. You likely want to override the tokens provided using a callback which is supported by the module:

  Callbacks: sometimes we can’t use the token system, for example if we
  need to show different results based on the value of _two different
  fields. This is an advanced feature, which is meant for developers,
  and is documented in the module.

I've not done this myself yet, but I've used the Message module and Views -- digging through the module and documentation should get you there now that you know it's possible.

From the message_example README it sounds like you want an activity stream:

  The UAS (User activity stream) view is dependent on Panels, as it uses
  "Panel fields" as a row plugin, along with the Message's partials.

Which you should be able to look at for inspiration in the example module.


How do I implement the autocomplete functionality in Webforms? I have a drop down box with college names that has 9000 options to choose from. I am unable to use the drop-down field in Webforms.

Is there a way to use an autocomplete in a text field for Drupal 6?

Autocomplete is implemented in Drupal through AJAX. When users type
  into a textbox, code on the client page dynamically loads new data
  from the server (a Drupal website) and uses this data to update the
  user display (provide a drop-down list of matching options, which the
  user can select from).

Available autocomplete functions (D6):

user_autocomplete() - Use this function to load matching user names.
taxonomy_autocomplete() - Use this function to load matching taxonomy terms.

If you want to have your own autocomplete function it is also possible.
Please see a full article on this subject on drupal.org "Textfield that uses autocomplete"
to see how to build a custom autocomplete function.


A Report of Logins on the Site Is there a way to see a report of the users on a site that shows who is logging in and who isn't logging in? (other than just looking at 'People' tab I mean...we have thousands of users on the site).

The DB log should log user logins. It usually appears as "Session created for [user name]".

Alternatively, you can create an admin-only view of users and the time they last login and/or the last time they accessed. iirc, users have access and login fields in the DB which are timestamps that represent last page access while logged in and login time, respectively. I believe they are exposed to Views.

For reports, there is Views Data Export which adds a display to a View, exposing itself as an endpoint from which you can download the data. Exports in various formats, most especially CSV.

However, for the views approach mentioned, it will only display the latest data. This doesn't do historical record-keeping.


Blog posts are being listed under content I know nothing about Drupal, trying to help a friend out.

Right now blog posts are being listed under /content [site.com/content/blog-post-title] instead of /blog.

I'm trying to figure out where to look to figure out why.

The fact that blog-post-title appears suggests that the module PathAuto is somehow involved.  Try to disable that module (If you're on Drupal 7, navigate to Home » Administration » Modules, locate PathAuto and remove its tickmark, then press "Save configuration" and clear all caches.)

If the blog posts now appear under /blog, you know why.

After you've etablished that PathAuto is indeed resposible, you can re-enable the module (all its settings will be left intact), and you can then proceed to change its settings to put blog posts in the place you want them.


Why do I keep getting this error? I am getting this error message in the logs after installing RNG module for Drupal 8 and trying to submit a completed a event form. The error log contains this error.

  Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Value is not a valid entity." at /home/vhosts/***********/public_html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php line 757, referer: http://**********/node/add/event_1

Any idea on how I can resolve this please?

I eventually traced back the issue as being caused by the rules module not RNG. Removing the rules enabled me to save the event.


Taxonomy term duplicates result I have created nodes and added taxononmy

Under views i want taxonomy seperarte. it is showing

A, B, C, A , B

A, B , C are my taxnomy terms

i want A , B, C are in tabs  as a taxonomy

Any idea

I believe you can use Views to display your node and aggregate your Taxonomy terms to prevent duplicates.


Files attached to nodes are never deleted from server even after they're removed from the node (and that edit is saved), Drupal 7 I've noticed something strange on my site: after attaching a file to a node (via the regular file field), that file never gets deleted from the server.  I remove it from the node, save that change, but I can see the file is still on the server.

This makes replacing files very difficult, because when a user tries to attach a replacement, the file name has the "_0" or "_1" suffixed to it (since the original file is still on the server and that makes the name a duplicate).   That means that we would need to find all links to the file and edit each one to match the new file name/url.  It's a total mess.

I'm looking online and nobody seems to have this issue -- the files ought to be deleted from the server once they're removed from the node.

Any ideas why this may be happening in my case?  I'm not sure where to start looking.  Certainly the 'File system' configuration page has nothing of that nature as an option that may have been checked.  And the field options themselves seem to not have anything of that nature I may have inadvertently set.  Any other ideas?

I got it!  It's a revisions thing.  I guess it makes sense.  If you have revisions enabled for that content type, it keeps all your old files on the server (associated with old revisions), so replacing a file definitely is harder.  If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question.  Since a file with that name is kept on the server and there is a name duplication, it adds those "_0", "_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace.  Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!


Which function(s) actually create the physical resized image files? By default, Drupal 7 ships with 3 images styles: thumbnail, medium, and large.

For example, I upload a image file ('abc.jpg') with the image field (I assume the field name is called 'image'); while I am creating an "Article" node, the image file will be uploaded and stored in "sites/default/files/field/image/abc.jpg," and a record of this uploaded file is saved into database in the "file_managed" table.
By that time, the medium and large styles versions of "abc.jpg" is not yet created.

The teaser of the "Article" node displays the image field with the medium style.

Then, I navigate to the teaser viewmode of that node for the first time. The medium version of "abc.jpg" is generated, and sits in "sites/default/files/styles/medium/public/field/image/abc.jpg."

The default view is set to display the image using the "large" style.

I view the node using its default view, and the large version of "abc.jpg" is created in "sites/default/files/styles/large/public/field/image/abc.jpg."

Basically, the image upload is quite smart; when an image has been upload, Drupal won't create all the different styles version of that image. Drupal only creates the style of an image when you first browse to the view using that specific image style.

Which functions/hooks are creating the file for the styled images?

The function that generates the image URL basing on the style is theme('image_style'), which is called by theme('image_formatter'), which then called from image_field_formatter_view(); this function is the implementation of hook_field_formatter_view(), the hook that in a field formatter outputs the content of the field in the view for the entity containing that field.

The image is only generated when you access its URL. I tried the following code:

theme("image_formatter", array("image_style" => "thumbnail", "item" => array("uri" => "test.png", "title" => "Image title", "alt" => "Alternative text")));

The output that I obtained is the following:

<img typeof="foaf:Image" src="http://tero.local/dr72/sites/default/files/styles/thumbnail/public/test.png" alt="Alternative text" title="Image title" />

If you look at the code of image_menu(), you will find the following lines:

  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

image_style_deliver() is the function that generates the image.


Warning: Cannot modify header information - headers already sent by I am getting this Error

Warning: Cannot modify header information - headers already sent by
(output started at
/home/aigair1/public_html/site1/sites/default/settings.php:1) in
drupal_send_headers() (line 1236 of
/home/aigair1/public_html/site1/includes/bootstrap.inc).
Warning:
Cannot modify header information - headers already sent by (output
started at
/home/aigair1/public_html/site1/sites/default/settings.php:1) in
drupal_send_headers() (line 1236 of
/home/aigair1/public_html/site1/includes/bootstrap.inc).
Warning:
Cannot modify header information - headers already sent by (output
started at
/home/aigair1/public_html/site1/sites/default/settings.php:1) in
drupal_send_headers() (line 1236 of
/home/aigair1/public_html/site1/includes/bootstrap.inc).
Warning:
Cannot modify header information - headers already sent by (output
started at
/home/aigair1/public_html/site1/sites/default/settings.php:1) in
drupal_send_headers() (line 1236 of
/home/aigair1/public_html/site1/includes/bootstrap.inc).

I don't get this when my website in Localhost(Xampp), But When I upload site to web I get this. What's problem ?
Here is the Setting.php file as txt

There is an output in your settings.php file. Maybe a whitespace before <?php, maybe you closed PHP tag at the end of your file, can't know without seeing it. Inspect your file carefully.

Be sure to transfer your files in binary mode, and disable all automated conversions your FTP software may offer. Save files as utf8 without BOM, Linux line endings. That's the safest way. If your editor can't do that, use another.

As Daniel Tome correctly pointed out, it may be case of warning turned off on your localhost, not a transfer issue. But the things you need to check are the same either way.


How to dynamically manipulate canonical entity URLs I've got a project with a multi-user / multi-domain environment. There is one "main" portal like www.myproject.com and for every registered user with a specific custom permission has_personal_subdomain there is a subdomain and a theme with his username, e.g. user johndoe has a subdomain johndoe.myproject.com and this domain is using his custom theme johndoe.
I've already set up all the domains and the theme switching part. All editing/administrative actions are always done on the main portal domain, also users with personal subdomains work on the main portal domain.
The problem are the canonical entity links: When editing nodes, editing is always done in admin theme on the main portal domain, so of course all canonical entity links also point to the portal domain. E.g. for users with a personal subdomain, the canonical links to www.myproject.com/node/123 or www.myproject.com/my-node-url-alias, but I want johndoe.myproject.com/node/123 or johndoe.myproject.com/my-node-url-alias.
What is the best way to dynamically manipulate the canonical entity view links? I'm not asking for a complete code, I'm just looking for the best starting point/hook/event/service to inject my custom logic.
What I want to avoid:
Create a million custom hooks for hook_menu_local_tasks_alter AND hook_form_alter AND hook_views_pre_render AND whatever else...
I do not care about metatags, SEO, duplicate URLs,... I just want a better editor experience with personalized entity view links pointing to the correct subdomain using the correct theme.
I know there is the OutboundPathProcessor, but this seems a bit over the top, as I only want to change canonical URLs and none of the admin links.
Is there a service specifically for generating canonical URLs I can decorate?

Is there a service specifically for generating canonical URLs I can
decorate?

Yes, for a route based handling of outgoing canonical links you can use OutboundRouteProcessorInterface::processOutbound
For example like core implements the dynamic route <current>.
/core/lib/Drupal/Core/RouteProcessor/RouteProcessorCurrent.php
  public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($route_name === '<current>') {
      if ($current_route = $this->routeMatch->getRouteObject()) {
        $requirements = $current_route->getRequirements();
        // Setting _method and _schema is deprecated since 2.7. Using
        // setMethods() and setSchemes() are now the recommended ways.
        unset($requirements['_method']);
        unset($requirements['_schema']);
        $route->setRequirements($requirements);

        $route->setPath($current_route->getPath());
        $route->setSchemes($current_route->getSchemes());
        $route->setMethods($current_route->getMethods());
        $route->setOptions($current_route->getOptions());
        $route->setDefaults($current_route->getDefaults());
        $parameters = array_merge($parameters, $this->routeMatch->getRawParameters()->all());
        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheContexts(['route']);
        }
      }
      else {
        // If we have no current route match available, point to the frontpage.
        $route->setPath('/');
      }
    }
  }


Get form element's label/value pairs from &$form or &$form_state I need to pass an array with all the fields (with their values) from a form from the submit function to a rules_invoke_event.

to do this I'm calling a get_fields() function, in this function I have acces to the form and form_state objects. Just wondering how I could loop through one of these with a foreach to get an array with the pairs?

function get_fields($form, $form_state)
  $fields = array()
  foreach(element in form)
  {
    $fields[$element[key]] = element[value];
  }
  return$ fields
}

something like this but with correct syntax?

Help would be greatly appreciated :)

This might work.

function get_fields_this_step($form_state) {
    $fields = array();
    foreach($form_state['values'] as $key=>$value){
        $fields[$key] = $value;
    }
    unset($value);
    return $fields;
}


Display data basing on the group permission I have implemented hook_og_permission() in a custom module.

/**
* Implements hook_og_permission().
*/

function logic_board_og_permission(){
   return array(
    'rulesprm' => array(
      'title' => t('Rules Form Perm'),
      'description' => t("Allow og user to fill form"),
    ),
  );
}

Using this permission like in the following code doesn't work: The code inside the if() statement is not executed.

    if (user_access('rulesprm')) {
      // Some code
    }

Why?

user_access is for core permissions, I.e. those added through hook_permission. For organic groups’ own permissions hook, you need to use the complementary og_user_access:, eg:

if (og_user_access($group_type, $gid, 'rulesprm')) {
  ...
}


How to show html  marks to Views Custom text - field? I need to put < input    > - html tag to my Views Custom text field, but it wont show up? Somehow these codes will be disabled? What I need to do?

I tried to find solutions from web, but I didnt find anything for this. But I really need to put these html to Views custom text - field.

Text format settings is fine, but no help.

This works when I put < input > tag to Views "Header" and "Footer" section with "Custom text" field, but  why not in section "fields"?

I hope there is a simple solution for this. Thanks.

I've had similar problems trying to show a  tag. The only way I've been able to get around it is to install the Views PHP module - https://drupal.org/project/views_php - and add the HTML through that

Hope this helps you!


Access to image uploaded in article content type is denied when I attach an image to my article content type it doesn't show image. I mean when I creat an article content type and I upload an image to its using Image filed of article content type and publishe my article, the image not shown and when I right click to image and clicl "open in new tab" it goes to "Access Denied" page and says you don't have access to this image. this is true for my galley images too.
pleas help me :)
thanks

If you have uploaded an image as a private file it is not accessible by other users even if any user has access to the node. Please check "Upload destination" in image field settings.


Taxonomy Term Page is showing the same body for all nodes I'm converting my old site to drupal and updating my Teaser view mode so that the nodes appear as I want them on the Taxonomy Term page.

http://dev.inadaydevelopment.com/tags/ipad

The problem is that the Body field for all of the nodes is showing up with the same text. The nodes do not have the same body text, so I have no idea how or why all of these Teasers are showing the same body text.

Any idea?

Found the problem. Some poorly written jQuery was dynamically swapping out the body tags. Blerg.


image_style_create_derivative not resizing the image I am using image_style_create_derivative to create image styles on fly. Before that I am using image_style_path which creates style path.

$derivative_uri = image_style_path([style_name], [source]);
image_style_create_derivative([style_name], [source], $derivative_uri)

It generates image. Which is fine. But it is generating image with original size. Not with the size of style_name.

For example if style name is thumbnail, the generated image style size should be 160x100.

How can I achieve it?

image_style_create_derivative needs the style passed as array..,
so _ first you need to load the style or fake the array

  applying all image effects defined in $style['effects']

see: image_style_create_derivative

i usually use image_style_url like this (if taken from field), otherwise just pass the source.

        $field = field_view_field('node', $node, $field_name, reset($image), $arr_display);
        if ($img_style) {
          $uri = image_style_url($img_style, $field[0]['#item']['uri']);
        }
        else {
          $uri = file_create_url($field[0]['#item']['uri']);
        }


Using Guzzle with SELinux setenforce 1 is there anyway to run drupal 8 with guzzle to access remote server rest server without turning off selinux.

for example in httpd, i can do:

  setsebool -P httpd_can_sendmail on

to be able to make apache send email without turning off selinux.

Thank you,

I think it is:

setsebool -P httpd_can_network_connect on


How can I sum aggregate of expression I have a problem that looks relatively simple.

An activity entity has multiple invitation entities, the reference is from the invitation.activity_id => activity.

Invitation has a completion_date (when the user completes the activity) which can be zero (not complete) or a timestamp of when it was completed.

(I created a reverse relationship so I can go from the activity to the invitations, that works fine.)

I want to create a table view where each row is an activity, and it has two columns - total invitations and completed invitations.

The total is easy: switch on aggregation and count the number of invitations.

Calculating the number of completed is another matter.

I've created my own views field plugin (extended from boolean) which inserts an expression field instead of using the actual field.

class InvitationCompletionState extends Boolean {
  /**
   * Called to add the field to a query.
   */
  public function query() {
    $table_alias = $this->ensureMyTable();
    $this->query->addField(
      NULL,
      "IF($table_alias.completion_date > 0, 1, 0)",
      'completion_state'
    );
  }

But I can't aggregate it. I know aggregation doesn't work with everything, and I suppose this is a situation where it doesn't.

I wanted to use the boolean option (although INT might be better) because I can count the number of completed by simply SUMming the results.

This is the Views query if I try to use the aggregation

SELECT activity.name AS activity_name, activity.type AS activity_type, activity.start_date AS activity_start_date, activity.end_date AS activity_end_date, activity.estimated_time AS activity_estimated_time, COUNT(invitation_activity.id) AS invitation_activity_id, SUM(invitation_activity.completion_date) AS invitation_activity_completion_date, MIN(activity.id) AS id, MIN(invitation_activity.id) AS invitation_activity_id_1
FROM {activity} activity
LEFT JOIN {invitation} invitation_activity ON activity.id = invitation_activity.activity
GROUP BY activity_name, activity_type, activity_start_date, activity_end_date, activity_estimated_time
ORDER BY activity_start_date DESC

And it just forgets about inserting the expression.

Further investigation:

Pasting the following code into Workbench works and gives me the answer I want:

SELECT
    activity.name AS activity_name,
    activity.type AS activity_type,
    activity.start_date AS activity_start_date,
    activity.end_date AS activity_end_date,
    activity.estimated_time AS activity_estimated_time,
    COUNT(invitation_activity.id) AS invitation_activity_id,
    SUM(IF(invitation_activity.completion_date > 0, 1, 0)) AS completion_state,
    MIN(activity.id) AS id,
    MIN(invitation_activity.id) AS invitation_activity_id_1

FROM activity activity

LEFT JOIN invitation invitation_activity ON activity.id = invitation_activity.activity

GROUP BY activity_name, activity_type, activity_start_date, activity_end_date, activity_estimated_time

ORDER BY activity_start_date DESC

which means that MySQL can handle the code, it's just that Views does not know how to generate it.

I need to be able to make this work in a standalone handler (for any future devs), writing a hook to modify a query is not really an option.

Any thoughts?

Yeah, no way to do it without major surgery to the Views Query class - the assumptions it makes are hardwired.

The only practical solution seems to be the Views Aggregator module, which has a D8 dev version. This provides a Views Table Style which performs aggregation functionality on the fetched records - in other words, you do an ordinary non-aggregated fetch and the module does the aggregating just before display.

It has the advantage that you can do all sorts of interesting things - far more than you can in SQL, against the fact that it adds to processing time for large data sets. (And I can think of other potential issues too.)

However it solves my problem, so that's good.

https://www.drupal.org/project/views_aggregator

The conversion from D7 to D8 is minimal (still uses hooks instead of plugins) but, as I say, it works.


Modules to extend the Display Suite module? Just that. I find the Display Suite module really useful for my projects.

Are there more modules to extend its functionality in any way?

Thanks.

I really like the combination of Display suite with Custom Formatters - http://drupal.org/project/custom_formatters & with the Omega Theme, with these tools you can almost entirely skip having to use tpl.php files to theme your site's layout and content.

Also listed on the Display suite page you have Field Group - http://drupal.org/project/field_group & Rendable elemenets - http://drupal.org/project/rel However Rendable elements doesn't seem to work that well quite yet but it looks promising.


Limit Entity Reference to Only Display Content Created By User This might be an easy solution, but I can't seem to figure it out. I have a content type referencing another content type. I have the entity reference field in the cotent type, and wish to limit the display to only show cotent from the other content type that the user has created. Right now, it is displaying all the content created from the other content type.

You can create a view to return only the content by the current user and then use that as the entity field reference.

You can select this form ENTITY SELECTION


Preventing frequently updated nodes from keeping them on the top of View I have a view that lists content profile node and set the sort criteria to node:Updated date.

However, the problem is that some of the users updates their content profile node everyday to keep it on the top of the list.

I need to user sort criteria to node:Updated date but is there any way to prevent their nodes from being on the top of view?

Lest's say for example, within one week after their last update even if they update it again it stays where it is now and doesn't get to the top or somthing.

Not possible using views out of the box! Because updated date is stored as a single value in the database. If a user updates again the new value overrides old value.

So, there is no way views can track within one week after their last update even if they update it again .

You need to use hook_nodeapi either to track all updates in separate table and query that table to list users.


Call another field inside preprocess_views_view_field how can I access the value of another field inside the preprocess_views_view_field.
This is an example:

function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      $my_output = manipulation(ANOTHER_FIELD_NAME_IN_VIEW);
      $variables['output'] = $my_output;
    }
  }
}

It's possible or should i use it _preprocess_views_view?

Ok,
I solved it like this:

function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  $rows = $variables['rows'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      foreach ($view->field as $fieldId => $field) {
        if ($fieldId === 'ANOTHER_FIELD_NAME_IN_VIEW') {
          $my_output = $view->style_plugin->getFieldValue($row->index, $fieldId);
        }
      }
      $variables['output'] = $my_output;
    }
  }
}


How to disable CACHE in FORM which loads database values in form fields I am loading database values in my FORM and seems form is CACHING and loading old data from the database.

I have followed instruction here (How do I prevent a form from being cached for Anonymous users in D8?) but still old data is loaded in form fields.

Here is my code and would appreciate if anyone can shed light where I am missing;

....

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

return $form;
}

....

Do I have to add 'use Drupal\Core\Cache;' on top of this file?

Thanks a lot.

In the linked question the module Internal Page Cache was not enabled. If you don't want to disable page caching for all pages, but only for this form page, then add \Drupal::service('page_cache_kill_switch')->trigger() before you return the form:

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

\Drupal::service('page_cache_kill_switch')->trigger();

return $form;
}


Search API Database Search score calculation I'm trying to understand how the Search API Database Search calculates the score for a search result. I understand Solr uses the Lucene scoring model and there's also command that can be used to output the actual calculation (debugQuery=true).
Is there documentation and/or a debug command I could use to understand how the engine is coming up with the score for a result?

When you use debugQuery=true in a query, you can see all debug informations and how solr calculate scores for the result documents.


Creating one view for taxonomy page teasers so I don't have a ton of views this seems like a simple problem but I can't seem to find a straight forward answer for Drupal 7.  I have a ton of taxonomy vocabulary pages and I just want to configure them the same all the way through the site. So I just want one view that formats them all.
Can someone point me in the right direction?
Thanks!

When you have the taxonomy and views module enabled you should see a couple of disabled views and one of them is a view that format the taxonomies pages and their XML feed. Enable them and you will be able to play with them as need it.

See image below:


How to properly compare values of two identical entities? I have a custom entity that is not revisionable and I need to store any differences made by the user - and only differences, so if nothing has changed there should be no entry.

I am doing this in preSave method because the original entity has the same format as current entity(ie. some fields do some value processing and therefore the original entity does not match the current entity exactly in postSave method).

The issue I am facing is that I cannot properly compare values($entity->toArray()) because the data is not consistent. For example in the original entity a field's value can be 123.8 but in the current entity it can be 123.8999999... If I type cast it to string I end up with something like '123.8' vs '123.80' so the values won't match. Or 1 can be '1' and so on. Also with arrays I think keys get misordered sometimes(either that or the same issue but in the whole array).

I have tried to use the DiffArray::diffAssocRecursive() and Differ::diff() but neither is working reliably.

One thing that comes to mind is doing something like
Differ::diff($entity->view('somemodewithallfield'), $entity->original->view('somemodewithallfield')) but that won't cover fields that are hidden or invisible in UI and also diff would be "ugly" and too big.

So I am wonder what would be the correct solution in this case? I would like to avoid going through each value and doing some insane comparisons and data transformations(string/int/float).

I remember that there was a story on d.org to not save any field data if the data hasn't changed but I haven't looked into that yet and I'm not sure at what state that is at the moment.

Assuming you have two entities $a and $b.

You can convert them to arrays and compare the two arrays.

// if the position matters
$is_equal = ($a->toArray() === $b->toArray())

// if the position doesn't matter
$is_equal = ($a->toArray() == $b->toArray())

Edit: I thought the OP was about discovering if two entities have identical data.
After reading the question again it seems that OP wants a way to mark what is the difference in data.


Enforcing minimum number of characters for #autocomplete_path I have a form that is using #autocomplete_path on a textfield.  In general it works fine.

Is there a way to have the autocomplete callback not fire until a minimum number of characters have been entered?

Is the only real option to override Drupal.ACDB.prototype.search with my own version, or is there a clean way to do this?

I am not interested in server side solutions to limit the result set; I am trying to decrease server load here and really need a client-side solution to prevent useless requests from ever being generated.

Here's two approaches:

Replace the entire autocomplete.js with your customized version

/**
 * Implements hook_js_alter
 * Replace autocomplete.js with customized version
 */
function MY_MODULE_js_alter(&$javascript) {
  $javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/js/autocomplete.js';
}

Override Drupal.ACDB.prototype.search with a custom version

Copy to theme script.js or module js file, as long as it's added after /misc/autocomplete.js it will override it.

(function($) {

/**
 * Performs a cached and delayed search.
 *
 * Override adds minimum text string length for lookup.
 * See /misc/autocomplete.js for original function.
 */
Drupal.ACDB.prototype.search = function (searchString) {

  // Minimum search string length
  var min = 3;
  var db = this;
  this.searchString = searchString;

  // See if this string needs to be searched for anyway.
  searchString = searchString.replace(/^\s+|\s+$/, '');
  if (searchString.length <= min ||
    searchString.charAt(searchString.length - 1) == ',') {
    return;
  }

  // See if this key has been searched for before.
  if (this.cache[searchString]) {
    return this.owner.found(this.cache[searchString]);
  }
  // Initiate delayed search.
  if (this.timer) {
    clearTimeout(this.timer);
  }
  this.timer = setTimeout(function () {
    db.owner.setStatus('begin');

    // Ajax GET request for autocompletion. We use Drupal.encodePath instead of
    // encodeURIComponent to allow autocomplete search terms to contain slashes.
    $.ajax({
      type: 'GET',
      url: db.uri + '/' + Drupal.encodePath(searchString),
      dataType: 'json',
      success: function (matches) {
        if (typeof matches.status == 'undefined' || matches.status != 0) {
          db.cache[searchString] = matches;
          // Verify if these are still the matches the user wants to see.
          if (db.searchString == searchString) {
            db.owner.found(matches);
          }
          db.owner.setStatus('found');
        }
      },
      error: function (xmlhttp) {
        alert(Drupal.ajaxError(xmlhttp, db.uri));
      }
    });
  }, this.delay);
};
})(jQuery);


How to hide node webform programatically? I want to make hide WEBFORM  particular content type programmatically in default / custom mode.
Any help will be appreciable.

Try implementing hook_node_view.Then you can put your condition on $node->type, access the webform with $node->webform and use $view_mode to load the current view mode.


drupal field list data I have created a custom field list, but of all documentation I have read, I can't find a clear example on how to add data on the list.

The code so far is this:

/**
 * Adds field.
 */
function _my_installed_fields() {
  $t = get_t();
  return array(
    'my_dropdown_list' => array(
      'field_name' => 'my_dropdown_list',
      'label' => $t('Select an item'),
      'type' => 'list_text'
    )
  );
}
/**
 * Adds instances.
 */
function _my_installed_instances() {
  $t = get_t();
  return array(
    'my_dropdown_list' => array(
      'field_name' => 'my_dropdown_list',
      'type' => 'list_text',
      'label' => $t('Select an item'),
      'widget' => array(
        'type' => 'options_select'
      ),
      'display' => array(
        'example_node_list' => array(
          'label' => $t('Select n item'),
          'type' => 'list_text'
        )
      )
    )
  );
}

I need to let only one value to be selected and saved.

Try to add cardinality and settings parameters:

  function _my_installed_fields() {
    $t = get_t();
    return array(
      'my_dropdown_list' => array(
        'field_name' => 'my_dropdown_list',
        'label' => $t('Select an item'),
        'type' => 'list_text',
        'cardinality' => 1,
        'settings' => array(
          'allowed_values' => array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
          ),
        ),
      )
    );
  }


Checking which radio button was clicked on a cck form using Javascript or Jquery I have a content type which I am loading in a block as a form. I am looking to know which radio button out of 2 buttons was clicked so that I can display additional fields. What is the best way to achieve this using JavaScript?

 I am: *

 <input type="radio" id="edit-field-org-or-part-value-organizer" name="field_org_or_part[value]" value="organizer"   class="form-radio" /> Organizer

 <input type="radio" id="edit-field-org-or-part-value-participant" name="field_org_or_part[value]" value="participant"   class="form-radio" /> Participant

If you want to have an 'other' type of field you could use: http://drupal.org/project/select_or_other

I maintain custom code to achieve what you want (on very long fake multistep forms) and don't recommend this, it quickly becomes very unmanageable.


Views - Filtering view results by current user profile field I have been trying to do this last couple of days but no luck.

Every user have a custom field (favorite_car) which is taxonomy and there is different terms ('Audi','Bmw' etc).

I have also content type 'Cars' which had also a custom field (favorite_car).

I need to display only the results, that user have selected.
If user have a custom field selected to 'Bmw', view need to return only nodes which have a favorite_car field set to 'Bmw'.

I think that there is a way to do this in drupal 7. Every kind of help is welcome.

You can filter contents on their term_reference_field by the field_value of a term_reference_field of the current_user:

So we go:

Create a content_view
Create a relationship with "favorite_car"
Create a relationship with "term from favorite_car"
Create contextual filter user:uid with provide default_value: user_id from logged in user and the relationship favorite_car

This works for me!


Drupal forum post not showing on forum index I posted a new topic in the Drupal "Post installation" forum. When I clicked "Save", I got a new page with my post at the URL

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

The post is in a red box on that page. When I go back to the forum index, the post is not listed there. It's also not listed when I go to my profile and click on "Your posts".

I don't see any message that the post is awaiting approval nor anything in my dashboard saying that my account needs anything.

What's going on? I'm not likely to get a response if people can't see my post!

Thanks for your help.

The red box means the post has been unpublished.  You are still able to see the post, but everyone who is not a webmaster gets a 403.

Drupal.org uses a number of automated tools to detect and unpublish unwanted posts (e.g. suspected spam).  The most likely explanation is that your post tripped up one of these automated tools.

If you believe your post was unpublished in error, request it to be republished in the Drupal.org webmasters issue queue.


How to hide the "Add comment" link in the teaser? I don't want the Add comment link displayed in the teaser. But the comment form should be displayed along with the content of the node which forms a part of a page.

Edit:  I don't have access to the php code. I want to do it through the admin console. Is there a way I can uncheck "Add comment" from appearing in the teaser and instead appear in the full content node which forms a part of a page?

You can accomplish this with a custom module, as I found here https://drupal.org/node/1257788

Here is the code you'll need:

function MODULE_node_view_alter(&$build) {
  if ($build['#view_mode'] == 'teaser') {
    // remove "add comment" link from node teaser mode display
    unset($build['links']['comment']['#links']['comment-add']);
    // and if logged out this will cause another list item to appear, so let's get rid of that
    unset($build['links']['comment']['#links']['comment_forbidden']);
  }
}


Proper way to delete Images uploaded in Image fields What is the proper way, through code, to delete images on an entity?

I have a cron function that processes like so:

function processQueuedPropertyPhotoset($entity, $photos) {
if (!is_array($photos)) {
  watchdog('mymodule', 'Trying to process photos for a property but it has no photos. Aborting.');
  return;
}

if (is_array($entity->field_property_image) && count($entity->field_property_image)) {
  foreach ($entity->field_property_image['und'] as $key => $value) {
    $photo = file_load($value['fid']);

    if ($photo) {
      file_delete($photo, TRUE);
    }
  }
}

// wipe clean the records in the field_ table

unset($entity->field_property_image);
$entity->save();

// rest of code processes and saves new images

I am curious if this is the proper or effective way. Also, do the image derivatives generated get cleaned out by Drupal this way too? I notice there is a 'deleted' field in the database on the Image field table definition. When is this ever used?

This method cleans the entity data, removes the images from the server and files table. I am simply curious as if is an acceptable method that covers all the bases in Drupal or if there is an API function to simplify this. This function is called daily when we run a third party integration web service.

If you want to make sure that the image files are definitely deleted (regardless of whether or not another part of the system has declared a vested interest in that file), what you're doing looks spot on to me.

There's already a function run by core on cron (system_cron() specifically) that deletes files marked as  FILE_STATUS_TEMPORARY in the file_managed table, but that function consults the file_usage table and doesn't delete if the file is reported as being in use (which it will be if the field values haven't been removed from the entity yet).

Passing TRUE as the second parameter to file_delete() like you're currently doing is the cleanest way to force the deletion (any records in file_usage are also cleaned up so there's no stale data).

The image derivatives will be deleted automatically, as the image module implements hook_file_delete() and flushes the image cache for the file URI (see image_file_delete()).

The deleted column in the field tables is just there to mark the fields for deletion at a later date (I imagine so the subsequent page load isn't affected if there's a lot of data to delete). There are identical columns in the field_config and field_config_instance tables for the same reason.

The field module purges any data marked for deletion in the cron run (field_cron()).


Reordering login form components I am using the very helpful hybridAuth module to allow people to login with their social media accounts.

However, the login form shows up as shown below:

Looks a bit confusing, doesn't it?

I want to move the social media login button either to the top or bottom and create distinction with the actual login form

The form structure displayed at the top of the page is from hook_form_alter but I saw no obvious way to manipulate the form to achieve the desired effect.

I implemented the following code in an attempt to get my hook_form_alter to execute after hybridAuths' and perhaps find a way to reorder the form:

function mymodule_module_implements_alter(&$implementations, $hook){
    if($hook == 'form_alter '){
        dsm($hook, 'Hook');
        dsm($implementations, 'Implementations - form-alter');

        $group = $implementations['mymodule'];
        unset($implementations['mymodule']);
        $implementations['mymodule'] = $group;

        dsm($implementations, 'Implementations #2 - form-alter');
    }
}

However, my debug dsm code does not show up on my user/login page even though there is a form and hook_form_alter does respond to it on the same page.

Can anyone suggest something that might help, please?

HybridAuth module can make the block for this icons then you can place that icons block top of the main content block. it will show top of the login form


Nested OR and AND condition with db_select How can I convert the following query with db_select

SELECT *
FROM 'my_table'
WHERE
(condition1 < "value1" AND ((conidition2 > "value2") OR (condition3 < "value3")))
  OR
(condition4 < "value5" AND ((condition6 < "value6") OR (condition7 < "value7")))

I am trying with

$query = db_select('mytable');

$query->condition(
          db_and()->condition("condition1","value1")
                 ->condition(
                             db_or()->condition("condition2","value2")->condition("condition3","value3")
                             ));
$query->condition(
          db_and()->condition("condition4","value4")
                 ->condition(
                             db_or()->condition("condition5","value5")->condition("condition6","value6")
                             ));

  $query_debugg = $query->__toString();
dpm($query_debugg);

issue is with the "AND" in between where is should be "OR", it is expected I know.how can I change it

Output String

SELECT
FROM
{mytable} mytable
WHERE ( (condition1 = :db_condition_placeholder_0) AND( (condition2 = :db_condition_placeholder_1) OR (condition3 = :db_condition_placeholder_2) ))AND( (condition4 = :db_condition_placeholder_3) AND( (condition5 = :db_condition_placeholder_4) OR (condition6 = :db_condition_placeholder_5) ))

In Drupal, conditions are AND by default. It's easier to use objects directly, in my opinion:

$left_condition = new DatabaseCondition('AND');
$left_condition->condition( ... ); // add what you need

$right_condition = new DatabaseCondition('AND');
$right_condition->condition( ... ); // add what you need

$condition = new DatabaseCondition('OR');
$condition->condition($left_condition);
$condition->condition($right_condition);

But you can use db_and() and db_or() if you prefer.


Create a custom view, and add a custom sortable column I want create a view for display a list of contents. (same type)
(its my first fully custom view x) )

I want display the view like this :

//form : the user select a Date field, its an exposed filter field

COLUMN1           COLUMN2_sortable
-----------------------------------
content_title0    "special_value0"
content_title1    "special_value1"
content_title2    "special_value2"
...
content_titleN    "special_valueN"

First, can you tell me a good web tutorial for learn to create a fully custom view (so, create the user select form (contain exopsed filter) , the content of the view). After several google search, I difficulty finding a good guide...

Second, the COLUMN2_sortable contain a integer data. And this data is calculed via an another custom module (this value depends on the date entered in the exposed filter field). I have no ideas how add a custom column (here, the COLUMN2_sortable) in my view.
Because this is my first try in fully creating of view, can you advise me about the good way for implement that ?

You can make a column sortable by clicking on your type of view "fields" and check the "make sortable" checkbox.


How to delete a scheduled task using Rules Scheduler? I use the rules scheduler module (D7). So far all fine.

What I use it for:

a user registers with username and email
this users then gets 4 emails over the next four weeks, sent by the scheduler

BUT: In case a user wants to unsubscribe from these scheduled emails? How can I achieve it?

It is true that one can delete particular sort of scheduled tasks with the according action (Delete scheduled tasks). But I don't know how to indicate it shall only delete the tasks that are related to a particular?

When I list the schedule with ...
/admin/config/workflow/rules/schedule

... there is one column called "USER PROVIDED IDENTIFIER" - maybe it would help to do it with such an identifier. But I don't know how?

UPDATE TO THE QUESTION:

I tried to import with the suggested changes, this is how my rule looks like now:

{ "rules_user_reminder_after_30_days" : {
"LABEL" : "User Reminder After 30 Days",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : { "user_login" : [], "node_insert--article" : { "bundle" : "article" } },
"DO" : [
  { "schedule_delete" : {
      "component" : "rules_send_email_notification",
      "task" : "[account:name]"
    }
  },
  { "schedule" : {
      "component" : "rules_send_email_notification",
      "identifier" : "[account:name]",
      "param_user_to_notify" : [ "account" ]
    }
  }
]
}
}

But now I got this error:

  Integrity check for the imported configuration failed. Error message: Missing configuration for parameter date

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" for an illustration about how to delete scheduled tasks, using the "schedule_delete". As explain in that answer: the schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

To make this work (that you actually indicate the exact scheduled task to be deleted), you need to specify an appropriate "identifier", like "[account:name]" in my example. To understand how I know what in my case the identifier is of the task to be deleted, look at the way I specified my (new) scheduled task to be created: it is "identifier" : "[account:name]", which  is what I used as my identifier to schedule a task.

In your case, I think "[account:name]" would be a pretty good choice for such identifier. But your questions states "... users then gets 4 emails over the next four weeks, sent by the scheduler ...". So if the 2nd email only gets scheduled after the first email (and not schedule all 4 emails upfront together), and similar for the 3rd and 4th email, then you should be fine using this identifier also.

Note: Specifying an "identifier" like "[account:name]" is what you'd do in your Rules Action (similar to my "step 3" in the above sample). While you'd probably want to create a Rules component similar to my "step 2" in the above sample to actually send an eMail.

Update: The "integrity check" problem shown near the end of the updated question, is probably because in your rule, as shown in the updated question, does not specify the date to schedule your component. Have a look again at my answer I mentioned above: the rule there specifies a date via this part of it:

  "date" : {
    "select" : "account:field-next-article",
    "date_offset" : { "value" : 2592000 }
  },


How do I inspect mail messages in Behat tests? I am  writing a Behat Scenario that checks that an email generated by the Drupal system under test is sent to the correct recipient but I [could not] capture the mail messages from test_mail_collector. How do I do this?

[Update]
The code below is essentially my current working version and should work for you ... at least as long as you don't have an anti-spam module interceding ... in which case see the extra code in my answer.

In FeatureContext.php I switch over to the mail system sender test_mail_collector in the @BeforeScenario tagged with @email and revert to the site's original mail system sender in the @AfterScenario tagged with @email.

However, [before I discovered my answer, there were] never any messages in the array returned by \Drupal::state()->get('system.test_mail_collector') when a scenario should generate them,

Here's a typical scenario:

...
@email
Scenario: Send an email when a user resets her password
Given users:
  | name    | mail           | status |
  | Jo User | jo@example.com | 1      |
When I visit "user/password"
And I fill in "name" with "jo@example.com"
When I press the "Submit" button
Then an email should be sent to "jo@example.com"

And here are the FeatureContext.php snippets:

...
/**
*  @Then an email should be sent to :recipient
*/
public function anEmailShouldBeSentTo($recipient)
{
  // Reset state cache.
  \Drupal::state()->resetCache();
  $mails = \Drupal::state()->get('system.test_mail_collector') ?: array();
  $last_mail = end($mails);
  if(!$last_mail) {
    throw new Exception('No mail was sent.');
  }
  if ($last_mail['to'] != $recipient) {
    throw new \Exception("Unexpected recpient: " . $last_mail['to']);
  }
  $this->lastMail = $last_mail;
}

/**
 *  @BeforeScenario @email
 */
public function beforeEmailScenario(BeforeScenarioScope $scope)
{
  $this->m_config = \Drupal::configFactory()->getEditable('mailsystem.settings');
  $this->saved_mailsystem_defaults = $this->m_config->get('defaults');
  $this->m_config->set('defaults.sender', 'test_mail_collector')->save();
  \Drupal::state()->set('system.test_mail_collector', array());
}

/**
 *  @AfterScenario @email
 */
public function afterEmailScenario(AfterScenarioScope $scope)
{
  // revert mail system after scenarios agged with @email
  $this->m_config->set('defaults.sender', $this->saved_mailsystem_defaults['sender'])->save();
}

The website is normally set up to run with swiftmailer enabled but I have tried all the other available mail system formatters and senders - like Default PHP Mailer - without success.

As a kind of "proof of setup" within FeatureContext.php, I can send test messages to the test_mail_collector:

$language_interface = \Drupal::languageManager()->getCurrentLanguage();
\Drupal::service('plugin.manager.mail')
    ->mail('test', 'test', 'jo@example.com', $language_interface->getId());

This shows me that the test_mail_collector is working - but messages generated from the website [were] not being collected.

Ensure you don't have anti-spam modules installed and doing their job!

The @BeforeScenario and @AfterScenario code in the original question is correct except in the case where you have an anti-spam module that is interfering with a Scenario.

For example, if  you've got honeypot installed, ensure that you disable the time_limit setting. time_limit is there to protect the Drupal site against spambots .... and test programs! ... on the assumption that humans can't enter stuff in less than a few seconds whereas bots and test programs do so almost instantaneously.

So, if you, as I did, have honeypot installed, then you will need to temporarily disable time_limit for the duration of the test. For example my @BeforeScenario and @AfterScenario code is now as follows:

/**
   *  @BeforeScenario @email
   */
  public function beforeEmailScenario(BeforeScenarioScope $scope)
  {
    $this->m_config = \Drupal::configFactory()->getEditable('mailsystem.settings');
    $this->saved_mailsystem_defaults = $this->m_config->get('defaults');
    $this->m_config
      ->set('defaults.sender', 'test_mail_collector')
      ->set('defaults.formatter', 'test_mail_collector')
      ->save();
    // Reset the state variable that holds sent messages.
    \Drupal::state()->set('system.test_mail_collector', array());

    // If we have honeypot installed then ensure that we disable time_limit
    // So that automated tests / bots can run
    $this->h_config = \Drupal::configFactory()->getEditable('honeypot.settings');
    $this->saved_honeypot_time_limit = $this->h_config->get('time_limit');
    if ($this->saved_honeypot_time_limit) {
      $this->h_config
        ->set('time_limit', '0')
        ->save();
    }
  }

  /**
   *  @AfterScenario @email
   */
  public function afterEmailScenario(AfterScenarioScope $scope)
  {
    // revert mail system after scenarios agged with @email
    $this->m_config
      ->set('defaults.sender', $this->saved_mailsystem_defaults['sender'])
      ->set('defaults.formatter', $this->saved_mailsystem_defaults['formatter'])
      ->save();

    // Ensure we protect against spambots again if honeypot is installed
    if ($this->saved_honeypot_time_limit) {
      $this->h_config
        ->set('time_limit', $this->saved_honeypot_time_limit)
        ->save();
    }
  }


Drupal Commons update is having troubles using drush I have Drupal Commons distribution's based website,everything was good untill I updated the site with drush.

The problem is drush downloaded the file to sites/all/modules instead of profile folder. Now I am getting bunch of redeclare function error.

When I remove everything from sites/all/modules I get can't find function xxx. How will I get back the site to normal.

Drush just wasn't cut out to automatically update profiles.  pm-updatecode does not do the right thing, and as you noted, even pm-download picks the wrong location by default.

To download a new version of a module that is in a profile, use --destination to tell Drush exactly where to put the module.
If you get into a situation where Drupal no longer has the right location for your modules, run the registry rebuild tool to fix things up.


EntityFieldQuery and "legacy" nodes Here's the situation, which I suspect is pretty common:

A site is deployed where a node type has no fields added.
Lots of nodes are added.
The site is changed and a new field is added to the node type.

At this point, I've got my original nodes that do not have a value for the new field. There aren't even any field value records in the database for these nodes.

I now need to query for the nodes where this field is set to a certain value (a new or updated node) OR where it's one of the original nodes. So I'm thinking something like this (note the NULL in my array of possible values):

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->fieldCondition('field_myfield', 'value', array('myvalue', NULL));

Unfortunately, this doesn't work, and I suspect it's due to the nature of the join. Is it possible to return results where the field is a certain value OR where there is no record of a value at all?

ps: how do I see/debug the resulting query?

Although EFQ is a good tool, it starts with the assumption that you are querying about a field value.  It does not do the join because it is more efficient to get what you want the way it does it.  For you legacy nodes, I think you should do a legacy Dynamic Query.  This way you can specify a Left Join to get a result set that includes nodes with NULL/absent entries in the field table.

$query = db_select('node', 'n');
$query->leftJoin('field_data_field_myfield', 'f', 'n.nid = f.entity_id');
$query->condition('f.value', array('myvalue', NULL), 'IN')
  ->condition('n.type', 'my_content_type');

Joins in the dynamic query method.


How to show a field value instead of the node title for nodes displayed through an entity reference field? Edit: I think I found the place, just not the method yet. If correct, I will close this question. Sorry.

I have no clue which hook or direction to look into. I would like to have a label or title preprocess function, but that doesnt exist I think.

Its only for a specific content type that I need to show a field's value as title for the referenced nodes.

So it's not about the entity reference widget when editing nodes but rather the title display wherever that reference field is rendering the nodes' titles.

No code necessary, Drupal has built-in features for this:

Create a new view mode singlefield for the referenced content type foo, showing only the field value
Optionally, create a very minimalistic template for this node--foo--singlefield.html.twig
In /admin/structure/types/manage/foo/display change the view mode of the host entity reference field to Rendered entity, using view mode singlefield


Developing for Drupal 7 I am trying to wrap my head around the Drupal 7 framework using the debugger in eclipse. The thing is, I'm feeling a little overwhelmed with the endless function calls and watching data bounce back and countless number of times (I'm sure it could actually be counted with more patience).

What is the best way to understand what is going on and get a good overview of how everything fits together? Is using just a debugger the wrong approach?

Using a debugger to understand which function called another one is not necessary all the time. If you look at the documentation on api.drupal.org, for example for user_load_by_name(), you will notice the documentation shows the number of
functions calling it, which is also a link to a page listing them.

In the case of hooks, such as hook_field_info(), the documentation page shows how many functions are implementations of that hook, and the number of functions invoking that hook.

The page listing the hook implementations can sometimes include functions that are not hook implementations; the short function description shown in that list makes evident when a function is not really a hook implementation.

In some cases, the documentation page lists the functions that reference a function, such as in the case of system_batch_page().

The documentation on api.drupal.org includes some sections that describe a group of functions correlated to each other, for example in Batch operations. The list of all the groups is on Topics.

Other topics are linked in the API reference page.


Date Module / Date Repeat: Hourly or Minutely Recurrence? I'm setting up a Drupal 7 based calendaring system ,and the Date module has been super amazing; it does pretty much everything I need out of the box. However, correct me if I'm wrong, but it doesn't look like there's a way to set an event to reoccur, say, once every hour.

Do you have any idea for the best way to accomplish this?
I know PHP fairly well, so I'm game for writing code, but I have no idea where to start. Do I need to create a custom module that implements the Date Repeat API? What form would take, and how would it integrate with the existing Date module? Is this an unreasonably huge undertaking for a Drupal newbie?

Recurring events are handled in good old unix cron, see (http://drupal.org/cron). But there is a more, Php way .. Poor Man's Cron, see http://drupal.org/project/poormanscron (in D6, part of core in D7).

Basically, since some hosts didn't allow cron jobs Poor Man's Cron simply "hooked" a bit of code into each page using Ajax. If an amount of time had past it would run cron.php (which in turn calls drupal_run_cron()).

Either way ... you need to put your task into the cron queue, make sure your site is set up correctly and let the core system execute it. If your going to use a custom module see

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_cron_queue_info/7


Multiple pagers in single page Hi I have a page in which I have added 2 blocks in both blocks I have paging,but when ever i click any page number of either a block both the page change simultaneously in Drupal7

$output .= theme('pager', array('tags' => array()));
This is generating pager.

Pls help

You can use the element parameter:

  An optional integer to distinguish between multiple pagers on one page.

e.g.

First call:

$output .= theme('pager', array('tags' => array(), 'element' => 0));

Second call:

$output .= theme('pager', array('tags' => array(), 'element' => 1));


Is there a way to find out how many activated, registered users there are? I am seeking to track some KPIs for my site, one of which is the number of activated, registered users there are on the site. Is there a way to get this number?

You can query the users table, counting the number of rows where status = 1, which will give you the number of active user accounts.


Values missing in $form_state inside form function but available in ajax callback I have a custom ajax form in a custom module, the form function code is over 400 lines so it's too big to post here, but hopefully I can explain the situation clearly here.

The form has a form function mymodule_form($form, &$form_state) and also an ajax callback attached to a button mymodule_ajax_callback($form, $form_state). I put a dpm($form_state['values'], 'form state values from form function);  in mymodule_form function, and also dpm($form_state['values'], 'form state values from callback'); inside the mymodule_ajax_callback function.

Now when I change the values in the form, and press the ajax'd button, the form state values from the form function only has 1 element in the array, and that's the button that was pressed. All other values are missing. At the same time, the form state values from ajax callback function has all the form fields with the correct values. If I understood ajax forms in D7 correctly, you're meant to change the form inside the form function and only do return render($form['element']) from the ajax callback. This situation makes it impossible to do so as I can't access all the values from the form function.

There's nothing in the Recent Log Messages about ajax errors. The form has only 1 Ajax button, but it has also 1 ajax'd select dropdown which when changed, changes options for another select dropdown.

I'm currently sitting here scratching my head, ready to pull some hair out wondering what could cause such weird behavior.

I'm posting a screenshot of the dpm's for clarification:

As you can see values from form function has 1 element in array, values from ajax callback has 56 elements in array.

When I change the Ajax'd select dropdown however, the form state values from form function shows 55 elements, which is probably correct:

So it's only when I use the Ajax button this weird behavior occurs. Any help greatly appreciated. Can post the form code if needed.

It seems you are a bit confused about how the form API works. What you are seeing is exactly as expected. I'll try to explain about how the form API works.

The ajax callback is called in a context of the form being submitted, which is why, all of the form values are passed along, the actual form function is called in the context of being initialized where no form values exist.

There are different ways of structuring ajax. One way could be to add another input like what's possible with fields that can hold many values. In that case, the ajax callback function should only worry about a subset of the form, and return this (You shouldn't call render inside ajax callbacks).

Another way to use ajax is to restructure the entire form. In that case, what you can do, is to set

$form_state['rebuild'] = TRUE;

Which will force Drupal to rebuild the entire form, with the current values and make it possible to fx create a multistep form. This can be done both with and without AJAX.

It sounds like you will need to rebuild the form, to get $form_state values into the form function. Then you can add ajax behavior to the form, where you get this working.


Multi stage search views I'm building a website that needs the following functionality -

So two different content types - work type profile and job type.

So work type profile contains a field 'Skillset A' and a 'Skillset B' so I can create this content type and select the different skills the type has.

Job type has lots of different detail about the job, like salary etc.

I want a user to be able to select their work type as stage one, and then select the salary level they require for the the second stage filter.

Then I want a list of jobs to appear that they can do based on the skills within their salary range (so the jobs that match their skillset profile)

And I want the jobs to then be further filterable by the skillset. So they can see all the jobs that match the skillset.

How would I configure something like this with views?

Thanks for your help!

I would see how these projects approached this popular scenario & go from there as opposed to starting from scratch:

https://www.drupal.org/project/recruiter
https://www.drupal.org/project/drop_jobs

[edit]...So I decided to try both those out as I was thinking about simple data modeling and how to communicate it best. There's a demo linked on the recruiter distro but decided to use https://simplytest.me/ which is great in case you haven't heard of it.

The drop_jobs broke but the recruiter distro worked and it provides facets which is probably the way you should go too so people can just refine their search to their needs - the trouble with trying to do it in just views alone is you start with a big list of data and provide options from the boundaries you know, e.g. salary bracket, but if there's nothing in the one they choose then you'll end up with no results.

The benefit of using facets is by default it will only display the available facets, and you can have things like facet counts. You can display all the facets so you get things like $10k-$20k(0) if there aren't any, but at least the user doesn't have a fruitless search.

See http://dgo.to/facets


Fetching Facebook posts I'm creating a custom module to deliver an amalgamated news feed from various sources, all ordered by date. One of these sources is FB, and I'm having real issues with it.

I'm using fbapp module as a dependency (https://www.drupal.org/project/fbapp), so that I can use it's authentication fbapp_app_authenticate() and fbapp_graph_request() without having to worry about the constant facebook graph updates making my own code obsolete.

I've created a facebook app, so authentication should be app token, using appid and app secret. This seems fine and I'm getting back access_token. However, when I try to read posts from a publicly available page (the clients), I get the response:

"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api"

Here's my code:

$token = fbapp_app_authenticate(variable_get('my_module_fb_app_id', ''), variable_get('my_module_fb_app_secret', ''));
$type = variable_get('my_module_fb_query', -1); // this is "posts" in this case
$graphId = variable_get('my_module_fb_graph_id', '');
$target = "$graphId/$type";
$params = array('access_token' => $token['access_token']);
$data = fbapp_graph_request($target, $params);

As an update, here's the queries and responses it produces:

graph.facebook.com/oauth/access_token?client_id=<redacted>&client_secret=<redacted>&grant_type=client_credentials

array(1) {
  ["access_token"]=>
  string(43) "<redacted>|<redacted>"
}

graph.facebook.com/<page_id>/posts?access_token=<redacted>|<redacted>"

string(183) "{"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100}}"

Does anyone know if this is a correct way to query Facebook, or if there's a better way of programmatically obtaining a page posts?

Here's the solution I got on the main stackoverflow site (https://stackoverflow.com/questions/31306242/facebook-graph-api-unsupported-get-request):

If page restrictions apply, the page's feed can only be retrieved with an user access token as far as I know (because FB needs to evaluate the visibility criteria, and setting your app to the same restrictions doesn't help here):

See

https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed#readperms

The alternative is to use page access tokens, but you need admin access to the site page to generate those. This means you will receive all posts, regardless of restrictions.