Sort view before print I have some node IDs I'm passing to a view; however the sort order is wrong.

Here's my pseudo code:

//query to grab the nids

if (!empty($nodeids)) {
  $view = 'taxo_listing';
  foreach ($nodeids as $nid) {
    print views_embed_view($view, block_1, $nid);
  }
}

What I need to do is pre-build the view then run implement hook_views_query_alter to sort the view before printing out the view.

Been looking at http://views.doc.logrus.com/ for a while now, but it's all a bit confusing, can anyone offer any clues as how to go about this? I know what I want to do but unsure how to go about it, sound familiar guys?

Thanks in advance.

I don't know where $nodeids comes from, but I expect it's an array of nids from a database query? If so, you're effectively running a view with a view and can probably get away without writing any code for hooks.

Therefore, you can either:

Sort the $nodeids yourself with uasort() which will mean probably returning more fields to sort with and maybe writing your own comparison function.
Let Views handle all of this, thus gaining access to the UI and all it's powers.

The latter 'view within a view' approach is better for sustainability and sanity because it uses the Views UI and theme layers more consistently. A good approach that's worked for me is:

Make a view that can either:

return the properly sorted $nodeids, or;
get it to take an argument of a comma-separated list of nids you can pass implode(',', $nodeids) to.

use Views PHP to add a field that can contain your views_embed_view($view, block_1, $nid), probably with $nid replaced by $row->nid but will depend on your setup.
Add any sorting or sorting code to the view you want.


How to display a block if a Boolean on/off checkbox is checked? I will eventually install Panels to accomplish this. But I can't at this time. I want to allow an editor to display a right sidebar menu on any page when they want by checking a Single on/off checkbox . I added a CCK field to the Page type - Boolean -Single on/off checkbox. I am using Drupal 7.43 on Centos 7 and php 5.4

There is a php block invoke inside another php that checks if a cck field is not null. The first php is looking at the Boolean field  'field_hide_sidebar_menu' to see if it is null or not checked. If it is null it will display the block. This is not working. I have used 'if!empty'
before to check if an image field is null and it works. Now I want it to check if the Boolean is checked or not checked so do I need to write this
in a different way to check if the Boolean value is on or off - equal to 1 or equal to 0. Here is my code:

<?php if (!empty($entity['field_hide_sidebar_menu'])): ?>

Menu
 <?php $block = module_invoke('views', 'block_view',
'menu_sidebar-block_1'); print render($block['content']);?>
<?php
 endif; ?>

Generally, if you're wanting to enable or disable a block based on some parameters (and assuming this block is defined within a module of your writing), you'd use hook_block_list_alter(), test for your condition, and then either display or hide your block.

You can see how this works by look at the block module's implementation of it's own hook, block_block_list_alter().

For instance, if you wanted to hide something based on the current node:

MYMODULE_block_list_alter(&$blocks) {
    $node = menu_get_object();
    $my_hiding_condition = isset($node->somefield[LANGUAGE_NONE][0]['value'])
      && $node->somefield[LANGUAGE_NONE][0]['value'] == TRUE;
    if (isset($blocks['my_block_id']) && $my_hiding_condition == TRUE) {
        // Hide the block.
        unset($blocks['my_block_id']);
    }
}


How to block / restrict a list of URLs using Rules? I'm currently blocking access to some admin menu pages using the Rules module as follows:

Events: Drupal is initializing

Conditions:

Data comparison > Data to compare:[site:current-page:url] then URL1 to block
Data comparison > Data to compare:[site:current-page:url] then URL2 to block
Data comparison > Data to compare:[site:current-page:url] then URL3 to block
...

Actions:

Show a message on the site
Page redirect to home

I want to supply a list of URLs in one field rather than multiple data comparison conditions, is this possible in Rules?

Assume the relative paths for your 3 URLs are like my/path1 (for ULR1),  my/path2 (for ULR2) and  my/path3 (for ULR3). And assume your homepage has a relative path MyHomePage. And assume this question is about D7.

With these assumptions, you could use a rule that answers your question which looks like so (in Rules export format):

{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "my\/path1",
              "my\/path2",
              "my\/path3"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "MyHomePage" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

Note site:current-page:path token in this rule, which is different from site:current-page:url.

To make the above rule work in similar situations, just adapt the paths by changing 'my/pathX' (with X=1, 2, 3) to whatever fits. And adapt the message to be shown.

Some more samples where you can see this technique at work:

How to use the Rules module to implement a custom redirect for an outdated URL?
How to hide the content of nodes/ completely, and still maintain use within Drupal 7?
What is the best way to restrict website's direct access through node urls?

Remark: Instead of using a data comparison in this Rules Condition, you may also want to try using a text comparison. That would allow you to use regular expressions. If your URLs have a common pattern for which you can write to single regular expression (such as URLx, with x=1, 2, 3, ..., 456, 457, ...), you would only need 1 such Rules Condition.


How do I create a photobox for image? Can anyone please guide me on how do I create a photobox that contains image and I wanted to display that image on landing page.

I have created content type as an Image. But, I don't know how to display that image in landing page.

I am new to Drupal. Any help will be appreciated.

Thanks!

First of all: welcome to Drupal :) But then I right away have say sorry, but I think it's not really a good idea to ask people to "guide you on how to…". People here try to ask straight questions and give straight answers – if they can.

About your actual question: for displaying a specific page as your front page a.f.a.i.k. all you have to do is to go to Configuration > then Site Information > then you can adjust the Default front page setting by entering the path of any of your pages… Hope this helps…?

And last but not least I can just recommend you spend some time with some basic recources and tutorials – for example Drupal 7 – the Essentials is sheer greatness! And the Community Documentation has almost every important aspect of Drupal listed, that one could need for a start…


How can I change the redirect that happens after a node is edited? Normally, after a node is edited, the user is sent to the node's display page.  I would like to change this so that the user is sent to a different page.  Is there a module for this or is there a native setting that I can use?

You have a few options.

If you want to install a module and use a GUI you should be able to do that with Rules.  Just install the module, and setup a new rule to react on saving new content.

If you do not plan on using Rules for anything else, it is probably wiser to just use a hook_form_alter in your custom module.  Just edit the forms $form_state['redirect'] in a submit callback. Something like:

function test_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='MY_FORM') {
    array_push($form['#submit'], 'test_userlogin_submit');
  }
}

function test_userlogin_submit(&$form, &$form_state){
  $form_state['redirect'] = 'MY/NEW/PATH';
}


What is the expiration time of Email verification link? When we use the "Require email verification" in account settings for creating new accounts, does the link have an expiration time or it will last forever?

If if never expires, is is possible to add an an expiration time, preferably using a contrib module?

The first time login link has no expiration time. Only password reset links have expiration time, which can be get or set using the system variable user_password_reset_timeout which has a default value of 86400 (24 hours).


Ho to make a whole block clickable? I have made the block and want it to be clickable(entire block) and we can provide the path to it?

Note: There is other question with same heading but it does not provide the answer and it is in context of views.

In the template.php, add an "onclick" attribute with theme_preprocess_block:

function mytheme_preprocess_block(&$variables, $hook) {
  if ($variables['block']->delta == "my-viewblock-name") {
    $variables['attributes_array']['onclick']='my_click-routine()';
  }
}

Then, in a .js file you add

function my_click-routine(){
  // Do whatever you want here, e.g. show the "page view" when clicking on the block view;
  document.location="page-view-url";
}

This makes the entire block clickable. You can also do more than just navigate to another page.


Search not selectable on iPhone I just finished a mobile-responsive site using an Omega sub-theme in Drupal 7. I just noticed that it is not possible to tap or double tap on an iPhone to access the search field.

I'm not sure where to begin looking for answers to this issue. Any suggestions?

Site:

http://dianalogan.com/

I have found out what was going on. Omega builds the mobile page by changing the side-by-side layout of regions to a stacked layout. The region with the search field and button was layered behind another region in the same zone. Once I removed this layering, there was no issue. An easy fix.


Allowing simple footer customisation in settings? So, I want to give the client the ability to edit the footer, copyright & legal area. This isn't worth it's own content or block. I don't think....

Is is possible to add a text entry field into setting to customize the footer area or alike areas on the website.

In Drupal 6, the Site information settings page at /admin/settings/site-information has a "Footer Information" field that meets your description above.  If this field is not empty, and you do a major upgrade of your D6 site to D7, then your footer information will be moved into a block called "Footer message".  While it would be possible to re-implement the "Footer Information" field from D6 in D7 with a custom module, or in the settings for your theme (which would be even easier) I think it is clear that D7 designers felt that using a block for this purpose was the best and most general solution.


Drush 5.9 - unable to untar Using the command:

 drush arr ~/drush-backups/site.tar.gz --db-url=mysql://df_database:password@localhost/df_databaseuser --destination=~/domains/site.kz/public_html/temp

(archive size is ~5gb),

I get this error:

 Unable to untar /home/user/drush-backups/site.tar.gz.                [error]
 Unable to extract site archive tarball to                            [error]
 /tmp/drush_tmp_1384866055_528b6107d88d6.

Why does it happen? However, when I try to untar archive lower than 1gb I'm not getting any errors.

By default the command drush archive-restore creates a unique temporary folder under /tmp (*/tmp/drush_tmp_1394487346_531e303223...*) where it will extract the archived tarball content, and later will move the $doc_root into the $destination - with the option overwrite.

I guess your /tmp folder resides on a separate partition, ~4GB in size; restoring a 3GB archive worked well, but it fails for 5BG. It looks like drush archive-restore works only when the system's temp folder is large enough to accommodate the extracted tarball.

PS. drush archive-restore is defined in archive.drush.inc :

function "drush_archive_restore" (drush_tarball_extract($file, $tmp)), where $tmp = drush_tempdir();

Funtion drush_tempdir() is defined in filesystem.inc - creates a unique temporary directory  and returns its path. drush_tempdir() uses drush_find_tmp() which more likely returns /tmp


How to display add node form below the view in Drupal 6? I have a very similar functionality to stackoverflow - i.e. I have a a view that display question and below it there are answers (seperate nodes references). The user can comment on both the question and answers. Below it I would like to display a form that is used to add another answer by the user. This node will simply create an 'answer' node and display it above (just as stackoverflow) How can I add such a form below the view?

You should check Form Block module. This block can be placed in any region beside your view.


How to get id of selected entity in an "entity_autocomplete" form element? I have a form element of "entity_autocomplete" type.
Also I have an ajax callback of the element.
Here is its code.

$form['autocomplete_places'] = [
            '#type' => 'entity_autocomplete',
            '#target_type' => 'node',
            '#selection_settings' => [
                'target_bundles' => ['place'],
            ],
            '#ajax' => [
                'callback' => '::autocompleteGetPlaces',
                'event' => 'autocompleteselect',
            ]
        ];

public function autocompleteGetPlaces(array &$form, FormStateInterface $form_state){
        $ajax_responce = new AjaxResponse();
/// some code here
        return $ajax_responce;
    }

Unfortunately, I can't find out how to get the id of selected entity inside the ajax callback function. For example, in my case, it would be id of a node of "place" type.

I tried to debug it, but couldn't find information about it in $form_state.

Could you clarify me, how to do it ?

Seemingly I managed to find the solution.

The event for the autocomplete element should be "autocompleteclose" instead "autocompleteselect".
And in this case it's possible to get entity_id via

$entity_id = $form_state->getValue('autocomplete_places');

if the list of values was closed without selected element then $form_state->getValue('autocomplete_places') is null.


AJAX in a calendar view block I have a month-view calendar block and would like to change months without page reload.
How can I achieve it?

This has been coming to Calendar for a while now, and I believe is currently in dev (issue queue). Having said that, I notice that fullcalendar has 666 sites using it, so it might be good to increase that number and make it less devilish :)


Get results from content indexed from other site with search api We are using the Search API module to implement the search pages on the site.

Current setup:

A custom backend to store the index. It is powered by Lucene. We were able to get a new search API backend plugin to do CRUD on the indexes.
This backend also implements the search functionality. It is implemented alright and I am able to retrieve the results in the view of the index.

Requirement:
The custom backend is used by other sites as well (not necessarily on Drupal) to store their index. I want to display results of these sites as well whenever a user does a search on our site.
However, there seems to a limitation in a way Search API module works.

In the custom backend we created, there are following lines which are responsible for letting the module know about the results

$item = $this->getFieldsHelper()->createItem($index, $row->item_id);
$results->addResultItem($item);

We took the Database backend as a reference to build this custom functionality from the search_api_db module which is a part of the search_api module.

Question: How do I display results from other sites along with the current Drupal site?

My guess is that you will not be able to do this with the standard search view process.  I believe that views does some linking of results to content that exists on the site.  So remote content will be filtered out.

That said, you can get what you want if you use the native Solr query requests.  These return the raw json (or xml) data from the server.  You can use this with custom code to display your results.

See the solr tutorial on how to create queries.

A site I used to manage used this with Angular.js to manage some really complex searches.


How to link a view´s field to attachment´s field? I am stuck with links in views. I need to rewrite one field of a view to a link to a field of view´s attachment.

Basicaly: view displays a grid of images. This view has an attachment. In the attachment is a list of [body]. The click on the image should navigate to appropriate [body] in the attachment.

I have set view (with exposed filter, relationships...), but I cannot think how to set up the link. I added field: nid to the attachment, but still don´t know how to link to it from the main view. Maybe I did something wrong, still learning on the go. Could you, please, help me?

So, my mistake, it is quiet simple. If you struggle with similar problem:
in the Attachment:
-add a field content: NID, hidden

-In global: custom text add, for example,
[title]

This way we have an NID anchor we can link to.

In the block view:
-add a field content: NID, hidden (so our link field gets NID as a value, not as a string "nid")

-we rewrite some field (for example title): output this field as a link. Link path: #[nid]

Voila, it works. My problem was I forgot to include content: nid in block view.


Import images from RSS with Feeds module without Feeds Image Grabber I'm passing all the sites from D7 to D8 and so far so good. But one of my sites gives me a couple of problems.

I was populating the RSS site in Drupal 7 using Feeds Image Grabber. Now, Feeds Image Grabber for Drupal 8 is not there. So how do I get RSS images then?

I read that maybe you can do it with the Feeds extensible parsers module.

Any advice?

RSS feeds are XML files, so you could indeed use the XML parser from Feeds extensible parsers to extract data from it. This parser works with XPath queries. XPath is a query language to select data from a XML file. So to select the image from the RSS feed, you'll need to figure out how to select that data with the right XPath query.

It would be a good idea to learn more about XPath before using the XML parser. I think that the XPath tutorial from W3Schools is a good resource for this.


how to bulk edit all users (change city field for example) I need to run bulk operations on all the users. Like changing the value of a field for all users.

I am using Profile 2 module for extended profile fields.

You can use views and views bulk operations for this.

You can create a user view and add a relationship that joins it to the profile2 profile.

Then add the views bulk operations field and configure it to include the "Modify entity values" operation. You could also change the label to "Change profile values" or something if you prefer.

Then on your bulk operations view, select the checkboxed for all the users you want to update a value for, select the "Modify entity values" operation, click the execute button, then complete then next form.

When you do this, you must be setting the fields to the same values for all the users you selected.

If you need to give some users a different value you have to go through the process multiple times.

If you have lots of different data and it wouldn't be feasible to go through this process so many times then you would be better off using something to import your data from csv, like the feeds module or the migrate module.


How can I prevent or limit CRON during SimpleTest? I have a CRON job that tops up a huge cache table. Normally, it only updates a few records. But the first time it runs in a new installation, it has to load the entire table with thousands of requests to an external API. This gives SimpleTest a big overhead for any minor test in the module.

How can I skip or limit CRON when SimpleTest creates a new installation?

I didn't find a way to know directly whether SimpleTest is running. For now, I am checking a role that the module creates for users. If there are no users of that role, I assume its SimpleTest running and limit my CRON.


Custom Field is disabled I have created a D8 module for creating a custom field. I have done it following the given links.

https://www.drupal.org/node/2052601
https://www.drupal.org/node/2620968
https://www.drupal.org/node/2620966

I have created an module.info.yml file . Then created a three folders inside

/src/Plugin/Field , namely,

FieldFormatter
FieldType
FieldWidget

I have coded in each of the folders as per the links.
I could see my custom field in the field list. But my problem is that it is categorized under disabled. Please help me to figure out the problem.

After both your field and your field instance are created, you need to enable it in the related form:

entity_get_form_display('node', $bundle, 'default')
  ->setComponent('field_custom', array(
    'type' => 'string'
  ))
  ->save();


Views with two content type and different fields in one table I've got these two content types, A (2014) and B (2015),  I'm tryging to combine in a view but  content A needs field to view node and content B to edit node,

The view show the fields but it show both options edit and view for all contents.

My actual view

The view I would like to do

For things like this I use Views Conditional.
Work with the replacement variables and hide unused content.


How to create a view returning untranslated entities I'm using entity translation and I want to create a view returning a list of untranslated nodes in the current active language. I have been searching all day but I cannot get this working...

I do not think you can filter for untranslated nodes. It is not exactly what you are asking but the way I did it is this:
1. Create a Content View
2. Add the field which can be translated (e.g. Body)
3. Add the field "Entity translation: Body: translated"
4. Choose one language of the translation (e.g. Current User's Language)
5. Click "Rewrite the output of this field" and type "X" in the Text box
6. Click "No results behaviour" and type "-" in the Text box
7. Repeat steps 3 to 6 for other languages if you want to check multiple

This should produce a table with the first column being the source language and the rest of the columns corresponding to the different languages of the translations. When a record has been translated an X will appear, otherwise a - will appear.


How to determine the code for settings.php config override based on .yml? I am trying to put my API keys in a separate file instead of storing them in config management.

For example, I installed the Commerce Stripe module.

When I export the config, it looks like this:

commerce_payment.comerce_payment_gateway.stripe_test.yml

uuid: 430a9544-c852-4a14-b7b0-3a833a02dd06
langcode: en
status: true
dependencies:
  module:
    - commerce_stripe
id: stripe_test
label: 'Stripe Test'
weight: null
plugin: stripe
configuration:
  publishable_key: thisishidden
  secret_key: thisishidden
  display_label: Stripe
  mode: test
  payment_method_types:
    - credit_card
conditions: {  }
conditionOperator: AND

Now, I want to store publishable_key and secret_key in a file, but how do I determine the "path" to call them?

$config['whatgoeshere?']['configuration']['secret_key'] = 'abcdefg';

The first key is the name of the config object/file, so... commerce_payment.comerce_payment_gateway.stripe_test.

The rest you already figured out, it's an array that's recursively merged into the other one.


How to trigger a popup window/overlay in my module? I am stuck in my project. I am working on a module for account management page. When the user update their billing address, a service call will be triggered to send request to a third party API to get a response indicating if the address if valid or not. If valid then display the returned normalized address in a popup box or overlay, the user can choose if he want to use that address or not. My question is that how to trigger displaying this popup box in php code?

Thanks!

Take a look at the Colorbox module.

You can find a few examples here.

Usage Example:

open URL in Colorbox (iframe)


Downgrade jquery from 1.5.2 to 1.4.2 How can I downgrade the jQuery library on Drupal 7 from 1.5.2 to 1.4.2; it looks like i've lost some functionality in Panels and Views after enabling the jQuery Update module.

The jQuery Update module updates Drupal's jQuery library from 1.4.4 to 1.5.2. If you don't want version 1.5.2 then you just need to uninstall the jQuery Update module and everything will go back to normal.

If you want to use jQuery Update just to update the jQuery UI library to v1.8.11 it looks like you'll have to patch the jquery_update.module file directly, as the version numbers for the base library are hardcoded into the jquery_update_jquery_replace() function using this code:

switch ($version) {
  case '1.5':
    $trueversion = '1.5.2';
    break;
  case '1.7':
    $trueversion = '1.7.1';
    break;
}


page template for view I have a view which I want to give a different look and feel from the rest of my page. Now the view is displayed as a page at a specific URL. I have tried naming my custom page template like views-view--mobile-special-events--page.tpl.php, (mobile-special-events being the name of my View) but this didn't work, it seems to apply this template only to the actual view area on my page but I want to re-theme the complete page, what do I need?

edit 1

I found this page: https://www.drupal.org/node/701920 where they say that you can preparte a page template from the link but I called my template page-mobile-special-events.tpl.php while my page is reachable under www.mysite.com/mobile-special-events but it doesn't seem to work, I've cleared the cache... what's going on, I'm wondering... :o

The thread you link to is for Drupal 6, if you are using Drupal 7 I think the template file should be:
page--mobile-special-events.tpl.php (note the double dash).


What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc? I have seen many times people saying not to use custom PHP/PHP filter (from the Drupal UI) in blocks, nodes, views-args, rules, etc. I have searched around a bit and haven't found much, it seems like this is a Drupal best practice that all "just know".

I understand it poses a potential security risk especially in the hands of end users or people new to Drupal or PHP, but as a developer/site builder what are the real reasons to not use custom PHP from the Drupal UI?

Some reasons:

Code in your database can not be version controlled and is also harder to find in general later on.
Eval()'d code is much slower than something hardcoded in a file.
If there is an error somewhere in that code, you will get a very unhelpful error message (error in eval()'d code at line 3) and you might even have go through your database manually to find and fix the error. If it is inside a block that is displayed on all pages and results in a fatal error all the time for example.
The above is also true when upgrading from Drupal 6 to 7 and whatever API's you used were changed. So you will have to port your code while migrating. If the code is in a module, you can port it in advance, test it, and only deploy it on the new site. Inside a node or block, it will only work with either Drupal 6 or 7.
Writing and maintaing that code is also harder, because you are working in a textfield inside your browser. Having it in a module allows you to use an editor/IDE with syntax highlighting, autocomplete and so on.
There is always the possibility of a misconfiguration that gives people access to a text format/block/whatever with php execution enabled. If php.module (in D7, D6 is not so strict, for example for block access rules) isn't even enabled, that risk is much lower already.
If your CMS allows execution of PHP then an attacker who finds a security vulnerability of XSS or privilege escalation can now use your server for enormously malicious things (as part of a DDOS, sending spam, hosting malware, hacking into other sites/databases on the server, hacking into other servers on the network that might be behind firewalls). In addition to making small vulnerabilities more painful, this makes the site a more likely target of attack if its known that it can be used to execute php.

There might be more reasons, but that should be enough :)


Adding option to one product in Commerce but not to others of the same product type Ok so my situation is I am developing a website for a takeaway / restaurant and there are a number of products that fall under a product type, lets call this starters product type.

One of these products has the option for couscous or rice.

I would rather not have to list this as 2 listings on the menu and instead have it as one with some kind of option either before or after the person has clicked add to cart.

Are there any modules out there which are close to achieving something like this? Most I have found seem to be directed at product types as a whole.

You can build your restaurant menu based on views, where you list commerce_products instead of product types(nodes). This will render one row for each variation.
You can also add relationship to your product types(nodes) for rendering/grouping/filtering.

You can also render the view of product variations at the product full page. Then the user will see all the possible variations of current product at once.


modifying results displayed for Search API Live results module I really like the SEARCH API and have been playing with Search api live results. I have two questions about this though:

Is there a way to bold the the part of the live search result that matches what i've typed so far? Ex: if i've written "cat" and there's a node with the title "caterpillar" the live search results will show "caterpillar" I know that Search api autocomplete does something, but I was wondering how to do so with this module. I did check out this tutorial but I want to modify the content that appears below the search box, not in the search page.

My second question is: Is there a way to have the results (again, not the ones on the search page, but the ones generated below the search box) organized in subsections, by contentype.Ex: I type cat and there are results of content type a, content type b, content type c.

Contenttype a
cat a1
cat a2
Contenttype b
cat b1
Contenttype c
cat c1
cat c2

Would I be able to do this with a view or would I have to write code to do this?

----------------UPDATE------------------
I think I found the function that generates the html for the live results. I’ve attached an image of it.
In this function, I can see how a live-result-search-item div is created but I haven’t quite fully figured out how they generate the href inside it. I feel like it's done in another jquery function which I've also attached an image of.  I posted an answer. I still haven't figured out how to group items by content type though.

for(key in matches){
   var endOfUrl = matches[key].search('>')+1;
   var url = matches[key].substring(0,endOfUrl);
   var rest = matches[key].substring(endOfUrl);
   var regex = new RegExp( '(' + searchString + ')', 'gi' );
   bolded= rest.replace( regex, "<b>$1</b>" );
   matches[key]= url+bolded;
}

right before the line

db.cache[searchString] = matches;

This bolds all occurrences of the word in the Title and makes sure the bolding goes into the cache for when it's pulled up again.

Another update:
I was able to get my results grouped by content type by installing and enabling Search API grouping and modifying my index's filter (admin/config/search/search_api/index/node_index/workflow) so that under "enabled processors" i checked grouping.

Once I did that, I also modified my search page so that my view mode was Live Result Search. This gave me access to the node content type in the js file I was modifying so that I could then parse the html string for the node-type and add an element to the live results list that was the content type label. Comment if my JS file interests you.


How to filter view with date field by today's date? I came up short on good ways to filter a user list to only show users who's birthday is today.
There has been efforts in D6 but nothing in D7?
As a "hack" I used an exposed filter for the birthday field (a date field) and then created a link from a block using PHP code:
$today = date("m-d", strtotime("today"));
print 'Today\'s Birthdays';

Ideally, I would like to override the input field with a select option to show " yesterday, today, tomorrow, next week".
Are there any better options doing this in D7?

Based on the comments, it seems like you already have an answer, so I'm posting it as such.

A regular date filter already has support for doing a check for field_birthday == now. You can granularity, such as hour, day, week, and even do simple arithmatic, "now + 1 day" and similar.


Set expiry time for fields on content type Is there a module which allows to set expiry date on fields on content type. Needed when we want a particular field to be expired after a given interval of time, not the complete node as in case of node expire module.

First feature of Node expire is:

  Perform custom actions when the nodes expire

Just write a custom action that will change field's value instead of unpublishing node.


Rules - show information after certain time I'm wondering how can I achieve this.
I have built a page, on which the content of certain type was being unpublished after 2 weeks. I created rule for that (component + component schedule) and it worked without problem.

But now I have to change the behavior - instead of old content being just "removed from sight of users", it has to remain visible but display a message. Something in the line of "this content has expired, but you can check for available offers on the main page".

I thought that setting the rule and picking up the "display message on site" could be what I'm looking for, but seems like I was wrong. No idea if I can do it in Views (how to link specific Rule to it?), so I'm looking for help.

Any ideas how to achieve that message displaying to users after certain time has passed?

If you want to achieve it with rules, you can do it with the following steps:

Add new rule
React on event: Content is viewed (under Node section)
Add new condition: Data comparison
Data to compare: node:created
Operator: 'is lower than'
Data value: Switch to the direct input mode and put '-2 weeks', or '-14 days'
Add new action: 'Show a message on the site' (under System section)
Put your message in as value, and select the type of the message. E.g. 'Status'


Layout of multiple items of the same field in Panels node template My content type is a preview of a music album so the fields include mp3 file and text fields about the track (title etc). I am using a panels node template which looks like this

This works fine for one track and the result looks like this:

But if I add a second track it looks like this:

ie

All items in Field 1
All items in Field 2
All items in Field 3

How can I make it look like this:

ie

field 1 item 1
field 2 item 1
field 3 item 1
field 4, item 1

field 1 item 2
field 2 item 2
field 3 item 2
field 4, item 2

etc

I think I would have the same problem in Views.

Edit your content type and Use a field collection. instead of multiple fields. It's difficult to achieve what you want without explicit entities.

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

Field collection will allow you to add multiple fields into one group, so instead of adding data to each field, you can just keep adding groups of data.
This will allow you to add a collection of Artist, track number, track title, mp3 Then when you call the field collection via panels it will give you the results you want.

You are using multiple fields which will list the values from each individual field right underneath eachother.


Views Calc always uses contextual filters of master display I have many displays in the view.
One of them is a views calc table.
Contextual filters in the master display and in the views calc display are different.
And when contextual filters differs from master views calc doesn't work correctly.
Views calc ignoges contextual filters of the current display and shows calculation results using contextual filters of master.

Has enybody noticed this issue?

As temporary solution :
I've deleted all contextual filters in the Master display and overrided them in other displays

But then i patched Views Cals module.

Views calc realy always executes "filter criterias" and "contextual filters" from default display.
So before executing view we must set view in a needed display. It's very important!
Here is the patch for it:

http://drupal.org/node/1868900#comment-7026538


How do i select all from database and do while loop with them I did this easy select and im getting Error: Call to a member function fetchAssoc() on boolean , im beginner, im just trying to pull out two variables and make operations with them.

$result = db_select('cities', 'c')
        ->fields('c')
        ->execute()
        ->fetchAssoc();

  while ($row = $result->fetchAssoc()) {

    $city_id = $row['city_id'];
  $city_name = $row['city_name'];

Only this is working for me

     $sql = "SELECT * FROM {cities}";
           $result = db_query($sql);

  while ($row = $result->fetchAssoc()) {

    $city_id = $row['city_id'];
  $city_name = $row['city_name'];

Try with this:

   $results = db_select('cities', 'c')
    ->fields('c')
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);

   foreach ($results as $result){
    $city_id = $result['city_id'];
    $city_name = $result['city_name'];
   }


preprocess views view field find view block name I need the to find the block view name so I can add it to the if statement in hook_preprocess_views_view_field in Drupal 8. How would I do this? When I use kint($variables['field']) to find the variables Drupal explodes so I don't even know if the variables exists

/**
 * Implements hook_preprocess_views_view_field()
 *
 */
function mytheme_preprocess_views_view_field(&$variables) {
    //-- I need the to find the view name
    //-- so I can add it to the if statement
    if ($variables['field']->field == 'nid') {
    }
}

Try the following

//gives you views current display - "block_1" or "page_1"
$variables['view']->current_display;

//gives you views id - "recent"
$variables['view']->id();


Adding more menu in the menu settings? In Drupal 7, in admin/structure/menu/settings we have the main links and the secondary links.

Can we add third one here? Is there any way to get the list of all menus created in backend?

Can we add third one here?

Yes, we can. Use hook_form_alter(), alter form_id menu_configure.

How do I know what form_id? Let's see menu_menu() at http://api.drupal.org/api/drupal/modules--menu--menu.module/function/menu_menu/7

  Is there any way to get the list of
  all menus created in backend?

Again, We can. Select menus in table {menu_links} where {menu_links}.menu_name = management.

    $result = db_select('menu_links', 'm')
    ->fields('m')
    ->condition('menu_name', 'management','=')
    ->execute()
    ->fetchAssoc();


Entity reference field pointing to a Configuration Entity I develop a custom statistics module to log all node views of a chosen bundles, file downloads and the keywords used to filter a view.

Then I build my Entity Log with a user reference (who does the action), a node reference and a file reference. I want to know if I can make a views reference to point the View (as a configuration entity) that the user searched for some keyword.

I don't know if this is crazy... Is it possible to reference a view from an entity?

I'm using drupal 8

This is no problem, in ui you can configure bundle fields referencing all entity types, content and configuration. And for base fields this is an example from the user entity for a reference field pointing at the configuration entity user_role:

$fields['roles'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Roles'))
  ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
  ->setDescription(t('The roles the user has.'))
  ->setSetting('target_type', 'user_role');


How to imitate EVA with TWIG? On my Drupal 8.9 (with Twig Tweak module) home page I integrated a block with the following code :
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}

This block displays the rendered entity (with display mode tasks-frontpage) of the stores of the current user.
I rewrote the display mode of the stores with by creating the following file :
commerce-store--professionnel--tasks-frontpage.html.twig

Here is the file code. All views included in this code have a context filter with the path of the current store :
Vous avez
{% set dangers = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1') is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1') is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1') is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1') is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1') is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{{ dangers }}
tâches importantes dans votre {{ store_entity.type.entity.label }} "{{ store_entity.name.value }}".
Voir la liste

MY PROBLEM :
When the {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }} block is rendered on my home page, the blocks in the commerce-store--professionnel--tasks-frontpage.html.twig templates do not work. This is normal because I think it searches for the store ID in the URL.
How do I fix this ? There is an EVA module, but is there another way to do this directly with TWIG ?
THE OBJECTIVE :
The goal is to create a list of tasks in stores and display it on the user's home page.
The blocks views in the commerce-store--professionnel--tasks-frontpage.html.twig template are used to control this :

If the store has no product.
If one of the products in the store has no variation.
If the store has an order in progress.
If the store does not have an associated delivery method.
If the store does not have an associated payment gateway.

It may be possible to control this directly in a store template without using views ?
SOLUTION :
Vous avez
{% set dangers = 0 %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1', store_entity.id()) is not empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1', store_entity.id()) is empty %}
  {% set dangers = dangers + 1 %}
{% endif %}
{{ dangers }}
tâches importantes à traiter dans votre {{ store_entity.type.entity.label }} "{{ store_entity.name.value }}".
Voir la liste

MY PROBLEM :
When the {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }} block is rendered on my home page, the blocks in the
commerce-store--professionnel--tasks-frontpage.html.twig templates
do not work. This is normal because I think it searches for the store
ID in the URL.
How do I fix this ? There is an EVA module, but is there another way
to do this directly with TWIG ?

If you don't want context filters getting IDs from the current path or current user you have to pass arguments to the View:
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1', store_entity.id()) }}

The arguments can be an array or a scalar if it is only one argument.


Drupal Login for my Android application? How to use drupal login in my android application I want to use the same database that is used in the drupal site.I want to login with the same user name and password that is used in drupal

Please any one help me with this

Services module allows remote login validation using REST calls.


Views date field does not follow custom date format I have a custom date format defined (via code), and this is what I see in the administration pages:

Custom Date Formats (png screenshot)

In views, I've attached a field, and trying to use a formatter, but they're all showing up like this:

Views Date Format (png screenshot)

I can't seem to select my m/d/y feature, and even the default (short, medium and long) are strange. I have tried clearing caches, and the usual. The view is being exported with a feature, and I have not tried recreating it, yet. Any ideas?

Here's the code generating the custom date format:

/**
 * Implements hook_date_formats().
 */
function custom_date_formats()
{
  $formats = array();

  $formats[] = array(
      'type' => 'm_d_y',
      'format' => 'm/d/Y',
      'locales' => array(),
  );

  return $formats;
}

/**
 * Implements hook_date_format_types().
 */
function custom_date_format_types()
{
  return array(
      'm_d_y' => t('m/d/Y'),
  );
}

I still did not find the answer to this problem, but fixed it. I fixed it by simply saving the custom date format form in Date & Time in Drupal. Simply submitting that form, without making any changes, refreshed the Drupal views, and it started working properly.

I will look into the submit handler to see what caused the problem, and post if I find anything.


How to check whether the page content is been managed by blocks, views or anything? I have one webpage (created in Drupal 7) and I am not able to figure out wether the content comes from blocks, views or anything else? I have checked blocks and views but there it is not appearing. How to check?

If you are logged in as administrator of the site, usually you should see either a edit button (for full nodes) or a contextual link for editing the a view or a node. You will need to have permission to see contextual links.


How can I create a node via ajax call? I have a site where a custom form is in opened in a modal, and when submitted calls an ajax function to POST to a REST service to create a node.

The problem is I keep getting "Forbidden" response upon submission.

I only want logged in users to be able to send these ajax requests and the auth should be different token for each user.

Here is my code:

$('#create-node-submit').click(function(e) {
    e.preventDefault();
    var newNode = {
        _links: {
            type: {
                href: 'http://mysite.dev/rest/type/node/article'
            }
        },
        type: {
            target_id: 'article'
        },
        title: {
            value: 'This is a test Article from REST'
        },
        field_description: {
            value: 'Here is some test description.'
        }
    };
    getCsrfToken(function (csrfToken) {
        postNode(csrfToken, newNode);
    });

    return false;
});

function getCsrfToken(callback) {
    $.get(Drupal.url('rest/session/token'))
        .done(function (data) {
            var csrfToken = data;
            callback(csrfToken);
        });
}

function postNode(csrfToken, node) {
    $.ajax({
        url: 'http://mysite.devdev/entity/node?_format=hal_json',
        method: 'POST',
        headers: {
            'Content-Type': 'application/hal+json',
            'X-CSRF-Token': csrfToken
        },
        data: JSON.stringify(node),
        success: function (node) {
            console.log(node);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Status: " + textStatus);
            console.log("Error: " + errorThrown);
        }
    });
}

When running a test in POSTMAN it is successful, but the authentication was slightly different there:

As you can see in the picture, I get 201 created when using POSTMAN.

I believe it has to do with the CSRF token being used in the Javascript implementation.  I'm not sure what authentication method I'm supposed to use when POSTing to the same site via JS.

I used the information here.

I created a bug report as it seems the CSRF token check passes successfully and grants access, but access is denied from somewhere else.
Issue #2831251 Trying to create nodes via REST with ajax POST request returns 403 response

You can use Postman, a Google Chrome browser app that allows you to POST, GET, PATCH, and DELETE to any site (for testing purposes), to generate the code for you:

After completing the 3 steps shown in the picture, you need to perform 1 more step:

Then paste the code into your custom module.

PS: I believe you can delete the postman-token line in the headers.


Printing nice menus using template file I am having a custom menu created in admin/structure/menu configured to nice-menus. and now I am trying to print that menu using my section.tpl.php file like

$nice_menu = block_load('nice_menus',"1");
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($nice_menu ))));

What I see is only the menu title displaying on the page, when I inspect the html source in firebug I see the html needed for the menus are generated. This is frustrating me for the last couple of hours, is there is another way to print my nice menu using the template file?

Try This

$nice_menus_block =_block_get_renderable_array(_block_render_blocks(array(block_load('nice_menus', '1' /*1,2,3 more,  this is get nice_menus_2 block*/))));
print render($nice_menus_block);


If a Views Contextual Filter using PHP code doesn't resolve, can I make Views "Display all results" Situation:

Contextual filter "Has taxonomy term by ID"
Filter is set to "Provide default value" > "Type: PHP Code"
The PHP code resolves in most cases, but on some pages it shouldn't.  In those cases I'd like to do what Views does when you choose the "Display all results for the specified field" option.

Is there something my PHP code can pass back to Views that will cause it to display all results?

(Or even 'Display contents of "No results found"' because then I could use a View inside there)

Config: Views 3, D7

when you want to show all then

return "all";

;)


Problems Installing Colorbox Module "Requires: Libraries (2.x) (incompatible with version )" I followed the instructions and installed the Colorbox plugin, the Colorbox module, and the Libraries API module. For some reson, when I go to the Modules pages and try and enable the Colorbox module, it says Requires: Libraries (2.x) (incompatible with version ). Even though libraries 2.x has been installed. I can't figure out what I'm doing wrong.

It should just happen when the Libraries API doesn't contains the version line in libraries.info. That would explain why the message doesn't report the Library API version.

I made a test on my test site. On the .info file for a custom module I added the following line.

dependencies[] = libraries (2.x)

In the libraries.info file, I removed the following line.

version = "7.x-2.0+5-dev"

When I visited the module page, I saw the following message for my custom module:

  Requires: Libraries (2.x) (incompatible with version )

I thought it would happen when the installed module was a development snapshot, but it's not true. If I add the line I removed, all back to normality, even if I installed the development snapshot of the Libraries API module.

If you copied the Libraries API files from a Git repository, the libraries.info file is missing the version line, and that would explain the message error you see.

Removing the version from the dependency line is fine, as long as you don't install the Libraries API module 1.x by mistake.


Where in the database does fieldset and field instance info live? Background: I'm writing a module that will hopefully make reverse-engineering specs for site audits easier. (If you're interested, you can see the Topograph module-in-progress on my Github account.)

Basically it's a bunch of byzantine views that use custom handlers to pull things like serialized data out of the DB to display stuff like nodetype settings to the admin user.

I'm having a lot of trouble finding certain things, though. Fieldset info is a major one, as well as settings like whether the field is required. I'm not finding it in the blob of data pulled from the {field_config_instance} table (though I might be overlooking it). Can someone point me to where this info can be retrieved per nodetype/field instance?

Whether a field is required or not can vary by content type (ie, the bundle).  I am pretty sure you need to use field_info_instances($entity_type, $bundle_name).  You can then use field_info_field($field_name) on the results.  Something like:

$fields_info = field_info_instances('node', $bundle);

foreach ($fields_info as $field_name => $instance) {
  $field_info = field_info_field($field_name);
}

dpm() both the $instance and $field_info.  Everything you need should be in those two variables.  This is a snippet from a dynamic exporter I have.


Why do Drupal.behaviours and document.ready behave differently? I have the same piece of jQuery that works differently depending whether it is wrapped in document.ready or Drupal.behaviours. The code is intended to enumerate a list of tabs generated by the vertical tabs module.

Using

Drupal.behaviors.myModule = function (context) {
   $('ul.vertical-tabs-list li').each(function(i){
     console.log(i);
   })
}

Logs no output, but the following works as expected.

if (Drupal.jsEnabled) {
$(document).ready(function() {
      $('ul.vertical-tabs-list li').each(function(k){
      console.log(k);
      })
    })
 }

Why is there a difference and how can I get the first version to work?

Drupal.behaviours are similar to document.ready but Drupal make sures that on every ajax call code written in a Drupal.behaviour is executed again. While code written in document.ready is called once on page load.


Where is FID xxx used? Is there a way to see where a file is used, with FID? I see the entry in the file_managed-table (Drupal 7), but not where it is used.

To show a usage list for a particular FID (file ID) you can visit the following url on your site:

/file/FID/usage

Just replace FID with the file id you want to check the usage for.

You can see an overview of all file usage at /admin/content/file. You can access this page from the admin toolbar at Content > Files.

Here is an example of what the file usage table looks like on that page:

This shows the name of the entity where the file is in use, the entity type and the usage count.


How do I alter a boolean value and display a string in views output? Whats the best way to override a simple 0/1 boolean field in views output so instead of 0/1 it would output "Hello" or "Goodbye"?

EDIT: To improve on my question:

Whats the best way to add further options to the default view boolean handler? For example ...

$default_formats = array(
  'yes-no' => array(t('Yes'), t('No')),
  'true-false' => array(t('True'), t('False')),
  'on-off' => array(t('On'), t('Off')),
  'enabled-disabled' => array(t('Enabled'), t('Disabled')),
  'boolean' => array(1, 0),
  'unicode-yes-no' => array('✔', '✖'),
  'drunk-sober' => array(t('Drunk'), t('Sober')),
  'hello-goodbye' => array(t('Hello'), t('Goodbye')),
);

Well, that was a lot easier than I thought. Basically took a gander into node.views.inc and got the answer.

function MYMODULE_views_data_alter(&$data) {
  $data['MYENTITY']['MYFIELD'] = array(
    'title' => t('MYFIELD'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
      'output formats' => array(
        'drunk-sober' => array(t('Drunk'), t('Sober')),
      ),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      'label' => t('MYFIELD'),
      'type' => 'yes-no',
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
}


How to change content url content/title to text/title? I created some content and changed the URL content/title to text/title.
My issue is why my changes didn't apply on some content.

You probably have to delete and then bulk create them from the admin/config/search/path/delete_bulk and admin/config/search/path/update_bulk pages.

Be careful though if there are links pointing towards pages.


how to update a node field value with jQuery callback the drupal way? added the callback for jQuery to the hook_menu in my module.

// callback for jQuery with nid and new status as arguments
$items['vacancies_manage/status_callback/%/%'] = array(
    'page callback' => '_vacancies_manage_status_update_callback',
    'page arguments' => array(1,2),
    'access callback' => array('manage own vacancies'),
    'type' => MENU_CALLBACK,
);

return $items;

but how do I call this callback from the module using jQuery instead of just the link? Is there a drupal way for this?

The jQuery would be pretty simple, something like this:

$('#link-id').click(function() {
  $.ajax({
    url: '/vacancies_manage/status_callback/' + id1 + '/' + 'id2',
    data: {'arg1': 1, 'arg2': 2},
    success : function(data) {
      alert(data);
    }
  });
});

You'll need to replace id1 and id2 with the arguments appropriate to your situation, and arg1 and arg2 with whatever you want your POST vars to contain.

Then you just need to make sure that you callback actually prints directly to the page, and doesn't return the entire rendered Drupal page so that the jQuery code can receive a response:

function _vacancies_manage_status_update_callback() {
  // Do something with $_POST vars here

  // Print something, perhaps a status message to be picked up in jQuery
  print 'OK';
  drupal_exit();
}


call to undefined fucntion error Call to undefined function modalframe_close_dialog() in

I am using Drupal 7

function close_model_dialog($form, &$form_state) {
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  $form_state['redirect'] = FALSE;
  modalframe_close_dialog();
  modalframe_child_js();
}

It means what it says: There is no file included in the current page request that contains the definition for a function called modalframe_close_dialog().

A quick Google search shows that this function is part of the ModalFrame API module, for which there is only a Drupal 6 release (not Drupal 7). I guess you've copied this code from a Drupal 6 site without changing it?

The comments on the ModalFrame API module page say:

  It seems this feature is being included in Drupal core itself. So, probably there will be no stable release of this module for Drupal 7 because it will be already there

My best guess is that the Drupal 7 equivalent of this function is overlay_close_dialog(), but I can't comment as to whether that will work as in a drop-in replacement for you current code.

It might be worth reading the Initial D7UX admin overlay thread, it's basically the discussion about moving ModalFrame API into core.


How to change Search API index field machine name? I am using Search API and Search API Solr modules on drupal 7. I have also drupal 8 and drupal 9 sites, and all those sites are indexed on the same solr index. So I need the same machine name for indexed fields on Solr index. For this purpose, I need to change marked machine names.
Solr index field names are generated from those machine names.

For drupal 7 I can't find a field mapping solution like Search API field map module for drupal 8, 9.
Is there any solution to override those fields' machine names in index creation?
Thanks.

My answer I found in search_api_solr module search_api_solr.api.php file. I used hook_search_api_solr_field_mapping_alter
/**
 * Change the way the index's field names are mapped to Solr field names.
 *
 * @param SearchApiIndex $index
 *   The index whose field mappings are altered.
 * @param array $fields
 *   An associative array containing the index field names mapped to their Solr
 *   counterparts. The special fields 'search_api_id' and 'search_api_relevance'
 *   are also included.
 */
 function hook_search_api_solr_field_mapping_alter(SearchApiIndex $index,
                                                               array &$fields) {
   if ($index->entity_type == 'node' && isset($fields['body:value'])) {
    $fields['body:value'] = 'tm_text';
   }
 }

Here you can add required Solr index field name('tm_text') for according field('body:value').


Can I create a link to a nodes taxonomy page? I have a page that has a single category applied to it, for this example, "Self Help Books".

I want to put a place on content type that display a "view all [insert category here]" that links to that category listing page. I was hoping I could do something like:

view all %taxonomy:books%

and it would pull in the category for anything using that content type. I'm using the panels modules so I had planned on placing this in a panel the content type was using. Is any of this possible?

I thought about creating a block and placing that in a panel in the panels module.

(also, if you can't tell, I'm pretty fresh to Drupal.)

There's a default path that links to taxonomy/term/term_id. For instance if the term_id for the term Self help books is 42, the following path will list all self help books.

taxonomy/term/42

Now, to replace this with the appropriate string, navigate to:

Home » Administration » Configuration » Search and metadata » URL aliases

and specify that Self help books should be an alias for taxonomy/term/42.

First, make sure all nodes that you want listed as self help books is tagged with the tag Self help books.

Then, to create a link to the nodes tagged with a specific term based upon vocabulary, you need to install and enable the Token module and the Token Filter module (unless you've already done so).

Next navigate to:

Home » Administration » Configuration » Content authoring » Text formats

and click Configure on the text format (or formats) you plan to use. Under Enabled filters. make sure the filter named Replace tokens is activated.

You can now see the what tokes that exist by going to:

Home » Administration » Help » Token

and expand the Nodes item.  Let us say that your book category field is named node:field_book_category.

Then, if you put an HTML link like this somewhere on a page tagged with Self help books:

View more [node:field_book_category]

you will get a link back to a page listing all nodes tagged with Self help books.

This will of course work with any other taxonomy term (e.g. sport books, cooking books, etc.) as well. However, the node can only be tagged with a single term from a particular vocabulary for this method to work.

Note: For this to work, the node must actually be tagged with exactly one taxonomy term from the relevant vocabulary.  You can easily check that the node is tagged this way: When you view the content of the node, the taxonomy term or terms it is tagged with is automatically inserted by Drupal with link to a list of all nodes tagged with the term. If this link does not appear, then the node is untagged. If multiple links appear, then there are multiple taxonomy terms. If the node is untagged, there will be no token replacement and the token will appear as plain text. If the node is tagged with multiple terms, then the token will expand into a list of taxonomy categories, and can no longer be inserted in a single link.

PS: As an alternative solution you can override the template for the node (node.tpl.php), you can replace the simple link mentioned in the previous paragraph with the string "View more" followed by the link.  This also work if there are more than one tag from the vocabulary on the page.


How do you dynamically redirect a user's role? This is a two parted question that deals with two different Modules "User" (or even possibly "triggers and actions") and Profile2. The main task is to have a user dynamically placed within a user role based on the information they submit within the user registration form fields. Presently, I have the form set up with a taxonomy button list. What happens next is the user should then be given a profile type that they can edit after the account creation is complete. Can you help?

Checkout Auto Assign Role module.

You might need some customization or might have to play with the rules module as well.


Routing to production and testing Drupal installations on shared hosting account I am having issues with routing users to different domains on a shared hosting account.  Each of these domains are separate Drupal installations with separate databases.  site is intended to be the production environment, and site1-test is where we do our development and testing of content and modules prior to upload to the main site.  Also, if it has any impact on this issue, clean_urls are enabled.

Here is my file structure

+ public_html
   + site1
   + site1-test

site1 should route to www.site1.com (or site1.com)
site1-test should route to www.site1.com/site1-test (or site1.com/site1-test)

To me, this should be fairly straightforward updating of the .htaccess files.

Here is what I have done so far:

public_html/.htaccess

Options +FollowSymLinks
RewriteEngine on
#========================================================================
# FIRST Handle the http requests first before removing the additional url junk
#========================================================================
#rule for site1.com to link to site1 directory
RewriteCond %{HTTP_HOST} ^(www.)?site1.com$
RewriteCond %{REQUEST_URI} !^/site1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /site1/$1
#rule for site1.com/site1-test to link to site1-test directory
RewriteCond %{HTTP_HOST} ^(www.)?site1.com/site1-test$
RewriteCond %{REQUEST_URI} !^/site1-test/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ /site1-test/$1
#rule for site1.com to link to site1folder directory

#==========================================================
# SECOND Remove the additional url junk once the new url is loaded
#==========================================================
#rule for site1 url rewrite to remove /site1/index.php from the URL
RewriteCond %{HTTP_HOST} ^(www.)?site1.com$
RewriteRule ^(/)?$ site1/index.php
#rule for site1-test url rewrite to remove /site1-test/index.php from the URL
RewriteCond %{HTTP_HOST} ^(www.)?site1-test$
RewriteRule ^(/)?$ site1-test/index.php

public_html/site1/.htaccess and public_html/site1-test/.htaccess

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  #RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

  # no changes within <IfModule mod_headers.c> ...

public_html/site1/sites/default/settings.php

...
$base_url = 'http://www.site1.com';
...

public_html/site1-test/sites/default/settings.php

...
$base_url = 'http://www.site1.com/site1-test';
...

public_html/site1-test/sites/default/settings.php

So, there are multiple issues that I have.  With the code listed above, all themes and login information is completely broken when visiting www.site1.com.  However, visiting www.site1.com/site1-test works fine, although there are some issues with the Testing module (cannot run tests from the web interface, though I think this issue is linked to something being wrong in my htaccess file).

If I comment out the base_url for site1.com (i.e., //$base_url = 'http://www.site1.com';) then site1.com works, however all links show up as http://www.site1.com/site1, and all navigation after leaving the front page also shows that subdirectory.

Unfortunately I don't have access to the domain registration, but I do not believe that any redirects currently exist there, simply that the domain points to the site1 subdirectory.

Most shared hosting plans have a feature called subdomains or addon domains (these features exists in cpanel plans for sure. I m attaching a screenshot from a godaddy hosting plan). You may use this feature to effectively create a new apache virtual host so you dont have to mess with the .htaccess file to do the routing depending on the domain name

Also note that most shared hosting providers do not support overriding many features using the .htaccess file so many on of the options in your .htaccess file may be ignored depending on the apache configuration file (which you usually do not control)

Also note that .htaccess is an Apache concept. If your hosting provider uses another http server (e.g. nginx or IIS) the .htaccess file will be totaly ignored.

Last if you really want to do this with .htaccess (i dont recomend this) make sure you dont miss the query option in any of your cases. Notice the last part here index.php?q=$1  the ?q=$1 part is very important


let the user choose role upon registration I'd like to let the front-end user to choose user role upon registration.

When the register form submit, I'd like it to redirect to the respective profile page concerning with their chosen role.

I use profile2 module and profile2 registration path module.

Is there any existing module for that ?

Thanks in advance!

If you love custom coding and if you already have a custom module, I would recommend to do this with a custom module rather than using Profile 2 and other related modules. I personally prefer to write custom modules because it will let you get exactly what you are looking for.
But you still need to use Auto Assign Role module to let user choose a user role on registration.

My solution is to show/hide the respective profile fields upon user role selection on the registration form. It would not redirect to the respective profile page.
You can create profile fields at admin/config/people/accounts/fields and you can export them to the registration form, but they cannot be created by role. What you would need to do is to show/hide each field by role from hook_form_alter and use #ajax attribute.

Here is an code snippet for this purpose. I did not test the code. Just for example.

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

    if($form_id == 'user_register_form' || $form_id == 'user_profile_form'){

        $form['autoassignrole_user']['user_roles']['#ajax'] = array(
          // #ajax has two required keys: callback and wrapper.
          // 'callback' is a function that will be called when this element changes.
          'callback' => 'ajax_form_alter',
          // 'wrapper' is the HTML id of the page element that will be replaced.
          'wrapper' => 'replace_field_div',
          // Don't show any throbber...
          'progress' => array('type' => 'none'),
         );

        # This profile field will be shown or hidden when the respective "user_roles" is selected
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#prefix']     = '
';
        $form['field_first_name']['und'][0]['value']['#suffix']     = '
';

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['autoassignrole_user']['user_roles']) && $form_state['values']['autoassignrole_user']['user_roles'] == {rid_here}){
            # when the respective user roles is selected, show this field and set required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'textfield';
            $form['field_first_name']['und'][0]['value']['#required']   = TRUE;
        }else{
            # when the respective user roles, hide this field and remove required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
            $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        }
    }
}
/**
 * Callback for user_roles
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['field_first_name'];
}

You may notice that you have to use ['und'][0]['value'] for the profile field to tweak its attributes. If you are not sure about this, you can print $form for debugging purpose:

dpm($form); // if Devel module is enabled
echo '
'; print_r($form); echo '
'; // if you don't have Devel module

If there is another better solution, please post it and it will be appreciated.


how to start fresh and add custom backgrounds I am completely new to Drupal 7 and have searched the web hard for a good tutorial that teaches me how to add a custom background to Drupal sites, but to no avail.

I have a Drupal 7 multi-site set-up and I am just trying to change the background image of the Bartik theme to a custom image.

In my project directory I have the following folders:

mysite/files
mysite/modules
mysite/themes
mysite/tmp
mysite/settings.php
mysite/default.settings.php

Could someone please tell me a way to create a custom background, exclusively, for the site "mysite" without editing any of the core files?

Thanks.

Create a folder called "myTheme" in sites/all/themes
Create a file in that new folder called "myTheme.info"
Copy the sample .info from below into the info file
Now create a folder in your theme called "css"
Now copy style.css from Bartik's css folder into your css folder
Now change the background using CSS
Any other changes you want to make? Copy from bartik into your theme folder, make the change

Sample info file:

name = My Theme
description = My theme is amazing
core = 7.x
engine = phptemplate
base theme = bartik


Using hook_form_alter() only on loading I am using hook_form_alter() in  Drupal 6, which successfully works. As for now, when I submit the form, it again runs the same hook. I want to run it only on load and edit.

Do you have any idea on how I do this?

Use the following code for the load operation of existing forms

hook_form_alter(&$form, &$form_state, $form_id) {

  if(empty($form_state['post'])) {
    //do you load operation
  }

}


Can original text be edited in translate interface or elsewhere? When translating strings in the translate interface, I would also like to be able to edit the "original text" (for the default language), and not only fill in the translation strings for other languages.

Indeed, it's no secret you regularly have to modify or improve the text of a website pages. If the website is multilingual, each time you make such a change, you have to do all this foe each piece of text :

recreate the translation set by reloading the involved page/template
in the desired language
find and delete the initial translation set in the translate
interface
refill the new translation set with the same translation as the
original one in the translate interface

It would bee so much easier to be able to edit the original source text of the initial translation set...

Maybe I'm missing this feature somewhere... can anyone help me on this ?
Thanks you so much for your answers.

You can use the String Overrides module to change the original strings.
Here is a quote about it (from the module's project page):

Provides a quick and easy way to replace any text on the site.
Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


Add a Folder to an ImageField I'm currently trying to setup a picture gallery with Drupal 7. The Gallery module is set up and works, but it needs pictures added to an image field.
Since I have thousands of pictures to add, I don't want to add them one by one. The best solution for me would be uploading them via FTP and then adding the whole folder into the image field.
I found a script (http://drupal.org/node/1266646) which would do this for me, but it's for Drupal 6 and it doesn't work anymore.
I also tried IMCE with FileField Sources, but I can't add files I uploaded via FTP.

The IMCE for FileField module suits your use case. The description given in its project page is the following.

IMCE for FileField allows users to select files from IMCE File Browser. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a FileField.

The latest stable release (7.x-1.1) has been released on April 8, 2015. It's covered by the security advisory policy. The development snapshot for that release has been last update on August 11, 2017.
As of today (April 10, 2021), there are 5 bug reports still open; the older of them has been opened almost 7 years ago. Only one of them got a reply from the project owner, who is also the only project maintainer.


Remove all Div wrapper from comment form I want to strip all default Drupal form wrappers and have something like below in comment form output

                    <form>
                        <input type="text" name="name" placeholder="Your name">
                        <input type="email" name="email" placeholder="Email">
                        <input type="text" name="website" placeholder="Website">
                        <textarea name="comment_body" placeholder="Comment"></textarea>
                        <input type="submit" value="Send">
                    </form>

I try

    $form['comment_body']['#theme_wrappers'] = array();
    $form['subject']['#theme_wrappers'] = array();
    $form['author']['mail']['#theme_wrappers'] = array();
    $form['author']['name']['#theme_wrappers'] = array();

But not worked for comment_body field,
I also use Display Suit I want to know how Can implement comment form like I want without any wrapper.

To achieve this you need to create one template page for comment-form.tpl.php. For this you need to specify in template.php that uses template page.

<?php
function phptemplate_comment_form($form) {
  return _phptemplate_callback('comment-form', array('form' => $form));
}
?>

and in comment-form.tpl.php you can create your own strcution like

print drupal_render($form['name']);
print drupal_render($form['comment_body']);
print drupal_render($form['subject']);
print drupal_render($form['author']['mail']);
print drupal_render($form['author']['name']);

This works for me with register/login form.


How to send an email once every 6 months using the Rules module? How to send an email once in every 6 months at 12:00 am for a date field about user renewal which is there in user profile using the Rules module?

Its mail should send in cyclic form every once in 6 months to notify user, repeating the mail once in 6 months.

So far I followed the tutorial "How to Send Follow-Up Emails Using Rules Scheduler in Drupal 7", and I have created a Rules Component, I then created a Rule like so:

Rules Event: After saving a new user account
Rules Conditions: None
Rules Action: schedule the Rules component (which I created before), with Scheduled evaluation date:+6 month and User > Data Selector: account.

So this is what I have done so far and this email I want to send every 6 months once repeatedly same email

The Rules module together with Rules Scheduler (a sub-module of it), can be used for sending such eMails, as explained in the steps below.

Step 1: Create a field to store the "next renewal" date

Add a field to the "user" entity with machine name (say) field_next_renewal. Allow only 1 date (to store the "next" renewal date).

Step 2: Create a Rules "Component"

Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Reminder about your next renewal",
          "message" : "This is a reminder about your next renewal on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.

Step 3: Create a "Rule" using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):

{ "rules_email_user_every_6_months" : {
    "LABEL" : "eMail user every 6 months",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-next-renewal" ], "value" : "+6 month" } },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 15552000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

The above rule refers to the Rules Component from the previous step.

Note that the 15552000 is the equivalent of 6 months in seconds. You may want to reduce that a bit, e.g. with a number of seconds equivalent to a few days (or a week or so). That way the eMail will be triggered a few days before the actual renewal.


How is it possible for users to submit a node without a required image field? I am using Drupal 7 and I have defined a custom content type, Picture, which has only one required field, an image field.  I am using the default core image field with the Manual Crop module.  The number of images to be added is limited to one.  The field is marked as required.

If it matters, the title is not required because it is automatically generated by the Automatic Node Titles module.

I created this content type to allow users to upload their pictures to the site.  However, sometimes users are somehow able to create nodes of this content type that do not have any image file attached.  Since the image field is marked as required, I do not understand how Drupal can permit the creation of the node without such a file attached.  However, when I click edit, there is no file in the image file dialog box.

I have tried to debug this problem, but I am unable to create a node without an image file myself.  What kind of situation can cause this problem, or how can I debug it?

A contributed module was to blame-- the Manual Crop module.  Thankfully, the issue is already fixed.


Add ubercart catalog paths to xml sitemap The catalog paths don't appear in the xml sitemap with ubercart 3 and drupal 7. How can this be done.

Make sure that you have XML sitemap node enabled.

Go to /admin/structure/types and make sure that your product type in set for inclusion in the XML Sitemap by default. If you have to change it, then if the pages you already have are set to 'default' they will react properly. If they are set to 'exclude' you will have to edit each page and change it.

Then go to /admin/config/search/path/patterns and set your catalog path to catalog/[term:name]
and your catalog product page paths to catalog/[term:name]/[node:title].

If you have to regenerate your aliases, make sure that you retain the old alias, or use the Redirect to issue a 301 redirect for old aliases.

Then regenerate the site map. These steps should cover off any reason why the paths are not in your current sitemap.


Profile2 view with all profile fields How can I create a view, where all profile fields are as columns of a table view, without having to add each profile field indivudally? Is this possible?

I think it would work if you create a view that displays users as rendered entities, not fields.

You can then tweak the way user entities are rendered and show all fields.


Views settings Menu Tabs not working I think module views have problem with menu tabs.
I was created a simple views with settings menu tabs like this.
Custom view for user

Custom path

Settings menu Tabs

Contextual filter and settings

After i go to url: examples.com/user/1/display  and get error

RuntimeException: Callable
"Drupal\contact\Access\ContactPageAccess::access" requires a value for
the "$user" argument. in
Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument()
(line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

and url examples.com/user/1 with error:

Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
Some mandatory parameters are missing ("arg_0") to generate a URL for
route "view.user.page_1". in
Drupal\Core\Routing\UrlGenerator->doGenerate() (line 171 of
core/lib/Drupal/Core/Routing/UrlGenerator.php).

I was doing something wrong? Can you help me?

This a documentation error.

The correct path for users is user/%user/display

In case of nodes should be node/%node/something


How to programmatically get the NID of the current node I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way.

And solutions like

global $node;
$nid = $node->nid;

don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates $node with a NULL value.

It feels like there must be something really obvious that I'm missing.

So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?

Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using menu_get_object() or arg():

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

or

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.


Link "My Workbench" no longer visible I've always used the Workbench and the Workbench Moderation modules, but recently, the link "My Workbench" in the admin menu has disappeared...

I tried reinstalling the module several times, but no luck there. And all the permissions are checked and double checked, so nothing wrong there.

What else could be the issue?

In order to have it appear in the admin menu.
You need to give access to:

"Use the administration pages and help"

Because the My Workbench link is child of admin:
/admin/workbench


Modify and add of unlimited collection field I have a content who contains an unlimited collection field. Via a custom module, how can I get and set the informations which are in field collection in the content (nid) ?

I have read the api documentation of field collection but I don't understand how it works (I'm french..)
By example I see this function : field_collection_item_load, the parameter is an item but...what is an item ? xD

Another question, my field collection contains an another field collection. Is there a particular way to get and set this "sub"-field collection ?

If you can me a very sample example of get and set, I thank you very much

Suppose we are in a hook_node_view(), a hook_preprocess_node() or something and we have access to $node, and my collection field is 'field_collection_field':

<?php
if (!empty($node->field_collection_field)) {
  $collection_fields = field_get_items('node', $node, 'field_collection_field');

  // Extract the field collection item ids
  $ids = array();

  foreach ($collection_field as $fc_field) {
      $ids[] = $fc_field['value'];
  }

  //Get the entities
  $collections = field_collection_item_load_multiple($ids);
  // dpm($collections); Devel output the items
  //Loop over the array - if you have more than one entity
  foreach($collections as $collection) {
    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
     // DO STUFF WITH COLLECTION FIELDS VALUES
    }
   }
 }//end if


Automatic registration for anonymous node authors I need anonymous users  to be automatically sent drupal 'welcome' link  when they create nodes (it's required to enter email and to create login when creating nodes). So AFTER the node is created, the user can go on with registration.

I am not sure how easily you would be able to do this, but you might be able to do this using rules.

Have a look at Inline Registration.  You can configure quickly to attach a registration form to the node creation form.


How to exposed custom profile fields in views The custom fields were created using a custom form in a module, not user entities or Profile2.

How can I expose these fields to views? My goal is to allow an admin to filter users by exposing those custom fields.

Here's the function that creates the custom profile form:

function mymodule_profile_form($form, &$form_state, $account) {
[...]
//
// Basic Info
//
$form['fs_basic'] = array(
  '#title' => 'Basic Info',
  '#type' => 'fieldset',
  '#prefix' => '
',
);

$form['fs_basic'][SOME_SF_CONTACT_FIRSTNAME] = array(
  '#title' => 'First Name',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_FIRSTNAME],
 );
$form['fs_basic'][SOME_SF_CONTACT_LASTNAME] = array(
  '#title' => 'Last Name',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_LASTNAME],
);
$form['fs_basic'][SOME_SF_CONTACT_MIDDLENAME] = array(
  '#title' => 'Middle Name',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_MIDDLENAME],
);
$form['fs_basic'][SOME_SF_CONTACT_SUFFIX] = array(
  '#title' => 'Suffix',
  '#type' => 'textfield',
  '#default_value' => $contact[SOME_SF_CONTACT_SUFFIX],
);
//
// Profile Info
//
$form['fs_profile'] = array(
  '#title' => 'Profile',
  '#type' => 'fieldset',
  '#prefix' => '
',
);
$form['fs_profile']['name'] = array(
  '#title' => 'Username',
  '#type' => 'textfield',
  '#default_value' => $account->name,
  '#maxlength' => 20,
);
[...]
$form['submit'] = array(
  '#value' => 'Submit',
  '#type' => 'submit',
  '#attributes' => array('class' => array('btn btn-primary align-left push-
down')),
);

$form['#validate'][] = 'user_account_form_validate';
$form['#validate'][] = 'user_validate_picture';
$form['#validate'][] = 'user_profile_form_validate';
$form['#validate'][] = 'mymoduler_profile_form_validate';
$form['#submit'][] = 'mymodule_profile_form_submit';
// Add the final user profile form submit handler.
$form['#submit'][] = 'user_profile_form_submit';

  return $form;
}

I want to be able to expose the Last Name in Views to I can allow an admin to search.

In order to use it with Views, one of the following have to be true:

You are using Profile2
You are using core User profile
You are using actual fields from Field API
The profile storage is an entity
None of the above, and you are using a custom table

One of these should let you add a relationship in Views from 'User' to 'Profile2' associated to that user, if not, the core profile fields should be available.

However, if you used a custom table, you will have to do some legwork describing your data to Views in order for it to be an option.

Here are some resources that will help you in that direction:

How to add relationship in view for custom entity
hook_views_data
https://groups.drupal.org/node/400598
http://www.zyxware.com/articles/3280/drupal-how-to-add-view-relationships-programmatically-with-custom-database-tables-in-drupal-7

Do know that just because they are 'fields' in a custom form does not mean that it is represented in Drupal the same way. As far as Drupal knows (and from what I see in the provided code) it is your standard form made with FormAPI. They are not really "custom fields" so much as form items abstracting the input to store data.


Rewrite taxonomy_term_reference urls to read /taxonomy/term/(name) After creating a view to allow /taxonomy/term/(name) to show content tagged with that term, I am trying to find where I can override the generation of field links (field_type_taxonomy_term_reference) so that they create links following this format. Currently they still show the id number for the term at the end. I have tried (mytheme)_preprocess_taxonomy_term and altering $variables['term_url'] but that hasn't worked. Can anyone please give me any pointers about how to do this, I am running out of ideas.

Any thoughts welcome.

Cheers
Paul

You should be able to set URL aliases for your taxonomy terms using the Path module that comes with Drupal core. (EDIT: As mentioned by jordojuice, you'll also need the Pathauto module to automatically generate these patterns in the manner I instruct below).

Go to the Configuration menu and select "Url Aliases" in the "Search and Metadata" section. (admin/config/search/path)
In the upper tab of the URL Aliases menu, select "Patterns." Here you can set the path to your taxonomy terms to whatever you'd like.

The only problem is that I don't think Views overwrites the URLs generated. There was a module for this in Drupal 6, but I don't think there is anything similar for D7.

There is a View that comes default in Views that should overwrite the default taxonomy paths; you could see what it does and try to tweak it.


Panel frontpage overrides site front page after migration I have migrated an old Drupal 6 site to Drupal 8.

On the old site I used a panel page as a front page.

Now on the new site there is no way to change this path.

No matter what I put in the "default front page" form on the "Basic site settings" page the front page keeps linking to the old panel node. And if I delete all panel nodes and the panel module itself I get a 404.

So I'm guessing this is some weird variable stored in the database but I have not been able to locate it. Any ideas?

Managed to solve it by rolling back the "***_d6_i18n_system_site"
So this seems to be some kind of hiccup between the panels and i18n migrations.


Custom menu items with hook menu I'm using hook menu here for the first time as token menu doesn't seem to be doing what I need.

In the end, I need a menu that will use a wildcard and load a view based on that wildcard. I have the views working, now working on the menu.

I have a "directory" structure like so:

committee/committee-name/charter
committee/committee-name/roster
etc...

So I am using hook menu like so:

$items['committee'] = array(
        'title' => 'Committee Page',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/roster'] = array(
        'title' => 'Roster',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/charter'] = array(
        'title' => 'Charter',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

Committee shows on my menu, but Roster and Charter don't. I am not sure why not? If I give a wildcard, committee/%, to committee for example, I get no menu item. So is this a wildcard issue? should I be able to use a wildcard here? I am going to pull in a view based on wildcard and charter/roster content types.

See hook_menu for reference under using Wildcards but you need to tell your menu which page arguments are going to be passed into your function:

$items['committee'] = array(
        'title' => 'Committee Page',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/roster'] = array(
        'title' => 'Roster',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/charter'] = array(
        'title' => 'Charter',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

In this case array(1) would be the second positiong (as array(0) would be the first) if your wildcard resided in committee/charter/% it would be array(2).

I do not believe your items will be showing in the menu because there are wild cards, you would have to do that in your local tasks instead as the menu would not have any idea.


Execute custom JavaScript code after Webform has been submited with Webform Ajax Module I have an Webform that uses Webform Ajax modules, Steps module and few others.

I would like to execute some custom JavaScript code after the WebForm has been validted and submited.

I know I could execute custom PHP code by modyfing function _webform_ajax_callback_completed($form, $form_state) {...} inside of webform_ajax.module:

elseif ($form['#node']->webform['webform_ajax'] == WEBFORM_AJAX_CONFIRM){
...
//my custom code
...

But I don't want to mess with this module's code. And I want to execute JavaScript not PHP code.

Is there an way to do so, e.g. via some hook? Or maybe I can detect that form has been submited in JavaScript?

Okay, try this. After the ajax request is completed on "#myform", it runs the function.

$("#myform").bind('ajax:complete', function() {

     // tasks to do

});

Source | API Documentation