Drupal 6 webform: send email if a checkbox is checked? I have a webform in Drupal 6 with a checkbox component: 'Send email'. If this box is checked I would like a rule to trigger an email send. Is this possible with a Drupal 6 webform? Thanks

You can use the rules module to send an email if the checkbox was checked

Install drupal [Rules module][1]
Install drupal [Webform Rules][2]
Create a rule
On condition section you need to custom PHP to check if the checkbox was checked
Make sure that you can access the field in data selector
Chose the operation equal
For the "Data Value" field, you can input values in two modes, make sure you are using "direct input mode". You should then be able to check the checkbox that represents TRUE for that field. Translated, what you are saying is, "Is this field equal to TRUE?" You can also negate it by leaving it unchecked or using the "negate" option below.


Set a view filter programmatically I have a view that includes a date field that only uses the year part.  I want provide a default filter value for this field based on the current date.  So far, I have this

function results_view_views_pre_view(&$view, &$display_id, &$args) {
  if($view->name == 'results_view') {
    $year = date("Y");
    $view->display['default']->handler->options['title'] = $year . ' Results';
    $view->display['page']->handler->options['filters']['field_season_value']['value']['value'] =  = $year;
  }
}

This doesn't throw any errors but the filter view isn't filtered

I'm not sure what I'm doing wrong here, or if I'm even going down the right path.  The value I assigned above is based on the fact that when I hard code the year into my view, the view object looks like this

[field_season_value] => Array
(
        [id] => field_season_value
        [table] => field_data_field_season
        [field] => field_season_value
        [relationship] => none
        [group_type] => group
        [ui_name] =>
        [operator] => =
        [value] => Array
                (
                        [min] =>
                        [max] =>
                        [value] => 2013
                        [type] => date
                )

Just to clarify, the date field is based on a fiscal year that runs September through August. So if its May 2013, the date would need to be 2012. My example above is just a simplified version if what I'm going to need to do in the final version.

Set the default value to now using GUI. This should give you what you need without any code.

If you need to use fiscal years, either create own custom filter, one that will translate real date to fiscal year. Read manual and more detailed manual to see how to do it. Simply changing default value in date will not be enough, as user may inject date with more than a year set, making built-in filter not work the way you want it to. And then, well, then use now as default value.

You probably want to inherit from class views_handler_filter_date and override it's extra_options() method


How to pass parameter to 'options list' attribute in hook_rules_condition_info? I am declaring a condition in which I have the following parameters:

            'node_type' => array(
            'type' => 'text',
            'label' => t('the node type'),
            'options list' =>/*'entitystep_get_list_node_types'*/ 'node_type_get_names' ,
            'restriction' => 'input',
        ),
        'node_field' => array(
            'type' => 'text', //TODO: find or create node_field datatype? *node_element?
            'label' => t('the node its field to be checked'),
            'options list' => 'entitystep_get_fields'

// TODO: check how to pass a parameter to the entitystep_get_fields!!! ($node_type)
            ),

In the 'entitystep_get_fields (on the bottom) I have to pass the selected node_type (=the first parameter)

These are the functions I need to call:

function entitystep_get_list_node_types() {
    $types = db_query("SELECT n.type FROM node_type");
    return types;
}

 function entitystep_get_nodes_by_type($node_type) {
        $nodes = db_query("SELECT * FROM node WHERE type=" . $node_type );
        return $nodes;
    }

Have a look to the entity condition "entity_is_of_bundle"

In this example there are three parameters and they are displayed through a multistep form. To do this, you will need to alter the form. In this example, it is rules_condition_entity_is_of_bundle_form_alter

You can notice that depending on the form state, some elements are hidden. When you go to the next step, you can access form values. In this example, we can access entity bundles of the entity type as do the function rules_entity_bundle_options. The type of the entity is within $element->settings['type']

I hope it is clear for you.


drupal_set_message for anonymous user I am having hard time displaying drupal message for anonymous users. My scenario is, I need to display message if there is certain query string and remove the query string with message. I am using following code but without success. I also tried with session variable without success.

 if(isset($_GET['action']) && $_GET['action'] === 'loggedoff'){
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    \Drupal::logger('vrpboostrap')->notice('query parameter has value loggedoff');
    $url = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($url);
    $alias = strtok($alias, '&');
    header('Location: '. base_path() . $alias);
    exit;
  }

With Session variable, I tried with:

if (isset($_GET['action']) && $_GET['action'] === 'loggedoff') {
    $_SESSION['vrp_action'] = 'loggedoff';
    $url = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($url);
    $alias = strtok($alias, '&');
    header('Location: ' . $url);
    exit;
  }
  if (isset($_SESSION['vrp_action']) && $_SESSION['vrp_action'] === 'loggedoff') {
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    session_unset('vrp_action');
  }

Can you guys advise me what am I doing wrong here and to display message for anonymous users?

The fact that you use header() and exit is most likely the problem.

You need to use response objects that you return to properly terminate the request and write the session data.

You can't do this anywhere, I'd recommend implement a Request event subscriber. \Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber is a simple example for this:

class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    // Get the requested path minus the base path.
    $path = $request->getPathInfo();

    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request->getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event->setResponse(new CacheableRedirectResponse($request->getUriForPath($path) . $qs));
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}

And then register that in yourmodule.services.yml:

redirect_leading_slashes_subscriber:
  class: Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber
  tags:
    - { name: event_subscriber }


What is the purpose of the "token" custom display setting? On the manage display page of a given content type, you can choose between various display settings. The most commons are "teaser" and "default" or "full content".

However, there's also a "token" display mode (disabled by default). I assume it's added by the token contrib module, but I have no idea what its purpose is and how we're supposed to take advantage of it?

Also: is it typically used somewhere that I'm not aware of? Can it be safely deleted if it's not activated?

As Neograph734 commented, it allows you to change the output of field tokens without actually changing the default display of the field. You can find more information here: https://www.drupal.org/node/1299662

Actually, a similar question already has been answered: Effective use of tokens view mode?


CSS defined in library is not included, but theme works themes/custom/teleci/teleci.info.yml:

base theme: bartik
core: 8.x
name: Teleci
package: Custom
type: theme
version: "1.1"
libraries:
  - teleci/global-styling

themes/custom/teleci/teleci.libraries.yml:

global-styling:
  version: "1.1"
  css:
    theme:
      css/override.css: {}
      css/style.css: {}

I also have custom template in themes\custom\teleci\templates\block--teleci-branding.html.twig that is loading correctly - that means the theme works. But the CSS files are not included (they are not in the generated HTML).

I tried

php drupal.phar cr all
setting bartik as default and then set my theme back
clear browser cache
open in private window
disable JS/CSS minification in settings
check both yml files in yamllint.com
disable base theme (bartik)

I'm out of ideas and would appreciate any help :(

Update: I created minimal theme (that does not work as well) for you to test. Could you please test it and let me know if it works for you? https://github.com/tomasfejfar/drupal-simple-theme/ (i have it in /themes/custom)

Update 2: the mini-theme works when I fixed a small bug that is not present in my theme. So there is something about my theme that makes it break.

Finally it seems to have been fixed. I re-created the same template again under a new name. Checked the diff of theme.info.yml and theme.libraries.yml files - only difference is the name. The new template has all the same functionality the previous had and is 1-to-1 copy except for the name. So only thing I can think of is that while playing with the template something has broken and left some residue in the database that prevented the theme from functioning properly ever again.

Thanks everyone who tried to help!


Installing extra/additional plugins for standalone CKEditor module library I have the CKeditor plugin installed by itself (i.e. not using WYSIWYG module.) Then, it uses a CKEditor library located in sites/all/libraries/ckeditor. This works fine. I'd like to add more plugins to it; namely, the footnotes plugin. (For the moment, please refrain from "just download a new library from ckeditor.com and replace it"; there were other issues/considerations involved.)

Now, I see this everywhere when I try to look for a solution

config.extraPlugins = 'footnotes';

I tried adding that to admin/config/content/ckeditor/edit// -> Advanced Options -> Custom JavaScript configuration, but it white screens the editor.

I tried adding it to the config.js in sites/all/libraries/ckeditor like below, but it had no effect.

CKEDITOR.editorConfig = function( config ) {
  config.extraPlugins = 'footnotes';
};

I can't really add it to a ckeditor.config.js file, dump that file in my theme, and choose "Yes" for "Load ckeditor.config.js from the theme path", since (for content creation/editing) it uses the admin theme which is different from the theme we're developing.

So, I'm at a loss. The only other thing I can think of is to use a hook in the module we have for the site, but I'm not sure if that's write/what hook would be called.

Is it just me, or does it seem like clear documentation on how to manage CKEditor in Drupal is severely lacking? Any help would be appreciated.

UPDATE: After some testing, it looks like the "Custom JavaScript configuration" is supposed to work, but it is possibly broken for CKEditor 4.4+ I read something (can't seem to find it now) that suggested the plugin/widget import was broken on 4.4+, so I changed to 4.3 and the extraPlugins worked. Now, I wasn't able to get footnotes working (which is what kicked this whole thing off), but some other plugins that previously failed during the same steps now work on 4.3. So, there's that. I'm wondering now if it's something with footnotes itself.

Here are the steps about how I am doing it:

install CKEditor using the CKEditor module and NOT through using the wysiwyg module.
Put plugin in sites/all/modules/ckeditor/plugins and NOT in /sites/all/modules/ckeditor/ckeditor/plugins
Go to /admin/config/content/ckeditor and click edit on the profile you're using.
Under Editor Apperance, from Available buttons, drag up your plugin icon to the Current tool bar.

Scroll down a bit and you will see a Plugins section.

Checkmark your plugin and save changes.

PS: Here is my CkEditor Global Profile settings /admin/config/content/ckeditor/edit/


How can I display "new" or "update" in the view that overrides admin/content/node? I have override the page admin/content/node with Views.
The default page of admin/content/node displays "new" for new contents and "updated" for updated contents. How can I display them in the custom View?

Just use the "Content: Has new content" field, the same field used from the view that emulates the tracker page.


hook_field_presave() isn't getting called Summary

I need to edit some data before it gets saved, and hook_field_presave() looks like exactly what I need, but it doesn't get called for some reason.

The Scenario

I'd like to edit data coming from changes to the location field (location module), so that I can look up latitude and longitude information when none is provided and make sure it gets saved.

The implementation

At the moment I'm just adding the hook to the location.module for testing purposes before moving them into a separate module. The code I'm using is this:

function location_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  watchdog('location', 'testing location_field_presave', array(), WATCHDOG_NOTICE);
}

However, the dblog is never updated with my message; the code never runs.

If you are editing an enabled module, you need to first disable, and then re-enable it. Drupal saves in cache the list of hooks implemented by modules; the one I described is the way to force Drupal to update that cache.

hook_field_presave() is invoked for the module implementing the field; the other modules should implement hook_field_attach_presave(). If the Location module is not implementing the field, it should implement hook_field_attach_presave(), which is what your module should do too.

The documentation is not much clear about this; but looking at field_attach_presave() is a little more clear what happens.

function field_attach_presave($entity_type, $entity) {
  _field_invoke('presave', $entity_type, $entity);

  // Let other modules act on presaving the entity.
  module_invoke_all('field_attach_presave', $entity_type, $entity);
}

_field_invoke() invokes the hook for the module implementing the field; module_invoke_all() invokes the hook implemented by any module.

That is why the documentation for hook_field_presave() says, "Define custom presave behavior for this module's field types."


How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile? What I try to achieve with Rules:

After saving a new comment, this comment has to be sent only to those users who've checked a corresponding boolean box on their profile page.

Any suggestions?

Assuming your question is about D7, there are basically 2 ways (options) to answer your question, as further detailed below.
Option 1: Use Rules and Views Bulk Operations
You could create a view (using the Views module) of those users that you want to send an eMail to.
After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, using a rule that looks like so:

Rules Event: After saving a new comment.
Rules Actions:

Load the VBO list of the users in your View.
Add a loop to perform a Rules Action "Send an eMail", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
Option 2: Use Rules and Views Rules
a) About this module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

b) Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

c) Create a rule using the view of display type 'Rules'
Create a rule that looks like so:

Rules Event: After saving a new comment.
Rules Actions:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.


How to add a sub-theme for mobile version? I finished my drupal site, and now I should create the mobile version.First I'm using Bootstrap 3.3.5 with a sub-theme, and drupal 7. I'm sorry I don't know how to explain it but I want like, add a another sub-theme  like my existing sub-theme and change on it for mobile with saving all my node and views, thank you.

Create another subtheme (lets call it mobiletheme ) and with mobile theme module set your mobile version of site use mobiletheme.

  Adds the ability to choose a mobile theme in
  admin/build/themes/settings which is used for serving users on mobile
  devices.

another solution is detect and set theme for mobile with themekey module (Check  tutorial here: http://mustardseedmedia.com/podcast/episode52 )

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules. In combination with Drupal's
  theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
...

  And unlike other theme switching modules, ThemeKey should play well
  with internal and external page caches, like Boost or Varnish, even
  for anonymous users.

but really it is heavy module and if you want only want switch to another theme when user surf site with mobile I strongly recommend you to use   mobile theme module.


Load a variation (or Line Item) based a previous choice I asked this similar question already (Variations price adjust based on previous variation), but I am thinking to make the solution more 'base'.

Is there a way to 'load' different fields based on a selection of a previous field?

If I select 'Size: Medium', I want to load those colors and styles that have a different price than 'Size: Small' has.

Please use COMMERCE OPTION module with COMMERCE PRODUCT ATTRIBUTES to explore the possibility of achieving this. Go through by documentation for using it properly & I hope you will have fun in achieving what you want...


Search text box for Search API + Database + Search Views + Facets API + Facets Bonus I have check boxes and radio buttons (after a few patches) in my facets, using Search views.  I want to be able to present the user with a text search box so they can search for a title and another text field.  I can't seem to find this, however.

Do I need to create a new facet, or am I just missing this functionality?

You should enable title and other fields for search in your search index.
Select type as "Fulltext". Reindex content.
After that add new exposed filter in your search view. It's fulltext search filter. In settings of this filter you can select your fields from index.


.htaccess rewrite doesn't work I have custom module with page at /page wich expects $_GET['id'] to do it's job.

Here's .htaccess rewrite rule that works on empty website

RewriteRule category+/(.*)$ page.php?id=$1 [L]

On Drupal 8 I suppose that line should be

RewriteRule category+/(.*)$ page?id=$1 [L]

but it gives me 404 Error when i visit /category/5

The rewrite rule will not work because page is not a valid path on the server. By default Drupal rewrites all requests into index.php. When you rewrite to page apache will expect a path page on the server.

This is not quite the right way to accomplish what you are trying to do in Drupal. However you can achieve what you are trying to do with the following

RewriteRule category+/(.*)$ page?id=$1 [R=301,L]

That will redirect category/5 to page?id=5 and you will get 5 in $_GET['id']

Check these out as well

https://www.drupal.org/docs/user_guide/en/content-paths.html

How do I retrieve the query parameters from a path?


How can I hide a nodereference url link for users who have already created a node I am working on a job listing site and wants users to be able to apply for jobs on the site.
I created 2 content types "Job posting" and "Job Application".

I used the nodereference_url module to add an apply now link on the job posting node that directs the user to the "job Application" form.
This works fine but i would like to make each user to be able to apply for a particular job only once.

Is there a way i can achieve this with my current setup? Is there a different way to go about this that will give me the desired result?

Thank you for the help

One solution that comes to mind includes using the nodereference_url_create_link function that is included in the Node Reference URL Widget module. From the documentation of the specific function:

/**
 * Helper function for themers to easily create a link.
 *
 * This function should be used in custom themes, rather than making manual
 * links because it first checks a user's access before showing the link. If
 * the user does not have access to create the node then an empty string will
 * be returned.
 *
 * @param $node
 *   The node object that will be referenced.
 * @param $field_name
 *   The name of the Node Reference field.
 * @param $type_name
 *   The name of node type that contains the Node Reference field.
 * @param $attributes
 *   Optional. An array of additional attributes to add to the link.
 */

You can use this in the node.tpl.php file for the Job Posting content type (which should be along the lines of node--job_posting.tpl.php if you're in D7 or node-job_posting.tpl.php for D6). The outline of the process should be as described below:

Hide the field at the top of your template file (you will render it later on if the user did not apply for the specific job).
Check if the user has already created an application node that references to the current posting.

The first step can be easily implemented by writing something along the lines of:

hide($content['YOUR_FIELD_NAME']);

at the top of your template file. Use a dpm($content); first to make sure that you are hiding the right field.

The second step is a bit trickier. The most elegant way that comes to mind is to use the Corresponding Node References module so that when you create a reference from the application to the posting, a corresponding reference from the posting to the application is also created (this can also be useful if you want to show all the applications that were created for a specific posting in the posting's page).

After you have "linked" the posting and the application with CNR, all you need to do is check if the author of the other postings is the logged in user. Specifically, you can use the node reference array in the $node object to get the referencing applications with node_load_multiple and then with a foreach loop compare each $node->uid against the uid of the logged in user.

There is a blog post in Drutácora that describes a similar process and includes relevant code snippets (it's not in English but you should get the basic idea from the code).


What's the difference between indexed and non-indexed field in Views and Search API? I'm using Search API with a database backend and Views to build the search results page. More specifically, I'm using fields in Views. When selecting fields, I see two options for example:

Title
Title (indexed field)

When using this field, I get the same result. So I'm wondering why might I use the indexed version over the regular?

Simple:

Title provided for Views from Content entity.
Title (indexed field) provided for Views from SOLR.

For example: You have 1000 contents, and you want to show 10 of these, titles of that starts "Z" letter.
If you use Title as filter - Drupal will use it by Views handlers, so:

It will request data from SOLR server, in our case - all 1000 items.
The Views filter on found items, reducing it to the required 10 "Z" contents.

As you see - it's not good for performance. Better is using Title (indexed field)as Views filter, that will request only required 10 records from SOLR server.
p.s. Against it, title will prefer for Views output than indexed field (for some cases).


"contact" SQL table: what is it for and where do I edit it? We are running a site with the Hotel Diamond theme. Today we received a bounced email: apparently, someone had tried using the contact form in the site to send us a message, and the system had tried sending it to "test@localhost.com".

Now, the Hotel Diamond theme has an option to configure the email for the contact page, but it is correctly configured (i.e., it's NOT "test@localhost.com"). So I decided to look for that address in the raw SQL dump of my site, and I found this:

INSERT INTO `contact` (`cid`, `category`, `recipients`, `reply`, `weight`, `selected`) VALUES
(1, 'Website feedback', 'test@localhost.com', '', 0, 1);

My question is: where do I edit that in the admin pages? And why is Drupal using this entry to send contact email, instead of the address we had configured in the Hotel Diamond config page?

Go to admin/structure/contact/edit/1 and change Recipients email address to whatever you want.


Defining module.links.action.yml with route parameters How can I pass dynamically route parameters to module.links.action.yml?

My code of module.links.action.yml:

module.group_apply:
  route_name: module.group_apply
  title: 'Subscribe to group'
  weight: 0
  appears_on:
    - entity.node.canonical

My code of module.routing.yml:

module.group_apply:
  path: '/projects/{project}/usergroup/{group}/subscribe'
  defaults:
    _controller: '\Drupal\module\Controller\SubscriptionController::subscribe'
    _title: 'Apply'
  options:
    parameters:
      project:
        type: entity:node
      group:
        type: entity:node
  requirements:
    _permission: 'access content'

My subscibe function (actually):

public function subscribe(NodeInterface $project, NodeInterface $group) {
    return array(
        '#markup' => 'HERE WE GO!',
    );
}

I was on the wrong track the whole time.

The right way is to use entity.node.canonical as route (/node/{node}) and using other variables from node itself in the subscribe function ($node).

Thank you @4k4 for your help.


With a view of flaggings, how do I get the flagged entity? I want to create a view of flaggings and show content from the flagged entity.
However, on a flaggings view (Flag 4.x, Drupal 8/9), when I try to add a relationship, I can only add a relationship to the User, not the flagged entity.
Is this functionality not available in Flag?
When I create a view of nodes and want to pull in the flags, all I have to do is add a relationship to the Flag and it pulls in the flaggings automatically. So the Flag module supports going from nodes to flaggings, but how do I go from a view of flaggings to the flagged nodes?
Why I am trying to do this
Normally, I would just go from nodes to flaggings. However, this time, I have three different flags, and the same node may be flagged by multiple flags, and I want to show an entry for the node for each flagging, not one entry for the node for all flaggings.

Whoops, this is a work in progress to be added to Flag at some point.
In the meantime, this can be worked around using an entity reference field.
First, add an entity reference field to the flag.
Next, set the entity reference using hook_flagging_presave().
function MYMODULE_flagging_presave(FlaggingInterface $flagging) {
  switch ($flagging->getFlagId()) {
    case 'MYFLAGTYPE':
      if ($flagging->isNew()) {
        // Set entity reference for new flaggings.
        $flagged_entity_id = $flagging->get('entity_id')->value;
        $flagging->set('field_myflag_entityreference', $flagged_entity_id);
      }
    break;
  }
}

Finally, you can use the entity reference to the flagged node in your view in the same way as any other entity reference.
Because the flag module patch to solve this issue is in flux, it seems to me a bit dangerous to apply the patch to a production site, because the ultimate direction of the flag module may differ from any given patch. So, using an entity reference has the advantage of achieving the desired solution now (get access to the flagged entity in the flaggings view) while still allowing the future flag solution to be used (when flag becomes able to support this, you can simply delete the entity reference field, as it will no longer be necessary).


Creating separate list of a custom content type for every user I have a custom content type named Movie.

Every user must have 2 lists of movies :-

1) Seen Movies

2) Unseen Movies

For this purpose a ADD button (or 2 buttons - 1. add to seen, and 2. add to unseen) should appear on every movie page , by which a user can add the corresponding movie to his seen list or unseen list.

How can i do this??

I am using Drupal 7.

I am new to drupal, so what should be my approach to solve this problem ?? Please help :-)

THANX IN ADVANCE

I would take a look a the flag module. It allows you to create an unlimited number of "flags" that can be placed on nodes that users can select/deselect. You could create one for "seen" and "unseen".

It has views support so you can create a view using the user id as an argument on each user's page that will show them which movies that have flagged.


How can I ensure automatically that a module is disabled on my live site? I'm using a development -> staging -> live server workflow, and all three sites run off the same Git repository. The repository contains a few modules (a custom module for Selenium testing, etc.) that I never want to run on the live site.

Is there a way (in settings.php, perhaps?) to block a module from ever being enabled? I suppose I could also remove it from the repository, but my workflow is easier if I keep everything together.

You can hide modules from the admin UI by using the hidden property in the module's .info file:

hidden = TRUE

This method might be useful if you want to make sure the module is never enabled via the UI.

In case you're interested in how to do the opposite (stop a module from being disabled), it's also done in the .info file by setting the required parameter:

required = TRUE

Once you've done that Drupal will see the module as a 'core' module and stop it from being disabled through the admin UI.


How to check for entity type in Views when using hook_field_access? I have some code that checks user access to a certain field using hook_field_access below.

The code runs fine when viewing nodes normally, but throws an error when viewing a node of type 'lesson' through a View:

Notice: Trying to get property of non-object

The error comes from the check for entity type: $entity->type == 'lesson'

If I debug with:

dpm($entity->type);

I get the right value ('lesson'), so the check seems to work.

How can I resolve this error?

function HOOK_utility_field_access($op, $field, $entity_type, $entity, $account) {

  //Check video field only when attached to 'lesson'.
  if ($field['field_name'] == 'field_video' && $entity_type == 'node' && $op == 'view' && $entity->type == 'lesson') {

    //Grant access only if user is logged in.
    if ($account->uid > 0) {
      return TRUE;
    }
    return FALSE;
  }
}

Based on @clive's comment above, I adjusted the code to check that $entity is actually present. I'm not sure if this is a problem unique to my install or not. I only saw the error when viewing a node of type 'lesson' through a paged view that depends on some custom relationship code, so entirely possible the error is mine somewhere in a custom module.

function HOOK_field_access($op, $field, $entity_type, $entity, $account) {

      //Check to make sure we have an entity. Abort if not.
      if (is_object($entity)) {

        //Check video field only when attached to 'lesson'.
        if ($field['field_name'] == 'field_video' && $entity_type == 'node' && $op == 'view' && $entity->type == 'lesson') {

          //Grant access only if user is logged in.
          if ($account->uid > 0) {
            return TRUE;
          }
          return FALSE;
        }
      }
    }


How to create a Content pane view of nodes with common taxonomy terms (creating relared contents)) I need to create a list of related contents to the current node with common taxonomy terms in Panels. I tried Related Articles - a block view of nodes with common taxonomy terms, it works well with blocks but I have problem with moving this idea to a Content pane display mode.

After following the above method I add Term from node relationships to get the following contexts in the Panels

and it is Argument input configuration of the Views pane

The problem is this View is not available in the Add content -> Views pane section of the panels. But if I remove Argument input configuration it will be available.

How can I create a View pane of the above block that works with panels?

Found it, I should have select Multiple terms from node in Relationships to create Contexts not the Term from node


How programmatically create custom field type with some base fields? I want to emphasise that I don't want to use field_collection.

I want to create custom field type that can be reused in different entities and bundles. This should be kept in one custom module. So when I enable it and go to 'manage fields' page on any entity type then I should be able to pick up my custom field type (e.g.: foo). This field should be combined with base image field and simple one line text field. I don't want to use field_collection module because as far as I see I can not recreate my field, even features give me ability to export it in field_base section. After flushing my drupal to clean instance and enabling this feature again I can not see it in 'Add existing field' in [structure > content types > CONTENT_TYPE > manage fields] page. Maybe I'm doing something wrong. (?)

So how can I programmatically create custom field type with existing base fields? e.g. Custom foo field type with image field and text field?

OR (if I done something wrong with features..)

How can I export custom field collection with sub fields, only as a field definition (not attached to any content type/entity) using features?

What you want to do is create a field type with multiple properties. This is indeed more efficient than a field collection, because a property only needs one more column in the field table, while a field collection is a complete new entity in the database.

This is the documentation how to build a custom field type from scratch in a custom module:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-type

As you want to add a property to an existing field type use this tutorial

https://www.lullabot.com/articles/extending-a-field-type-in-drupal-8

and extend the class ImageItem for the new field type. You also need to extend ImageFormatter to display and ImageWidget to provide a form field for the new property.


How to call form function in menu callback in drupal7? I have one menu and two functions that want to call on same menu. What I am doing is, in hook_menu page callback i am calling a function and in that function i am calling another function.Means, calling function inside a function in page callback of menu.
Now my PROBLEM IS, my secong function is a form.

$items['component/%/edit'] = array(
    'title' => 'Edit Component item',
    'page callback' => '**component_list_edit**',
    'page arguments' => array(3),
    'access arguments' => array('administer users'),
    'file' => 'popup.inc',
    'type' => MENU_CALLBACK,
  );

My Page callback:

/**
 * ajax popup edit function : ctools implementation
 */
function component_list_edit() {
ctools_include('modal');
  ctools_modal_add_js();
  return _mid_component_make_link('Title').component_type_select_list_form($form, $form_state);
}

It is giving "ARRAY" as an output. no form m getting.
I also tried to return drupal_get_form('component_type_select_list_form');
This is also not working.

After some sort of study, I got to the answer. we can get form by using drupal_get_form and then in return function, we need to render it also.
for example:

function component_list_edit() {
  $form = drupal_get_form('component_type_select_list_form');
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return '
Title:'._mid_component_make_link('Title').drupal_render($form).'
';
}


How make patch in PHPStorm suitable for Drupal.org? PHPStorm will create patch in this form:

Index: core/modules/node/templates/node-edit-form.html.twig
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- core/modules/node/templates/node-edit-form.html.twig    (revision 4652b443e9f89734487e225fb76829595b5239a1)
+++ core/modules/node/templates/node-edit-form.html.twig    (revision )
@@ -1,6 +1,8 @@
 {#
 /**
  * @file
+ * Default theme implementation for a node edit form.
+ *
  * Two column template for the node add/edit form.
  *
  * This template will be used when a node edit form specifies 'node_edit_form'

After I export it I always have to remove the header and add the a/.. and b/.. prefixes and convert to LF so it'll look like this:

--- a/core/modules/node/templates/node-edit-form.html.twig
+++ b/core/modules/node/templates/node-edit-form.html.twig
@@ -1,6 +1,8 @@
 {#
 /**
  * @file
+ * Default theme implementation for a node edit form.
+ *
  * Two column template for the node add/edit form.
  *
  * This template will be used when a node edit form specifies 'node_edit_form'

Is there a way to export patch that I can directly use for drupal.org?

PHPStorm patching issues have a long history. I have corresponded with their staff more than once, about a year ago. They told me then, that my issue was taken up to developers, but never actually corrected it. Right now, PHPStorm issues patches incompatible with Drupal.org, and we can do nothing about it.

To create a working legit patch, you need git, and create a patch like this: git diff > patch_name.patch

See http://drupal.org/node/707484

A number of PHP Storm request related to this issue have been merged into a single issue http://youtrack.jetbrains.com/issue/IDEA-92793


How to get taxonomy tree with path auto token? I'm using Path auto module to automatically set url of articles.
Last part of url is node title and [node:title] works just fine. But url part before node title should follow taxonomy structure (tree) of tag used for tagging that article (taxonomy name: "structural_category".

So i.e. if article is tagged with tag "Child" and that tag has parent tag called "Parent" then url of my article should be:

/parent/child/node-title

I can get only Child tag with tokens like this: [node:field_structural_category:0], but I don't see the way to get Child's tag parent with token. With "Browse available tokens" I just can't drill any deeper than tag which is used directly for tagging the article.

For Drupal 7 I found that there is a solution with "join" keyword, something like:

[term:taxonomy_name:join:/]/[term:name]

What are the URL Alias pattern replacements for taxonomy parent terms when building up Node paths?

And I know that for Drupal 8 there should be something like:

[term:parent:url:path]/[term:name]

But when I try to save pattern like that I get an error "Path pattern is using the following invalid tokens:..."

When I use "Available tokens" helper tool I don't see this "term" at all?! All I see is:

There's no a word on "join", "parent" or any other similar token.

Found it. Token should look like:

[node:field_structural_category:entity:parents]

It appeared (I think) after I changed reference field from multiple to accept only one value.

While it was accepting multiple values I could access first 3 elements, but not their parents. So this option is available only for single value fields. I see that lot of tokens are missing when tag reference field is set to accept multiple values. Bug or feature - can't say.


Add database value in views for entity type user I want to extend the user profile with a rank (a decimal ranging from 500 - 2500), which needs to be updated on a regular basis (10 times per minute) for several users. (it is for http://achtungdiekurve.net/ ) I already implemented it with a seperate table, containing a rank field and implemented a table to show the rankings (http://achtungdiekurve.net/ranks ).

However, I want to use views to create this table. But I cant seem to alter the entity type user in such a way, that it shows Rank in the views forms. How to do this? My current code:

<?php
function achtung_entity_property_info_alter(&$info) {

  $info["user"]["properties"]["rank"] = array(
    "label" => t("Rank"),
    "description" => t("The rank of the user"),
    "type" => "decimal",
    "getter callback" => "achtung_get_entity_callback",
    "computed" => true,
    "entity views field" => true,
    "query callback" => "entity_property_query",
  );
  watchdog("ACHTUNG entity info alter", "
".print_r($info, true)."
");
  return $info;

}
function achtung_get_entity_callback($account, $options, $name, $entity_type) {
  watchdog("ACHTUNG entity info callback", "
".print_r($account, true)."
");
  return 2;
}
?>

Although I haven't had a chance to play with it myself just yet, assuming everything else is implemented correctly, it seems as though using EntityFieldQuery Views Backend as your Views backend should make your new Rank field visible to Views.


how to comment individual image in popup form drupal 7? I have created view to display images and when I click on the image it gets displayed in pop-up form. I want to allow user to comment on image in pop-up form only so i have displayed comment form with php code. But its not working properly. It displaying preview button instead of comment. And when I click on preview it redirects to the image node page which should not be happened. I want it to work properly please help me suggesting solution. Hope image below will help you to understand what actually I have done.

First, in your content type edit page, make the "Preview Before Submit" option disabled or optional. Once you do that you will see the Submit button.

Even you make the Submit button appear, the same will happen and user will be redirected to the actual page with no modal display. From the pattern of your modal window, I guess you are using colorbox plugin. If yes then you need to open this colorbox as an iframe option.

<script>
    $(function () {
        $(".example6").colorbox({iframe:true, innerWidth:425, innerHeight:344});
    })
</script>

So even you submit the page, the page will not be redirected outside of modal.

EDIT #1
Then I think you may have to alter the form you are using and check for form elements with a debug() function. Then I guess in your form_alter you can do the following,

<?php
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['type']) && $form_id == 'mymodule_node_form') {
      // Hide the preview/submit button.
      $form['actions']['preview']['#access'] = FALSE;
  }
}
?>

Have a check on the variable that sets the preview, by

variable_get('comment_preview_' . $node_type);

If it's set then can be disabled via,

variable_set('comment_preview_' . $node_type, DRUPAL_DISABLED);

I hope this will be helpful to your cause.


How do I add a JavaScript file from a module? $form['set_end_date'] = array (
  '#type' => 'date',
  '#title' => t('set end date'),
  '#required' => TRUE,
);

$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('Fetch'),
  '#button_type' => 'primary',
);
return $form;

How do I add a JavaScript file from a module?

You will have to add the js in libraries.yml, like

dirty_forms:
  version: VERSION
  js:
    js/jquery.dirtyforms.js:{}
dirty_forms_ckeditor:
  version: VERSION
  js:
    js/jquery.dirtyforms.ckeditor.js:{}

and then include in the form via

$form['#attached']['library'][] = 'dirty_forms/dirty_forms';


db_update add value to field I want use db_update to update a field,instead of update a field with new value (replace) , I want add a value to last value,
I know I can do it with mysql command

UPDATE `databasename`.`tablename` SET fieldB = fieldB + 1 WHERE fieldA='2';

but I use below code, It is not add to credit field, only replace it with $credit value,
anybody know where is my problem and how can I achieve this job?

$cr_update_no = db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ,'credit' => 'credit'+ $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

The problem is way I used to update,
for this job drupal has syntax, according to  Update query with a dynamic expression in Drupal 7?
I found my solution

$cr_update_no= db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ))
                ->expression('credit', 'credit + :amount', array(':amount' => $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

I submit this answer maybe helpful for another in future.


How to set up a cron job that runs for a specific rule? I have a 2 rules that should run each on a specific time interval instead of the regular cron job setting.
I have a list of "Sessions" (entity type) that should be evaluated to see if their booking has expired, if their starting date is in the past, etc. and then certain settings should be updated  on each.
I have another list of "Events" (entity type) that does something similar but shouldn't be executed with the same frequency as the Sessions.
Both are rules components.
My first problem
These components fire when I force run my cron job with Elysia Cron module and that works. But it should be automatic. So I have assigned the "rules_cron" job to a new channel, "channel 2" and it should run every hour but it doesn't do that. rules_cron apparently runs every 48 hours or so.

My second problem
What I really need is the Session component to run every hour and the Event component to run every 15 minutes?
What am I doing incorrectly and how do I accomplish that?

What I really need is the Session component to run every hour and the Event component to run every 15 minutes?

According to your screenshot, it seems you're only running Cron once a day, so even having a shorter schedule than that will not work unless your Cron runs at those needed intervals.
Re-configure your crontab to run at the shortest interval needed. In your case this will be 15 minutes. The configuration of each of those schedules should still ensure that whichever cron hook is only run at the specified times.


Drupal PHP filter being overwritten in Lexicon Module I've been using the PHP code text format on my Drupal website and I have been encountering a frustrating issue with the Lexicon Module. I bet the answer is dead obvious, but I haven't been able to figure it out.

After I write my PHP code in the appropriate text format (php code) in the Lexicon modules "optional introductory text field", I hit save, and everything displays as it should on the page (great!). Problem is when I go back to make changes, "Full HTML" is selected as the text format and the PHP code has been replaced with HTML. When I then choose PHP Code as the text format, I can see some of the code I wrote (not all) but it's commented out with HTML comments. I know that my PHP code has been converted and replace with HTML not only in the input field because if I hit save again, then there is no PHP script saved - just garbled HTML gets displayed on the page.

Does anyone know how to use the PHP text format and make sure their PHP code actually sticks around if the content type is revisited?  The reason I need to put PHP code in this field is because I want to do a language check of the current user and display text in either English or French.

I have been able to get a fix - but not an ideal one. I moved the PHP text format to be displayed as a first priority at admin/config/content/formats. Doing this preserves the PHP code after hitting save. The reason I say it's not ideal is because now PHP code will be displayed as the default format for making new pieces of content - fine for me, but I'm sure the client will wish they could get their WYSIWYG right away.

If anyone knows a way to target the display order of text formats for just one specific module, I'm sure that would be the solution.


Count the no of people who viewed a particular blog Is there any module that could count the no of people who viewed a particular blog?

Enable the statistics module and using views module create a mini report. Other modules you could use in combination with the statistic module are Visitors module and Counter module


Updating taxonomy terms with vbo and workbench I'm using VBO to bulk update taxonomy terms on my nodes. I'm running into an issue when using workbench that VBO only updates the published revisions, and doesn't touch any of the drafts.

The problem with this is that when there are drafts, the published revision is not the newest revision. So by updating the published revision via VBO, then later publishing a draft, the taxonomy changes done with VBO do not carry forward, since they are part of an older revision.

How do I use VBO to only update the latest revision (whether this is a draft, or published content)?

The basic principle behind using Views to display the latest revision, instead of the published revision, is to base the view on the node_revision table instead of the node table. Unfortunately you cannot change the base table of an existing view, so you'll have to rebuild the entire view showing "Content revisions" instead of "Content".

To display only the current revision, use the filter criteria "Workbench Moderation: Current" on the node_revision table (otherwise all revisions will be displayed). To gain access to fields on the node itself, add a Relationship of "Workbench Moderation: Node" (and then be really careful you don't use this relationship unless you intend to reference the published node).

To avoid a potential security bypass in your view, you should also include the filter criteria "Content access: Access" on the Node relationship.

With all that plumbing out of the way, you should now be able to edit the taxonomy term field on the most recent revision of your nodes using "Content (historical data): [taxonomy field name]".


How can I trigger a Drupal Core action without writing any PHP code? On my D8 site I have configured an action of type "Send email" using the Drupal Core "Actions" module (module can be installed under "Administration > Extend"). I want this Drupal Core action to trigger when a new comment is submitted.

In D7 there was another Drupal Core module named "Trigger" which allowed me to configure the desired trigger. In D8 there's no longer a "Trigger" module, nor can I find any other means to configure any Drupal Core action triggers. In the D8 docs I have found this not-very-helpful paragraph:

  In D7, there are triggers defined, supporting the core Trigger module. This is not supported in D8.

My general question therefore is: How can I configure a D8 site to trigger an action that was defined via the Drupal Core module "Actions" when a certain event occurs? Specifically in my case: How can I trigger a "send email" action when a comment is submitted?

As the title of this question mentions, I don't want to write PHP code to achieve this. I am willing to install a stable third-party module, though, as long as it cooperates with the Drupal Core "Actions" module.

In a wider sense, I am trying to understand what the Drupal Core "Actions" module does. To me, the module seems to be quite useless if as a site admin I cannot configure triggers for its actions.

In your specific case the commment notify module would be helpful.

From description,

  Comment Notify is a lightweight tool to send notification e-mails to visitors about new, published comments on pages where they have commented. Comment Notify works for both registered and anonymous users.

Otherwise is could be done using Rules I think.


hook_form_alter() only firing after cache clear I have a custom module that I'm using to add a Java applet to some of my admin forms. The applet is necessary to get details about the product being entered.

I'm noticing that after 15 minutes (or more) of site inactivity, my hook stops firing. If I clear the cache, the hook begins firing once again. However, this only seems to last 15 minutes or so.

Is it possible there is some admin form caching happening?

Possibly salient details:

I'm using Seven as the admin theme
I'm using D7 with Commerce Kickstart install profile (commerce_kickstart-7.x-1.8)

I think your problem stands in cascading caching logic : your form must be called by something (a block, a template, a function...) that must be itself cached.

What you have to think about is "When, and by who, is my cache warmed up, with which conditions ?" : the most logical answer is that when your cache is created for the first time, conditions in your hook_form_alterare not TRUE.

For example, are you searching, in your alter, for infos coming from the session, or user roles, or static variables...

We could do more with your code :)


How used function drupal_render_children in file twig? I want use function drupal_render_children in file *.html.twig Drupal 8. What solution for do ?

Well, for one, it is deprecated. Two, you cannot use PHP functions directly within the Twig template.

You can implement the appropriate preprocess hook to do this, to pass to Twig as a variable.


Get the invalid URL which throw a 404 I have a catalog of products in one of my website, each year there are new products and some old products are unpublish (never deleted). Some websites put links to the products, so when a product is unpublish, all those referents links becomes invalid and are redirect to a 404 pages.

Now i don't want that, i want a custom redirection to parent category of the product. For that i catch the 404 event, and then i tough i could just make a dbquery on my node items to found the parent's category, and create a redirection.

I catch the 404 in the template.php file like that :

 function myTheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  if (!empty($node)) {
    $headers = drupal_get_headers();
    if (preg_match('@HTTP/1\.[01]\x20+404@', $headers)) {
      //want to do my redirection here

    }
  }

but when i try to get my url, i get in fact the url of the 404 pages but in the url bar, it's still the product url.

So how can i get that url or simply the invalid nid?

My bad, i had one of those blind drupal moment :)

Yes it seem that drupal can't find the url because of the 404 which become the current node, but with some PHP we can still get it.

  $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
  print $pageURL;

[that is not my code, so thank you Google.]


Drupal views show all taxonomy of specified vocabulary I have a taxonomy vocabulary with the followings terms.

Benginner, Intermediate, Advanced.

I want to show a view that show these terms, but one term is associate to node, and I need stand out this term, but show all terms of this vocabulary, try to find the solution and nothing.

All you gotta do is create a view of Taxonomy Terms and use fields

Then use a template file for your view.

In your template file all you gotta do is load your node's taxonomy term field value and compare it the view's taxonomy term name. If it's equal we print the underline <u>.

<?php

    $node = node_load(arg(1));
    $node_term = check_plain($node->field_name[0]['value']);

    if ($fields["name"]->content == $node_term) {
        print '<u>' . $fields["name"]->raw == $node_term . '</u>';
      } else {
        print $fields["name"]->content;
      }

?>


How do i pass 2 values to a view? I have a Drupal View that displays the 2 most recent articles from our db. How do i allow a user to select which article they would like to display. And, if the user does not choose the 2 articles then the 2 most recent will be shown.

I tried to use filters and the "Expose this filter to visitors, to allow them to change it" option. But I cant seem to figure out how this would be done.

Thanks.

I would pass the argument in via the URL, you can pass multiple args in using '+'. So http://example.com/my-view/[nid1]+[nid2]


How to create a view with 1 item in left column and 2 in right column? I need to make a view of featured content. I'd like to make it so that two columns display: the left column with one item, and the right with 2 items. Essentially like this spot:

I've been trying with some different layouts, but for some reason this is escaping me. It can't be that hard, can it?

EDIT: I may not have been clear enough in my original post. The answers given so far seem to refer to formatting the fields in different positions, so that for each piece of content, field A would be on the left, and fields B and C on the right. That is not what I need.

What I need is instead of displaying three fields in this format, I need to display three pieces of content in this format. For this view, each image links to a different piece of content, so I'm only using a single field. I need to display the image for node A on the left, and images for nodes B and C on the right.

If you are having panels module installed than the best would be to use the Panels fields as following:

Set the display style in your View to show Panel Fields.
Add the fields you want to show in your view.
Configure the settings of Panel fields as:

Select Panel layout: Two column stacked
Assign fields to the respective section (e.g: top, right, left), as per your requirement.

Save the view.

Check the attached screenshot for reference:


Is there any possibility to migrate translations from Drupal 5 based project to Drupal 7 project? I have a legacy Drupal 5 project which is currently moved to a newer Drupal 7 platform, but the old project also contains a lot of custom translation sets. So I am wondering if there is any possibility to migrate those translations to the new project?

Solution: There is a build-in possibility to export translation strings for each language into .po files in Drupal 5 projects as well. Export form is available under the "admin/settings/locale/language/export" admin menu.


Imagecache_external: Thumbnails of external URLs aren't accessible Modules:

Imagecache External, Media, Remote Stream Wrapper

Scenario:

I created a content type, in which I want to collect Movie Actors. My aim is to add images of those actors which arent hosted on my drupal site itself. They are being linked via Remote Stream Wrapper but RSW doesnt allow to use Image Styles on those external images (for example thumbnails). The solution is Imagecache External, which allow Image Styles even on external hosted images.

Problem:

Imagecache External returns Image-URLs which ends with a cryptic snippet, which resolves into an error message: Access denied

  localhost/drupal/sites/default/files/styles/cover/http/img4.picload.org/image/acdcwwi/imagestyle_examp.png%3Fitok%3DAyQfRnDQ

Thumbnails are being saved in a directory, which represents the URL of the external image:

  drupal\sites\default\files\styles\cover\http\img4.picload.org\image\acdcwwi\imagestyle_examp.png

Detailed Problem Description:

Imagecache External creates thumbnails with such URLs:

  localhost/drupal/sites/default/files/styles/cover/http/img4.picload.org/image/acdcwwi/imagestyle_examp.png%3Fitok%3DAyQfRnDQ

If I open this URL directly, I get an "Access Denied" error because I dont have permission for that page (-> even as an admin!?). If I remove this cryptic snippet at the end of the URL (%3Fitok%3DAyQfRnDQ), the Thumbnail is accessible.

The other problem is that the thumbnails are saved in a directory, which is equal to the external URL:

  drupal\sites\default\files\styles\cover\http\img4.picload.org\image\acdcwwi\imagestyle_examp.png

This will result in a not overviewable directory tree.

The external image I linked externally for example is this one:
http://img4.picload.org/image/acdcwwi/imagestyle_examp.png

I hope anybody has a solution to my problem. :-/

Greetings,
KG

I think it is a bug in imagecache external when there are special characters in the URL. Try to file an issue on the module queue on drupal.org to see.

About the "cryptic" end, it's http://drupal.org/node/1934498.


Cannot log in in to my site I am having some problems when I try to log in to my drupal site. When I visit http://mysite/user, i am getting redirect to the login page and in my url appears something like this:

user?name=user&pass=111111&form_build_id=form-iCrzIe6KBq1g5MoA3z0JeBI98QU8q2f-FvfcIcp3Cvk&form_id=user_login&op=Log+in

I'm trying to find the problem, but I don't know what to do.

When i restore the site(from my last backup) i can do the login, but when i restart my machine, the problem comes back.

I hope you could give me a hand with this problem.

Regards

I would check /sites/default/settings.php and look into your $cookie_domain = setting - does it match your domain?


Export user profile fields in pdf I`m using Drupal 7 and i have added some extra fields in People > Account Settings.

What I`m trying to accomplish is to give logged in user link ( in sidebar block ) to export those fields into .pdf

I created a view with all user fields and i found module called Views Data Export

But unfortunately it does not support PDF. Is there any other way/module to do this?

To answer myself here.

There is a module Views PDF that does the job. Not sure how i missed it earlier...


Drupal Commerce Total Order Weight I am writing a custom module to add surcharge values to a commerce order at the time of UPS shipping calculations. I am trying to find a way to access the total weight of the order.

I thought I would be able to access the weight from the array returned by:

entity_metadata_wrapper('commerce_order', $order);

Unfortunately it's not present in the data that I can see.

Does anyone know how I can access the total weight of an order or are these generated dynamically when the UPS shipping process is called?

I believe it is generated when it's needed, and not stored. But, after looking at the Commerce Order Weight Token module, you can get the weight using the following:

$weight = commerce_physical_order_weight($order);


How to hide certain fields on the User Edit form? So I have three types of users - admin, LA admin and users.
I am trying to set it up so that admins and LA admins cannot edit the username, password and timezone for users. I am talking about the default user edit form for admins and the form ID is "user-profile-form".

I have created a custom module but this doesn't seem to be working. Any idea what I might be doing wrong?

Even the var_dump does not seem to be outputting. I have cleared the cache and verified that the module is enabled.

function profile_change_form_alter(&$form, $form_state, $form_id) {
    if ($form_id === 'user-profile-form') {
    // Use var_dump  to dump the $form array to see the fields.
        var_dump ($form);

        hide($form['account']['pass']);
        hide($form['account']['current_pass_required_values']);
        hide($form['account']['current_pass']);
    }
}

You need to replace form id user-profile-form with user_profile_form

Your code should look like the following:

function profile_change_form_alter(&$form, &$form_state, $form_id) {
    // changed form id
    if ($form_id === 'user_profile_form') {
        // Use var_dump  to dump the $form array to see the fields.
        var_dump ($form);

        hide($form['account']['pass']);
        hide($form['account']['current_pass_required_values']);
        hide($form['account']['current_pass']);
    }
}


How do I add a hash link in menus? Is there a way to add a hashed link in the menu under drupal menu to just make a menu item that jumps down to an anchor or id on the page?

Unfortunately as far as I am aware, Drupal cannot do this out of the box. However, you can use the Special menu items module to create a new menu item, and place "nolink" in the path settings.


How to resolve error with drupal commerce 2 installation via composer I am following the instructions at http://docs.drupalcommerce.org/v2/getting-started/install.html

After providing the  console command for a new installation, console starts to download the various requirements, but before completion, returns the following error.

  Failed to execute git checkout '879356bbf75608f86d8fb89d76a21dc1e99a39ae' -- && git reset --hard '879356bbf75608f86d8fb89d76a21dc1e99a39ae' --
    fatal: Not a git repository (or any of the parent directories): .git

I have read elsewhere that I need to initialise a git repo first? Not sure if I am missing something or whether the documentation is incomplete. I assumed it was a one line command.

What am I doing wrong and how do I resolve this?

I am not a very advanced user and intend to use Acquia Dev Desktop as working environment.

Further to the above, I went on to try creating the MYSITE directory first and then ran git init from within this folder. I then ran the composer commands for a full install, and then received another error as below.

  [InvalidArgumentException]
  Project directory commerce8/ is not empty.

This turned out to be a problem of running composer through Acquia Dev Desktop's terminal launcher.

When using native terminal the installation completes without issue.


Assigning css class to a particular block I want to add a CSS class to a particular block. I am using the module Block Class for it as shown in block_class module. I am able to enable the module and assign the class by going to structures/block/configure. I am facing problem in where to add the php snippet. I am using a Zen starter kit theme and have copied the block.tpl.php from Zen/templates to my theme/templates and added the lines as specified...

Here's what my code looks like:

Before:

<div id="<?php print $block_html_id; ?>"
class="<?php print $classes;   ?>"
<?php print $attributes; ?>>

After:

<div id="<?php print $block_html_id; ?>"
class="<?php print $classes; ?> **<?php print block_class($block);** ?>"
<?php print $attributes; ?>>

As far as I know, you don't have to add any code to use the class you set on structure/block/configure. The class should be automatically added to $classes array.


How to alter/hide the label of the input element in form (create/edit)? We can theme the label of any field in tpl or even simply by changing the manage display option but wondering how to do the same in form (while creating or editing a content) ?

I'm looking for the proper way to alter/hide the label especially with field collection fields when the content is created or edited.

You can do this with hook_form_alter() or hook_form_FORM_ID_alter() in your custom module or also in your theme's template.php file.

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form_id
  if ($form_id == 'YOUR_FORM_ID') {
    // To hide the label
    $form['your_form_element']['#title_display'] = 'invisible';
    // To alter the label
    $form['your_form_element']['#title'] = t('Your new title');
  }
}

If you use hook_form_FORM_ID_alter() instead, you don't need to check the form_id.

You can find more information on the Form API Reference for the #title and #title_display attributes, and also all the other form elements and their attributes.

In case of Field Collection, it can be a bit complicated. Below is an example code:

function YOURMODULE_form_YOUR_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $your_field_collection = element_children($form['your_field_collection'][LANGUAGE_NONE];
  foreach ($your_field_collection as $key => $value) {
    if (is_numeric($value)) {
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title'] = t('Your new title');
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title_display'] = 'invisible';
    }
  }
}

Explanation of the above code:

First I assigned the field collection itself to a variable, to make it a bit readable. I used LANGUAGE_NONE for simplicity but a better practice would be to use $form['your_field_collection']['#language'], admittedly it makes the whole code more complicated to read.

Second, I used a foreach, since most of the time we use a field collection if we want to have multiple values of some collection of fields. So the foreach loop would take care of all instances of the field collection.

Third hack, is a dirty trick I learned from someone on Drupal.org, maybe there would be a better approach, but it just works so I didn't dig into. I check if the $value is numeric, to exclude all other meta attributes and loop only through the elements.

Then, finally, in each element I alter the field in the field collection.


How to force migrations to not copy files I have a migration with an image field and the files already exist on the server where I want them.

There is a file, some_file.jpg that already exists at sites/default/files/some_file.jpg but when I run the migration, it tries to copy the file from sites/default/files/some_file.jpg to sites/default/files/node_type/some_file.jpg and then also creates another file entity for it.  I just want it to re-use the file and file entity that already exist for it.  The destination field type is an image field.

I have this on the field mapping for the file field:

$this->addFieldMapping('field_upload_image', 'field_res_upload_photo');
$this->addFieldMapping('field_upload_image:preserve_files')
     ->defaultValue(TRUE);
$this->addFieldMapping('field_upload_image:file_replace')
     ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

Well if thats not working do a scan for the file on the destination location to set or unset the field value (so it's not updated on save). You can do this in the prepare function of your migration class. See the commonly implemented migration methods page for example implementations.

Also have you tried setting the preserved_files key:

    $this->addFieldMapping('field_images:preserve_files')
  ->defaultValue(TRUE);

I haven't done any file migrations myself lately, but I stumbled across that in this thread: https://www.drupal.org/node/1886404  it looks like you got the field ordering correct (well from the issue the source field primary and sub-field ordering now no longer matters).


drush handling array variable values I am using Drupal 7 and drush 7.4.0. How do I handle array variables with drush?

For example, I have a variable, social_sharing, for which

drush vget social_sharing

Produces:

facebook: facebook
google_plus: google_plus
linkedin: linkedin
twitter: twitter
pininterest: pininterest

Using a drush command,

How can I get the value of only facebook using drush vget?
How can I delete one specific variable? for example if I want to remove google_plus from the list using drush vdel?

Step 1. Get the value of only facebook

drush ev '$v=variable_get("social_sharing"); print $v["facebook"]; print PHP_EOL';

Step 2. Remove google_plus from the list

drush ev '$v=variable_get("social_sharing"); unset($v["google_plus"]); variable_set("social_sharing", $v);'


How to add a custom antispam questions in User registration Form Recently I am receiving some user registration Spams...I use reCaptcha module but I want to add a anti-spam questions while User registers registration as you see in many forum sites.

Does anybody know how to do that ?...is there any module ..?

You can also customize captcha by the CAPTCHA Pack module. Here is a quote about it (from the module's project page):

  ... contains several CAPTCHA types for use with the CAPTCHA module. The CAPTCHA Pack module is meant to provide lightweight, yet effective alternatives for the traditional image CAPTCHA, which is undesirable in certain situation (e.g. bandwidth restrictions, cpu restrictions, accessibility constraints, etc).


Change content types Is it possible to change node content types? I have a bunch of story nodes and I would like to create several content types and reassign each story to a different content type. Is there a way to automate this either through the drupal administration area or the database?

Thanks!
Jane

It is possible with Node Convert.

  Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability of converting the node from it's current node type, to another node type. Also it gives the ability of transfering all the custom cck field values of the current node type, to the destination cck fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accesed in Administer-> Content -> Convert Nodes.


Undefined property error in custom module I am getting errors on specific pages of my drupal site pointing specifically to this line..

if (is_object($argument) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {

what could be the problem? Here's the complete error and function.

Notice: Undefined property: stdClass::$type in custommodule_menu_local_tasks_alter().

function custommodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if (($value['#link']['path'] == 'node/%/edit'||'node/%/view') && (!user_access('administer nodes'))){
          unset($data['tabs'][0]['output'][$key]);
        }
      }
    }
  }
}

Edit:
There are similar error in following line..

foreach ($data['tabs'][0]['output'] as $key => $value) {

--Notice: Undefined offset: 0 in custommodule_menu_local_tasks_alter() (line 59 of...)
--Warning: Invalid argument supplied for foreach() in custommodule_menu_local_tasks_alter() (line 59 of ...).

Most likely  $router_item['page_arguments'][$key]->type is undefined.

Try with :

if (is_object($argument) && isset($router_item['page_arguments'][$key]->type) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {

Same thing for that foreach loop. Just add an if isset() before that loop and you'll be ok.

if (isset($data['tabs'][0]['output']) ) {
    foreach ($data['tabs'][0]['output'] as $key => $value) {
        ....


Features Hook after successfull import I wrote a feature module that contains content types and test nodes. After importing those nodes, a certain cache has to be rebuild.

Both hooks I know (hook_install() and hook_enable()) are called before the import happens.
Is there any hook that is executed only once after the feature import is done?

It depends on how the nodes are imported really. You should be able to use hook_modules_enabled which is the last hook invoked when a module is installed and enabled. You might need to tweak your module weight to make sure it's invoked after the import of the nodes.


Functional tests performance In Drupal 8, I am creating functional tests extending the BrowserTestBase class.

Launching a test though (even an empty one) requires about 2-3 minutes.

Is this normal, is it there a way to speed up the functional tests?

Do not use standard (as you said in a comment).

Use testing and then create only what you need in the test. That's the main thing to speed up your tests.

They are still rather slow, but that should help.

Another thing to consider is to avoid having many test methods. Each runs in a completely new, isolated environment. A trick that is often used is to have a single testAll() method and many doTestSomething() methods, then they are faster by almost factor count(test methods), since set up is usually by far the slowest part.

You can also run tests in parallel with --concurrency 8 (nummber of cpus is a pretty good value for concurrency)


Drupal 7 Views 3.13 Filter groups returns nothing if one group is empty I have a need to display a block with nodes from different content types.  The content types contain different fields, and I would like to filter based on different criteria of each type.  I had hoped to use the grouping function of Filter Criteria, but it's not operating as expected.

I am using two content types, Article and Career.  Career has a Status field, which indicates if the career posting is open or closed.  The filter criteria I have designed looks like:

Each part on it's own works as expected..  so if I remove "OR (Career AND Open)", I get a list of articles that meet the criteria.  Conversely, if I remove "(Article AND Published AND Promoted) OR", I get open careers.

Together, I get the result of the 2nd group - I only get open Careers, and no Articles.

If it matters (not sure that it does .. ?), the fields I'm displaying are the node title, and two custom fields that are common to both content types.

Help please?

I think this is a bug/changed behavour in views introduced a long time ago.

A workaround might be to select the Reduce duplicates checkbox from one of the fields in OR group filter - which will transform your query to LEFT JOIN instead of INNER JOIN.

I found the solution here:
https://www.drupal.org/node/1766338#comment-6973984

It worked for me in Views 7.x-3.13


Create a new page of particular content type and make it home page during drupal installation I am building a installation profile. I want to create a page of particular content type and make it as front page during drupal installation. How do i do this?

You should do it in the same way as in common module. Your code will be in files YOURPROFILE.install and YOURPROFILE.profile.
You can see, for example, how new content type “Article” created in Standard profile. To set front page programmatically you can easily call variable_set('site_frontpage', $path);

If I needed to create this functionality, I would create a content type, a view and a Feature with my content type and view. Then I would add Views, Features and my Feature module in dependencies. So I wouldn't write any PHP code in my profile except maybe setting front page.

Other way is to create your own module with your own hook_menu(), page callback and all the staff you need. Then again you should add this module in profile dependencies.
Modules from dependencies can be placed in profile folder or downloaded manually to sites/all folder.
Of course, you can add all the code from such module to YOURPROFILE.profile and it will work, but I think it can be difficult for support.

Reading:

How to Write a Drupal 7 Installation Profile
Drush Make theory for happy profile development


Why are there 2 ways to handle configuration? In Drupal when we are working with read-only config we use

$page_cache = \Drupal::config('system.performance')->get('cache.page');

Why this static call for read-only object?

and when we use working with a config where both read and write is possible. we use this service 'config.factory'

$config = \Drupal::service('config.factory')->getEditable('system.performance');
$config->set('cache.page', ['enabled' => 1, 'max_age' => 5]);

what leads to this design?

This change record explains it all: Configuration objects by default are immutable.

  ConfigFactoryInterface::get() no longer returns configuration
  objects that can be saved. This is to ensure that configuration
  overrides do not get into active configuration. Configuration
  overrides are, for example, global overrides set in settings.php or
  translations provided by the locale module. If you need to get a
  configuration object that can be saved, use
  ConfigFactoryInterface::getEditable(). Objects returned by that
  method will not have overrides applied.

  Previously

// Just get the site name (with overrides).
$site_name = \Drupal::config('system.site')->get('name');

// Set the site name.
\Drupal::config('system.site')->set('name', 'My fantastic site')->save();

  Now

// Just get the site name (with overrides, same as before).
$site_name = \Drupal::config('system.site')->get('name');

// Set the site name.
\Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();

Are you also/alternatively asking why there's a Drupal::config method, but not a Drupal::configFactory method, i.e. why do you have to use the generic Drupal::service method for the second one?

If so, that's simply because the shortcut methods exposed on the Drupal class are for the most regularly used services. The config service is used in procedural code a lot more than config.factory, so there's no shortcut method for it. There are hundreds (thousands?) of services throughout the system so providing a method for each would be overkill


How does the #submit property works with #ajax? I'm having trouble understanding how works the #submit property of a submit element in Drupal 8, when Ajax is used.

I found this code, as an example of how to implement ajax buttons which add or remove items to/from a form : https://gist.github.com/leymannx/72d41cf0baa4dee62d6ddc89bc7c7a5a

The "add item" submit button in the form is described by the code below :

$form['container']['actions']['add_item'] = [
  '#type'   => 'submit',
  '#value'  => $this->t('Add another name'),
  '#submit' => ['::MYMODULE_MYFORM_add_item'],
  '#ajax'   => [
    // Could also use [ $this, 'colorCallback'].
    'callback' => '::MYMODULE_MYFORM_ajax_callback',
    'wrapper'  => 'my-container', // CHECK THIS ID
  ],
];

There are 2 callback functions used here : the value of the #submit property and the value of callback in the #ajax property.

What happens exactly when the user clicks on the button ?
As I understand it, MYMODULE_MYFORM_add_item function is first called, then MYMODULE_MYFORM_ajax_callback function.

But, in a custom module, I'm currently doing something like this :

// Implementation of hook_form_FORM_ID_alter(), to customize the user register form
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    // Add a "Fill username" button
    $form['account']['fill_username'] = array(
        '#type' => 'submit',
        '#value' => t('Fill username with Bob'),
        '#weight' => -1,
        '#submit' => ['mymodule_fill_username_submit'],
        '#ajax' => array(
            'callback' => 'mymodule_fill_username_callback',
            'wrapper' => 'edit-account'
        )
    );
}

// #submit function of the button
function mymodule_fill_username_submit( $form, FormStateInterface &$form_state ){
    \Drupal::logger('mymodule')->notice('mymodule_fill_username_submit');
    $form_state->setValue('name', 'Bob');
    $form_state->setRebuild( true );
}

// callback function of the button
function mymodule_fill_username_callback( $form, FormStateInterface &$form_state ){
    \Drupal::logger('mymodule')->notice('mymodule_fill_username_callback');
    return $form['account'];
}

The aim is to inject a value in the "Username" field, just to try and understand how this works.

As I click on the button, mymodule_fill_username_callback is called (I see the log) but mymodule_fill_username_submit never. And, of course, the field is not filled at all...

I don't understand what happens here. Nor how it's supposed to work.

Can anybody help ?

I don't think its good idea to handle form submission using the submit_form function in case of AJAX form. All the form submission logic should be handled in AJAX callback only.
https://drupalabc.xyz/question/how-handle-form-submission-using-ajax-drupal-8

The following link has a running example of AJAX form submission in Drupal 8. I hope this helps.
Thanks.


Change Classes in Nav-Tag of Custom Menu On a Drupal 8 installation, I have a menu in the sidebar first region. I want to add classes to bootstrap classes to the different levels of that menu. For that I created a my own menu template, which looks like this:

{#
/**
 * @file
 * Theme override to display a menu.
 */
#}

{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0, my_menu) }} {# 1. #}

{% macro menu_links(items, attributes, menu_level, my_menu) %} {# 1. #}
    {% import _self as menus %}
    {# 1. #}
    {%
    set menu_classes = [
    'navbar-nav', 'mr-auto' ~ my_menu|clean_class,
    ]
    %}
    {# 1. #}
    {%
    set submenu_classes = [
    'navbar-nav', 'mr-auto' ~ my_menu|clean_class,
    ]
    %}
    {% if items %}
        {% if menu_level == 0 %}

 {# 1. #}
        {% else %}

 {# 1. #}
        {% endif %}
        {% for item in items %}
            {# 1. #}
            {%
            set item_classes = [
            'nav-item' ~ my_menu|clean_class,
            item.is_expanded ? 'expanded' ~ my_menu|clean_class,
            item.is_collapsed ? 'collapsed' ~ my_menu|clean_class,
            item.in_active_trail ? 'trail' ~ my_menu|clean_class,
            ]
            %}
            {# 1. #}
            {%
            set link_classes = [
            'nav-link' ~ my_menu|clean_class,
            ]
            %}

{# 1. #}
                {# 1. #}
                {{
                link(
                item.title,
                item.url,
                item.attributes.removeClass(item_classes).addClass(link_classes)
                )
                }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1, my_menu) }} {# 1. #}
                {% endif %}

        {% endfor %}
        {% if menu_level == 0 %}

        {% else %}

        {% endif %}

    {% endif %}
{% endmacro %}

This works fine. However, I also need to change the classes of the nav tag. I can't seem to figure out, how that can be done and I can't find any information anywhere explaining this. So how do I change the nav tag classes of that menu?

In the end I want it to be a bootstrap offcanvas menu like this one:
https://getbootstrap.com/docs/4.0/examples/offcanvas/

But I just can't seem to change the nav tag classes, since I don't know how.

You'll need to enable Twig template debugging output to do this. Once you do that you should see a number of template suggestions upward in the DOM for the <nav> tag. For example:

   * block--mainnavigation.html.twig
   * block--system-menu-block--main.html.twig
   * block--system-menu-block.html.twig
   * block--system.html.twig
   x block.html.twig

(Note this assumes you are using Drupal's block system to render the menu.) Above are a number of suggestions. If I look in a likely candidate from above, for example, block--system-menu-block.html.twig, I see markup like this:

<nav role="navigation" aria-labelledby="{{ heading_id }}"{{ attributes|without('role', 'aria-labelledby') }}>

You can grab any of these templates from core and then override by using a copy of the template in your theme and then alter the markup per your requirements.

If you are using Twig Tweak to render the menu, then in that case, you can just add your own custom <nav> tag like so, usually in a page template such as page.html.twig:

  <nav role="navigation" aria-labelledby="off-canvas-menu" class="main-menu" id="off-canvas-menu">
    {{ drupal_menu('main', 1, 4, TRUE) }}
  </nav>


Modify template.php for custom HTML It was suggested the below script in template.php might work to assist in creating a modified HTML page.

<?php
function YOUTHEME_preprocess_html (&$vars) {
if (module_exists('path')) {
$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
if ($alias != $_GET['q']) {
$template_filename = 'html';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '__' . $path_part;
$vars['theme_hook_suggestions'][] = $template_filename;
      }
    }
  }
}
?>

I tried it but broke my site. Do I need to copy just the code minus the php brackets? Use my exact subtheme name to replace YOURTHEME and then create my html--foo.tpl.php to correspond?

you can try function themeName_preprocess_page(&$vars, $hook) to override theme theme_hook_suggestions.  More detail you will find here.


Having trouble POSTing value for a select element with SimpleTest I am trying to write a SimpleTest for a form that already exists. The form passes tests for GET, valid HTML and having the select element, which looks like this:

<select id="edit-buid" name="buid" class="form-select">
  <option value="1">New Business Unit</option>
</select>

The relevant code from my test case is:

$this->drupalGet('path/to/form');
$this->assertFieldByName('buid', NULL, 'form has buid field');

$edit = array(
  'buid' => 1,
);

$this->drupalPost('path/to/form', $edit, t('Save'));

I have tried passing the string "1" and array(1) and array("1") as well, but the test always fails with:

"Failed to set field buid to 1"

How can I make the test pass with the correct option selected?

After talking this through, I realized that I had not created the database records necessary to fill the select element in the test case. So, during the test, there actually was no <option value="1">. The lesson is to think carefully about the entire context when writing test cases.


What is your way to get the fields information when using Services 3 I have a registration form with 50+ input fields. What is the best way to get form filed information to pass it to iPhone or Android developers to make a form in the mobile app?

Currently i am doing something like inspect the form with firebug and copy/paste the form to make this work.

Recently i have written some code to get the form field information.

This is the idea.

In the hook_formalter add a $form['#after_build'][]
Get the keys in $form['#after_build'][] and get the basic information.
Render the information to a item and add it to form so that i can copy/paste

But its not perfect; when the form fields like add custom modules for Registration like Logintoboggan etc i am not getting expected results.

What is your way to do it?

This is the result i expect in case of a select field

  Array
         (
                [Title] => Marital Status
                [Field Name] => field_marital_status[und]
                [Type] => select
                [Options] => Array
                    (
                     [151] => Status
                     [154] => -Divorced
                     [155] => -Married
                     [153] => -Never married before
                     [157] => -Separated
                     [156] => -Widowed

                    )

       )

As @Clive has suggested in comment its best to write your own service resource for this.

Approach 1:

But i wouldn't bother to programaticality supply the form field values anymore.  Reason being, its usually not cost-effective to spend enough hours trying to figure out every possible field type that has been implemented or may be implemented in the future.

Instead create an API documentation. The implementation details is the liberty of IPad / Android dudes. Make sure you enable version control over the docs and also maintain a well documented change logs.

Approach 2:

If you do want to supply the form field information via services.

Then create a resource action.

Something like www.mysite.com/your-endpoint-name/your-resource-name/get-form

This action should be responsible to provide the field details.

This could be done by calling drupal_get_form($form_id); and then passing the $form array through a function that would filter out lots of unnecessary data which drupal adds.

Please note that the main difference here is "We are removing unwanted data from the form definitions" instead of "adding necessary field data".  Thus it will help reducing missing fields that might be added later by some modules in to the form.

After you are done with removing you may add additinal information into the form array like API interface Version, timestamp, and some default values that maybe useful for the Ipad/android dudes.


How to get unpublished date of a node? Is there a way to get the unpublished date of a node? I want the date of unpublishing of nodes to be displayed in the view in a grid.

I need it non-programmatically (ie, tweaking the UI), but if it is only available programmatically, then how do I display it in the grid view?

A total Drupal noob here. I am using D7 btw.

Create a View (using the Views module) that shows Content and displays a Grid of fields in Display format. Add the field Updated datein the list of Fields. Be sure to select Published: No in the Filter Criteria. You can add other fields if you want (e.g. Title). This will get you the date of the last update. If the node is not edited after being unpublished, the unpublished date will be the last update.

EDIT:
If you specifically want to show the unpublished date, I am not aware of a module for this. I suggest another approach that is a bit circuitous, but it works. It involves creating a date field to store the unpublished date, and using Rules to set it when the node is unpublished.

Download the following modules: Date and Rules.
Edit your Content Type. Create a date field
Create a Rule that reacts to After updating existing content of type XX. Add a condition node:status equals unpublished
The Action should be set the date field value to now

That's it. Now, if you want to hide the date field in the node edit form or display, you can play around with your theme's CSS classes or explore other modules. Let me know if you have questions


Rate/VotingAPI - Add class to button if user has voted I want to add a class to a button after the user has voted to display another picture.

This was posted here as a solution for Drupal 6.

<?php
  // Print all rate buttons
  foreach ($links as $link) {
    if ($results['user_vote'] == $link['value']) {
      // user has voted
      $class = 'voted';
    }
    else {
      // user has not voted
      $class = 'not-voted';
    }
    print theme('rate_button', $link['text'], $link['href'], $class);
  }
?>

I couldn't get it to work, so I assumed that I had to convert it to D7 first. However, I have no skills of converting code, so a little help would be nice.

This change will only work for "Thumbs up" widget. You can place this code in your template.php under your custom theme or in a custom module.

function MODULE_NAME_OR_TEMPLATE_NAME_process_rate_template_thumbs_up(&$variables) {
  extract($variables);

  $classes = 'rate-thumbs-up-btn-up';

  if (isset($results['user_vote']) && $results['user_vote'] == $links[0]['value']) {
    $classes .= ' user-voted';
  } else {
    $classes .= ' user-not-voted';
  }

  $variables['up_button'] = theme('rate_button', array('text' => $links[0]['text'], 'href' => $links[0]['href'], 'class' => $classes));
}

Make sure to replace MODULE_NAME_OR_TEMPLATE_NAME with an actual template name or module name.


Change teaser image size I've noticed that the article images are sized to a width of 220px to be displayed in the teaser on the frontpage in Drupal 8. I'm wondering how to change that to 300px, for example.

I created an image style with the size I want with the image module at admin/config/media/image-styles, but how do I associate that with the teaser that's shown on the home page? I looked in the Frontpage view, but didn't see any way of editing the image style there.

What's the best way to do this?

This is in the view mode "teaser" of the content type "article":

/admin/structure/types/manage/article/display/teaser

Go there and click on the setting symbol in the field "image" and choose the new image style.