How to get one time login for all the users? I want to send one time login for all the users, So I am using drush uli and getting link like:

  http://html/user/reset/1/1509979615/VBPx_FMfKeJUEt1moVcsSQGUMX_tFUSYEdEfRlmq7eA

So if the user 5 wants to use one time login, this will be used for only the user 1, right? Basically I want to set one time login for all the users.

How do I pass this URL in Drupal 8?

I just wanna know that how could use this in forgot password mail.

drush

To get one-time login for the specific user, use this syntax:

drush uli <user>

Where <user> is either uid (e.g. 5), user name, or email address for the user.

To get one-time login URL for multiple users or all, you need to run drush in the loop, e.g.

for uid in $(drush sqlq "SELECT uid FROM users"); do drush uli $uid; done

Run drush help uli for help with syntax.

To correct your http://html part, add -l http://example.com parameter, or set your $base_url in your settings file.

Custom code

If you're interested in sending one-time login via e-mail using Drupal, you can use user_pass_reset_url() function in your custom code.

  Generates a unique URL for a user to login and reset their password.

Contrib module

Or use Login one time module (for D8, check this issue).

  Login one time provides the ability to email one-time login links to users.


Drupal Commerce - Reference Product in another product I am building a Drupal Commerce based site and now I am facing the following issue.

I have created some T-Shirt Products like,

T-Shirt (White)
T-Shirt (Black)
T-Shirt (Blue)

And also created a product display called "Shirts". In that product display I created a new node "T-Shirt". Since The "size" is an attribute to the product type so I am having a select box to select the color while viewing the "T-Shirt" content.

But the problem comes here. As per my need, if the user selects "Color - White" while viewing
the product display, we need to add another product "Blue-Jeans" to it. So that means, White Shirt and Blue Jeans will go together in cart if selected.

I am using inline_entity_form to reference products in a Product display (Same as Commerce Kickstart Demo "Tops" product display). How can I achieve this functionality?

What you are looking for is bundling of products.

Take a look at Commerce Product Bundle Module

The project page says

  You can define products that consists of other products. They are all
  combined in one add to cart form. The form works like the core add to
  cart form with all the fancy selection and ajax magic. So the
  customers can make their selections as usual. The difference is, that
  the products from mulitple reference fields were presented on one add
  to cart form.


How to migrate from using the Taxonomy Access Control module to the Group module? We have a Drupal 6 site, and we are making use of the Taxonomy Access Control (=TAC) module for access control. We evaluated the migration steps, and even if TAC could be ported to 8, maybe we could use a different approach.

We are evaluating Group as an alternative to content access control, but there are no automatic path to migrate from (as now). What would be the preferred migration path for TAC to Group?

My recommendation: go for such replacement. In doing so, you could use the approach detailed in How to bulk assign content to a group. This community documentation page explains how you can use the Rules module together with the VBO module to bulk-assigning existing content to groups.

Here is the Rules Component included in that page (in Rules export format):

{ "rules_assign_a_node_to_a_group" : {
    "LABEL" : "Assign a node to a group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "group" : { "label" : "Group", "type" : "group" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:group" ], "value" : [ "group" ] } } ]
  }
}

Refer to the community page mentioned above for more details.

PS: the above rule assumes your migration target is D7 (there is no stable Rules release for D8 yet ...). But by using the Group module you're in very good shape also to later on upgrade to D8 also, since this module supports both releases.


Is this the correct way to complete aliases.drushrc.php in order to avoid messing with other accounts? I´ve read many questions about drush in a multisite configuration. This case isn't a multisite, but several different installations in a single VPS. Something like a reseller account. They are all my sites, but I don't want to mess them up. I need drush commands to be applied to a single site each time.

I´ve installed drush using my root access, under home/root/drush.
So when I try to access ssh using one of my site´s credentials (not the root user, but one of the site´s admin), it doesn´t recognize drush commands.

Should I install drush in every single account, right outside /public_html, or should I edit the .bashrc file in any way? And in that case, how may I prevent the commands to affect other sites when I try to do something with a single specific installation?

I'm using Drupal 7 and Drush 5.x because of my php version (5.2.17).

I understand that I should have (inside the drush folder?) a file called aliases.drushrc.php, with something like this.

$aliases['site1'] = array(
    'uri' => 'mysite1.com',
    'root' => '/home/site1username/public_html',
    'remote-user' => 'site1username',
  );
$aliases['site2'] = array(
    'uri' => 'mysite2.com',
    'root' => '/home/site2username/public_html',
    'remote-user' => 'site2username',
  );

Is this correct? And how may I access drush only to a specific site?

"when I try to access ssh using one of my site´s credentials (not the
  root user, but one of the site´s admin), it doesn´t recognize drush
  commands."

The only requirements for using Drush from another user (than the one that installed it) is a) the drush directory should be readable, and b) drush should be in your PATH.

It is okay to install Drush once per user.  I use a custom move-in script to accomplish this, but in my case it's rare for me to have more than one Drush-using user on one system.  Setting the PATH in your bashrc to include the Drush directory of the root user is also fine.  [Aside: it is best to avoid calling Drush using the root user, for security's sake.  Any Drupal module can define code that runs during the execution of any Drush command.]

You aliases file looks okay, except that you only need to define remote-user for remote aliases.  The aliases you are defining are local, so remote-user will be ignored.  The alias file should go in the ~/.drush directory (inside the home directory of the user that is calling Drush).

You can download the Drush chapter of DGD7 for free; it is one of the book's sample chapters.  It does a pretty good job at describing alias files and configuration.  Although it was written for Drush 4, most of what it describes is unchanged in Drush 6 and Drush 7.  Be sure to also read all of the Drush README.

Update: Forgot to mention: to use your aliases, type drush @site1 status.  If your settings.php file is in a folder called default, then you may also access your site via cd /home/site1username/public_html && drush status.


Comments filter by Last in Twig I try to render the last comment  from a list of comments.

I try {{ comments|last }} ---> no result.

Then {{ comments|reverse }} ---> this render them

Then {{ comments|reverse|first }} ---> no result

The above part is  solved.See anser 1. Pls if annyone have a solution for rendering the last comment in views.

I like to achieve the same in a view. There is a relation filter that output the last comment. But I think I do something wrong.

The last item in comments is the pager, which you have to remove first to get to the last comment. Then you can build a new render array with the single comment and the pre-render callback:

{% set last_comment = comments|without('pager')|last %}
{% set pre_render = comments['#pre_render'] %}
{% set last_comment_build = { '#pre_render': pre_render, '0': last_comment } %}
{{ last_comment_build }}


How to resolve 'Fields pending deletion' and force deletion of said field? I'm stuck with an uninstallable module. Drupal insists that there are Fields pending deletion and that the module can not be uninstalled. I've run cron zillion times already as advised for such situations but without success. Cron runs fine, but drupal insists that still, Fields pending deletion.

Visiting /admin/reports/fields gives no clues - the fields provided by that module are not listed. I even tried using drupal console to uninstall module with --force switch, but also without success.

I also tried drush field-info in hope to get some clues, but that's apparently not yet implemented as drush 8.1.2 gives fatal error:

  Call to undefined function field_info_fields().

How do I make drupal delete those fields that pending deletion? Do I have to do this manually in database?

I've seen few tables like field_deleted_data_f5e7b87e32 or field_deleted_revision_be01eddd10 but they are all empty. Is that even relevant?

You could force field deletion using drush with the command:

drush php-eval  'field_purge_batch(500);'

or you could install devel module and go to /devel/php and run

field_purge_batch(500);


adding data to an existing content type programmatically I am sure this question has come up before, but right now my google skills are failing me.  I am trying to create a migration module since I haven't had any luck with either the migrate module or migrate_d2d.  Right now I am trying to populate a content type with the data from my field remap, but I can't find out how to do it.

would a simple db_insert work or is there something special I need to do to generate the field data?

Matt,

To create a node programmatically,

You firstly need to create a content type for same. This will make sure that Drupal architecture is followed to create a node.
Now you need to create a node from UI, and in hook_node_presave, make sure you print the node object - dprint_r($node); die; and see what is the Object architecture like.
Now you need too create the same object before saving it.
To, create the object, create $node = new stdClass();, define the node type $node->type = 'YOUR CONTENT TYPE NAME' and do a node_object_prepare($node), this will make sure that all the basic settings are added to the node object.
Post this, make sure you create the object, same as it was in node presave stage.
Just before calling node_save, call node_submit, which will prepare the node for submission.

Hope this helps !!!


Privatemsg module shows admin and myself in autocomplete I am using Drupal 7. In the Privatemsg module my autocomplete shows myself and admin. How can I disable displaying the user who's logged in in the autocomplete and disable displaying admin?

Put this code in your template.php file

function yourtheme-name_query_privatemsg_autocomplete_alter($query) {
  global $user;
  $query-> condition('u.uid' , $user->uid, '<>');
}


Change Dropdown to checkbox in View I'm using

Content: Translation language (exposed)

in my code, And I Have two Options
- autocomplete
- dropdown

I'd like to have Checkbox, How Can I enable it?

I'm using Drupal 8

Not sure where you're trying to do this, but if it's a node edit form, you can just change the widget to "Check boxes/radio buttons" on Manage Form Display (admin/structure/types/manage/<content_type>/form-display). Make sure the Options module is installed.

For an exposed filter in a View, say, you can use a hook_form_alter to change the #type to whatever you want; e.g.:

function YOUR_MODULE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_your_field']['#type'] = 'checkboxes';

  // If there's no user input (code not shown), rebuild the form.
  $form_state->setRebuild();
}

Only makes sense if #multiple is set to TRUE of course.

UPDATE: Added the call to setRebuild().


Missing group audience field(og) from node add form by panel I have 2 content types, and they are Organization(group) and Contact(group content)
From Contact, I add the group audience field and bundle with Organization.

When I use the node/add/contact from default node add form, everything is great.

I am trying to create another node/add/contact form from other url (organization/add_contact).
However, my problem is after setup a page(page management) and add the context with node add form, I find out my new add node form is missing the group audience field.

Is anyone have same problem or some setting was missed.......

It's a bug in "og/includes/og.field.inc". When the form is built twice "og_field_widget_form()" returns an empty array, thus the element has no options and seems to be missing.

Here is a link to the bug tracker: https://www.drupal.org/node/2481709

Issue is still open. For now I just commented the offending if-block out.


Include a partial template I'm trying to use Drupal 8, with a custom theme, due big structure differences for my requirements I have a page--front.twig.html and a page.twig.html, I would like to create template parts as used in phrozn oder in a normal Symfony2 project, for example a footer.html.twig and a header.html.twig. These templates are saved under a subdirectory /parts/.

But when I call this templates as normal I just receive a string with the name of the template.

For example:

{# in page.html.twig or page--front.html.twig #}
{% include 'parts/footer.html.twig' %}

Returns the file name as string:

parts/footer.html.twig

It's possible to do that with Drupal 8?

You can't do relative paths, all paths must either be from the Drupal root or based on the namespaced path to your 'templates' directory: https://www.drupal.org/node/2143557.

I would avoid "from the Drupal root" and use namespaces, at least until https://www.drupal.org/node/2291449 is resolved.

{% include '@mytheme/parts/footer.html.twig' %}

  Edit: If you want to pass additional arguments for loop or for
  checking some vars to your included twig template you should write
  in this way:

{% include '@mytheme/includes/form-block.html.twig' with {dog: true} %}

Edit: Now that https://www.drupal.org/node/2291449 has been committed you can also do:

{% include 'footer.html.twig' %}

See https://www.drupal.org/node/2369981 for why you saw the file name as a string instead of a helpful exception.


When no terms are chosen as filters in a view all results are returned I have a view with exposed filters that are taxonomy terms. These are multiple select.

When none of the options are selected the nodes are not filtered by that vocabulary so everything is returned. But what I need to happen is only noes not tagged with any of those terms be shown. Can this be done?

So you want the inverse of a search? Or have I misunderstood?

If thats what you mean I think you can change that inside your view settings.

Go to Structure > Views > edit your view

Then select your filter criteria and edit it. I think you need to check the following check box.


Why are modules showing up as themes? I am uploading my Drupal Commerce Kickstart website to the host from my local computer, and I seem to be facing issues at every turn. I have not edited any of the code (trying to avoid it) or moved around any folders except in themes so it's likely something to do with that.

It does not seem to be affecting the functionality of the website but clearly I've moved (or not properly uploaded via FTP) something important. I searched through as best I could and haven't found anyone else who has broken Drupal like this so I'm feeling pretty special.

Why are modules showing up as themes?

Drupal uses a function called _system_rebuild_theme_data() to help determine the list of themes (both enabled and disabled) to show on that page. That function does a number of things, but the first thing it does is to look for any .info files within the "themes" directories, which can include /themes, /sites/all/themes, sites/anydirectory/themes.

So, based on the screenshot, it appears that you have some modules placed in a themes directory. I would go through your themes directories to make sure that that isn't the case.


Creating a View filter for a CCK field I have created a custom filter which displays some select options to the user in order to filter a view. However, I am uncertain how to add this using the hook_views_data() hook, being that the table which the filter is being applied to is a CCK table called content_type_sm_mention.

Currently I have the following, which I am not sure is right. What is missing?

function smd_views_data()
{
    $data = array();
    $data['content_type_sm_mention']['sentiment'] = array(
      'title' => t('Sentiment'),
      'help' => t('Filter by mention sentiment.'),
      'real field' => 'field_mention_sentiment_value',
      'group' => t('Content'),
      'filter' => array(
        'handler' => 'views_handler_filter_sentiment',
      ),
    );
    return $data;
}
function smd_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'smd') . '/includes/views',
    ),
    'handlers' => array(
      'views_handler_filter_sentiment' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

To find out what is missing, implement hook_views_data_alter() and dsm($data) in the function to find the right path for your field.


How to remove Home title from the home page? There are several posts on a similar question. Despite that, I couldn't find the best way to resolve it. Display Suite is installed but don't see option to turn off page title. Our home page content type is Slider. I can see the html code using Inspect Element on Firefox. Don't know where the page is to remove it.

I think there is no way to remove it from the BO:
You can use code to remove it something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function myTheme_preprocess_page(&$variables) {
  if($variables['is_front']){
    drupal_set_title('');
  }
}


Updating a block inside an update hook I want to update the configuration (weight, pages, region) of some blocks within an update function. I know I could do this directly inside the database. Is there a better way of doing this? I scanned http://api.drupal.org, but I didn't find anything like block_load() and block_save().

Do you have any idea?

No, there is no such thing.

One of the typical update block configuration tasks was changing the cache flag (before 6.22, that is). You can find updates that mess with the {block} table directly in many projects, including mine: privatemsg_update_6002().


Is there a way to override paths defined in *.libraries.yml Guess I found a bug here and already filed it:

Created custom profile,
added https://www.drupal.org/project/mmenu dependency (which then is placed under profiles/profile_name/modules/contrib/mmenu).
Added MMenu libraries (jquery.mmenu, hammer.js, jquery.hammer),
activated everything but then Drupal looks for the wrong library paths under libraries/mmenu instead of profiles/profile_name/libraries/mmenu.

libraries_get_path('mmenu') returns correct path (profiles/profile_name/libraries/mmenu).

drupal_get_profile() returns correct profile.

Drupal seems to only take the paths defined in mmenu.libraries.yml into account. Changing them makes everything work as desired. So, I'm asking myself now: Is there any possibility to override the paths defined in mmenu.libraries.yml from a custom module?

Yes, this is possible. hook_library_info_alter() is used to alter basically anything in the library definition.


How do I override the content region for a specific page? I want to override the content region for a specific page, but using the hook page--mypage--region--content.tpl.php won't work. How should I name it?

My site supports block override, I tested this with a dummy region.tpl.php and I currently use a custom page.tpl.php.

For this you have to override preprocess region

function MYTHEME_preprocess_region(&$variables) {
    if(CONDITION){
        $variables['theme_hook_suggestions'][] = 'regionspecial__' . $variables['region'];
    }
    print_r($variables['theme_hook_suggestions']); // comment this statement
}

After that your template suggestion name will be 'regionspecial--content.tpl.php' For certain desired condition.  Once you clear Drupal's caches your new template file should start being used for that region. It might be worth noting that you'll probably need a copy of the core region.tpl.php file somewhere in your theme folder as well, or the theme registry might not pick up your custom file.


How can I remove only submitted time from node view? I only need to remove the published time from the submitted by field while viewing the node. Is it possible to do with display suite or there are other different approaches?

Step 1->create a custom date format go to "admin/config/regional/date-time" then click "Add format" link,give appropriate name, in my case i have taken name "new custom", in format string input "l,F d, Y" then save.

Step 2->In your Your_theme.theme file write the preprocess function for node:

function Your_theme_preprocess_node(&$variables) {
// Getting the node creation time stamp from the node object.
  $date = $variables['node']->getCreatedTime();
// Here you can use drupal's format_date() function, or some custom PHP date formatting.
 $variables['date_custom'] = \Drupal::service('date.formatter')-
 >format($date, 'Machine_name_of_created_date_format'); //In my case machine name was "new_custom"
   }

Step 3->Create a twig template of your content type like node--your-content-machine-name.html.twig

replace the following line :
{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

with

{% trans %}Submitted by {{ author_name }} on {{ date_custom }}{% endtrans %}


How can I get a summary from a view into another view? There are a few views that gather and analyze data from several nodes to form a budget based on their workflow. These views have a "total" area (defined as a custom content field within the view), which calculates the the total amount of money allocated by each node.

Each node is also associated with a team object, and what I want to accomplish is to get the "total" field from each view to act as a column in another view, so we can see how much money was allocated/spent with each team.

Essentially, what I'm trying to do looks more or less like this:

Team Number | View 1 Total | View 2 Total | View 3 Total | Total of the Totals
1           |          $33 |         $-10 |         $-20 |                  $3
2           |          $50 |         $-15 |         $-10 |                 $25

I've looked into trying views-field-view, but I haven't been able to find an option that allows me to select that specific row, which is created with a summarized table as the format. This is the same across all three views. How would I go about achieving this, with either views-field-view or another module? Or should I just go ahead and do this with a panel using custom PHP code?

You can combine the Views Field View module with the Views Aggregator Plus or with the Views Calc module.

Views Calc:

  Adds simple calculations to a views table. You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).

Views Aggregator Plus:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

  ... and it puts summary statistics at the bottom of your aggregated
  table as well!


Drupal Time Zone Problem I've got some nodes which have different time value when I edit and display them.

13th November 2012 6 pm is the value that I input, however, when I tried to display that, it becomes 13th November 2012 7 am. My drupal time zone setting is Australia/Melbourne. When I output the whole array for displaying the time, the time zone value seems to be Australia/Melbourne as well. The array is:

Array ( [0] => Array ([value] => 2012-11-13 07:00:00 [timezone] => Australia/Melbourne [timezone_db] => UTC [date_type] => datetime ))

Has someone got some ideas?

This is why when viewing data out of a Drupal database you should always use the provided wrapper functions. Because the timezone is applied at runtime and not stored in the database, which makes sense because Drupal allows for users to be "part of a timezone" and format their dates based on such.

So for you to get the field rendered just:

render(field_view_field('node', $node, 'field_date_name'));

More on this function can be found here.


How do I render a form with JavaScript? I'm trying to render a Drupal 8 modal dialog form through JavaScript, so it can appear on multiple pages across my site. In the controller class, I create an AjaxResponse object with an openModalDialogCommand for the modal form. I want to render the modal dialog through JavaScript, so that I can control in which pages it displays.

$(document).ready(function() {
  $('body').append('

');
  console.log(Drupal);
  jQuery('#ao-interstitial-modal').load('/aao_additions/modal_form');
});

This the JavaScript code I write so far, but it renders a textarea in the body tag with the AJAX command object as text inside it.

What do I need to do to render the form as a dialog popup?

Loading a form via ajax is no different then loading any other page with ajax. The quick answer is that you should create a route to display the form and then call that route via ajax but for a detailed description you should take a look here: https://www.drupal.org/node/2046693


How to create a menu block which is created by the active trail I'm trying to create a sidebar block which contains secondary and tertiary menu links for a page which is in the main menu. I would also like to ensure that all children pages also have this same menu block.

I have been looking into the Menu Block module, but I don't think it will work for my situation. It looks like that module shows a subset of a particular menu, but it doesn't change per page. I don't want to create multiple menu blocks, just use one and have it change dynamically.

Is there a solution in the community for this?

Menu Block does cover your use case.

Go to /admin/config/user-interface/menu-block

You will see

  If a block is configured to use "the menu selected by the page", the block will be generated from the first "available" menu that contains a link to the page.

That screen is for administering which menus are available when the menu block is supposed to simply rely on the active trail to determine which menu to show.


Centered layout with div borders on left and right (with bg images) I have begun a new theme on drupal using the Boilerplate theme.
I am trying to achieve a centered(responsive width) layout with borders on both left and right sides. I have attached a diagram. DIAGRAM HERE

I have the left side borders  working fine, they are within the #PAGE div which is the one and only WRAPPER of all content. (there is no other div above it)

As i have shown in the diagram, i am having trouble with the RIGHT side borders. With the same CSS syntax as the left borders, you can see they are positioned all the way to the right, even though they are inside the #PAGE div. Why is this? why is the #PAGE div not pulling it together?

Thanks for the help!

EDIT
codejsFiddle demo/mockup

PS- these 'borders' need to hold images as backgrounds so i can not simply use the 'border' property. And the 'border-image' is not well supported. DIV's is what i need.

The main problem in your example is that your "border" <div>'s have position: fixed; so they refer to the viewport rather than to the parent <div id="page">.

It's why you observe the right ones behaviour, which is pretty normal.
The left ones seem to refer to #page, only because they have not any left or right property set, so it defaults to auto.

Hence here is the first point: you must set position: absolute; for these "borders".

Additionaly you must remember that, for the absolute positioned element to refer to its nearest parent, this one must not have position: static, or another parent will be looked for as reference... till <body> if none is found, so it will be the same as for a fixed positioned element.

So here is the second point: you must set position: relative; for the parent #page.

From there you have to manage with leftand right properties to get what you want.
You can look at this fiddle, where I added the needed properties to strictly conform to your DIAGRAM exposed wills.


In Views, how can I show users with one role before all other users? I have several views of users and I want to show all users with a certain role (example, "show_me_first") before all other users in all of these views.

I thought this would be easy, but apparently there is no "User: Role" as a sort criteria (I'm using Views 3.5 on Drupal 7.15).  I can filter by role, but I don't want to filter; I just want to show users with the role "show_me_first" before all other users.

How can I implement this?  Minimal view customization is best because I will have to repeat this for a lot of views.  If there is a way to do it without using roles, I would be open to that as well.

It looks like it's not possible with one View (Sort By User Role, Sort By User Role:  A New Idea?) which does kinda suck.

One option is to make two Views, one that filters on the user role you want at the top, and then one that filters OUT the user role.

Another option (this one would probably be easier to maintain) would be to create a field on the user accounts called Weight (you could hide it with Field Permissions), and then use Rules to populate that field with a high number for your chosen role when a user is created or edited, then you should be able to sort on that field.  If you do this though don't forget to create a second rule to remove/change the value in that field if the role is removed form a user.

tl;dr

Create Weight field on users
When a user is created, fire off a rule that looks for a particular user role
If it finds it, put a number in the Weight field
Sort your view on the Weight field
Make an "opposite" rule to remove the Weight value on Role removal.
Profit


How to find out which cron jobs are currently running? Is this possible to find out which cron jobs are currently running?

The answer can be found in drupal_cron_run.  While it is the case that you can tell if Cron is currently running by calling lock_acquire('cron', ...)), just as Drupal does (don't forget to call lock_release too), Drupal does not in any way set any information about the individual cron hooks that it executes during a cron job.

If you need more control over cron job execution, you could always copy the drupal_cron_run function into your own module and modify it to suit.  drush_core_cron() does nothing other than call drupal_cron_run, so you could call your own cron function via drush ev 'mymodule_cron_run();' from your crontab.  If you did this, you would need to review the implementation of drupal_cron_run on every update of Drupal core, and check for any significant alterations in behavior, so you should only customize cron if it's really important that you do so.


How to properly filter a form's data against XSS? Drupal 7.

I've got an (ECK module) entity form. The form's only field is a multi-value field of the field_collection (Field Collection module) type. The field collection contains two fields: a textarea, and a set of radio buttons. The user submits the form (AHAH), the entity is saved and the form is presented back to the user with the submitted values. For this project that is the intended (and necessary) behavior.

My (stripped down) validation handler is as follows:

/**
 * My custom validation handler.
 */
function my_module_eck_entity_form_validate($form, &$form_state) {
  $values = &$form_state['values'];
  $lang = $values['entity']->language;

  $fields = array('field_my_text', 'field_my_radios');
  foreach ($fields as $field_name) {
    // the values which get saved to the entity object
    foreach ($values['field_my_field_collection'][$lang] as &$item) {
      foreach ($item['entity']->{$field_name}[$lang] as &$child) {
        $child['value'] = filter_xss($child['value']);
      }
    }

    // the values which get output as part of the form on page-reload
    foreach ($form_state['complete form']['field_my_field_collection'][$lang] as &$item) {
      if (is_array($item) && isset($item[$field_name][$lang])) {
        foreach ($item[$field_name][$lang] as &$child) {
          if (is_array($child)) {
            $child['value']['#value'] = filter_xss($child['value']['#value']);
          }
        }
      }
    }
  }
}

It works and does what I want, but it is an ugly monstrosity that'll keep me up at night. There has got to be a nicer, cleaner way of doing this.

For the intents and purposes of this question, let's not discuss the pros & cons of Drupal's filter_xss() vs other tools - plenty of existing questions about that.

There's a huge issue with your implementation: it's destructive. Let's say a user writes about HTML, uses common comparison symbols or just uses the evil emoticon for despair: <o>. Changing data will make it harder for the user to later edit his post, it might even remove parts of it. Let's respect the user effort of typing into a textarea and hitting 'Save'.

So, what to do about XSS? Well, XSS is not dangerous in your database, it is only dangerous when displayed in a browser. So relax about saving it and worry about displaying it. Default formatters for text fields will use the text format settings to apply filters. Make sure the text formats available for your user are safe. And if you're writing your own formatter, don't forget to filter the output (preferrably by respecting the text format settings).

See https://drupal.org/node/28984 and https://drupal.org/documentation/modules/filter for more on this topic.


How can I add fields to blocks? Is there a way we can add some fields in Blocks, just like we can do in content types. For now I need an image field attached to a block.

I know about a module named Image Block but that is limited in its functionality.

Try one of the following modules:
Bean

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

Boxes

Boxes module is a reimplementation of the custom blocks (boxes) that
the core block module provides. It is a proof of concept for what a
re-worked block module could do.

My personal preference has always been Bean (before I started using Panels more frequently), but I don't think there's a lot in it to be honest.


What is the Drupal 7 version of FILE_STATUS_TEMPORARY? My use case is that I want to set an uploaded file as FILE_STATUS_PERMANENT until I know it has been processed correctly by my custom module. Once that is done, I'm happy for Drupal to delete it. There used to be a FILE_STATUS_TEMPORARY in D6 but no more. What should I use?

That is strange, as FILE_STATUS_PERMANENT still does exist indeed. But the value of FILE_STATUS_TEMPORARY used to be 0. So I suppose you can use anything that evaluates to zero: FALSE, NULL, 0. Personally I have always used 0.

But why set your file back to temporary to have it deleted by cron, why not just delete the file directly after processing? You can use file_delete() to do that.


Is there a way to assign an html ID automatically to a field in a content type? I am using JavaScript in my custom module and the field is inside an div, but that div only has a class tag.  Is there a way to automatically give an ID to the field so that whenever it shows up, it's easier to manipulate it with an ID tag?  The field belongs to a content type.

Since I was only displaying the content with a view, in the view settings
- I edited the specific field
- clicked REWRITE RESULTS
- checked "Rewrite the the output of this field"
- and wrote:

<p id="file-types"> [field_file_type_text] </p>

This solved the problem


How to get the contents created by a User? How to get all contents from which the current user is author?
 $currentUser = \Drupal::currentUser();
 $user = User::load($currentUser->id());
//get the contents from which $user is author?

$currentUser = \Drupal::currentUser();
$query = \Drupal::entityQuery('node');
$query->condition('uid', $currentUser->id());
$author_nids=$query->execute();


Allow html tags in Form submit button in block plugin I'm using a block plugin to render a user specified form. I'm retrieving the form like so:

public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['template'] = $form_state->getValue('template');
    $selected_entity_type_bundle     = $form_state->getValue('entity_type');
    $values                          = explode('.', $selected_entity_type_bundle);

    $this->configuration['entity_type']             = $values[0];
    $this->configuration['bundle']                  = $values[1];
    $this->configuration['entity_type_submit_text'] = $form_state->getValue('entity_type_submit_text');

}

private function buildEntityForm() {
    $values = array();
    // Specify selected bundle if the entity has bundles.
    if (\Drupal::entityManager()->getDefinition($this->configuration['entity_type'])->hasKey('bundle')) {
        $bundle_key = \Drupal::entityManager()->getDefinition($this->configuration['entity_type'])->getKey('bundle');
        $values     = array($bundle_key => $this->configuration['bundle']);
    }
    $entity = \Drupal::entityManager()
        ->getStorage($this->configuration['entity_type'])
        ->create($values);

    if ($entity instanceof EntityOwnerInterface) {
        $entity->setOwnerId(\Drupal::currentUser()->id());
    }

    $form = \Drupal::entityManager()
        ->getFormObject($this->configuration['entity_type'], 'default')
        ->setEntity($entity);

    return \Drupal::formBuilder()->getForm($form);
}

This grabs the form just fine, and I render it using

public function build() {

    if ($this->configuration['entity_type'] != '') {
        $entityForm                                = $this->buildEntityForm();
        $entityForm['actions']['submit']['#value'] = t($this->configuration['entity_type_submit_text']);// Editable submit button value.
        if ($this->configuration['template'] == 'learnmore') {
            $entityForm['actions']['submit']['#value'] = ''.$entityForm['actions']['submit']['#value'];
        }
    } else {
        $entityForm = '';
    }
    $entityForm['actions']['preview'] = '';

    $content = [
        'template'     => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => [$this->configuration['template']],
            ],
            'header'  => [
                '#type'  => 'html_tag',
                '#tag'   => 'h5',
                '#value' => $this->configuration['label'],
            ],
            'form' => $entityForm,
        ],
    ];

    return $content;
}

Which renders the form. But I'm setting the submit button text as specified by the user like so

$entityForm['actions']['submit']['#value'] = t($this->configuration['entity_type_submit_text']);

And I want to add an icon inside the button before the text like so

$entityForm['actions']['submit']['#value'] = ''.$entityForm['actions']['submit']['#value'];

The issue is when it renders the button it includes the html tags so the actual submit button text is

  Submit Button Text

It displays the html tags instead of rendering the actual icon.
Is there a way to allow html tags inside of a submit button on a form?

Use a formattable markup:

use Drupal\Component\Render\FormattableMarkup;

  $value = new FormattableMarkup('<i class="fa fa-mail"></i>@text', [
    '@text' => $value,
  ]);

The formattable string will not be escaped. The variable in the placeholder @text will be escaped and that is important, because it contains user input.


How to display nodes in a view, each row using a preselected view mode ? I would like to create a view that displays a number of nodes, each using its own chosen view mode.

I've installed the Display Suite module and created a number of view modes. Using the Views module, I've created a view that displays a number of entities/nodes and I can set a view mode for each row, or a default view mode for all rows.

However, I would like the view to somehow use the view mode that has been selected when creating the content itself (under the display settings tab).

So far I have no idea how to achieve this. Could anyone give me some pointers?

First you need to save the view mode for each entity (e.g. in a field).

Implementing hook_entity_view_mode_alter you can override the view mode:

function mymodule_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node') {
    $entity = $context['entity']
    if (get the view mode of $entity) {
      $view_mode = 'custom_view_mode';
    }
  }
}

Remember to do a check to run this in your view only, otherwise this will affect the node everywhere.


Advanced Forum - Forum View Hello Advanced Forum Module Experts!

I have installed the plugin and started styling on it and I also took a look on the views were they have listed a couple of views. I looked them up but I don't seem to find the view that display the discusion forums like General Discussion.

The url is /forum/view but I dont seem to find it on views

Where can I find it?

Thanks

General DiScussion - using this view view-advanced-forum-topic-list
You can find it here - /admin/structure/views
view name - Advanced Forum topic list


How to delete a particular variable from a configuration created by a custom module I have created a custom module and a configuration say 'abc_settings'. This configuration creates a variable for each vocabulary present on the site like vocab1_options, vocab2_options, vocab3_options etc.
I want to delete 'vocab1_options' when vocabulary 1 (vocab1) will be deleted. How to achieve this ?

Deleting a config key:

Updating per Berdirs comment, deleting/clearing a key within a config object, not deleting the entire config object:

Drupal::configFactory()->getEditable('abc_settings')->clear($entity->id() . '_options')->save();

Deleting config objects:

I did this within TVI module, anytime a term or vocab is deleted:

/**
 * Implements hook_ENTITY_TYPE_delete().
 * Remove TVI settings when vocabularies are deleted.
 * @param EntityInterface $entity
 */
function tvi_taxonomy_vocabulary_delete(EntityInterface $entity) {
  Drupal::configFactory()->getEditable('tvi.taxonomy_vocabulary.' . $entity->id())->delete();
}

/**
 * Implements hook_taxonomy_term_delete().
 * Remove TVI settings when terms are deleted.
 * @param EntityInterface $entity
 */
function tvi_taxonomy_term_delete(EntityInterface $entity) {
  Drupal::configFactory()->getEditable('tvi.taxonomy_term.' . $entity->id())->delete();
}

Of course, you would pass your own config name to getEditable(), and the hook names need to have your module name and not tvi.

This will delete any config matching that name when a term or vocab is deleted.

I haven't taken the step yet in my own code, but you could go further and implement a method that before a vocabularly entity is deleted, get all of its children, loop and delete config, then delete the vocab and its config.

Example:

Drupal::configFactory()->getEditable($entity->id() . '_options')->delete();


hook_menu() items created in a custom module don't retain the active-trail of the parent tab So I have a custom module that is adding 3 menu items (a main tab, and 2 sub-tabs). When navigating to the main tab (url: /casereports) the default_local_task is displayed as expected and both menu items (Case Reports and Jobs Completed) are active as expected. Everything is working fine except that when I click on the second tab (Jobs Created), the main tab (Case Reports) loses it's active status.  I can't seem to figure out what I am missing here and why it is not picking up it's parent and the active-trail.  Any ideas?

function casereports_menu() {
  $items = array();

  $items['casereports'] = array(
    'title' => t('Case Reports'),
    'page callback' =>'drupal_get_form',
    'page arguments' => array('casereports_completed'),
    'access arguments' => array('access content'),
    'menu_name' => 'features'
  );
  $items['casereports/default'] = array(
    'title' => t('Jobs Completed'),
    'type' => MENU_DEFAULT_LOCAL_TASK
  );
  $items['casereports/created'] = array(
    'title' => t('Jobs Created'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('casereports_created'),
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK
  );
  return $items;
}

OK...so this basically ended up being more of an Open Atrium issue than anything else.  Due to the fact that Open Atrium relies heavily on Features and Context, the style sheet was setup to deal with the classes added by those modules.  Drupal's implementation of active-trail and active classes was working fine, however the theme's 'active' styles weren't setup to work without the classes added by the Context module.

I could either a) add a Context for the menu item added via my module (which is the route I took), or I could have (b) modified the CSS for the theme by adding a custom stylesheet.

Thanks for all the help guys, but I am embarrassed to say that in the end, it was just a bit of a theme problem from the Open Atrium install.


Populating fields from the User entity during a Commerce checkout When a user checkouts out, they need to fill in some specific information which should be saved to the User entity.

Thus I need to modify the checkout form to collect the information I want, then save it to the User.

It seems like a cheeky way to simplify the process would be attaching User fields directly to the Commerce Order entity. Is this possible, or should I just load the User entity form and copy the fields I want in a hook_form_alter?

You could attach the fields from the user to the form, but you would need to handle saving the user in the form submit. You could in form alter do something like this

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id') {
    $form['user_fields'] = array();
    global $user;
    field_attach_form('user', $user, $form['user_fields'], $form_state);
  }
}

You also need to add validate and submit handlers in the form_alter in the validate handler do

 field_attach_validate('user', $user, $form['user_fields'], $form_state);

And in the submit handler do

field_attach_submit('user', $user, $form['user_fields'], $form_state);
user_save($user);


Why Can't Panels Select My Organic Groups? I'm trying to create panels that are visible or show up on pages specific to certain groups. I'm using Organic Groups 7.x-2.7 on Drupal 7.34. So, our company's technicians would only see panels specific to them and the same for office staff. I'm having an issue integrating Panels with Organic Groups. When setting the "Selection Rules", "Visibility" or any other value for a panel to the group of the User who is viewing, the option to select the group is there and selectable BUT it only shows up as an empty string and the panel doesn't abide by this rule. I'm pulling my hair out and eating it in a mad attempt at proving to the gods of drupal code that I am worthy of a solution.

Update (3/20/15)

I changed my Organic Groups installation to version 1.5. This seems to work. I'll try each version incrementally until I reach the first one that breaks and just place it here. I still have no idea why this is occurring, though.

The way I accomplished this was with Views Contextual Filters and the Views Content Panes module, displaying only content belonging to the particular groups I wanted to see the content.  This approach, however, requires the content being viewed to have a field instance of the group ID that it belongs to (and, incidentally, a field instance for "other" groups the content will be visible in).  Note, in order for the two contextual filters to work properly here (i.e. for the content pane to be visible in two or more groups) I had to install the "Views Contextual Filters OR" module (I can't link twice because no rep).

I couldn't comment because I don't have enough rep, but this approach worked for me, but it might not work in your specific use case.  It should be noted that if nothing matches the filter, the pane is omitted from display entirely (which is what you are ostensibly trying to accomplish).  So many ways to skin a cat with Drupal.


how to get tinymce value in javascript?+ Drupal7 I am using drupal7 form

$form['subject'] = array('#type' => 'textfield',
        '#title' => t('Subject'),
        '#maxlength' => 200,
        '#size' => 100,
        '#required' => TRUE,
);

$form['body'] = array('#type' => 'textarea',
        '#title' => t('Body'),
        '#type' => 'text_format',
        '#base_type' => 'textarea',
        '#format' => 'full_html',
        '#required' => TRUE,

);

we used tinymce editor. Posting form with jquery like this

$.ajax({
            url: '/myevent/preview',
            data: $('#eventform').serialize(),
            type: 'POST',
            success: function(data){
                $('#eventdata').html(data);
            }
        });

At my local its working fine, but on server, I couldn't get value of body textarea.

Try this I suppose this may help.

  tinyMCE.triggerSave();

  $('#textarea-selector-id).val();

i suppose that your text area would be inline:TRUE;
change the text area to a div this may work

or

var editor='textarea-selector-id';
var content =tinyMCE.activeEditor.getContent();
alert(content);


Sort a view by price using commerce price? I have a custom view (created with Views) that is working fine. But when I add a price field to it and sort the view with same field in descending or ascending order, it is not working.

Any suggestions to get this to work?

Follow the below steps and share the output:

Create a views with the same content type in which the field exists from which you need to filter easily with "filter section" in views.
Select the same field of content which you want to filter.
Select the same fields in filter with sorting order "ASC" or "DESC".

Mention please use Commerce Views plugin for the same.

Thanks.


How to Automatically Manage a LARGE Number of Views Pages Under ONE? I am developing a website for a school's Alumni Association that has been around since the 1800s. Every student has a Grad Class specified in the database:

e.g. /students/1947/John_Doe (indicates graduated in 1947; all of this is ready to go).

But now I want to create a page for every year (1890, 1891, ... 1970, 1971, etc.) and have each listed on that page:

e.g. /students/1947 (would list all students who graduated in 1947)

Using Contextual Filters, this is easy!! But the problem is that creating each individual page for each individual year would be extremely cumbersome. Do each of these pages needed to be created manually (with an identical Contextual Filter) or is there a way to automatically manage all of these graduation classes under a single view? If so, how would those pages be created?

All you have to do is to add a wildcard to the URL pattern of your view like /students/% and then use this as argument for the contextual filter.

Similar to how the default "Taxonomy term" view does it (screenshot attached):


How to assign define role to group creator in groups created with the Group module? I am using the Group  module. Whenever a new group is created, member is added to that group with role none.

I want to assign a role to a group when a user creates a group. How can I do that?

The latest beta release of the group module (8.x-1.0-beta5) includes that functionality.

Download, install, run DB updates and go the the settings page for the group type.


How are Field API fields transfered from config entities to content entities? So I am creating a content and config entities - exactly like node and node type.
After I've created them I've noticed that I can add fields to the config entities, which is ok but then I've realised that I'm working with two separate entity types, so I wonder how re Field API fields "transferred" from the config entity to the content entity?

This works essentially the same way as in Drupal 7.

Config entities like node types, custom block types, vocabularies and so on are used as storage and are then exposed as bundles of nodes, custom blocks, taxonomy terms, ...

There's not much magic involved, you can see what happens in e.g. node_entity_bundle_info() and taxonomy_entity_bundle_info(), so the modules have to do that part themself, you'll notice small differences there e.g. how they handle the bundle label.

The bundle_of annotation key was added recently that allows to explicitly define that relationship between two entity types, but it's currently only used by field_ui_entity_operation_alter() to automatically add operation links to the listings of node types, vocabularies and so on.

While it looks like you add the fields to config entities, you really add the field to the corresponding content entity for the given bundle. Just like it already was in 7.x, the only thing that really changed is all those different things now use the same API for storage, in 7.x, they were stored in separate tables and didn't have anything in common.


Different theme for different languages In drupal 7 how do I change site's theme based on current language?

The Themekey module will handle that for you.


How to get notified by eMail after someone edited his own webform submission? I have a webform, and I'd like to be notified whenever someone edited his own submits. I'm using the Webform module.

I found the Webform Rules module but I didn't get how to use it,
any way to set this up?

Using Webform Rules (and Rules of course), it's a peace of cake to send an eMail using Rules Event "After a webform submission is updated". To actually do so, refer to the answer from CodeNext. However, the real challenge in this question here, is to address this part of the question: "someone edited his own submits". Read on for more details on how to implement that part of it.

Assumptions:

It should also work for "someone edited 'her' own submits".
The question is NOT about anonymous users (for that you might need things like IP address, session API, etc ... be my guest to also get that to work ...).

With these assumptions in mind, you'll need to have something in your webform available to store, as part of the submitted webform, the uid of the user who actually submitted the webform. I've not found (yet) any such data that is available as a token to Rules (you'll need it in Rules to get this challenge to work). So therefor I'd use an approach like adding an extra (hidden?) webform field that is automatically set (eg using Rules) when the webform is first submitted, let's say using a field with machine name field_webform_submitter_uid.

After all the above is in place and agreed about, you're in good shape to address the challenge "someone edited 'his/her' own submits": all you'd have to do is to further enhance the rule detailed in the prior answer, by adding an appropriate Rules Condition, to check if the uid of the currently logged in user matches field_webform_submitter_uid.

But, there is 1 more challenge to implement that extra Rules Condition: how should the Rules token look like for the value of field_webform_submitter_uid? To find the answer to this, refer to the README.txt of Webform Rules: based on what's documented there, the token to be used in that extra Rules Condition should be [data:field_webform_submitter_uid-value].

Voilà ...

Note (about the token for the uid of the user who submitted the webform): each submission has data like "submitted by" and "submitted on", however from all uid-variations I've experimented with, none of them contain the value that always matches the "submitted by" (not to be confused by tokens like node:author:uid, those are for sure not what matches the "submitted by"). To convince yourself, try a scenario where the user who submitted the webform is different from the one who edits that submission ...


How do I create multiple nodes on the same page? Im on d7. I am trying to create node submission process where I can create multiple nodes on the same submit page and have them all reference a single separate node on the site. any suggestions?

You could create multiple nodes by creating node objects and using node_save() function to save the node.

      $node = new stdClass();
      $node->nid = NULL;
      $node->nid = NULL;
      $node->is_new=TRUE;
      $node->type = "CONTENT_TYPE_NAME";

      node_object_prepare($node);

      $node->created = strtotime("now");
      $node->changed = strtotime("now");

      $node->uid = 1;
      $node->promote = 1;
      $node->format = 1;
      $node->language = 'en';
      $node->title = '"TITLE" ';

      $node->field_DATA['und'][0]['value']= "VALUE";
      $node->field_DATA['und'][0]['value']= "VALUE";

     // Prepare node for saving
      node_save($node);

you can create multiple objects like this on submit handler and save it. Each node will be assigned with new node id.

I hope this helps you.


Which hook or tpl file controls the output of a view (to manipulate the results)? I am creating a recurring events views page, but currently the output of my view is displaying multiple references of the same date event. I am also not using Fields as an output, I am using content|teaser.

I have come up with 2 methods of resolving this issue, but wanted to clarify which is best and how to go about it.

Find a hook that outputs the Views rows and then write a conditional to compare each row and delete the duplicates.
Create a tpl file and do a preg_replace() on the views output to delete duplicate rows of the same data.

Now the question is how do i go about finding this hook or what to name the Views tpl file as? I only want it specific to this events page.

Views Template Suggestion

All views templates can be overridden with a variety of names, using the view, the display ID of the view, the display type of the view, or some combination thereof.

Below are different template suggestions you can use for overriding the defaults.

Let consider a example View, named foobar. Style: unformatted. Row style: Fields. Display: Page.

Display output: This controls the structure of the overall view, including the position of and code around the view administrative links, header, exposed filters, pager, "more" link, footer and feed icon. This template also controls the position of and code around the primary view content, empty content, and attached views.

views-view--foobar--page.tpl.php
views-view--page.tpl.php
views-view--foobar.tpl.php
views-view.tpl.php

Style output: This controls the structure of this particular view display's style, e.g. HTML List, Table, Unformatted, etc. This includes the view title and the code surrounding each row (item in your view) of the given style.

views-view-unformatted--foobar--page.tpl.php
views-view-unformatted--page.tpl.php
views-view-unformatted--foobar.tpl.php
views-view-unformatted.tpl.php

Row style output: This controls the internal structure of each row (item in your view), including the label and the content for each field.

views-view-fields--foobar--page.tpl.php
views-view-fields--page.tpl.php
views-view-fields--foobar.tpl.php
views-view-fields.tpl.php

Fields: There will be one entry for each field in your display, allowing you to control the structure and code for each. If your row style is set to "Node," there won't be any field entries, and the view will use the node's template file instead.

Lets take you have added Title field in the field list, then below are the suggestion to theme title field

views-view-field.tpl.php
views-view-field--title.tpl.php
views-view-field--foobar.tpl.php
views-view-field--foobar--title.tpl.php
views-view-field--page.tpl.php
views-view-field--page--title.tpl.phpfoobar
views-view-field--foobar--page.tpl.php
views-view-field--foobar--page--title.tpl.php
views-view-field--page-1.tpl.php
views-view-field--page-1--title.tpl.php
views-view-field--foobar--page-1.tpl.php
views-view-field--foobar--page-1--title.tpl.php

Views Preprocessors suggestion
If you want to alter the display of any view with preprocess functions, then you can use the below suggestions to modify the display of any view.

Altering Views result
To alter the result of the view itself(i.e modifying the results before its being rendered) you can use any of the following hook,

hook_views_pre_render
hook_views_post_execute

For using these hooks, you can refer the answer by jimajamma.

References

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7
http://www.ostraining.com/blog/drupal/views-templates/
http://webpartners.es/en/drupal-7-views-templates-and-preprocess
https://api.drupal.org/api/views/theme!theme.inc/7
https://drupal.org/node/352970
Why doesn't adding results in hook_views_pre_render work?


Display a custom field of a content type in template with PHP? I'm using Drupal 7.  I have a content type called Widget.  One of the custom fields is field_widget_position.  When I did a <?php print_r($page); ?> in the template, I can see the key-value pair of field_widget_position buried deep in the array.  Is there an easier way to get a handle on field_widget_position instead of typing <?php echo $page['somefield']['somefield2']['somefield3']['etc....']['field_widget_position']; ?>?

$node->field_widget_position['en'][0]['value']

This is a bad solution.

The right solution is

render(field_view_field('node', $node, 'field_widget_position'));

or

render(field_view_field('node', $node, 'field_widget_position', array('label' => 'hidden')));

if you don't want to print a label.

See http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way for more info.


Change 'href' attribute in AJAX enabled links I have some links with the class use-ajax. Everything works fine with default settings.

The problem is that at some point I need to change the href attribute of a link and make the ajax call to the new url, which is not working. The call is made to the initial url of that link.

I tried to reattach behaviours but this doesn't seem to work.

Any help would be appreciated.

Any ideas? Thanks

Drupal link based Ajax, correspond to a Drupal.ajax['#id'] element object and drupal works with them not with DOM Objects.

So you don't have to change the href attribute you need to change the URL where it's doing POST in the Drupal.ajax element, in this case do this:

// Confirm structure first executing on console 'Drupal.ajax['#id'].options.url'
var href = 'hook_url/ajax/parameter1/parameter2';

// And change the href POST parameter
Drupal.ajax['#id'].options.url = href;

And it's done!


How can I take control of the rendering of a file entity when inlined in text? There are excellent instructions for how to allow embedding Media into text fields here Setting up WYSIWYG and CKEditor to include Media Browser / Embed Media button.

Now I'm trying to control the output of that embedding process, specifically I'm trying to render a text field for a caption next to an image. I started out by adding a new view mode to the file entity with hook_entity_info_alter, configured this View mode to display the correct fields, and thought that would output as expected.

However, this by itself does nothing unless "File display" settings are also added, and I can't seem to figure out how to make them respect field settings. I've done a fair amount of debugging and hacking by now, and can't get this right. I could fill the question with a great deal of more details, but given that I can't make heads or tails out of the problem, it's unlikely to be very useful.

The question How do I control the file appearance using File Entity? is definitely related, and possibly even a duplicate, but as this one concerns specifically inline media, it may be different enough that open this separate question.

Your best bet is http://drupal.org/sandbox/DevinCarlson/1823634 - which is an add on to media, but I'm not certain whether or not it can also display fields that are attached to a file entity.

As per http://drupal.org/node/1792738 this functionality is planned to be rolled into the media module at some stage.


Saving multiple field values in a users entity I am trying to reference other nodes on the user entity on field_clinic but everything else is saving except that multiple value field. What could i be doing wrong. The field_clinic accepts multiple values. Below is my code:

$clinics = [

        array('value' => 132),
        array('value' => 133),
        array('value' => 134),
    ];

    // if the user exsists update basestation
    $UserEntity = User::create([
        'name' => 'Final',
        'roles' => array('subscriber'),
        'field_age' => '2',
        'field_city' => 12,
        'field_clinic' => $clinics,
        'field_base_statition' =>  $bs_nid

    ]);

    $UserEntity->save();

The clinics array contains the node ids that I am trying to reference. Please help

The way you're setting the values may be failing to work if you've got the wrong keys in your array - setting any field from code requires you to know how that specific field type stores its data in the entity.

If you're not sure about that key, using the devel module you can simply save one of those users filling the field_clinic field with appropriate values then switch to the devel tab for that user and inspect what keys are actually being used to store the values in that field (probably one named target_id).

According to what you find there, fixing your code may be just matter of changing this:

$clinics = [
    array('value' => 132),
    array('value' => 133),
    array('value' => 134),
];

to this:

$clinics = [
    ['target_id' => 132],
    ['target_id' => 133],
    ['target_id' => 134],
];

(disregard the difference between declaring an array using the [] or the array(), I used the former in my edited code just for coherency)


Associate an user to a taxonomy term I'd like to associate an user to a taxonomy term. I create users in a process import managed by rules.

I didn't found a solution with an existing module so I try to develop mine. I've also installed Entity reference module but I feel confused.

I've added a field_user in my taxonomy term fields management.I've added a field_conventions in my user field management.

I do not understand how to associate one or many terms to an user with rules.

I found User Terms module but unfortunately only for a Drupal 6.x

User profiles are fieldable in Drupal 7, you can add a taxonomy field already, with nothing but core. You don't need Entity Reference or any other modules, you can simply  add field_taxonomy to your user. Sure, it is a bit opposite to "add users to terms" you described, but later, if you need it for Views etc, it doesn't matter which way it was created - there is a connection between user and term, and you can use it.


Views: Relationship with webform submission I have a view displaying a list of nodes. Each node has a webform submission related, and the sid is stored in one field "field_sid".

I'd like to be able to access the submission data in the node view, using a relationship thanks to the sid field.

Is there a good and efficient way to do this ?

Thank you very much and sorry for my bad english

Edit : I tried the Sivani solution but unfortunately I wasn't able to link the "field_sid" from the node to the good submission ID. How to do this ?

You have to use hook_views_data_alter for node and webform submissions relation in view.

function mymodule_views_data_alter(&$data) {
  if (isset($data['webform_submitted_data']['data_numeric'])) {
    if (!isset($data['webform_submitted_data']['data_numeric']['relationship'])) {
      $data['webform_submitted_data']['data_numeric']['relationship'] = array (
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'nid',
        'label' => t('Referred node'),
      );
    }
  }
}


How to get token of parent entity in paragraph? I have a paragraph, which is referenced by a node. Now I am trying to pass field values of node to the paragraph using tokens. I'm only aware of [paragraph:parent_id] and [paragraph:parent_type] but don't know how to get specific field values.

What I've tried so far without success:
[node:field_foo:value]
[paragraph:field_foo:value]
[paragraph:node:field_foo:value]
[paragraph:parent:field_foo:value]
[paragraph:parent:entity:field_foo:value]

The list of available tokens does not contain parent tokens. Is it even possible to get token of the parent entity? And if so, how?

There's nothing out of the box (see this issue for the details). Implementing your own token isn't too tricky.

I haven't had a chance to test this but I'm pretty sure it'll work:

function MODULE_token_info_alter(&$info) {
  $info['tokens']['paragraph']['parent_entity'] = [
    'name' => 'Parent entity',
    'description' => 'Parent entity of the paragraph',
  ];
}

function MODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'paragraph' && $paragraph = $data['paragraph']) {
    $parent = $paragraph->getParentEntity();
    $bubbleable_metadata->addCacheableDependency($parent);

    foreach ($tokens as $name => $original) {
      if ($name == 'parent_entity') {
        $replacements[$original] = $parent->label();
      }
    }

    $token_service = \Drupal::token();
    if ($parent_entity_tokens = $token_service->findWithPrefix($tokens, 'parent_entity')) {
      $replacements += $token_service->generate($parent->getEntityTypeId(), $parent_entity_tokens, [$parent->getEntityTypeId() => $parent], $options, $bubbleable_metadata);
    }
  }

  return $replacements;
}


Change text in Commerce Kickstart "order total" dynamically I want to change the label in the attached image, that is from Commerce Kickstart. I need to change that text depending on the role of the user.

If the user has role1 then the text will be "order total" & if user has role2 then the text should change to "Quote total". Any idea?

I tried to debug with Devel to see where to change the label but I could not find it.

You can use the hook_commerce_price_formatted_components_alter()
The following example checks if VAT has been applied to the order total and changes the string accordingly:

/**
 * Implements hook_commerce_price_formatted_components_alter().
 *
 * Alters somes text at the checkout form
 *
 * @param $components
 * @param $price
 * @param $entity
 */
function mymodule_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  $pieces = explode('/',current_path());
  if(!isset($components['tax|ch_vat']) && $pieces[0] == 'checkout'){
    $components['commerce_price_formatted_amount']['title'] = t('Order total (excluding VAT)');
  }
}


Which of the wysiwyg modules will get in to the core of Drupal 8? I heard that there will be a wysiwyg editor in core for Drupal 8. Is there any decision made yet which one will make it?
I heard about:

CKEditor
Aloha Editor
Wysiwyg

I have a decision to make which module I will add to my site and I need some deeper integration of the wysiwyg to the Drupal core. For example, that all external links are programmatically get stored in a link field an so on.
So I am hoping to get some of those features in feature when I choose the right module backported to Drupal /.

Dries answered this in From Aloha to Ckeditor on Jan 02, 2013:

  Therefore, we are going to switch from Aloha to CKEditor for Drupal 8
  core. By making this switch, we will not only have a more mature
  WYSIWYG editor, but we also free up resources to work on other parts
  of Drupal's authoring experience. The CKEditor team has committed to
  fix the 8 functional gaps that we've identified in their two next
  upcoming releases.


Requiring a package doesn't find a dependency When running HOME=/home/gymsagec composer require "drupal/commerce 8.2.x-dev", I get this error message:

  drupal/commerce 8.2.x-dev requires commerceguys/intl dev-master -> no matching package found

I can install the intl package by itself using composer but even after doing that, running the first script fails. Why?

As reported in Composer fails when installing a dependency of a dependency, but not when the dependency is installed directly. that probably happens because the root composer.json file doesn't set a minimum stability, or doesn't accept a less stable package.

Try with composer require drupal/commerce:@dev as suggested in that issue report.


How to build a custom block with a image field I want to build a custom block in Drupal 7 that instead of the standard title/text-format contains a single image field. It will be used on the front-page and allow a non-HTML-speaking editor to easily upload and update the big front image that will be shown there. Since there will be only one block I feel a block is more appropriate than a content type. I've built a bunch of custom blocks for Drupal 6, but they were all textfield-based, and I'm not sure how I should approach the problem now that I need a image-upload-field. Does anyone want to point me in the right direction? How do I build the image field from within hook_block_view?

You could create (anyway) a content type and use the module Node Blocks. Every content you create with this content type are automatically available as block. Maybe a bit overhead if you just need to create one.

Another solution may be the BEAN Module. But just dropping the module name, never worked with it.


Views Image Field - Field Collection Show Only one Image I have a view that displays an image from a list of image field collections. However, it is showing all the images from the collection. I only want the first image to be shown and hide the others.

The Views module provides the option to select -in the field's settings- how many items you want to render for multi value fields. See the image below:


Custom tpl.php render issues I'm in a custom tpl.php file. I'm also highly confused!

This line renders nothing...

render($content['field_subtitle']['0']['#markup']);

This line drops the subtitle as expected but in the Devel_Themer formatting.

kpr($content['field_subtitle']['0']['#markup']);

I'm trying to custom-theme a content type in a custom node.tpl.php file. Everything should work as expected... but, of course... it's not. Any ideas?

It looks like you could use:

print $content['field_subtitle']['0']['#markup'];

or else just

print render($content['field_subtitle']);


Loading Webform Content into Select Box So I have a Webform called "Department". It contains "Marketing" and "IT" as submissions.

I have another webform called "Person". It is a form that contains a dropdown. This dropdown should be loaded with values from the "department" Webform data.

So I add a new webform, and add a "Entity Select" called "Person Department".

I go to build, in "Person Department", in the "entity references settings", I select "Webform Submission" as the "type of item to reference", and select "Department" as Bundle.

However, when I go to my "Person" form, the drop down is loaded with Person:webform submission5.

How can I display the value of the Webform data in "department", not the key?

Thanks

I think you are going to use a View for the 'Select Entity' element's reference method but you might run into Issue #2174633: View output is not used for entityreference options


What is the quickest way to dump a node to insert into a test case? Is there a script, console, drush command etc that can dump a node in the format needed to create a test case?
How can I rapidly fill out
$this->drupalCreateContentType(['type' => 'bond',
  'name' => 'Bond',
  'field_bond_amt_issued' => '1000000000',
]);

You can use drush:
drush ev "var_export(\Drupal\node\Entity\Node::load(123)->toArray());"

and delete stuff you don't need like uuid, revision_*, ...
By the way if you are wondering why does this output old style array syntax, see https://stackoverflow.com/questions/24316347/how-to-format-var-export-to-php5-4-array-syntax
... or paste the output into your IDE and configure it to autocorrect the format.


Views > Exposed Filter > How to disable output of options that aren't attached/used by a node I have a exposed filter setup to filter content within a view.

The view is displaying a list of house designs. These designs need to be able to be filtered by number of beds, bathrooms etc.

"House Design" content type/node has a field (List (integer)) for bedrooms:

http://theexhale.com/screenshot_1.png

The allowed values for this field are 1,2,3,4,5 (bedrooms)

http://theexhale.com/screenshot_2.png

The issue I'm having is that the exposed filter is outputting all of these fields for sorting the view even though currently only values "2" and "4" are being used by the "House Design" content type.

http://theexhale.com/screenshot_5.png

QUESTION: Can the exposed filter be smart enough to check to see if values of a field/taxonomy vocab are actually being used by the displayed content type/node and then dynamically only display those values in the filter?

I want to do this to remove/lesson the possibility of no results when a user uses the filter.

Thank you :)

The concept's the same in Drupal 8 but the access of properties and handling is a little different from what's done on D7. Here's a working example of 3 exposed filters dependent on each other to allow only values available based on prior selections.

Tips:
- View is built with page that has exposed form in block checked to yes.
- Enable master display, make sure filter identify of exposed filter is same
- Use BEF (better exposed filters) for menu select and autosubmit
- See code comments

This is for D8:

/**

* @file
 * Provides functionality for handling exposed filters
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ResultRow;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\views\Entity\View;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Entity;

/**
   * Implements hook_views_exposed_form_alter().
   *
   * alters exposed filter for equipment selector to limit filtered results in a new view
   */
function ahern_equipment_selector_form_views_exposed_form_alter(&$form,  &$form_state){
    if ($form['#id'] == 'views-exposed-form-ahern-exposed-filters-page-1') {
        // Get whatever values selected by user in all menus
        $input = &$form_state->getUserInput();

        // Form fields have given/arbitrary name from Filter identifier in Exposed filter settings
        $selected_what_moving = $input['moving'];
        $selected_where_working = $input['where'];
        $selected_height = $input['height'];

        // Again, form fields have given/arbitrary name from Filter identifier in Exposed filter settings
        // NOTE: make sure also match Filter identifier in Master display
        // Also keep in mind that any view duplicated/cloned from main view should be disabled as
        // it can/will affect results
        $form['moving']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_what_moving,
          'moving_chosen'
        );

        $form['where']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_where_working,
          'where_chosen'
        );

        $form['height']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_height,
          'height_chosen'
        );
    }
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $contextualFilter, $menu_chosen){
//ksm($contextualFilter,'context filter');

  $associativeArray = array();
  $associativeArray['All'] = t('- Any -');
  $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);

  foreach($viewResults as $viewRow) {

    switch ($menu_chosen) {
    // views_get_view_result returns rows with original field name so don't use filter identifier name to acceess, use field name
        case 'moving_chosen':
            //ksm($menu_chosen, 'target menu to filter to');
            $term_name = $viewRow->_relationship_entities['field_what_are_you_moving']->getName();
            $term_id = $viewRow->_relationship_entities['field_what_are_you_moving']->id();
            if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            break;

        case 'where_chosen':
            $term_name = $viewRow->_relationship_entities['field_attr_where_are_you_working']->getName();
             $term_id = $viewRow->_relationship_entities['field_attr_where_are_you_working']->id();
             if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            break;

        case 'height_chosen':
            //ksm($menu_chosen, 'target menu to filter to');
            $term_name = $viewRow->_relationship_entities['field_what_is_the_working_height']->getName();
            $term_id = $viewRow->_relationship_entities['field_what_is_the_working_height']->id();
            if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            asort($associativeArray);
            break;

        default:
            break;
    }

  }

    $associativeArray = array_unique($associativeArray);
    return $associativeArray;
}


the question of enable "mobile switch" I install the module of "mobile switch" and enable it.
But I just only enable this module and set a mobile theme, the error message is showed:

Notice: Undefined index: ismobiledevice in mobile_switch_boot() (line 40 of D:\xampp\htdocs\drupal\sites\all\modules\mobile_switch\mobile_switch.module).

I don't know how to solve it.
Have anyone know what'w happen?
Thanks....

You could try an alternative Theme key module rather then using mobile switch module to check for the mobile device.
It provides flexibility for changing the theme not only based on the type of device but also can theme different parts of site based on different conditions.
You can check for a detailed video tutorial by Mustardseed to check this features.


Update packages conflicting with core update When updating drupal core via composer, you often get problems like:

  Problem 1
      - Installation request for drupal/core 8.8.2 -> satisfiable by drupal/core[8.8.2].
      - Conclusion: remove typo3/phar-stream-wrapper v2.1.4
      ... (and so on)

How can you tackle these issues before updating core?

Update:
Thanks to the comment below from @mpdonadio below, it seems better to follow the official documentation right here: https://www.drupal.org/node/2700999#s-special-considerations-for-upgrading-to-drupal-880-and-later

composer update
git add composer.lock; git commit # Save the updates as a separate commit.
composer remove webflo/drupal-core-strict --no-update
composer remove drupal/core --no-update
composer require 'composer/installers:^1.7' --no-update
rm composer.lock
rm -rf vendor # Also helps avoid conflicts.
composer require drupal/core-recommended:^8.8 --update-with-dependencies
git add composer.json composer.lock; git commit -m "Update Drupal to 8.8.0 and use drupal/core-recommended instead of webflo/drupal-core-strict"

Old answer

First, make sure your composer version is not fixed (e.g. drupal/core:8.7.10):

composer require drupal/core:^8.7.10

This will update to its latest version (e.g. 8.7.11) but also makes sure you can progress later. To see which projects would cause problems, run:

composer prohibits drupal/core:8.8.0

This will result in a list:

typo3/phar-stream-wrapper (^3.1.3)
typo3/phar-stream-wrapper (but v2.1.4 is installed)

Then you can make sure you update the package:

composer require typo3/phar-stream-wrapper:^3.1.3

Then update like this:

 composer update drupal/core typo3/phar-stream-wrapper pear/archive_tar


How to update Geofield using a custom form and DrupalGap's node_save? The code below successfully updates the title, but does not update the Geofield. The node_save function is provide by DrupalGap and described here http://api.drupalgap.org/node.js_.html

        var node = {
            'nid': nid,
            title : 'New Title', // THIS WORKS!!
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude.toString(), // NONE OF THESE DO
            'field_geocoordinates[und][0][geom][lon]':tripchi.geocoordinates.coords.longitude,
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude,
            'field_geocoordinates[und][0][geom][lat]':tripchi.geocoordinates.coords.latitude.toString(),
            'field_geocoordinates["und"][0]["geom"]["lat"]':tripchi.geocoordinates.coords.latitude.toString(),
            'field_geocoordinates["und"][0]["geom"]["lon"]':tripchi.geocoordinates.coords.longitude.toString(),
            'field_deal_count[und][0][value]' : 3, // simpler structure also does not update
            "field_geocoordinates": {
                "und": [
                    {
                        "geom": "POINT (2 1)",
                        "geo_type": "point",
                        "lat": tripchi.geocoordinates.coords.latitude.toString(), // I've tried this as strings and integers
                        "lon": tripchi.geocoordinates.coords.longitude.toString(),
                        "left": "2.000000000000",
                        "top": "1.000000000000",
                        "right": "2.000000000000",
                        "bottom": "1.000000000000",
                        "geohash": "s01m"
                    }
                ]
            }
        };
        node_save(node, {
            success: function(result) {
                console.log(result);
                utils.mAlert("Pinpointed Location to Latitude:" + tripchi.geocoordinates.coords.latitude + ' - Longitutde:' + tripchi.geocoordinates.coords.longitude);
            }, error: function(result) {
                utils.mAlert("UPDATE ERROR: " + result);
                console.log(result);
            }
        });

How should i be targeting custom fields in custom html forms / ajax update requests?

UPDATE:
@Jimajamma is correct in the comment below, but this only works when the property to update is value. It is not working on the Geofield module object shown in my code above.

From this example it looks like the syntax is along these lines:

var node = {
  type:"donation",
  title:"Donation",
  field_donation_amount: {
    und: {
      0: {
        value: form_state.values.amount,
      },
    },
  },
};

Addition:

So have you looked at something like this then?  Nesting things further, eg:

var node = {
  field_geocoordinates: {
    und: {
         0: {
            geom: {
                  lat: FOO,
            },
         },
    },
  },
};

(I think I have the correct number of }s :)  Perhaps a js version of php's print_r (here is an example) of a valid node object from node_load() would help out?


menu_alter did not work I try to use menu_alter for changing Delete option in access callback. I clear cache many times but it still not working.
I also tried some solution in this site but still got nothing. Please help me to solve this one.

function manage_child_menu_alter(&$items) {
   $items['comment/%/delete']['access callback'] = 'manage_child_comment_delete_access';
   $items['comment/%/delete']['access arguments'] = array(1);
   dpm($items);
}

Drupal Commons 3.28

Thanks.

This is very common problem. What's your module weight? You can find the value in the table system. Try to change it to something more "heavier".

update DATABASE_NAME.system set weight = '99' WHERE name = "MODULE_NAME";

Standard approach hot to set a modude weight is to declare it in MODULE_NAME.install file:

/**
 * Implements hook_enable()
 */
function MODULE_NAME_enable() {
    db_update('system')
    ->fields(array('weight' => 99))
    ->condition('type', 'module')
    ->condition('name', 'MODULE_NAME')
    ->execute();
}


PHP query in a view will cause website error I'm using a global PHP query in a View to find out the count of membership users.
The first query, that extracts the total number of users from the database works fine, but when I use the WHERE clause in a query for a comparison with a string, I received a website error like in the image attached below.

This is the query:

<?php
$count_users_premium = db_query('SELECT COUNT(license_id) FROM {commerce_license} WHERE state="active"')->fetchField();
print $count_users_premium;
?>

So, if I want to use WHERE some_number=3, it will work, but comparison with a string didn't work. (Drupal 8 version)

You cannot directly insert values into queries in Drupal. They need to be escaped. You would want something like this:

$count_users_premium = db_query('SELECT COUNT(license_id) FROM {commerce_license} WHERE state=:active', [':active' => 'active'])->fetchField();


How do I execute my custom submission handler before any other submission handler? I want to execute my custom submission handler for a button before any other submission handler associated with that button. How could I do this?

array_unshift() the name of the function onto the "#submit" array of the button.


Dynamic view listing nodes in proximity dependent on taxonomy term in url - which is not attached to the node itself I think what I want is quite complex, but maybe someone can help me with some basics of it.

In d7 I have a content type and each node uses address field and via geocoder creates the geo data for that node. I use taxonomy terms here to categorize the node (eg: shop, restaurant, hotel, etc ..) and some nodes may have multiple categories added as they may be multiple types at the same time(one may be a restaurant as well as hotel).

I have created a taxonomy tree as such:

country -> city, eg:

england -> london
        -> manchester
        -> newcastle

Each city also has geo data attached to it. The country and city will be used in the url to filter the results based on a set proximity.

So, for example I could have this url

www.example.com/england/london/restaurant

which is equal to (for examples sake)

www.example.com/country/$2/$3

The country page is a static page that may list taxonomy terms (cities) for that country.

The next page up - selecting the city from the country page - does not yet display a view, but gives options for which category the node is in (this taxonomy term is attached to the node (Shop, Restaurant, etc ..))

Now I want to create a view that uses term $2 to set the location from which to start the proximity search from (the geo data is already added to the taxonomy field for cities and mustn't first get geocoded from the city name)

Then term $3 is the category which is attached to the node.

It then displays all the nodes from that category at a  previously set distance (radius) away from the cities geo data. I presume I can either create an admin field where the distance can be set or simply hard code it in the module.

So, I am quite new to creating my own custom module and apart from field api I have not had much experience with other drupal api's - especially the views api.

Here is what I need to do - as far as I am aware:

Create a custom module - I don't think I can get around that - that:

1) gets the $2 and the attached geodata

2) creates a view for all nodes with taxonomy term $3 attached to it and filters them using proximity to only show nodes in a XX km radius from the geo point supplied by $2.
  This obviously includes converting lat/long to distances from the set point...

3) I want to be able to display a proximity slider so the radius value can be changed and the view refreshes.

I know this sounds like a massive job, but I thought that maybe I could do some of it directly in views and then maybe use some alter_hooks to add queries (for example to grab the geo data for $2)...

Can anyone help me with this, or give me some tips on how this can be done?

I just need some sort of strating point as I am totally new to this. I would also supply any code written back to the community and document my processes for others to follow.

Many thanks in advance.

This is a broad question and becomes difficult to answer clearly. There are too many things to do and too many details to resolve. It looks a bit like you are trying to eat an elephant with too many missing teeth. I agree that you will need to create a custom module and by the description you gave, you will need knowledge of php for server side (pre display) and Javascript for client side action (after display). The first thing to do is get do some exploring in the structure of Drupal and how it operates.  From my own experience I know that a couple months of exploration has made a tremendous difference in my ability to solve a problem like this. Do you have any programming experience? If not start with php basics. Then move on to Drupal.

There is an excellent video tutorial series at buildamodule.com.  It charges for some of its content, but it covers a lot of ground.  Building a module will require php/mysql expertise (book:Beginning PHP and SQL by W. Jason Gilmore), an understanding of Drupal operations (book: The Definitive Guide to Drupal 7 publisher:Apress) and a solid knowledge of the key modules (book: Drupal Building Blocks by Earl & Lynette Miles).

You'll know your ready when you find yourself looking forward to writing a custom module.


Page not Found error when Views block containing node titles links placed on a specific content type I have a content type News whose nodes are used to generate two blocks using views "Most read news articles" and "Latest news articles". These blocks are printed through node--news.tpl.php tpl file when news is displayed in full view mode.

Problem is that that all the title links in blocks lead to "Page not found" due to URLs overridden as http://example.com/news/node/49610 while actually they should be like http://example.com/node/49610

When checking through firebug I can see that links are correct:

Popular product taken down

All links work perfectly When same blocks are placed on the <front>.

Any help to resolve this is highly appreciated.

That link isn't correct. It should be relative to your web root ("/node/49610") and not the current page ("node/49610").


Where can I alter the path of the anchor around a views items title? I have a view with several items and they link to their respective nodes.
However I also have an external URL field which if populated needs to replace the path around the title of the views item.

I've been looking for a hook that builds this title path and associates it with the title but so far have not had any luck.

I thought hook_views_pre_render() might have it but the title is just a string.

@No Sssweat interesting proposal. Yes, if an external path field is
  populated we link this node to that path in the view. – dibs

For example: I created a field called external url

In you view add field path then external url and then title

They need to be in this specific order for it to work

Then for path:

For external url:

For Title:


Submit package to packagist.org I'm trying to submit a module to packagist.org so that it can be directly installed via composer. I've followed the necessary steps and created the composer.json as required. Now when I'm trying to submit the module to packagist.org its giving me the following error:

  The vendor is already taken by someone else. You may ask them to add
  your package and give you maintainership access. If they add you as a
  maintainer on any package in that vendor namespace, you will then be
  able to add new packages in that namespace. The packages already in
  that vendor namespace can be found at drupal

You should not put your Drupal modules on packagist.org. Drupal modules are available on packages.drupal.org, where the module will be automatically exposed if you add it on Drupal.org.

it is explained here:
Using packages.drupal.org.


Image styles to make all user inserted images appear as circles Users can insert images on my site...i want that all of them are displayed in a similar fashion. So i created a new style under Image Styles. However, how can i make sure that all images appear as circled. Even if a user inserts a square image, the final display should appear in a circle. I do not find any option to do so. Any help or advice.

Thanks

To create the image style you want, you'll need to install the ImageCache Actions module to get the "Rounded Corners" effect.  Note that when you install this module, you need to turn on several different modules in drupal (and I'm not sure which one provides "Rounded Corners"):  image_styles_admin, imagecache_canvasactions, image_effects_text, imagecache_customactions, imagecache_coloractions, imagecache_autorotate, imagecache_actions.

Once you have the Rounded Corners effect, you should be able to create the behavior you are looking for.  Here's an example:

The only thing that you can't see on the screenshot is the "radius" setting for the rounded corners effect.   To get a truly round image, it should be set to half of the height/width used in the scale & crop step.  In the example, scale & crop is set to 100x100 and radius is set to 50.  If you set scale & crop to 500x500, you'd set radius to 250.

Once you've got the image style you want, go to Administration > Structure > Content Types, and choose the content type that has the image field.  Go to the "Manage Display" tab, and click on the settings icon for the image field.  This will allow you to select the image style to be used for this image field.

You may need to do this for multiple display modes for your content type, for example "Default" and "Teaser."