Limit options when creating content according to selected value I have three content types, Events, Disciplines and Championships. An Event has entity references to Disciplines and Championships and Championship has an entity reference to Disciplines.

 ----- 1..n    1..n ------------
|Event|------------|Championship|
 -----              ------------
   |0..n               |0..n
   |                   |
   |                   |
   |1..n               |
 ---------- 1          |
|Discipline|-----------/
 ----------

When users are creating new Event nodes they initially select which Disciplines are involved from a list of checkboxes and then similarly the Championship(s) involved.

At the moment all Championships nodes appear, allowing users to potentially select Championships for Disciplines which are not part of the Event.

Is it possible to use the conditional fields module to create a dependency to display only Championships where the Championship's Discipline field matches the Discipline(s) selected when the dependency is triggered?

How would one fill the 'Set of values' in the conditional fields module?

For example when creating Event1, I select DisciplineA and DisciplineB. The list of Championships should only contain those which have DisciplineA or DisciplineB associations and not contain any Championships that do not have the correct associations

if event.disciplines were a list of selected disciplines I'd like something along these lines (with the dynamic aspects of conditional fields)

SELECT championships c WHERE c.discipline IN (event.disciplines)

edit

Dependent Fields seems to do the sort of thing i'd like but there's no D7 version...

edit 2

Changed the structure a little.

I suppose Discipline didn't need to be an entity in itself and have created a taxonomy vocabulary Discipline instead with terms for each discipline. Event and Championship now have term references to the same field_discipline.

Using the Reference field limit option module the Championship entity reference in Event has the 'Limit this field's options according to the matching field values' option selected and the matching field being discipline (field_discipline).

When creating an Event the list of Championships is empty but when I select the Discipline(s) the expected Championships do not appear.

No options are available for the current form values. Try selecting different values for the following fields: discipline.

edit 3...

Firebug suggested that the ajax wasn't actually firing for checkbox/radio button but was for select menu. Applied this patch and the section is now updating but still not finding any values. There are appropriate Championship nodes to find.

edit 4!

The Championship nodes didn't have the discipline taxonomies selected...

I got this sorted (eventually...)

Rather than having Discipline as a content type (since it was only really storing the name) I created a taxonomy vocabulary called Discipline and added all the relevant discipline names as terms.

Removed the entity references to Discipline in Event and Championship. Added a term reference (field_discipline) to Event and the same term reference to Championship.

Using the Reference Option Limit module (and patch; see question) in the entity reference in Event to Championship added the 'Limit this field's options according to matching field values' and selected the matching field field_discipline.

So now when creating an Event node the user is presented with a list of checkboxes to select the discipline(s) involved and when each is selected the appropriate championships are added to the list of available championships.


drupal hook_update_N() If I install all updates from site_name/update.php, and after change the system.schema_version from 7005 to 7003 using (to reinstall updates 7004 and 7005)

UPDATE system SET schema_version = 7003 WHERE name = 'test';
I then try to run site_name/update.php but it not run because the fields that hook_update_N() adds already exists. And I see when access update.php after error that 2 updates exists.
After I restore system.schema_version to its initially value (7005)

Are the updates 7004 and 7005 now installed or not?

What are you trying to do, and why are you trying to do this? To be honest, it makes no sense. First off, schema numbers should start at 7000 (in Drupal 7), and you should never be resetting them, particularly within hook_update_N(), as you're just going to cause the same code to be run every time the update process is run.


Turn off revisions for content types that contain certain types of fields (e.g. Field Collection) The Field Collection module does not support revisions. Yes there are lots of patches which are still under review. But what I want to do is create a module that on the node edit screen, queries the fields of the content type and removes the Revision Information tab (or disables the "Create new revision" checkbox) if the content type has one or more Field Collection fields. Any help on how which hook to use, how to query the fields of a node, and how to disable the revisions tab would be very helpful. This module needs to be applied to hundreds of sites.

Thanks to pcambra, here is my module:

function epc_no_revisions_for_fc_form_node_form_alter(&$form, $form_state) {

    $collection_fields = field_read_fields(array('type' => 'field_collection'));

    foreach($collection_fields as $FC){
        if(isset($form['#node']->$FC['field_name'])){
            $form['revision_information']['#access'] = FALSE;
            drupal_set_message("This node cannot accept revisions because it contains the following Field Collection: " . $FC['field_name'],'status');
        }
    }
}

UPDATE:

The above module didn't handle a fresh node where the fields had not yet been set. So I revised it to first load all the fields in the database and see if any belong to the bundle (content type) in question:

function epc_no_revisions_for_fc_form_node_form_alter(&$form, $form_state) {
    if(_epc_no_revisions_for_fc_test_for_fc($form['#node']->type)){
        drupal_set_message("Please note: This node cannot accept revisions because it contains a Field Collection",'status');
        $form['revision_information']['#access'] = FALSE;
    }
}

function epc_no_revisions_for_fc_node_presave($node) {
    if(_epc_no_revisions_for_fc_test_for_fc($node->type)){
        if($node->revision == 1){
            $node->revision = 0;
            drupal_set_message("No revision was created because the content type contains a Field Collection",'status');
        }
    }
}

function _epc_no_revisions_for_fc_test_for_fc($node_type){
    $fields = field_info_fields();
    foreach($fields as $field){
        if($field['type'] == 'field_collection'){
            foreach(array_shift($field['bundles']) as $content_type){
                if($node_type == $content_type){
                    return true;

                }
            }
        }
    }
    return false;
}

You could use hook_form_FORM_ID_alter to alter your node forms of the content type (s) you need.

function my_module_form_node_form_alter(&$form, $form_state) {
  if ($form['#node']->type == 'my_content_type') {
    // Your code goes here.
  }
}

Now you need to know whether or not it has a field collection field on it. You can use one of the field api functions for this, for example, this will give you the field collections in your site:

$collection_fields = field_read_fields(array('type' => 'field_collection'));

Then you can check if your node has one of these to see if you disable the revision feature or not.

You can disable the checkbox appearance by adding an #access FALSE:

$form['revision_information']['#access'] = FALSE;

It's probably safer to repeat this operation and checks in hook_node_presave if that makes sense for your workflow.

Additionally, there are a couple of modules relevant to this issue, Jammer allows you to hide some specifics from the node creation form and so on, but nothing condition based. There's also Field SQL no revisions that will skip saving information for revisions, be careful because there's no come back from this one so you need to be very sure you're not using revisions for your fields in any other content type.


how to have conditional Help text for a listbox field Remember the create password page of Drupal! While you are entering characters it tells you how strong your password is!

Now I want to have something like this in a list box but a bit different. I want to show an image and a text depend on the item which is selected in the list box! How can I do it? My first try was adding some code in help text of the field, but it doesn't work. What are your suggestions?

I can not use conditional field because I must add 60 conditions and it is illogical. Ao I need a programmatic way. The java script code and how to I make it dependent to two list boxes?
I add a markup field to my content type but I don't know who to find which item is selected in the list box with ajax ind how to show an item depend on it.

You don't have to code for this. You can use Conditional Fields to achieve it.

You can then use "Manage Dependencies" section (alongside manage display) to set the dependencies:

Then you can see the different fields being enabled or disabled depending on the entered input:

List option "No" Result:

List option "Yes" Result:


How to reduce the delay in sending email notifications about new content? I've set up a workflow rule to send an email to all users of a role when new content is saved.  I've tested it with three test users and have noticed that the email takes quite a while to actually be delivered.

I thought it was related to cron, so, I changed the setting to Run cron every 1 hour. The emails are eventually delivered, but, not in a timely fashion. It seems like they're delivered according to the cron schedule, but, I'm not sure.

I'd like to have the emails sent as soon as possible when the content is posted. Some of the content can be time sensitive. Is there any way to speed the delivery of the email?

As an alternative to what you're trying to get to work, you might want to consider using the Rules module.
Below is a summary of how you can get this to work:

Introduce an additional flag to allow "flagging" these (new) nodes by all users "with the role that should receive these eMails" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
Create a rule to flag the newly saved content, using the new flag (from step 1) for each of the users "with the role that should receive these eMails". A possible approach for this is to build a list of these users using Views bulk operations (VBO) module, which is then processed by the rule to actually flag this content by those users.
Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list.
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).
In that same rule, as the very last Rules Action, add an action to reschedule the exectuion of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).

Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will notify X users "as requested". Obviously, you'd have to think a bit about what the best values for X and Y would be in your case. E.g. if you have thousands of users in that role (to receive the eMails), you've to be careful to prevent that your eMails would be considered as spamming. However, if you only have a few users in that role, you should be OK with a low value of Y (even like every 5 minutes or so?).


Video Embed Field with Magnific Popup I'm trying to display an embedded video in a popup window using the Magnific Popup Module. For the video field, I'm using Video Embed Field.The popup window works with images trouble-free. However when I try to set up the display with the video field (Magnific Popup formatter), the throbber keeps turning and I'm not able to save this configuration. Any ideas on that?

I have the same issue.
the problem was in the module:

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:
  You have requested a non-existent service "colorbox.attachment";.

The module mantainer do not add colorbox to dependencies.

So you just to need to install and enable Colorbox module.


Strategies for approaching a client requirement to create quizzes One of my clients requirements seems to stretch Drupal's boundaries, and is forcing me to think differently on how to approach a problem. I am looking at potential alternatives and strategies to the following requirement so that I can get it right:

My client essentially wants to be able to create quizzes. We are unable to use the popular quiz module since it does not have a Drupal 7 version out yet and in any case, does not allow for multiple questions to be inputted in one go. Explored other module alternatives such as Closed question but they aren't exactly user-friendly.

Getting my hands dirty, my strategy around this is built as follows:

Create a new content type and have it powered via Web-form. The editors can now create questions using the web-forms following an instruction manual about the specific form elements to use. The question set essentially includes : - markup for questions
Radio buttons for option fields with the selected one denoting the correct field
Feedback field The entire question set is put into a fieldset. Subsequent question sets are created by cloning the first fieldset and once done composing, what we have is a node with webform elements that have been structured to appear as a quiz.
The problem:

The editors must follow an instruction manual in order to compose these question-sets and essentially the quiz since they are leveraging the webform. This is also in many ways a pseudo quiz, in the sense, I am leveraging web-forms to simulate what a quiz would appear like and not in essence a quiz. The process is tedious because for each question-set composed, the editors need to click each of these elements and have to fill in data making the process time consuming.

My ideal solution would be to have a content type that would allow the editors to specify a total number of questions in a content type and then have it generate the question-set(question markup, answer options as radio buttons, feedback). This would allow editors to quickly bang in the required content and in the process quickly compose quizzes.

Essentially the question is, if anybody knows how to achieve the ideal solution and if it is actually possible. If not, looking at the problem I have described, what alternatives are possible?

I am sure that the latest version of the quiz module has a full flow of functionality with Drupal 7 also. I have used the quiz module to develop a site in Drupal 7 and it worked fine. If you have any issue in working with the Quiz module, i am ready to help you out in solving your issue.


how to install package via composer? I would like to add library to my drupal 7 custom module. Library can be installed via composer, but i can't find a solution for install? How can i install this library? I have installed "composer manager" but i still can't get it running.

To get started, add a composer.json file to your module.  The only thing you need here is the require section that includes your external library.

Composer manager is one way to combine all of your dependencies together, but there are other options to get Drupal to load your autoload.php file.  The technique I prefer is to create a project-level composer.json file in your Drupal root, and use the module composer_vendor to include your autoload.php file.

The easiest way to get started is to use the composer_generate Drush extension to build your project-level composer.json file.

$ drush dl composer_generate
 $ cd /path/to/drupalroot
 $ drush composer-generate > composer.json
 $ composer install

Composer-generate will add all of the projects currently used in your Drupal site, plus composer_vendor, so composer install should just work for you.  The main magic here is in the custom autoloaders added to the template; take a look at the output to see what was included.

Some caution needs to be used here, of course; the default template will put all of your modules in sites/all/modules/contrib.  You can edit the template prior to running composer install if this isn't what you want.

You'll also have to be careful if you have any modified modules; there are a number of ways to deal with any hacked content, but that's a bit beyond the scope of this one question.

Update

If you don't want to run Drush, you can also hand-type your own composer.json file using the project https://github.com/drupal-composer/drupal-project.  This is the template that composer-generate is based on.


Specifying Taxonomy Term Filter in View from Page Editor I'm currently using a view to display content teasers and I want my users who are making pages to be able to incorporate these views, however I want them to be able to specify a taxonomy term to show that content. I tried doing this with a Contextual Filter, however I need some way to allow the user to specify the term in the page editor, not on the page preview itself. Is this something that Views allows you to do? Do I need to install a module, or do this programatically?

Hopefully I'm not being too confusing with that description, if so just let me know and I can try and clarify.

There are two parts to this question - one is to have creators of nodes to choose a Taxonomy term, the other is to have a Views Display show up on Node View based on the Taxonomy term set inside the node.

Taxonomy term reference

As you've already worked out, the easiest way to allow for users to influence what content list to display on their nodes is to allow them to choose a Taxonomy term.

You can do that by creating an Entity reference field referencing Taxonomy terms. The way you worded your question suggests you will only allow one term to be selected (limit number of values to 1).

When the node is saved, the information about the chosen Taxonomy term will be displayed when viewing the node. If you don't want this to be visible, if you only want this field to serve as a way to influence Views in the following steps, you can hide the field from showing up on node view by changing Manage Display settings. The info from the field will still be available for Views to read "on the sly".

Views Block listing content sensitive to the Taxonomy of the page they're on

Creating Views that display related content is probably the most common request in Views. With such a Views Block you don't have to have any additional interface for node creators to choose what to display on their nodes. Simply having a Taxonomy term reference is enough (already covered above).

First you create a Views Block listing your desired Content (set up all the regular Filters and Fields).

Then add a Contextual Filter of type Content: Has taxonomy term ID, and configure it to Load filter from node page (NOT taxonomy term page). Take a look at screenshots from this answer: display lists of related content that share the same Taxonomy term.

In the end place the Block in a region, and configure the block settings (to display only on node page where you want).

When your content creators save a new node, that Block will automagically show only Teasers of content tagged with the term they chose when creating the node.

If the content type of the created node is the same as the content type of teasers in the Block, the newly created node will also be displayed on the Teaser list. If you don't want the node you're currently viewing to be listed there you can exclude it with an additional Contextual Filter Content: ID (Provide default value: Content Id from URL, More (at the bottom): Exclude).


how to run "cd" command in drush I like to have drush command 'go_to' that will move my shell into different directory. My custom implementation does not move the shell directory. How come? here is the script so far:

#!/usr/bin/env drush
<?php

$dir = '/dir/to/move/my/shell';
drush_op('chdir', $dir);
drush_op_system('cd '.$dir);
//drush_shell_exec('cd '.$dir);
//print_r(drush_shell_exec_output());

Thank you for help

The "cd" command in your commandfile is working correctly; however, it is a standard behavior for *nix (and Windows) that environment variables, such as the current working directory variable set by the 'cd' command apply only to the process that they are set in.  Drush runs in a separate process from the shell that you launch it from, so your current working directory will revert to its original value when Drush terminates.  (It actually never changed, since each process has its own environment.)

Instead of using a Drush alias (site alias or shell alias), what you might actually prefer is a bash alias.  For example:

$ alias go='cd /dir/to/move/my/shell'
$ go
$ pwd
/dir/to/move/my/shell

There's a lot more you can do here if you define site aliases for your site, and source the example bashrc file that Drush provides; see the Drush README file, and the examples folder.

If you want to write fancy php code change your working directory, you need to put only the code that calculates the destination path, and then call 'cd' from a shell alais.  For example (from bash):

$ alias go='cd $(drush dd @mysite)'
$ go
$ pwd
/path/to/drupal/root/of/mysite

This one liner will also do the trick:

$ cd `drush @mysite dd`

zsh aliases have the same syntax as bash aliases:

http://zsh.sourceforge.net/Intro/intro_8.html

It also looks like process substitution has the same syntax in zsh as well:

http://zsh.sourceforge.net/Intro/intro_7.html#SEC7

However, I haven't tried any of this in zsh.


How to remove user picture on the nodes Is there a way to remove a user's picture from the node, or the teaser without any CSS modification, but just doing it from the GUI?

Look at the settings for your theme. There is a check mark to include the user pictures or not.
There are settings for the individual theme, and generic settings.


Drush > ignore files and folders (ie : IDE conf) when pm-update Do you know if is there a way (by command argument, or in config) to ask drush not to remove IDE's configuration files and folder?

To be clear, Phpstorm create a .idea folder with project configuration in the root folder; when I run drush pm-update drupal, this folder is removed. Is there a way to ask drush to not delete this folder?

Nope.  Drush always does a full directory replacement when upgrading a module with pm-update.  This insures that any files removed from the release do not remain on the disk after the update.  Contributions to improve drush in this area would be appreciated.

As a workaround, if you have your .idea folder checked into git, then you could always use git checkout -- .idea after pm-update to get it back.


Do I need a custom content type, entity, module or field? I'm working on a product information manager, and I have a content type of product which needs to reference stock and price levels for each supplier from a different database - these are stored as separate sqlite databases (one for each supplier) and managed outside of drupal.

I would like to reference the prices and stock levels without actually importing them all into the drupal database, instead pulling from the external database, but I'm a little confused how to structure this? One product can have many suppliers.

Do I need a separate entity to manage the pulling of the data (possibly one entity for each supplier) then somehow attach to the product node (manufacturer and part number would be used to search the supplier db), or, would it be considered a field, or a module with options set specifying the database location for each content type. Each product node shouldn't have to specify its list of suppliers.

The data would need to be shown when a node is displayed - I would like the data to be accessible from within views, but also searchable, e.g. display products where stock level < 3 for supplier xyz.

I'm thinking an entity wouldn't be correct as an input of manufacturer and part number would be needed before the data can be pulled?

The data would need to be shown when a node is displayed - I would like the data to be accessible from within views, but also searchable, e.g. display products where stock level < 3 for supplier xyz.

How can you say I want the data to be integrated into my website -- but not imported into Drupal. Your goal sounds like alot of work.

You could try something like Remote Entity. But honestly I would take some time to learn the Migrate module and use Rabbit Hole to insert the data as "hidden" data to drupal entities or content types in my site. Migrate is super powerful for this type of syncing of data (syncing being a topic I think you're glossing over).

EDIT

You could try to:

use hook_entity_view_alter to put content into a node view.
use hook hook_views_data and putting your DBs into settings.php to be useable by Views displays and filters.
use something like hook_search_api_query_alter to include your custom dbs in queries to search

... all of these in my opinion would be harder to maintain in the long run, rather than a recurring interval of updates or syncing of data using Feeds, Migrate, and storing a copy of the data locally in a drupal friendly format (eg a content type or entity).


Ajax pager failure in view after modifying view on hook_views_query_alter The requirement is for different pages on the website to show different Twitter feeds according to the current page. There is a context (triggered according to the path) that inserts a view block into the footer. A custom module kicks in when the query for the view block is about to be executed. The module does some simple processing to determine what Twitter feed(s) are required to be displayed on the current page.

So, the custom module contains:

/**
 * Implementation of hook_views_query_alter
 */
function twitter_feed_selector_views_query_alter(&$view, &$query) {

  if ($view->name == 'tweets') {

    // Some processing...

    $feed = _twitter_feed_lookup($matching_path);
    $view->query->where[1]['conditions'][0]['value'] = $feed;

  }
}

However, the view block has a lite pager and Ajax enabled. And when the user clicks on the pager links to see the next/previous page of tweets, no tweets are coming back from the view.

I can't find how to get around this. If I turn off Ajax on the view, all is well, but the whole page is reloaded each time the pager is clicked -- which is way too clunky.

Can anyone suggest a means to make my amendments to the view query work nicely also with the Ajaxed results from the pager?

When the view query is being called from inside the pager, the requesting URL is different. It becomes: '/views/ajax'. This URL does not match any that had been specified in my context, so no results were returned.

I solved the problem by checking if the query view is being called within the pager -- i.e. if $_SERVER["REQUEST_URI"] == '/views/ajax'. If so, then I extract the correct path instead from $_SERVER["HTTP_REFERER"]. If not, then it's okay to accept the path from $_SERVER["REQUEST_URI"].


How do I trigger an event when a button is clicked on a user profile? Let's say I want to make a bunch of nodes based on what's in a specific field when someone clicks a button on their user profile.

Is this possible with a custom built module? And if so what hook would I use to display that button on the user profile, and how would I get it to call a custom function on click?

Wow, this is a question with many solutions. Some stuff I can quickly think of:

Developers way:

create a custom module: https://www.drupal.org/developing/modules/7
implement hook_menu to create callbacks for your links
implement your logic in the callback functions defined for your entries in hook_menu.
"presentation layer". Depending on the structure of your website and your profiles:

a) Create a block with your links in it, references: block_example, link function

b) Implement a "pseudo field" on fieldable entities (e.g. user, profile2)

c) Use link function in your profile template file e.g. user-profile.tpl.php

extra points might be awarded if you use the link function and your hook menu implementation together with the ajax framework. example.

Site builders way (one way.. there are many):

create a flag
create a rule for flagging items
in that rule implement your logic
optional: undo the flagging (so the user can do this action again)

All of the mentioned solutions will probably require some logic for handling the access and display of that button as well.

(one) developer way, if this button appears on user/id:

<?php
global $user;
if (arg(0) == 'user' && arg(1) == $user->uid && null === arg(2) {
  print l('do something', 'yourcallballback/' . arg(1));
}

site builders way (for the example from above):

usually there's no additional access check required here, you can setup that flag to be global and only clickable once if you want to make sure that it's only available once. for the display part you probably really have to use code to only show that flag if the current user visits his own profile.


Alter Entity Reference View Widget available options I have 2 content types business, locations, programs and services.

At program level we select all the services associated with that program.

At business level we select the programs the business is associated with.

At the location level based on the programs selected we give the option to sub select the services.

Now the services entity reference is displayed via Entity Reference View Widget. All I want to do is alter or unset certain options based on the choices made at the business level in terms of program selection.

I tried working at the views level to pass it as an argument but was unsuccessful. Then tried the node form alter but the unset option still shows up but without the checkbox.

Tried to alter it using hook_field_widget_form_alter as well but was not successful.

It looks like it implements a preprocess function entityreference_view_widget_preprocess_widget but I am not able to override it.

Looking for pointers if anyone has come across similar problem.

Ending up using hook_views_pre_render(&$view). So I did something like this

function contractor_programs_views_pre_render(&$view) {
  if ($view->name == 'location_services' && $view->current_display == 'entityreference_view_widget_1') {
    // added my logic to get the service options
    if (!empty($services_options)) {
        $services_options = array_keys($services_options);
        if (!empty($view->result)) {
          foreach($view->result as $key => $value) {
            if (!in_array($value->nid, $services_options)) {
              unset($view->result[$key]);
            }
          }
        }
      }
  }
}


Drupal 7 + Commerce + Addressfield remove specific  from form markup i use drupal + commerce + adressfield and i am cleaning up the checkout-page form markup (at least i try).

i am familiar with the theme functions of form.inc and have removed some divs aleady using this functions but one of the divs i dont know were it is defined.

dpm(); says it resides in  $element['#children'] but ['#children'] is the whole markup including the div i want to remove.

to be clear: i want to remove the red marked outer div only!

The user's answer in the comment is wrong. We never want to hack a module. But we can use hook_form_alter() to modify the #suffix and #prefix.


Implementing Taxonomy hierarchy in View and Search I am working on a biology website that needs to make use of Drupal 7's Taxonomy system, for a biological taxonomy.

My goal is to allow users to tag all content with related species information, and provide the following functionality:

Display all nodes that are associated with a child term of the
specified taxonomy term (so if they access the "Birds" term,
"sparrow" would be included)
Include taxonomy terms in search
Allow for species nicknames, (synonyms), abbreviations and variations in spelling or singular/plural usage

I have installed the Hierarchical Select module, but am not sure it is working correctly. Or, I am not using it correctly. When I insert new terms deep in the hierarchy, they sometimes end up at the top level. There have also been intermittent errors showing in a red box. I'll add that to this post if it shows again.

Example taxonomy

Animalia
- Chordata
-- Aves
--- Passeriformes
---- Passeridae
----- Passer
------ Passer domesticus (primary species term)
------- Common sparrow   (synonym)
------- English sparrow  (synonym)
------- House sparrow    (synonym)
------- ENSP             (synonym/abbreviation)
------- House sparrows   (synonym/plural)

In the above example, I need users to see English Sparrow content when they view the Taxonomy page for Aves, as well as the Taxonomy page for "ENSP" if the node has been tagged with Passer domesticus or any of its child terms.

Ideally, a basic search for any of the child terms for Passer domesticus would also return a list of nodes tagged with any of the term's siblings.

I am open to configuring a View for this, if Search is not possible.  All advice is appreciated.

Similar questions from others:
http://drupal.org/node/1792256

How to have parent taxonomy terms include their children terms' nodes?

How to show the parent and child taxonomy term?

https://stackoverflow.com/questions/5910071/views-show-child-taxonomy-terms

I would look into using Search API for this and build up facets using the Facets API.

Once you have Search API installed you need to create a search index, choose which fields to index and what facets to create.

With the search index in place you can from Views create a Search view that uses your index as base.

Place the facets where you want them and tell them to show up at your search views url.

There is a guide that explains how to setup Search API here. In the guide they use Apache Solr as backend for the search index. That is not necessary, you can use the database as backend but I recommend using Apache Solr as backend as I've stumbled on a few bugs in the database backend which work with Solr.

You would be able to do searches such as this:

Good luck


Features : export content types with FieldCollection When I try to export my content type using Features, it works. But when I import it on another Drupal installation, I've got an exception :

Exception : Invalid field name given: **my_field** is not a Field Collection field. in FieldCollectionItemEntity->__construct() (line 119 in **path_to_module**\field_collection\field_collection.module)

That's strange, because IT IS a Field Collection, and it worked fine on the first Drupal installation.

Any ideas ?

There are two solution to this problem, the first one is a bug in the module that can be fixed via this patch https://drupal.org/node/1084268

The second solution fixes a problem caused by orphan fields in field_collection_item table.
First try removing my_field via drupal interface, if it didn't exists try
 searching your my_field in this table, if it existed , delete it

NOTE : the solution is dirty one, it worked for but it may have side effects, backup your database before trying it


How to use Rules to send an email after a user submits a first node and grant a new role after 5 nodes? I want to send a congratulations email to user on submitting his/her first node.

I want to implement this through the Rules module. But I am confused and think that there is no such option except PHP evaluation which seems bad to me due to eval().

And I also want to assign a special role to a user after a user submitted (= Save new content) 5 nodes.

Any suggestions?

This can be implemented perfectly by using the Goals module (disclosure: I'm its maintainer), as further detailed below.

Part 1 - Configure 2 goals

You'd start by configuring the appropriate set of Goals and related Tasks. For a basic introduction about Goals, have a look at:

How to implement gamification in a Drupal site and award incentives?
Its video tutorial.

Here is what it would take:

Goal1 = "New user", with only 1 Task = "Save 1 node" (say with machine name = save_a_node).
Goal2 = "Mature user", with Task = "Save 5 nodes".

Part 2 - Create a rule to record progress on the tasks

Create a rule using Rules Event "After saving new content". The purpose of this rule is to make Goals automatically track the progress on completing the tasks (which you can do via an appropriate Rules Action to record that progress).

The interesting part of this is that you can reuse the same rule (related to that machine name = save_a_node) to keep track of the progress of any user to become a New/Mature customer (check the video for a similar sample).

Part 3 - Trigger your rules after a goal is achieved

Together with what is above, you should write these 2 rules to implement what your question is actually about:

a rule with these specs:

Rules Event: "After a user completed Goal1"
Rules Action: "Send an eMail"

a rule with these specs:

Rules Event: "After a user completed Goal2".
Rules Action: "Assign role to user".


How to capture value of a field in a node I am nearly a complete newbie when it comes to writing modules (Drupal 7). I have a module that successfully calls an OpenStates API and retrieves information about a member of the legislature. The key is a custom field called leg_id. In testing this, I hard coded the leg_id in the module that creates the block I want to display.

I now have a node that has a custom field for leg_id. When that node is displayed, I want to pass the value of the leg_id to the module that retrieves the information from OpenStates and display it in a block in the right sidebar.

I need a simple example of how to get the value of the leg_id field and pass it to the module that creates the block.

Here is an example of how the page should look: http://dev-thecivithing.pantheon.io/node/1

Block creation Module Code

<?php
// $Id$

/**
 * Implements hook_help().
 */
function committees_help($path, $arg) {
  if ($path == 'admin/help#committees') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function committees_block_info() {
  $blocks = array();

  $blocks['list_committees'] = array(
    'info' => t('A listing of all of the committees for the member'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function committees_block_view($block_name = '') {
  if ($block_name == 'list_committees') {
    $list = get_committees();
    sort($list, $sort_flags = SORT_STRING);

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Committee Membership'),
      'content' => $content,
    );

    return $block;

  }
}

/**
 * Web service to list committees for the member
 */

function get_committees() {

$leg_id='NCL000208';
$apikey='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$list = array();

$request_url = "http://openstates.org/api/v1/legislators/$leg_id/?apikey=$apikey";
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$legislator = json_decode($result);
$roles = $legislator->roles;
    foreach ($roles as $role) {
        if (isset($role->committee))
            $list[] = $role->committee;

    }
    return $list;
}

Working Module

<?php
// $Id$

#print $body . PHP_EOL;

/**
 * Implements hook_help().
 */
function committees_help($path, $arg) {
  if ($path == 'admin/help#committees') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function committees_block_info() {
  $blocks = array();

  $blocks['list_committees'] = array(
    'info' => t('A listing of all of the committees for the member'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function committees_block_view($block_name = '') {
  if ($block_name == 'list_committees') {
    $list = get_committees();
    sort($list, $sort_flags = SORT_STRING);

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Committee Membership'),
      'content' => $content,
    );

    return $block;

  }
}

/**
 * Web service to list committees for the member
 */

function get_committees() {

if (arg(0) == 'node' && is_numeric(arg(1)))
$nodeid = arg(1);
$node = node_load($nodeid);
$field_leg_id = $node->field_leg_id['und'][0]['value'];

$apikey='a1e620771b1d463cb726eda33e8f3102';
$list = array();

$request_url = "http://openstates.org/api/v1/legislators/$field_leg_id/?apikey=$apikey";
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$legislator = json_decode($result);
$roles = $legislator->roles;
    foreach ($roles as $role) {

        if (isset($role->committee))
            $list[] = $role->committee;

    }
    return $list;
}

What u can do is, pass leg_id in the function definition, like:

function get_committees($leg_id = '') {
if(empty($leg_id)) {
$leg_id = 'NCL000208';
}
...

and in the content of block inside block_view, u can call this function, with leg_id, if u are sending leg_id through url, then u can get the leg_id from url using arg() function, and then passing it to function.

But since u want to get Leg_id from node, what u can do is:

if (arg(0) == 'node' && is_numeric(arg(1)))
$nodeid = arg(1);
$node = node_load($nodeid);
$field_leg_id = $node->field_name_field_leg_id['und'][0]['value'];

and sending $field_leg_id to function get_committees($field_leg_id)

// Edited

You can do the same by calling menu_get_object(), it will return you an array, what u can do is:

$menu_obj = menu_get_object();
$leg_id = $menu_obj->field_name_field_leg_id['und'][0]['value'];


Where are css injector files stored on the server? I'm using this module:

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

In the backent, the files show up at this path:

public://css_injector/css_injector_20.css

But in FTP I look in public.html and I can't find theme

They are not in here either:

/home/vincoixt/public_html/xuzo.com/sites/all/modules/css_injector

So where are they?

CSS Injector stores it's files in the files directory under:

'public://css_injector/css_injector_' . $crid . '.css';

as defined in _css_injector_rule_uri

This often maps to the following folder:

sites/default/files/css_injector

See also: css_injector_init for how the files are added by that module.


Is there a way to execte jquery event after ajax callback has been completed? Having a simple form with few input fields.
After clicking on ajax callback submit button, I'm returning the table element.

Code:

//Hypertension treatment
        $form['hyper_treat'] = array (
      '#type' => 'radios',
      '#title' => ('Hypertension treatment:'),
      '#options' => array(
        'y' => 'Yes',
        'n' => 'No'
      ),
    );

//Hypercholesterolemia
    $form['hyperchol'] = array (
  '#type' => 'radios',
  '#title' => ('Hypercholesterolemia:'),
  '#options' => array(
    'y' => 'Yes',
    'n' => 'No'
  ),
);

//submit button
    $form['action'] = [
    '#prefix' => '
',
     '#name' => 'ajax_action',
    '#type' => 'button',
    '#value' => $this->t('Submit'),
    '#ajax' => [
    'callback' => '::setMessage',
    'wrapper' => 'scrollable',
    'method' => 'replaceWith',
    'effect' => 'fade',
    ],
    ];

    //table
    $form['table'] = array(
    '#prefix' => '

View Data
',
        '#type' => 'tableselect',
         '#suffix' => '
',
        '#header' => $header,
         '#options' => $options,
        '#disabled' => $disabled,
        '#attributes' => array('id' => 'sort-table'),
        '#empty' => t('Select criteria and search data'),
      );

//callback function
   public function setMessage(array $form, FormStateInterface $form_state) {
  $options = getOptions(); //gets the associative array
  $form['table']['#options'] = $options;
  return $form['table'];
}

I had issues with the pagination and sorting of the table returned using ajax.
So I thought of using "Datatables" as the alternative option.

So after the callback, I would want to apply the below jquery to have the table shown as a datatable.

 $('#sort-table').DataTable( {
        order: [[ 1, 'asc' ]]
    } );

Tried executing the 'mousedown' event for the button but the jquery executes before the ajax callback.

Is there a possible way to represent the $form['table'] element returned from the ajax callback, as a datatable?

Triggering any other event after table returned would display it as a datatable, but I'm looking to have the returned table displayed as a datatable immediately after the $form['table'] is returned. This happens only when the jquery snippet is executed immediately after the table element is returned from the ajax callback function.

You can use custom ajax commands for this. Ajax commands are php classes that correspond to a JS function on the server, which the Drupal JS API calls after Ajax responses.

At a quick lookover, this tutorial looks like it gives a good overview on how to create a custom Ajax command in Drupal 8.


Having some conceptual trouble creating a View to list users that have nodes containing entity references Users on my site can create content by adding a new node of content type 'project'.

Projects are assigned to exhibitions through a drop down 'exhibition' field which is an entity reference to another content type named 'exhibition'.

Exhibitions are created by admins and each exhibition has a location field (one of three distinct values).

I would like to create a view that displays all users that have created projects for two or more locations. So that could be (for example) 5 projects for 2 exhibitions in location X and 2 projects for 1 exhibition in location Y.

Having some conceptual trouble putting the view together, any help much appreciated.

Danny.

Got around my mental block.

Created a 'Users' view.
Added an 'Entity Reference: Referenced Entity' relationship.
Turned on aggregation for my view
Added the field I wanted to count and selected COUNT (distinct)

Working well now.

Danny.


How I can alter reCAPTCHA script tag in html_head The reCaptcha module adds a Javascript with hook_captcha(). I want to add another attribute "type" to this script tag. I can't find a hook to achieve this.
Here is the code from the recaptcha.module (line 118):
$captcha['form']['recaptcha_widget'] = [
        '#markup' => '<div' . new Attribute($attributes) . '></div>',
        '#suffix' => $noscript,
        '#attached' => [
          'html_head' => [
            [
              [
                '#tag' => 'script',
                '#attributes' => [
                  'src' => Url::fromUri($recaptcha_src, ['query' => ['hl' => \Drupal::service('language_manager')->getCurrentLanguage()->getId()], 'absolute' => TRUE])->toString(),
                  'async' => TRUE,
                  'defer' => TRUE,
                ],
              ],
              'recaptcha_api',
            ],
          ],
        ],
      ];

When I try to access the script tag with e.g. hook_page_attachments_alter() or any other hook_preprocess_xxxx() it is missing. I also tried to increase my module weight.

I would suggest using a #process callback and avoid code duplication.
This is what such a solution could look like:
/**
 * Implements hook_element_info_alter().
 */
function my_module_element_info_alter(array &$element) {
  if (isset($element['captcha'])) {
    $element['captcha']['#process'][] = '_custom_recaptcha_process';
  }
}

/**
 * Add type attribute to recaptcha form element.
 *
 * @return array
 *   The processed element.
 *
 * @see captcha_element_info()
 * @see image_captcha_element_info_alter()
 */
function _custom_recaptcha_process($element) {
  $recatchaWidgetHtmlHead = &$element['captcha_widgets']['recaptcha_widget']['#attached']['html_head'] ?? [];
  array_walk($recatchaWidgetHtmlHead, function(&$captcha_widget) {
    if ($captcha_widget[1] === 'recaptcha_api') {
      $captcha_widget[0]['#attributes']['type'] = 'value';
    }
  });
  return $element;
}

and this would be the output:

Good luck!


Administration Theme switches to front-end theme I am using administration theme "Seven".

When I clear cache or I work with some module and then I save its settings, the administration theme switches to front-end theme.

If i reload browsers current page, then the front-end theme switches back to the admin theme.

Is there any setting that can fix this?

Overlay does not work with prefixed URL paths.
http://drupal.org/node/1075096


How to create a email notification to subscribers and the author who posted a comment programmatically in drupal 7? I want that if a user subscribe to a comments & post that has been posted by an author,  so how i can send mail notification to both the author and the subscriber at the same time.
I want that author should get a notification that he has some comment on his post.
and the subscriber that author has posted some status or post.

    <?php
/*
 * Implement hook_menu()
 */

function comment_notification_menu(){
  $items=array();
        $items['admin/customize'] = array(
          'title' => 'Send Comment notifications',
        'discription' => 'Admin will send notification to user about updates',
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('comment_notification_form'),
        'access arguments' => array('access adminstration page'),
        'access callback' => TRUE,
          );

  return $items;
}

/**
 * Form Structure
 */

function comment_notification_form($form, &$form_state){
  $form=array();
  $form['send_mail_from']=array(
    '#title' => 'Send Mail From',
    '#discription' => 'To whom you want to send form',
    '#row' => 5,
    '#columns' => 10,
    '#type' => 'textfield',
    //'#required' => TRUE,
    '#default_value' => variable_get('send_mail_from'),
    );
//here the admin can wite subject for the mail.
  $form['mail_subject']=array(
      '#title' => 'Subject',
      '#discription' => 'the purpous of this mail',
      '#type' => 'textfield',
      '#size' =>149,
      '#maxlenght' =>200,
      '#required'=>TRUE,
      '#default_value' => variable_get('mail_subject'),
    );
  $form['mail_body']=array(
      '#title' => 'Body',
      '#discription'=>'the body of your mail.',
      '#type' => 'textarea',
      '#row' => 20,
      '#columns' => 50,
      '#required' => TRUE,
      '#default_value' => variable_get('mail_body'),
    );
   $form['mail_bcc']=array(
      '#title' => 'BCC this mail to all',
      '#type' => 'checkbox',

    );

   $form['help'] = array(
        '#theme' => 'token_tree',
        '#token_types' => array('node') ,
     );

  return system_settings_form($form);
}

/**
 * Implement hook_comment_insert().
 */

/*
 *Implement token_replace(). , variable_get()
 */

function comment_notification_comment_insert($comment){

if ($comment->field_comment_notification['und'][0]['value'] == '1') {
      global $user;
      if ($user->uid == 1){

        $user_mail = $user->mail;//user has login
        //dsm($email);
  }
  else{

       $user_mail = $comment->mail;//uesr has not login
  }

      $to = $user_mail;
       // $to = 'm.nikhilanant@gmail.com';
      $message = token_replace(variable_get('mail_body')); // Body of your email here.

$subject = token_replace(variable_get('mail_subject')); // subject of e-mail
$body = token_replace(variable_get('mail_body')); //it might be any variable from the form eg. $form_state['values']['your_field']

//params is the array passed to hook_mail function
$params = array(
    'subject' => $subject,
    'body' => $body,
    );
      $message = drupal_mail('comment_notification', 'loaded',
        $to,language_default(),
        $params,$to, TRUE);
    }

}

function comment_notification_mail($key, &$message, $params) {
/*dsm($key);
dsm($message);
dsm($params);
*/
  switch($key) {

    case 'loaded':
      $message['subject'] = token_replace(variable_get('mail_subject'));
      $message['body'][] = token_replace(variable_get('mail_body'));
      break;

  }
}

I do not see a way to allow users to subscribe to comment notification, is that your issue?

In case it is you might have to do something like
Create a menu item as 'Subscribe to comments' check this link to ajaxify for menu item. On page callback of your custom menu subscribe the current user(global $user) to the comments, to hold the data you can simply use a custom table let's name as mymoudle_comment_subscription with columns as record_id|uid|comments_on_type|flag update this table in the subscription menu callback,

Rest is what you have covered in your code, i.e. implement hook_comment_update to notify on existing comment update, hook_comment_delete notify user on comment delete, hook_comment_insert notify user on new comment is added. In your hook Implementation query your custom table 'mymoudle_comment_subscription' fetch all uids get user mail by uids or in case you do not allow user to change emails you can store email directly in your custom table and use drupal_mail as your code shows to mail all users.


Peer-to-peer recognition system using User Points and Rules modules I would like to build a recognition system in the team where peers can recognize the effort of each other. I'm using User Points module.

For example:

UserA recognize the testing effort done by UserB.
UserA login to the recognition system and add 1 point to UserB in "Tester" category.
UserA get 1 point in "Supporter" category since he's recognizing others' effort.

The problem:

How to limit the points to be only +1; not more, not less, negative values shouldn't be allowed, more than 1 is not allowed.
How to automatically add +1 point to UserA who add point to UserB. I tried using Rules module but it always refers to the UserB.

To solve problem #2:

  How to automatically add +1 point to UserA who add point to UserB

In the rule Do section:

First, add action "Load current user account" and set User Id: [:global:user-id]. Name it as "Current user".
Then, in the "Grant points to a user", refer to "Current User" as User argument


Class not found in drush command definition In the drush command definition hook for the Node Revision Delete project I have the following code:

use Drupal\node_revision_delete\Utility\Time;

...

function node_revision_delete_drush_command() {
  $values = array_keys(Time::convertWordToTime());

The namespace exists and is in the correct place but once I use drush cr I got this error:

Error: Uncaught Error: Class 'Drupal\node_revision_delete\Utility\Time' not found in /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/node_revision_delete.drush.inc:34

It's weird because I call the same function in the line 179 for the drush nrd-st command and is working fine:

Time::convertWordToTime();

Trying to understand what happens I tried to use an Utility function from the Core in the drush definition command hook and works fine without problem, but with my function call it doesn't works.

Any idea about class not found problem?

As @Berdir says it seems Drupal is not fully bootstrapped when the hook_drush_command() is called as I tried to use a service defined in a custom module and I get the following error:

\Drupal::$container is not initialized yet.

So the solution for the moment is hardcode the values that should be returned by the function.


Displaying all values of a List (text) field, whether checked or unchecked [Drupal 8]

I have a List (text) field that allows multiple values, displayed as a check box list when editing. But when viewing the node, only the checked values are displayed.

How can I display all values, with an indicator which ones are checked/unchecked? Is this possible with theming?

What I found so far:

For Boolean fields, I can select something like this under "Output format" (e.g., "✔ / ✖"), but this doesn’t seem to be possible for List (text) fields. I guess the workaround would be to use multiple Boolean fields, but this makes Views Exposed Filters harder to use.
For Drupal 7, there is the module Selected and unselected values formatter (via the question How to display all values of List (text) instead of just the selected ones?)
I could imagine (but didn’t try) it would be possible to create a View and display it instead of the field, but then quick-editing would no longer work for this field, as far as I know.

You can easily generate a field formatter to output what you need in drupal 8 (generate field formatter => drupal gpff with drupal console) and get the result into a view.

Getting the field definition will allow you to get all possibles values (selected or not) for your list and display items as check or not considering the current node value.

$defs = \Drupal::service('entity_field.manager')->getFieldDefinitions('{ENTITY_TYPE}', '{BUNDLE}');
$field_definition = $defs['{FIELD_NAME}'];

Your custom formatter will be available in views (and everywhere it is usable, node display etc.).


audiofile throwing error on file size even though settings changed An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports.

Every time try to upload 8mb mp3 I get the above error even though have changed settings in field edit from 2 MB to 20 MB and using unmanaged VPS with plenty of space and memory plus php.ini file increased.

If you don't have apache access control, you can try to add the php.ini settings into

ini_set('post_max_size','16M');

and

ini_set('upload_max_filesize','16M');


How to remove the submit button on the form included by drupal_get_form? I have a hook_field_widget_form where I call drupal_get_form multiple times.

Here is my code:

foreach ($suppliers AS $supplier_id => $supplier) {
    $delivery_information = sbsl_order_delivery_information_new();

    $element['suppliers'][$supplier_id] = array(
      '#type' => 'fieldset',
      '#title' => $supplier['supplier_information']['visible_name'],
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );

    $delivery_information_form = drupal_get_form('sbsl_order_delivery_information_1_form_' . $supplier_id);
    $element['suppliers'][$supplier_id]['delivery_information'] = $delivery_information_form;
  }

How can I remove the submit button on the form included by drupal_get_form, and only use the submit of hook_field_widget_form to submit all the forms included by drupal_get_form?

If you look at the function drupal_render it will ignore all elements marked as #printed so just add that to the submit button's array.

You'll need to inspect the $delivery_information_form array to see exactly where your button is at, and when you find it you can do something like this:

  $delivery_information_form = drupal_get_form('sbsl_order_delivery_information_1_form_' . $supplier_id);
  $delivery_information_form['path']['to']['button']['#printed'] = TRUE;

before adding it to the $element array.


Get notification message in groups I created groups using Group module.

One group is a job poster(Group-A) and the other is a business owner(Group-B).

Group-B business is all about plumbing.

When Group-A posted a job about plumbing, Group-B should be able to get notified about the post as this is related to his business.

So, I use message stack as a method, but I still didn't get in the right way.

There is a message_notify module example that displays details in a page about a certain actions.

So what I need is that a group should get a notification message whenever a related job post is created.

Thanks!

What you need is to use the Message Subscribe module, also in the Message Stack. This will allow you to subscribe users to a particular entity, e.g. - your job post.

You need to be able to link your "plumbing" (taxonomy tag, or direct entity ref) to Plumbing Group. You need to use Rules if the functionality exists, or a custom module to hook into the submission of a new job posting with the reference or tag to pointing to plumbing group. If this tag exists, then subscribe all users in the Plumbing group to that new job posting and issue a notification using Message Notify.


How to apply suggested theme hook using hook_theme_suggestions_HOOK? Following this answer,  I'm trying to override core/themes/seven/templates/node-add-list.html.twig using hook_theme_suggestions_HOOK.

So, I added the following function in modules/custom/domain_filter/domain_filter.module

function domain_filter_theme_suggestions_node_add_list(array $variables) {
  $suggestions = [];
  $suggestions[] = 'node_add_list__' . 'custom';
  return $suggestions;
}

I created the custom twig file in my module: modules/custom/domain_filter/templates/node-add-list--custom.html.twig

The suggestion appear well in theme debug but it's not applied (the x is in front of node-add-list.html.twig):

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'node_add_list' -->
<!-- FILE NAME SUGGESTIONS:
   * node-add-list--custom.html.twig
   x node-add-list.html.twig
-->

How to apply node-add-list--custom.html.twig?

Finally I found a paragraph in the documentation. When using modules, we need to register the template using HOOK_theme(). So, I added the following function in modules/custom/domain_filter/domain_filter.module

/**
 * Implements hook_theme().
 */
function domain_filter_theme() {
  return [
    'node_add_list__custom' => [
      'base hook' => 'node_add_list',
    ],
  ];
}

Then my custom template modules/custom/domain_filter/templates/node-add-list--custom.html.twig is now applied.


Date format problem in view hello I encounter difficulties to display a date in the correct format in a view.

I souhaire display my dates like this 2009-07-19T03:00:00+01:00

I created a new format here / admin / config / regional / date-time / formats
here that Y-m-d\TH:i:sP

Then I created a new type of date and selected my new format.
When I go to my view, I select my new date format but the field shows a different format 2016-03-17+01:00 +01:00

So I have a time zone more and I miss the hour, minutes and seconds.
Do you have a solution ?

Try doing it like this, which works fine for me:

For date format select Custom and then enter Y-m-d\TH:i:sP


webform + form builder: how to clone an existing form I am using webform + form builder to manage some forms on my site.

I can't find a way to clone the form (with all its elements) to a new form?
I know that I can clone elements inside the same form, but I can't export them to another form (and I can't export the form itself).

There is a way to do it?

Thanks

Use node clone module to clone that webform node. Then, you will have a new node with webform fields.


Show all values of a multi File field sorted by upload time I have a content type with a File field that allows multiple values. What's the best way to display these files as a list ordered by upload time rather than delta but still using the file descriptions?

The Manage Display options don't really give any options for sorting the list on the node display.

I tried creating a File View using the content id in the url as a contextual filter, while this does let me sort by date I can't seem to use the file description in the output.

Is there a way to get file descriptions in File views or should I look at writing a custom formatter for the node display?

I found the module Extended File Field does exactly what I want.

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


How do you clear cache on a block when node of certain bundle added or updated? If you want to clear cache on a render array when any node is updated you can add as a cache_tag, "node_list":

  '#cache' => [
    'tags' => ['node_list']
  ],

But there isn't a way to do this when only nodes of a certain bundle are added or updated.

If you have a block, for example, and you'd like to clear the cache on it when any node with bundle "article" is added or updated, how would you do this?

You can easily create a custom cache tag related to properties on nodes by invalidating it yourself.

Based on this article:
https://www.drupal.org/project/views_custom_cache_tag

I created a custom tag for each node type, that is invalidated on node update:

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function mymodule_node_presave(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function mymodule_node_delete(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

Then in my build array for my block I added:

$build['#cache'] = [
  'tags' => [
    'node_type:article',
    'node_type:video'
  ],
];

This means this block will only refresh when nodes that are of type "article" or "video" are created or updated.

You could do the same process for any property on an entity, not just bundle.  For example, if you want a list of nodes to stay cached unless the nodes within it change their url alias, you could add code that checks if the url aliases is changing and then invalidate your tag node:123:url_alias".


Can I reference field item & label in node.html.twig? In Drupal 8, I defined a content type (say example) and made a separate template for it: node--example.html.twig.

I wonder if I can reference the item or label of a specify field in node--example.html.twig, instead of reference them in field.html.twig? By which I mean can I use something like the following, which I know is not working?

{{ content.field_example_field.label }}

If you can't find the label somewhere inside of content, then the code, which will prepare the label for rendering did not run at this point.

If you are inside the node twig, then there is a fully loaded node object. You can use this to get the field definition and the label:

{{ node.field_myfield.fieldDefinition.label }}

Or the first field item:

{{ node.field_myfield.0.value }}


Reference Based on Two Fields of a Content Type I have two content types account and device. device has a reference field named reference_account_number and it's referencing account_number in account, but the unique key for account is a composite key account_number and environment.

I used auto node title module to generate the node title based on account_number for account, and let reference_account_number map on to the node title of the account nodes.
So my problem comes up when I try to do feed import when there are duplicate account_number but different environment. The reference_account_number only map onto the account node that has matching node title.

Is there any way to reference another node based on two fields?
I was thinking about adding a environment field to device content type as well

Ideally, I would like this scenario happens when a user creates a new device content.

User enters the account number and environment, upon completion, user views the content just created, and reference account number provides a link to all existing account that matches the account number user inputted for the device content, same thing goes for environment

Thanks

Is there any reason why you could not just reconfigure auto node title to generate a node title based on a composit account number and environment -- say, something like "[account_number] ([environment])"?  It seems like if you did this, then your reference_account_number configuration would remain unchanged, your feeds will not get confused, and users can still add references by typing the account number only thanks to the standard autocomplete feature of node references.

If you did not like the way that "[account_number] ([environment])" looks in the output of your site, you could alter the render array, maybe in a hook_process_field.  For a good description on hooking the Drupal 7 render process, see The Scary Render Array.


How do I attach some entity fields (or widgets?) to a form? I am providing a form to a user to create a product.  I want to provide a few fields from a product type, along with some normal Form API input.  Example, I only want them to specify the price and SKU.  I want the submit handler to take care of creating the title name and any other fields.  In this case, a product lives as product entities and as product display nodes.  I want to present my user a single form to create and manage products.

I looks like I should be able to do this with the Field API, but I just see how to attached all fields from an entity.  I just want to attach a few.

Am I able to do this with the Field API?

EDIT TO ADD MORE INFO:

For example, when a user creates a new product, they will enter a 6 digit SKU.  Each product will have that SKU, with another 3 digits appended, specifying a category.  I want the user to simply enter the base SKU, like ABCDEF, select category Y and Z, and the submit handler creates the products with the correct SKUs, like ABCDEF-0001, ABCDEF-0002, and creates the node display.  There are also specific fields of the product type, so I need the user to populate the fields for these products, using the WYSIWYG filter they would otherwise use on the product create form.

I think you can certainly use field_attach_form. Take a look at the $options argument that is explained in more detail in the _field_invoke documentation. For more information you can also have a look at this issue: https://drupal.org/node/1825844

You can include any field of any bundle into any form using this approach:

field_attach_form('node', $entity, $form, $form_state, NULL, array(
  'field_name' => 'field_sku',
));

When I last used this approach I remember having passed a copy of the original form into field_attach_form() in order to prevent my original form from being modified to much. Then I have copied only field element into my original form:

$form_tmp = $form;
field_attach_form('node', $entity, $form_tmp, $form_state, NULL, array(
  'field_name' => 'field_sku'
));
$form['field_sku'] = $form_tmp['field_sku'];

Just look at the mentioned functions to see what they do. I'm not sure if this last part is needed.

And one more link to explore:

https://api.drupal.org/comment/49363#comment-49363


How can I print a field value in node.html.twig? I want to print a field value in node.html.twig. When I use {{ content.field_test }}, it prints the full HTML markup of the field.

How can I just print the field value?

While you can print the first value of the field without the surrounding div container with {{ content.field_test[0] }}, this is not a recommend way to do it.

The markup you want to change is in the field template. If you don't want for example any div's around the field field-test, then place a field template in the template folder of the theme:

field--field-test.html.twig:

<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

The benefit you get is that this outputs multi-value fields and that you keep the attributes of the field, which is important if you want the theme to work with core and third-party modules for client side functionality like, for example, quickedit.


Access denied to custom REST API endpoint for anonymous user I have developed a custom D8 REST API endpoint, and using the REST UI module, I have enabled it and set access to be allowed for the anonymous user using the permission created by REST UI. However, when I try to access the endpoint - either via Postman or with the D7 Feeds importer - I am unable to access the endpoint because I get a 403 - Forbidden return status code.

The settings for the endpoint in the REST UI settings provides the choices of basic or cookie authentication methods. Is the option of allowing anonymous access to a GET endpoint via the provided permission really doable, or is it required to actually send some type of authentication header?

Thanks.

So it looks like there is a core issue that doesn't permit leaving out some type of REST authentication. The easiest solution appears to be the Feeds HTTPFetcher AA (Advanced Authentication) module, as it allows you to enter your authentication credentials in the custom parser settings. The downside is that I have to create a user (and possibly a role) in D8 for this, but at least it's workable.


How to change the label of the "To:" field in the Date Module This doesn't seem to be the kind of thing you can change using hook_form_alter() unless I'm missing something.

The label of the "From" field can be any value you want, but the "to" field, if you have one, defaults to "to", see modules/date/date_elements.inc, line 369:

    $element[$to_field]['#title'] = t('to:');

so what's the correct way to change that to a value of my choosing, i.e. "Expires"? Via the Theme?

If you look further on down in date_elements.inc at line 412 you'll notice:

drupal_alter('date_combo_process', $element, $form_state, $context);

which allows any module to alter what it's created, eg, something like this:

function YOURMODULE_date_combo_process_alter(&$element, &$form_state, &$context) {

  $element['value2']['#title'] = t('expires:'); // this will change that to: to expires:

}

Just realize this simple example will do this for every instance of a combination to/from date, but information to get more specific is contained in $element, $form_state and $context.  For example, the specific field name is contained in $element['#field_name'] and the form_id is in $form_state['build_info']['form_id'].


create and save data to a file in the files folder from cron I currently have some working example code where when a URL path i defined using hook_menu has been passed; My custom module will use file_get_path() to pull a txt file from another ftp server. It will then return $data. The source data is stored that each line is a record. So I simply read the file one line at a time and use the explode() method to break the data into its components. From that I have it building a string in the format of a JSON at this point I return it to the user as a consumable JSON. This is used for my front end JavaScript. The problem is this data in the txt file changes very little over time. (its updated every night but very little changes).

I would like to reduce my request time by moving the fetch of the txt file to a cron job and build the JSON and save it in a sub directory of the Files directory. That way every request for the JSON data will be quick and not require a file_get_contents() and will also not require building the JSON data on every request.

I have been looking into the Files API and the hook_cron but very few quality examples show how to create a file or run a cron. I just need a simple example where a cron hook saves a simple file to a directory inside the files folder.

I'm using Drupal 7

UPDATE:

I tried the following: (objective to make sites/mysite.com/files/myDir/test.txt)

//File Name: MyModule_cron.inc
function MyModule_cron(){
    $baseDir = 'public://myDir';
    $fileContent = "hello world";
    file_prepare_directory($baseDir);
    file_put_contents($baseDir.'/test.txt', $fileContent);
}

This is loaded in from an inc file (added into the info file) and I have cleared my cashe then run cron. I then check in the sites files folder. The myDir is not created along with the file not being made. Is there something i'm missing? I'm not getting any error messages when running cron.

I just need a simple example where a cron hook saves a simple file to a directory inside the files folder.

That would be literally as simple as:

function MYMODULE_cron() {
  $path = 'public://foo/bar/';

  if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
    $content = function_to_generate_content();
    file_put_contents($path . 'baz.ext', $content);
  }
  else {
    // Log an error
  }
}


Add user to OG based on roles? I am using drupal 7, I want to add users having role 'R' to a OG group 'G'.

Is it possible to do that?

Here's some code I've used, you can't add the role condition to EntityFieldQuery so the array needs to be filtered afterwards:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
      ->propertyCondition('uid', '1', '>'); // skip the anonymous and admin
  $entities = $query->execute();
  $uids = array_keys($entities['user']);
  $accounts = user_load_multiple($uids);

  // filter the users array by role
  $include_roles = array('my_role', 'my_other_role');
  $filter = function ($value) use ($include_roles) {
        $isect = array_intersect($include_roles, $value->roles);
        return !empty($isect);
      };
  $accounts = array_filter($accounts, $filter);

Then, to add these to your group having id $gid

  foreach ($accounts as $account) {
    og_group($gid, array('entity' => $account, 'state' => OG_STATE_ACTIVE));
  }

Hope this helps. I think this should be doable in Rules, but I'm no expert in that.


Setting up and enabling Google CSE Is it possible to fully set up and enable Google CSE module before a website is launched? Or would I have to wait until it's launched and submitted to Google's search engine?

You can set it up now but it would be much use until your content is fully indexed by Google


Duplicate node on content creation Each time any node is being created, Drupal creates two copies of the same node, both in the default language.

What can be the reason of this duplication?

This is not the normal Drupal behavior.  In this case, what you need to do is start disabling modules one at a time.

Disable a module that you think might be causing the problem (just take a guess) and then create a piece of content to see if two pieces of content are created.  If you disable a module and then create content and you only get one piece of content, you know you have found the problem module.

Once you find the problem module, try to locate the source of the problem in the module configuration.  If you can't find it yourself, try asking again on this site.

Without knowing what module is causing the problem, it is very hard to answer your question, as there are too many potential modules that can cause problems.


How can I determine if a $form (or $form_state) is an entity create/edit form When in a function (e.g. a hook_form_alter) is there a reliable way to determine if the form is an entity form and if so, what type of entity?

You can check if the form is an instance of EntityForm and then get the entity to check the entity type:

if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity_type = $form_state->getFormObject()->getEntity()->getEntityTypeId();
}


Is there a way to alter the implementation of a hook given by a third-party module, or a core module? I have a module that should replace the implementation of a hook done by another module.
Is it possible to do it, with Drupal 7? If it is possible, under which conditions is possible?

By replacing the implementation of a hook done by another module, I mean using a function that is automatically called by Drupal when that module is enabled. For example, if the Poll module is enabled, then Drupal should call the poll_user_restriction_info() or the poll_metatags_info() (where hook_user_restriction_info() and hook_metatags_info() are custom hooks used by my module) function present in my module files.
I could use a function in my module that loads some include files from my module directory (e.g. poll_custom_hooks.inc) basing on the enabled modules, but I am looking for a system that would allow Drupal to automatically load such files.

You can use hook_module_implements_alter() to alter the list of modules which implement a given hook. So just implement the hook in your module too and then remove the one from the module you want to replace.

Note that this hook should be used very carefully, you can do really weird stuff with it which will make it very hard to maintain and understand, among other things.


How to create authentication token in the HTTP header request for Json view I have a view listing some fields from a content type then i made it in a Json format using View DataSource module, all is ok with me tell now

i want to add authentication token in the header request to restrict any user to access this json view

any module or code help me,
thanks

views_datasource uses the standard drupal session to authenticate.

First set the permissions on the view to what you want. And test this in the browser.

then you can go onto your user authentication.
Im assuming that you're using ajax to call the view, in a headless mode ?

then you've got 2 options

1) Make the users log into the Drupal site somehow first - that will then give them a session , and when they call that ajax request, the session will be sent.

2) Authenticate the user from your code - you can do this with the services module. you can follow this post https://www.drupal.org/node/910598 for more information


How to Schedule a node "Promoted to front page"? I am looking for a way to schedule "Promoted To home page" nodes to appear after a particular time.

When user creates a new node and checks "Promoted To home page", it should not appear immediately on publish on the homepage.

Then need a scheduler which set "Promoted To home page" nodes to appear on front page.

The node will published and visible if accessed directly or seen in other section.

You can do this using the Rules module in combination with the "Rules Scheduler" (a submodule of it). After you enable these 2 modules, create a Rules Component and a Rule. Here is a blueprint of doing so:

Create a Rules Component which accepts "node" as a parameter, and which has a Rules Action to set the node to "published".
Create a Rule like so:

Rules Event: Before saving a new node.
Rules Actions: (1) set the node to "unpublished" (to be sure it is not "published" when the node is saved) and (2) schedule the Rules Component created in the previous step.

Note: From the comment below this answer (which states "The node will remain Published all the time.") it doesn't seem to apply for the question here, but using a similar approach you could also schedule another Rules Component to mark it unpublished again later on, eg X days after the node gets published. In that case, you use Rules Event "After updating an existing node", combined with a Rules Condition to check if the update changed "unpublished" to "published".


How do I lock a field on Node Edit? I want to create a node field that is only editable upon node creation. Once the node has been created, the field of that node will no longer be editable.

Here you go: the Field Permissions module, which (as stated on its project page) "... allows site administrators to set field-level permissions to edit, view and create fields on any entity."


How do I send user credentials and get the access token? I am linking a Drupal site to an Android application. With the help of the Simple OAuth module, users will log in to my android app using their Drupal site credentials.

I understand that once the client application has the access token, it can be  included in the headers of any GET request to fetch JSON content from Drupal. I also know that https://example.com//simple-oauth/refresh will give a new access token, having the refresh token.

What should I do if both access and the refresh tokens are already expired?
How do I get them from scratch?
What is the URL to ask for the token, and how do I include the credentials with that via HTTP headers or in the URL?

Is there something I'm not aware of about this way of authenticating?

Moqbel,
Here is a Drupal 8 Android app code that uses Android accountManager to send user credentials and get the access token. https://github.com/onedrupal/One-Drupal-Android

Whan a token is expired, AccountManager can be used to get a fresh token.
https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java At the launch of the activity AccountManager.getAuthTokenByFeatures is called

mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

Here is the AccountAuthenticator https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java

authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);

It uses cookie auth by using endpoint /user/login?_format=json at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/provider/MyServerAuthenticator.java

But Android AccountManager also works with OAuth.

from https://developer.android.com/training/id-auth/authenticate

  The only way to discover whether a token is expired or not is to
  contact the server, and it would be wasteful and expensive for
  AccountManager to continually go online to check the state of all of
  its tokens.

  Because expired tokens are such a common occurrence, and fixing them
  is so easy, many applications just assume the token has expired before
  even asking for it. If renewing a token is a cheap operation for your
  server, you might prefer to call AccountManager.invalidateAuthToken()
  before the first call to AccountManager.getAuthToken(), and spare
  yourself the need to request an auth token twice.


Create template file for views block There is a lot about theming custom blocks, but what about blocks created by views?

My views block has id: block-views-posts-listing-block,

I try many ways for naming template file, ex: block--block--views-posts-listing-block.tpl.php,
but I can't find correct file name.

Edit your view. and Under the "Advanced" settings of your Block details, click on "Theme: Information". A list of options of template files will be displayed.

for example, if your block has a name "posts listing", see possible names listed by "Theme Information" option:

* Display output: views-view.tpl.php, views-view--posts-listing.tpl.php, views-view--default.tpl.php, views-view--block.tpl.php, views-view--posts-listing--block.tpl.php
* Style output: views-view-unformatted.tpl.php, views-view-unformatted--posts-listing.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--block.tpl.php, views-view-unformatted--posts-listing--block.tpl.php
* Row style output: views-view-fields.tpl.php, views-view-fields--posts-listing.tpl.php, views-view-fields--default.tpl.php, views-view-fields--block.tpl.php, views-view-fields--posts-listing--block.tpl.php
* Field Content: Title (ID: title): views-view-field.tpl.php, views-view-field--title.tpl.php, views-view-field--posts-listing.tpl.php, views-view-field--posts-listing--title.tpl.php, views-view-field--block.tpl.php, views-view-field--block--title.tpl.php, views-view-field--posts-listing--block.tpl.php, views-view-field--posts-listing--block--title.tpl.php

for example: your block has the name posts listing, and has style unformatted, then "Theme Information" suggest the name views-view-unformatted--posts-listing--block.tpl.php (this is only one of several names).  you can copy the original views-view-unformatted.tpl.php template file (located in /modules/views/theme) to your current theme directory, and rename this file with the name suggested :views-view-unformatted--posts-listing--block.tpl.php. then make the changes inside your template file. If this template does not allow make your wanted changes, seek other templates according your needs.

In the end, if you add a new template, rescan template files list:

  Important! When adding, removing, or renaming template files, it is necessary to make Drupal aware of the changes by making it rescan the files on your system. By clicking "Rescan template Files" button you clear Drupal's theme registry and thereby trigger this rescanning process. The highlighted templates (in your template list above "Rescan template Files" button) will then reflect the new state of your system.

Also Theme Developer Module http://drupal.org/project/devel_themer suggested by Oswald could be useful to detect possible template/s to change specific elements according your criteria. I do not recomend this module enabled in productions enviroments (in my case, even I have disabled the module in test enviroments, because seems to have conflicts with views, but when it has been necessary, has been very useful)


Adding attachment using Swiftmailer I am trying to add an attachment to an email from a form_submit. I can see the attachment loading in the hook_mail() before the email sends, but no attachment is coming through. I also tried to use the swiftmailer_swiftmailer_attach() hook and that doesn't work. The emails are coming over with Content-Type: multipart/alternative;

Here is the code:

// from submitForm()
$params['message'] = $body;
$mail_manager = \Drupal::getContainer()->get('plugin.manager.mail');

$mail_manager->mail('so_assets', 'banner_email', 'test@test.com', \Drupal::languageManager()->getDefaultLanguage()->getId(), [
  //'content_type' => "text/html; charset=UTF-8; format=flowed; delsp=yes",
  'from' => 'test@test.com',
  'message' => $body,
  'myattachment' => $store_logo[0],
]);

// in .module file
function so_assets_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );
  //var_dump($params['myattachment']); die(); // I can see the managed file ID here and load it.
  switch ($key) {
    case 'banner_email':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('New Request');
      $message['body'][] = $params['message'];
      //$message['params']['files'][] = \Drupal\file\Entity\File::load($params['myattachment']);
      break;
  }
}
// I tried this, with and without the file attachment commented out in the hook_mail()
function so_assets_swiftmailer_attach($key) {
  return \Drupal\file\Entity\File::load(5130);
}

Swiftmailer currently expects a plain \stdClass object in files as this part hasn't been fully ported from D7. See https://www.drupal.org/node/2713651.

So you need to do something like

$file = (object) [
'filename' => $file->getFilename(),
'uri' => $file->getFileUri(),
'filemime' => $file->getMimeType(),
];
$message['params']['files'][] = $file;


How to import translated strings having dynamic variables? Short: How can I import .po file having dynamic variables in strings like follows

$message = t('Hi @firstname, please follow @sitelink or mail me at @email ', $var);

Indetail:

I've written a custom module to send mail notification to users. In that module $message string has dynamic variables like follows (sample)

$var = array('@firstname' => $username, '@sitelink' => $GLOBALS['base_url'], @email => $email);
$message = t('Hi @firstname, please follow @sitelink or mail me at @email ', $var);

How can I import $message string to my site.

I could translate all the static strings to Spanish of other custom modules like follows.

#: mycustom.module
msgid "Are you sure to approve"
msgstr "¿estás seguro de aprobar"

But how can I write the same for Dynamic variables. Right now Spanish Users are getting their mail in English?

Note: I'm just using Drupal core Locale module.

There are two way to achieve this

Add string in a your .po file like follows

msgid "Hi @firstname, please follow @sitelink or mail me at @email"
msgstr "Hola @firstname, por favor, siga @sitelink o envía un email al @email"

and import that .po file by going

  Administration » Configuration » Regional and language » Translate interface » Import

 If you want to change individual translated strings go to

  Home » Administration » Configuration » Regional and language »
  Translate interface » Translate

You can find list of strings there each having edit link beside. So you change the individuals like follows.

Hope this helps someone.


how to programmatically alter the rendering of a field in Views I have a content type called 'Ping'. It has several fields and one of them is a url by the name 'filename'. I want the View of all such pings, names 'user-pings' to display not the url itself, but a link to it. How do I do that?

I've tried the following, but it doesn't work:

function feedback_views_pre_render(&$view)
{

    if( $view->name === 'user_pings' )
    {

        foreach( $view->result as $key => $val )
        {
           $lang = $view->result[$key]->_field_data['nid']['entity']->language;
           $field = $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0];
           $filename = $field['value'];
           $link = "(download)";
           $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0]['value'] = $link;
           $view->result[$key]->_field_data['nid']['entity']->field_filename[$lang][0]['safe_value'] = $link;

        }

    }

}

Additionally, if this code is a try in the right direction, I would very much like to learn how to do the same thing in less code.

Cheers and thanks in advance,
Alan

You can do that in the views interface, no need for pre- or post- processing on the theme level (as your script snippet suggests).

I assume that you are using Drupal 7.x and Views 7.x-3.x.

Go to the UI for the view you want to change:

http://example.com/admin/structure/views/view/yourviewname/edit
or Home » Administration » Structure » Views » Yourview

Make sure you are on the Display that you want to change (towards the top: Display has tabs "Page", "Add" and maybe others like "Block" or similar)

Under "Format", it shows "Format" and "Show". "Show" needs to be set to "Fields".

The click on the field with your url, like:

 Content: URL (URL)

A popup window will open with:

 Configure field: Content: URL

Click on "Rewrite Results" - a number of options open, check:

 Rewrite the output of this field

A couple of additional fields now open up.

Click on "Replacement patterns" and identify your url field, for example:

[field_url]

Now, enter the text you want to display into the "TEXT" field (can be html tags like an image tag):

An image tag
Some text

Check "Output this field as a link", and enter the replacement pattern into the "Link path " field [field_url].

If you want to use another field from your content type to show instead of something generic, that field needs to be on the "Fields" list BEFORE the field_url field, but can be marked as "invisible" if you don't want to display it otherwise.


How do I modify the "view" link in a view? I'm sure this is a simple question when you know what you're doing, but I'm a bit puzzled.

At the moment, I have a view, from the views module, listing published articles on the front page of my site. After each article, there is a link "view" or "voir" (depending on the language being used) which takes you to the article. This is simply an anchor tag generated by thte Views module containing a link to the article node appended to the end of the item.

However, the person for whom I am making the site wants this link to be styled in a specific way, with an icon and the text to read "Read more" or "Savoir plus". How or where can I modify the HTML markup and text content for this particular element of the View module output?

In the 'Add fields' on your View, you can select 'Content: Link', which generates a simple link to your content. When configuring this 'field' you can set the 'Text to display' property and under 'Style settings' specify any CSS classes you want (see screenshot below).


including js through module info file is not working mymodule.info:

name = custom
description = custom module

core = 7.x
version 7.x-0.1

scripts[] = custom.js

created the file custom.js in the same folder as custom.module file
I have the $scripts variable in html.tpl.php
cleared all caches

Still cannot see custom.js in page sources. What else it might be?

The problem is with a typo in the info file. It's missing a "=" on the version line.
Correct info file here:

name = custom
description = custom module

core = 7.x
version = 7.x-0.1

scripts[] = custom.js

Also note that the version properties is discouraged


How do I remove the default 'my cms' text from my drupal 7 webpage with the bartik theme? I have recently created a webpage with drupal 7 and currently have the bartik theme applied. However, I have encountered what I assume is a trivial issue but have been unable to fix it. The site has the default text 'my cms' appearing in the banner across the top of all pages and I have been unable to remove it. I assume it is the site's slogan, but I have not been able to locate where that is set in either the the admin of the site or the files of the site.

Here is the site to show what I am talking about.

Thanks for the help.

That My CMS text is the Site name setting value. You can change it from the setting page on /admin/config/system/site-information.


find all core patches I work on site that is drupal 7.20, I am sure previous team that worked on this project patch core in some places,I want to find all of patched they did, is there any way to find all patched they did?
one of my idea is find a clean drupal 7.20 core and compare it but I am not sure this is good solution

You can use the Hacked! module

This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.
Hacked! also provides drush integration so that you can see what files have changed from the command line.