How do I relate two similar text fields between users and content with user as argument? Getting a bit mixed up and need help with this. My restrictions are that I cannot use entity reference fields (or any reference type field); this is because Salesforce Suite isn't able to translate single strings to the array object normal reference fields use upon import and object creation.
I have two entity types, User and Content, which are dynamically created via the Salesforce Pull module. Both entities share a plain text field (SFID), which is the user's main ID.
The Content nodes' SFID field value can match any user's SFID field value, and I want to create a view that lists nodes on the user's page related in this way.
For example, I have the following users and nodes.

User 5
SFID 120

Node A
SFID 120

Node B
SFID 130

Node C
SFID 120

On /user/5/mynodes, I need a list of the nodes whose SFID matches the user's SFID. In this case above, the page would list the following nodes:

Node A
Node C

You need to make a View that lists nodes, containing a contextual filter that filters by SFID.  Do that, and what remains is the problem of how to pass the user's SFID value to the contextual filter.  There are many ways to do this, depending on how you're generating the user/%user/mynodes page.

Panels / Page Manager approach

My go-to recommendation for this sort of thing is to use Panels / Page Manager to generate the user/%user/mynodes page, and embed your view there.  If you enable the Views Content module (bundled with CTools) you will have a new type of Views display available called "Content pane".  Build your view using this type of display.  In the view configuration when configuring this display there's an option for "Argument input".  You'll probably want to choose "input on pane config".  Then, when embedding the view in your page (using Page Manager) you'll be given the opportunity to plug in a token there from the ctools user context that represents the user's SFID.

Custom module alternative:

Since you said you can't use Panels, your best alternative is probably to create your own menu callback at user/%user/mynodes wherein you extract the SFID from the user object and return the view by calling views_embed_view().

This is greatly simplified, but here's the gist of it:

function mymodule_menu() {
 $items['user/%user/mynodes'] = array(
  'page callback' => 'mymodule_user_nodes',
  'page arguments' => array(1),
 );
 return $items;
}

function mymodule_user_nodes($account) {
 return views_embed_view('viewname', 'displayname', array($account->field_sfid['und'][0]['value']));
}

Note: I haven't tested that code, it's just off the top of my head.  I may have forgotten something.  Don't forget to add things like an access callback since I presume you'll want to limit access to this page.

Views Field View or Entity Views Attach (EVA) alternative

This is a little bit icky but should work.  Either of the modules I listed (Views Field View or Entity Views Attach) will work for this approach.  I'll specifically outline how to do this with Views Field View but you could adapt these methods to EVA if you want; it would be similar.

You will make 2 views:

A view that lists users and accepts the user ID as a contextual filter.  So this view will always return only 1 single user (whatever user is passed in the URL).
The view that you've already likely created; the one that has a contextual filter that accepts a SFID value and lists nodes.

What we'll do is use view #1 to generate the page at user/%/mynodes, and view #2 will be embedded inside of view #1; view #2 will generate the actual list of nodes for us.

We'll assume you've created view #2 correctly already (it's basically what we've already discussed previously) and I'll focus on view #1.

Create a view based on the users table
Path for the view should be user/%/mynodes
Add a contextual filter to the view that filters on uid
Configure the view to output fields
Add the SFID field to the view, but check the "exclude from display" option so it's not actually displayed.  We add this to the view so that it's available as a substitution for our next step.
If you've installed Views Field View then you'll have a new field available called Global: View.  Add this to your view.  This field has a few settings; you'll need to select the name and display of view #2, above, and enter [!field_sfid] (this is the substitution token we get from the field we added in step 5) into the Contextual filters option.

Now you need only visit user/%/mynodes with an appropriate uid in place of the % and it should work.


Cron set in Drupal UI or by server? Under /admin/config/system/cron I can choose how often the cron runs. However do I still need to set up my server to ping the cron key (that I see in my reports page after I manually run the cron)?

How do these 2 work together? Is the server still required to run the cron, but then the cron wont run more often than is specified in Drupal's UI here: /admin/config/system/cron ?

Drupal has a built in "poor man's cron" which is invoked on a schedule when regular users visit pages.

Setting up a proper crontab entry (and turning off poor man's cron, i.e. set it to "Never") is usually the best thing to do.

If you set both, the poor man's (in-built) cron and also add a crontab entry to ping the cron URL, then yes the cron will run twice.


Is there a way to enable Basic Auth for only one specific type of node? Can't really find much useful in the way of googling.

I have a special content case on my site where I have created a page template which displays a series of blocks in my theme code. To apply this template to this particular page, I made a custom node type for it. However, this content is (and should be) restricted only to users with a certain permission, which I accomplished via the Content Access plugin.

I want to use wkhtmltopdf to output a PDF of that page for internal use. The only way I think I can get the node instance to allow wkhtmltopdf to view it is to run wkhtmltopdf with the --custom-header flag with an Authorization header. I need this to happen once per day, and was thinking of setting up a cron task to run wkhtmltopdf nightly on a Linux system (so far I have just been testing it manually on a Windows system where the node had no permission requirements and everything seems fine).

I know that enabling basic auth for certain paths is a thing I can do using a plugin, but this content is not defined by a plugin and is just a node I created using the Drupal interface.

Is this possible, or do I have to tear it down and start over and build a new custom plugin?

Probably there is no one here, that has tried the method you've described. I would start with a custom entity, use the basic auth or create a new authentication provider and apply this for the entity route. You can do this with drupal console within a minute.

And you don't need contrib code to configure access for the custom entity, because here you can do what you want in core. I wouldn't use an Access plugin from contrib, until there is a stable release.


Setting node ID sequence to a particular higher value for future created records We have an organic groups based portal in D7 where many blood banks add records. We recently initiated Drupal 8 migration and are close to completion. However, we would want to add selective blood banks first to the new D8 portal, have it tested before we ask all the other blood banks to use the new portal.
Is it possible to set a higher NID value when new records are created by new users? Migration data for remaining customers can happen seamlessly as their NID values will be lower.
Thanks.

Yes, you can set the nid to a higher value in your D8 instance, then continue to migrate D7 nodes under that.
Something like the following to set the auto_increment value.
// Set the next auto increment field value on the table
$result = db_query('ALTER TABLE {' . $connection->escapeTable($table) . '} AUTO_INCREMENT = ' . (int)$auto_increment);

e.g for node and node_revision
// Set the next auto increment field value on the node tables
$result = db_query('ALTER TABLE {node} AUTO_INCREMENT = 8000000');
$result = db_query('ALTER TABLE {node_revision} AUTO_INCREMENT = 8000000');


I can't get my module to show up in the Navigation I'm trying to create a custom module that has a block with a form in it.  I'm able to install my module, and even add the block to the content area of the site, showing my form on every page of the site.  But for some reason the page I set as the form's page won't show up in the navigation, and when I try to type in the pages address to get to it, it says the page is not found.

<?php
require_once('/includes/functions.php');
/**
 * @file
 *
 */

 /**
 * Implements hook_block_menu()
  */

 function search_engine_menu() {
    $items = array();
    $items['results_page'] = array(
        'title'         => 'Search Results',
        'page callback'     => 'search_engine_results_page',
        'access callback'   => TRUE,
        'type'          => MENU_NORMAL_ITEM,
    );

 }

 /**
 * Implements hook_block_info().
 */

 function search_engine_block_info() {
     $blocks = array();
     $blocks['search_engine'] = array(
        'info' => t('Search Engine'),
        'cache'=> DRUPAL_CACHE_GLOBAL,
        );

    return $blocks;
 }

 /**
 * Implements hook_block_view().
 */

 function search_engine_block_view($delta = ''){
     $block = array();
     switch ($delta) {
     case 'search_engine':
         $block['subject'] = t('Search Engine');
         $block['content'] = drupal_get_form('search_engine_form');
     }

     return $block;
 }

 /**
 * Implements hook_form.
 */

 function search_engine_form ($form, &$form_state){
        $form['searchOptions'] = array(
            '#type'     => 'select',
            '#title'    => t('You can search by GWF Number, name, email address or phone number.'),
            '#options'  => array(
                'gwf'           => t('GWF Number'),
                'applicant_email'   => t('Email Address'),
                'name'          => t('Name'),
                'phone_number'      => t('Phone Number'),
                ),
            '#value'    => 'gwf',
            );
        $form['searchInput'] = array(
            '#type'     => 'textfield',
            '#title'    => t(''),
            );
        $form['submit'] = array(
            '#type' => 'submit',
            '#value'=> t('Submit'),
            );
        $form['results'] = array(
            '#type' => 'markup',
            '#value'=> 'Test',
        );

    return $form;
 }
 /**
 * Implements hook_form_submit.
 */

 function search_engine_form_submit($form, &$form_state){
    drupal_set_message('Submitted');
 }

At the end of your search_engine_menu() function, you need to return $items. Also, you should clear your drupal cache after adding a new menu item.

 function search_engine_menu() {
    $items = array();
    $items['results_page'] = array(
        'title'         => 'Search Results',
        'page callback'     => 'search_engine_results_page',
        'access callback'   => TRUE,
        'type'          => MENU_NORMAL_ITEM,
    );
    return $items;
 }


Images are uploaded but those are not avaliable in a form I have a problem with webform module and that too with my site only :(
When I add form field with image upload, photos are uploaded but when I check submissions there are empty places, only I can find this photo in FTP in path sites/all/webform/

When I add required field, so user can not go to the next page break
I choose file, format and weight is correct, I click upload a file, looks that is uploaded

I try to go to the next page break but it is impossible because appears a notice that this field is required and is empty...

I try to do in another webform created, without page breaks and another fields, but issue is the same.

In another drupal site in my server I don't have this issue. If you want to reproduce please go to my site:
vidicon.nazwa.pl/brodnica/zgloszenie_firmy

please fill fields with* and after upload photo in last field and try to go to next step. It will be not possible but I will have this image on my server in /sites/default/files/webform/...

BTW I try to create a another simple form with image upload field and the same issue occurs, permission I set the same as in other site where webform works properly. I don't have any ideas, but I need this webform to my site :(

Thank you in advance for help.

Case is resolved, issue appears in drupal 7.43 and 7.44, I last version - 7.50 works ok


Panels and pager in the pane Is it possible to load next page of the view inside a pane (by using pager)?

If I understand the question correctly, you need to set the Use panel path to Yes in order for things like pagers, exposed filters/exposed sorting, and ajax to work properly.


Include panel in view? I have a view that is shown in the footer of a theme (Lucid & Nodestream Features?). Since my task and scope is small, I do not what to change up everything - just use what is there. I want to show panelized node or a panel page in the header and footer of the footer view. I have tried "Entity: Rendered entity", but I just get the node's fields and not the panel layout & content.

How do I include a panel (3.3) in a view (3.7)? (not view in a panel)

The views were supposed to be displayed in the panels not viceversa. Why not created a panel with header and footer for placing views instead?


How to call pages by Ajax using javascript I've a created an Ajax-callback page using my module available as myModule/somepage/%/% - you can see that last two arguments in this page changes dynamically.

I want to make an AJAX call to this page, writing javascript. Say, when I click a button an ajax call will be made to this page (POST method preferably for the two arguments).

I know how to create hyper-links that handle Ajax calls automatically, but in that way links are static, and I can not send arguments to my Ajax-callback page. So how do I write JavaScript to make an Ajax call to my page?

Here is the code to make POST req to a webpage.

$('#yourid').click(function(e) {
    e.preventDefault();
    var theUrl = base_url + 'myModule/somepage';
    $.ajax({
        url: theUrl,
        type: "POST",
        data: "name=John&location=Boston"
        success: function(msg){
        alert(msg);
        $('#displydiv').html(msg);
    }
    });
});


How to set required to TRUE or FALSE based on the GIVEN #states? I have problem with the required. It does not return a required validation when I clicked submit button. What is wrong with this code?

$form['fieldset1']['last_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Last Name'),
  '#states' => array(
    'required' => array(
      ':input[name="payment_method"]' =>  array('value' => array('credit', 'debit')),
    ),
  ),
  '#attributes' => array(
    'placeholder' => array('Last Name'),
  ),
);

States are used to set properties/values by javascript. The #required property is for the server-side validation, it can't be controlled using states.

You could either implement an AJAX callback on the text field change to update the required status and rebuild the form, or implement a validation handler which checks the status of the text field and throws an error if it contains text but no payment method has been selected.


Drupal module Date 2.7 update - Database Table name I just updated the Drupal7 module Date from 2.9 to 2.10.  There is a database table update that acccompanies that module update.  What is the name of the database table that is updated?  (or can you direct me where to find that information?)

Attaching screenshot of the database update performed when installing the date module.  What are Date text widgets?

It doesn't matter what tables are being updated, you can just go to /update.php of your site (you need to be logged in first) to apply these updates. You don't do them manually.

To find what was updated, you can look in the CHANGELOG.txt if the module has one, or, look in the install file for the module being updated within Date. It should have an applicable update hook that will show you (in code) what is being changed.

This is a list of everything that was changed in the last release.


Is is it possible to set an expiry time on the cached version of each node individually in a Drupal 6 website? Is is it possible to set an expiry time on the cached version of each node individually in a Drupal 6 website? The expiry time could be based on any factor.

Check out Scheduler.

From the project page:

  This module allows nodes to be published and unpublished on specified dates.

What are some examples of factors for expiry date?


Sending email only to active (unblocked) users of the site How can I send email and notifications to the active (unlocked) users of the site? What modules do I need for that? Could you explain it clearly?

Already I'm using messaging, notifications and the Mass contact module.
If I send mail through the Mass contact module, the blocked users also receive mails.

Add a category in Mass Contact

http://localhost/sitename/admin/config/system/mass_contact/add

and "Roles to receive e-mail" , just check "authenticated user" and save configuration.

And "authenticated user" are active user not the blocked user.


How to set a banner slideshow to run if images are only fully loaded I am new to Drupal, and not that good in Jquery. I just created a Drupal animated banner in Jquery. Each banner image is kinda large about 500kb each jpeg. My problem is, the banner images starts to run even the banner images are not yet fully loaded. Heres the code:

(function ($) {
  // Original JavaScript code.
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'http://www.site.com/sites/all/themes/layoutph/images/bg01.jpg';
backgrounds[1] = 'http://www.site.com/sites/all/themes/layoutph/images/bg02.jpg';
backgrounds[2] = 'http://www.site.com/sites/all/themes/layoutph/images/bg03.jpg';
backgrounds[3] = 'http://www.site.com/sites/all/themes/layoutph/images/bg04.jpg';

var customtitle = [];
customtitle[0] = "Welcome to Site";
customtitle[1] = "Site joined force with Site Foundation";
customtitle[2] = "Site Foundation school campaigns for 2014";
customtitle[3] = "New York visited by Site Foundation";

function changeBackground() {
    if(currentBackground > 3 ) currentBackground = 0;
    currentBackground++;
    $('.masterbg').fadeOut(1000,function() {
         $('div.slogan').text( customtitle[currentBackground] );
        $('.masterbg').css({
            'background-image' : "url('" + backgrounds[currentBackground] + "')"
        });
        $('.masterbg').fadeIn(1000);
    });
    setTimeout(changeBackground, 4000);

}
     setTimeout(changeBackground, 4000);

})(jQuery);

Can you give me a modification to my code, or theres a function I need to add my code to let the banner images load first before banner slideshow start.

Thank you in advance.

Note: This jquery code is for Drupal.

You can visit this post  Slideshow Tutorial to create slide show On drupal site in Drupal standard way. Try to use Drupal standards.


How to send POST request to https using \Drupal::httpClient()? I want to send POST request to https using \Drupal::httpClient().
But ended up with error like

  GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate
  problem: self signed certificate (see
  http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Below is my code.

$post_fields['name'] = 'aa';
    $fields_string = json_encode($post_fields);
    $response = \Drupal::httpClient()
           ->post("https://localhost/example/api/user-update?_format=json", [
         'auth' => ['admin', 'admin'],
         'body' => $fields_string,
    'http_errors' => FALSE,
         'headers' => [
           'Content-Type' => 'application/json',
    ],
       ]);
    dsm($response->getBody()->getContents());

How to send POST request with \Drupal::httpClient().

The error message should inform you what is going on. You are using a self-signed certificate locally. This probably won't be an issue on your production sites, but this is not really useful for local development.

Inspect the \Drupal::httpClient() static method you may discover that it uses the http_client_factory:fromOptions service. Use this directly allows you to pass options into Guzzle to allow requests to sites using self-signed certificates.

$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

Obviously this is not ideal. You should probably parameterize the URL that you are using instead of hard coding the URL. Then locally you can test without a self-signed cert or HTTPS. Or parameterize the options you pass into Guzzle so that verify => TRUE when you're on production. It is not recommended to set it to FALSE and this is a security risk.


Why is hook_form_alter() so messy? Here's an example I just ran into. I'm trying to put some HTML in the label of my field.

$form['field_feedback']['und']['#title'] <- has the title
$form['field_feedback']['und'][0]['#title'] <- has the title
$form['field_feedback']['und'][0]['value']['#title'] <- has the title. (Works)

Why are there three populated #title attributes with only one being used?

What you're seeing is how Drupal represents fields in a form. It breaks down like this:

The children of the outer array, $form['field_back']['und'] ('und' for 'undefined'), are the different languages the field has been translated into. In Drupal, you are recommended to use LANGUAGE_NONE for 'und' in code.
The children inside each language array, e.g. $form['field_feedback']['und'][0], represent the different entries for the field. For example, if a field has unlimited cardinality, and there are several entries for that field, they will show as $form['field_feedback']['und'][0], $form['field_feedback']['und'][1], etc.
Finally you have the form input element(s), for the field values themselves, e.g. $form['field_feedback']['und'][0]['value']. In this case the column name is value, for a node reference field type it would be nid, and so on. If a field has multiple data columns associated with it you'll see more children as well. These are represented by a text field/select box/special widget, and will ultimately provide the value for the field.

The fact that titles have been added to the various elements throughout the hierarchy is incidental to be honest. Whether or not those titles are displayed on the form is down to the particular settings of the render array in which each #title is contained.

To change the title on the actual form widget, you only need to worry about the form element at the very bottom of the array: i.e. the actual input elements ($form['field_feedback']['und'][0]['value'], etc.).

It's probably worth noting that the element/widget used for a particular field may be quite complex. If you don't already have it, you should install the Devel module and use the dpm() function to inspect the $form array; that will show you exactly where in the array the elements you're trying to target are.


What is the equivalent of Drupal.settings.basePath? I'm trying to get the site URL in JavaScript. In Drupal 7, this is stored in Drupal.settings.basePath. What's the Drupal 8 equivalent?

In Drupal 8 this setting is:

drupalSettings.path.baseUrl

You find more in core/module/system/system.module:

function system_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
  ...
    $path_settings = [
    'baseUrl' => $request->getBaseUrl() . '/',
    'pathPrefix' => $pathPrefix,
    'currentPath' => $current_path,
    'currentPathIsAdmin' => $current_path_is_admin,
    'isFront' => \Drupal::service('path.matcher')->isFrontPage(),
    'currentLanguage' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(),
  ];

  ...


How do I programmatically add a new search page to the search page list? I have been able to successfully create a search plugin for a custom module, which allows users to search for my custom entity by name. After creating this file, I have to enable it by visiting /admin/config/search/pages selecting my search type from the dropdown, and add it after specifying the target path. What is needed to do this within the module? I imagine I would have to create a route somewhere, and then associate this route with the search page list. Any advice on how to do it?

After you've configured the plugin in UI, export the config and look for the configuration file search.page.[search_plugin_id].yml.

Remove the uuid and hash line and place the file in the directory config/optional/ of the module.

You find examples in the core modules Node and User, see http://cgit.drupalcode.org/drupal/tree/core/modules/user/config/optional/search.page.user_search.yml


How to conditionally load - and allow a user to populate - a taxonomy image field in node create/edit form? pardon the bad headline. I have a node with a autocomplete taxonomy field "categories". When a user creates a node, he can add a single term/category to that node.

How would you make it possible to also attach an image to that taxonomy in the same "create" or with ajax?

Might I suggest that you avoid taxonomy all together?

I am not a fan of taxonomy namely because it isn't a reliable way to tag your content.  The most obvious is that any variation in the tags creates a whole new tag.  For example, if you are doing a web site and you want to use the taxonomy of the different fruit:

apple != Apple

If you now go and create view to show all related content for "Apple", you won't get anything related to "apple."  Technically speaking, you can have 256 (2^8 = 256) permutations of your taxonomy term; not very useful, if you ask me.

So, the question is, what to use then?

Use your own Content Types.

For example, I created a content type called "Section" and the only field I have in the content type is "Title" which I renamed to "Section Name".  (You can ignore the "URL path settings field."  This is because I had pathauto installed.)

Next...create some Section Names by adding content.  Here I have added two content types:  Big and Little.

And if you "Edit" or "View" that piece of content you will see that there is nothing but the one field that you created earlier.

Next, is to create an entity reference to that content field  This is where the magic happens.  In another content type like "Article" (or whatever you like), create an entity reference field that links back to the "Section" content type.

Here, I have a content type called "Static Content" with just "Title" and  "Body". I added an entity reference field called "Section", gave it machine name of "field_er_section" for readability, and made it a checkbox/options type of selector.

When you create/edit the field, you must make sure you reference back the content type you first created, in this case "Section".

How does this all come together?  Let's take a look at a new piece of content that we create....

As you can see, we now have "terms" that the user can select rather than type out.

Where does this come in handy?  How about Views?
You can now add some filters based on your new "Section"

Execute your view and you have all content related to your new term.

Now, if we were to do this with "contextual filters" (found under Advanced in the Views page) you could base your view on the values in the URI.  For example, using the section names in my pics above:

www.example.com/little/

That would display all content related to "Little." You could also create a block view that would display all the titles of related content based on the term in the URI.

Now, as for your specific question, how do you add an image to your taxonomy term?

This is a content type, after all.  Just add an image field and that image will follow throughout your site.

I hope that gives you a direction to go in and a nice alternative to taxonomy.


template file for content header of a view I am using views 2. In views, it asks you for the title of the view and this title is displayed on the screen at
div id=content -> div id=content-inner -> div id=content-header -> h1 id=title
I would like to know if there is a template file which I can modify that can modify this title (ie: add some text to it). I think I can do this with javascript or with css using :after, but I would like to use a template if is available.

As far I understood you want to  modify title of your views page.
This title is the title of entire page.
You can modify this title using drupal_set_title('Your Title');

If you want to modify this title you can load current title first by drupal_get_title() and then set new title.


How to manually create links to change focus on horizontal tab items? I have a horizontal tab group with a few horizontal tab items.  I want to create a text link that allows users to move through the tabs instead of clicking on the horizontal tabs themselves.

I found this other question:
How can I activate a horizontal tab?

Unfortunately the answers do not work.  I see that my horizontal tab items have a unique ID. For example, id="node_contenttype_form_group_stuff".  Simply creating a link like the below does not work:

CLICK HERE FOR NEXT TAB ITEM

By clicking on that link, it takes you back to the very top of the horizontal tab groups, but it does not put the horizontal tab item specifically into focus.  It just pulls you back to the top of the page where you can see the horizontal tab group.

EDIT: Looking at the source code, it appears that all the tab items are like the below in the HTML source:

      II. Text of horizontal item #2

There is a css trick that can achieve this.

Firstly, reset the default positioning on the a element:

.horizontal-tabs > ul.horizontal-tabs-list li a {
  position: static;
}

Secondly, apply an ::after pseudo-element to the link for the horizontal tab AFTER the selected/active one:

.horizontal-tabs > ul.horizontal-tabs-list li.horizontal-tab-button.selected + li a::after {
  content: "next";
  display: block;
}

Given we reset the positioning on the parent li (and the ul is relatively positioned by default) we can now position our pseudo-element relative to the ul, which spans the whole content block. So if you wanted to put your "next" link top right, do something like this.

.horizontal-tabs > ul.horizontal-tabs-list li.horizontal-tab-button.selected + li a::after {
  content: "next";
  display: block;
  position: absolute;
  right: 0;
  top: 30px;
}

This example assumes that our ul has a height of 30px. Given that the last li element (ie the final tab) does not have an immediate sibling, the "+" selector does not match on the last li, which automatically excludes the "next" link on the final tab.


Show name of the taxonomy filtered by in views block title I have an 'articles' content type with a node reference field that allows you to select a term from the taxonomy 'category'. I have a views block that gets all the a contextual filter to return the titles of all the 'articles' with the same category as the article being viewed. I would like the title of the views block to read 'More name of category articles'. I have tried using 'More %1 articles', but this returns 'More 15 articles'. I'm guessing that this is the taxonomy term number?

Is there a way get the taxonomy name filtered by and use it in the view title? This would be really elegant. I guess the alternative would be to do something with the views 'header' and hide the views title?

Thank you in advance.

Yes, you can get the taxonomy term name and use it in the view title.
It's possible with the contextual filter settings. You can achieve your goal in two ways:

  Option #1 ( Using "%1" for the first argument, "%2" for the second, etc. )

When the filter value IS available or a default is provided:

Override title -> More %1 articles

Specify validation criteria -> Taxonomy term

Filter value type -> Term ID

Action to take if filter value does not validate -> Hide view

  Option #2 ( using PHP code )

When the filter value IS available or a default is provided:

Override title -> check this option, but leave text field empty.

Specify validation criteria -> PHP Code

Enter the code:

$tid = $handler->argument;
$term = taxonomy_term_load($tid);
if ($term){
  $name = $term->name;
  $handler->options['title'] = "More $name articles";
  return true;
}
else{
  return false;
}

Action to take if filter value does not validate -> Hide view


What's the Drupal equivalent of Sentry? I use getsentry  for my Django deployments. It's awesome for automatically emailing me when a user experiences a bug in the code, and sending me the stack trace for any exceptions that occur.

Does Drupal have anything equivalent? I've seen the Drupal Sentry plugin but it doesn't look like it's under active development.

What's the best way of monitoring bugs in production for Drupal?

You can use New Relic.

  Database performance

  Viewing slow SQL queries is a breeze. Most Drupal sites rely heavily
  on Views and CCK which can generate non-optimal SQL queries. New Relic
  allows you to quickly pinpoint these types of queries.

  Modules Monitoring

  You can identify which modules are slowest by call count or by slowest
  call time. This may help you identify which modules may be running
  rogue within your application.

  Apdex

  New Relic uses Apdex scoring to help you evaluate how well your Drupal
  application is performing for your end-users according to an
  industry-standard measurement. This helps you provide better data as
  well as have a clearer understanding of what percentage of your users
  are frustrated or satisfied. Apdex scoring also provides more specific
  context than a general “the site is slow” complaint that may not even
  get to you until hours after the incident. Apdex also gives you a more
  objective way to measure your end-users’ experience with your
  performance improvements.

  Function Performance

  Using Web Transaction Traces, you can see which functions are the
  slowest in your application. You can use this to identify slow
  functions in custom modules you have written, or to track delays in
  your application caused by community module functions that do things
  like authenticate with third-party systems.

  Front-end performance

  All that wonderful flexibility within blocks, views, and panels can
  sometimes result in complex page renderings that need to be processed
  by the browsers of your end-users. New Relic’s Real User Monitoring
  (RUM) will actually gather timing information and show you which
  hotspots in DOM rendering time may be causing your page to take
  several seconds to load.


Is it possible to query against the ldap server stored in drupal without reconnecting? I have a drupal install that uses LDAP to authenticate users.  I use that same LDAP to return user info such as roles, employee photo, email, role, and the center they work at.

    $ds=ldap_connect("ldap-example.com");
            if ($ds) {
                $r=ldap_bind($ds);
                $sr=ldap_search($ds, "DC=tpcontact,DC=co,DC=uk",$search);
                $info = ldap_get_entries($ds, $sr)or die('get info fail');
}

I need to make it so that the server is pulled from drupal.  So, if it is possible to query ldap without reconnecting, I need to do that.  Otherwise I need to query the drupal DB's ldap_servers table, the only problem is that I dont have access to a MySql database that has LDAP enabled to see what the field is.

So I assume that you are using the LDAP module?

I've not looked into the code they use however I would expect that they will close the connection before your module runs, and even if they don't the connection won't be a global variable so your module will not have access to it.

If you are writing a custom module then you do have access to the DB - just use db_query and fetch the results, or look in your settings file for your connection details. Then you can connect directly to your DB using software like Navicat.

The table ldap_servers has a field called address. This is where you will find the address to your ldap server.


Add large number of images to drupal site I am trying to create an image gallery in my drupal site from the backend. Also I want to add images to existing content types since there are large number of nodes and attaching image to each of them from the front end is not feasible. What I have understood follows here:

The database contains the table named files that consists of path and type of each file uploaded from fronted. The fid corresponding to each of these paths is used in corresponding content type table to produce images at required node.

Plase tell me if this approach is wrong:

I wanted to upload images in bulk and add image names and there path in the files table as well as corresponding fid's in the content type tables.

But this does not work. Can someone help me with this. Have I analysed it wrongly?

I spent some time in understanding how Drupal 6 retrieves images to show on front-end. Since drupal is heavily database intensive, all the files and images are retrieved from the database itself.

If you are using CCK in your site, you must have created image fields for some content types. Now if you open the database and check the table for respective content type, you will find that there are three columns created for each image cck field namely field_name_fid,field_name_list,field_name_data .

The field "field_name_fid" is the key field that maps images to this content type. The fid is the key that is matched to the fid of the table "files". If you open this table, you will find that the primary key of this table i.e fid is used to map images throughout Drupal content.

Here comes the solution

Upload an image from the frontend to test where is your file saved
physically in you drupal directory. For every image uploaded to any
node from front-end there will be an entry in the files table with
its filename, filepath, filemime, file size, status and timestamp.
The fields that you should take care about in the files table are filename, uid, filepath, filemime, and status.
All you have to do is, Place all your files in that physical location.
Run SQL queries to first fill all the fields stated in #2. and match the fid of files table to the field_name_fid of respective content type.

And you are done.


Menu hook callbacks not working for anonymous users My custom error handler module is somewhat based on the customerror module, but instead of returning markup, my menu callback function redirects based on the original path. It registers error paths as follows:

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

  $items['my_customerror/%'] = array(
    'title callback' => FALSE,
    'access callback' => TRUE,
    'page callback' => 'my_customerror_page',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

'access callback' => TRUE should make it accessible to all users. I can use the path my_customerror/404 for example in the site settings and it is recognized as a valid path. This works fine in a local instance and on the Pantheon development  site, but once I pushed it to the Pantheon test environment, my_customerror/404 is not invoked on 404 - Drupal uses the default error response. Unless I am logged in, then it works in Test as well.

But the path my_customerror/404 works regardless when I type it in manually and does what it should. Somehow Drupal erroneously thinks that this path is not accessible to anonymous users.

What could be causing this?

Here is a simplified version of the callback function that shows what it does:

function my_customerror_page($code) {
  $dest = variable_get('my_customerror_' . $code . '_default', '');
  switch ($code) {
    [conditional stuff]
    default:
      header('Status: 301 Moved Permanently', false, 301);
      header("Location: " . $dest);
      break;
  }
  return "";
}

Don't ask why I use header() and not drupal_goto() ....

Just bringing something into the problem description that I already mentioned in a comment. When the Devel module is turned on and anonymous users are given permission to see developer output, it starts working! But this is not a solution, I obviously can't do this in the Live environment.

You're doing a switch(), but with only a default for the switch and no options, it means the switch is unnecessary. Drupal also provides the drupal_goto() function, which handles both redirects, as well as cancelling killing the script so the redirect can proceed. Your code can be simplified to:

function my_customerror_page($code) {
  $dest = variable_get('my_customerror_' . $code . '_default', '');
  drupal_goto($dest);
}

Or if you're really set on using header() to set headers for whatever reason, you just need to add drupal_exit() after your call to header().


disable translatable route object I've developed a module which generates and displays dynamic content.
The title of the page is also generated dynamically in the controller as show below:

if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', strval($title))
}

This provoques each title is marked as untranslated text and fills the locales_source table.

I tried to use this line to stop this

$route->setDefault('_disable_route_normalizer', TRUE)

but it doesn't work.

And I tried to use

['#title' => $title]

and it doesn't work.

How to avoid this?

Create a "title" function in your controller and declare it in your route, like here ( _title_callback):

entity.node_type.edit_form:
  path: '/admin/structure/types/manage/{node_type}'
  defaults:
    _entity_form: 'node_type.edit'
    _title_callback: '\Drupal\Core\Entity\Controller\EntityController::title'
  requirements:
    _permission: 'administer content types'


Using taxonomy to give option of page layout - working but showing error (Notice: Undefined variable: node in include()) I have been building a site in Drupal 7. I have the content type "Basic Page" but added taxonomy terms for the user to be able to select "Standard" or "Full Width" page.

If the user selects "Full Width" the page.tpl.php file has some code which recognises the value chosen for the page removes a sidebar (usually seen on the "Standard" page).

It is working perfectly on the frontend but has an error in the backend.

Here is the code in the page.tpl.php page:

<?php $field_page_width = field_view_field('node', $node, 'field_page_width'); ?>

            <?php if ($field_page_width['#items'][0]['taxonomy_term']->name == 'Standard') { ?>

                    <?php print render($page['content']); ?>

                    <?php print render($page['side_content']); ?>

            <?php } else { ?>

                    <?php print render($page['content']); ?>

            <?php } ?>

I am receiving this error:

  Notice: Undefined variable: node in include() (line 76 of /home/public_html/sites/all/themes/zen/child_theme/templates/page.tpl.php).

Why do I get this error? Do I need to have something which establishes $node in the template.php file?

The page.tpl.php template file will receive a $node variable only if the user is visiting a node page; in other cases, it will not get any $node variable, even if the template file is still used (if a module doesn't suggest another template file that takes the precedence).
In fact, the documentation for page.tpl.php clearly describes the $node variable as follows. (Emphasis is mine.)

  $node: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

Before accessing $node, you should be sure it has been set.

if (isset($node)) {
  $field_page_width = field_view_field('node', $node, 'field_page_width');
}

Also, field_view_field() is used to render a field. If you just need to get its value, you should use field_get_items().

if (isset($node)) {
  $items = field_get_items('node', $node, 'field_page_width');
}


404 Not found : Could not find the controller. Services module I have installed services module and enabled Resource-> node. Now i am using postman to test default services. My configuration details:
endpoint is "apis". Server is "REST". localhost url http://drupaltest.localhost.com. Also as per given in README file, i have downloaded spyc.php file and placed into servers/rest_server/lib/.

So when i am calling api http://drupaltest.localhost.com/apis/node its showing me result. when i am calling
http://drupaltest.localhost.com/apis/node/retrieve,
i am getting error: 404 Not found : Node retrieve could not be found.
And for http://drupaltest.localhost.com/apis/node/create error: 404 Not found : Could not find the controller.

Is there i am missing any configuration or any permission issue?

This may not have been part of your issue, as I also think a node id should be where you wrote retrieve. But regarding spyc.php, I noticed that this file should be placed at sites/all/libraries/spyc/spyc.php or you will get an error message on your status page.


Is there a module for creating images and labelling and placing them in a document? I am looking for a module which allows me to place images with additional information to the text of a page using a filter connected to the image's node id.

I need a content type with something with fields like this:

The image itself
A description
Additional fields with some information about the image, like source, size, attribution, date, license, etc

What I need is something like a filter that allows me to embed the image in a document displayed with some of the additional fields in a properly formatted manner.

Is there a module for doing this?

No such module exists.  The default Article content type in Drupal 7 already has an image field, but not  the fields you request for holding metadata.

However, with Fields in core in Drupal 7, it is trivial to add the required fields to any content type.  If you're not familiar with Fields, you may want to look at this tutorial.

After adding the field for the image itself, and the metadata you want, you may want edit the template for the content type to make sure all the fields are rendered nicely.


RESTful Web Services : How to simply post a paragraph entity I have simply activated the default paragraph ressource with core (8.8.3) module :

I would like to post a paragraph but even just with the "type" field, I got 403 error in response ! I have nearly the same request that works fine for node...

        var newReleve = {

          type: [{
            target_id: 'releve_de_chantier'
          }],
          parent_id: [{
            value: this.nid,
          }],
          parent_type: [{
            value: 'projet',
          }],
          // field_type_de_releve_de_chantier: [
          //   {
          //     value: this.typeReleve
          //   }
          // ],

        };

        if(this.pid) {
          newReleve.id = [{
            value: this.pid
          }]
        }

        fetch('/entity/paragraph'+(this.pid ? '/'+this.pid : '')+'?_format=json', {
          method: this.pid ? 'PATCH' : 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': csrfToken
          },
          body: JSON.stringify(newReleve)})
          .then(response => {
            if(response.ok){
              return response.json();
            } else {
              console.log(response);
              throw('Error posting datas ! Details below \n ' + response.status + ' : ' + response.statusText);
            }
          })
          .then(para => {
            // console.log(para);
            this.pid = para.id[0].value;
            console.log(this.pid);

          })
          .catch( error => {
            alert('Enregistrement du relevé non effectué : erreur interne du programme ! Détail de l\'erreur : \n ' + (error.message ? error.message : error) );
            console.error(error);
          });

Any idea ?

thanks

Finally, seems it comes from Paragraph module, file ParagraphAccessControlHandler.php function checkCreateAccess :

  protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Allow paragraph entities to be created in the context of entity forms.
if (\Drupal::requestStack()->getCurrentRequest()->getRequestFormat() === 'html') {
  return AccessResult::allowed()->addCacheContexts(['request_format']);
}
return AccessResult::neutral()->addCacheContexts(['request_format']);

}

Code goes in the second return as request format is not html but json. If I force the return to be AccessResult::allowed(), the paragraph is created. Why this restriction to forms ? How to overwrite this without patching ?


How to hide Quick Tabs Title I don't find a way to hide the quick tab title. Is there a hard way if not straight forward? Because I just cant use the title which doesn't make sense in my context/content.

My quick tab title is "Property Tabs". There are 3 tabs under it. Below SS is showing only one tab because I have checked "Hide empty tabs". My tabs are all blocks

3D Gallery
Image Gallery
Video Gallery

I don't want to show the "Property Tabs" (highlighted in SS). I have tried to give title as "" but its still showing the title literally "". Its not accepting "empty string" or "space"

In your Quick Tabs settings (admin/structure/quicktabs/manage/...) there's a checkbox to hide the title of your content and use the custom Tab-Title instead.

If you want to hide the block title (of the quicktabs block) itself, you can insert <none> in the block settings...


How to embed Drupal content in other websites? I want to be able to have widgets with Drupal content to be embedded in other websites. For example a widget could show "new stories" or "top stories".

You can use the Views module to output content as XML/RSS and add a widget to your target site that can build links based on the content in your XML feed.

Depending on your target site there may be pre-built (Wordpress, Drupal, Joomla, Blogger) plugins/addons available to do exactly what you're hoping to accomplish.


Importing Custom (Trumba ) RSS Feeds into Node I'm working on a Drupal 7 college project that involve in importing the college calendar feeds into a calendar content type in Drupal. The RSS feed is coming Trumba - 25livepub-collegenet-com in the following format.

    <item>
        <title>Worship</title>
        <description>Christ Chapel &lt;br/&gt;Sunday, Januar</description>
        <link>http://www.gettysburg.edu/events/inde.....</link>
        <x-trumba:ealink>http://25livepub......</x-trumba:ealink>
        <category>2015/01/25 (Sun)</category>
        <pubDate>25 Jan 2015 16:00:00 GMT</pubDate>
        <guid isPermaLink="false">http://uid....8</guid>
    </item>
</channel>

I went to Feed Importers under Admin/Structure/Feeds and set up the Node processor as well as the Mapping for the Node processor using the following:

Source --------> Target

Title - - > Title
Published date - - > Published date
Categories     ---    ---> Event Category
Item GUID - - - -  > Item GUID
Item URL (link) - - > URL
Description - - - > Description

The nodes are imported into the calendar content type. The problem is everything except the Title is imported into the description field - making it difficult to differentiate them especially when the description is combine with the publish date, category etc etc. Can somebody please point me in right direction how to go about this. Thanks alot.

Consider using the Feeds XPath Parser. Here is a quote from its project page:

  Feeds XPath Parser is a Feeds plugin for parsing XML and HTML documents. It enables site builders to leverage the power of Feeds to easily import data from complex, external data sources. Each element you wish to extract is setup using configurable mapping queries, saving time for developers who would otherwise have to code complex, specific-use modules. It also enables end-users to build web scrapers and other useful tools within Drupal.


How to set a placeholder to a form element in a exposed view filter? I have an exposed view filter in a view and I need to put one element label as a placeholder in his edit form element. How can I achieve that?

You can implement the hook_form_FORM_ID_alter() hook, in the case of the view exposed filter form the name is views_exposed_form

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  //You need to verify the id
  switch ($form['#id']) {
    case 'views-exposed-form-nouvelles-page-1':
      //Setting placeholder
      $form['title']['#attributes']['placeholder'] = $form['#info']['filter-title']['label'];
      //Cleaning the filter labels
      unset($form['#info']['filter-title']['label']);
      break;
  }
}

How you can find the element name? It's easy, you can Inspect your Element:


Remove name attribute - Form API For PCI compliance reasons, I need to remove the name attribute from a form field.

I have tried:

(1)

$form['field']= array(
    '#name'=>'',
)

(2)

$form['field']= array(
    '#name'=>false,
)

3)

$form['field']= array(
    '#attributes' => array('name' => ''),
)

(4)

$form['field']= array(
    '#attributes' => array('name' => false),
)

None of the above work (each of the above produce a field with the name attribute present, just empty. I need it removed altogether).

I haven't managed to achive it with the hook_form_alter hook either.

Any ideas?

Thanks

Assuming it's a textfield, I think the simplest way would be via a preprocess on theme_textfield:

function MYMODULE_preprocess_textfield(&$vars) {
  // Identify the element and remove the name property (which will always be present)
  if ($vars['element']['#foo'] == 'bar') {
    unset($vars['element']['#name'];
  }
}

Bear in mind that Drupal won't be able to process the value for that field correctly if you submit the form, but I guess you're submitting this offsite anyway.

If it's not a textfield you should be able to use the same principle with the the theme function for whatever element type you're using.


How to restrict JS applied to a block only to block visible pages? I am using Drupal 6. I have added the javascript to my block using hook_theme as shown below.

function theme_custom($text) {

        drupal_add_js(drupal_get_path('module', 'mymodule').'/sample.js');
        $output =  t($text);
        return $output;
}

I am using $(document).ready(function() { ... }); in my sample.js. I want this js to be loaded only on the pages where the block is set to be visible, but drupal loads this js on all the pages. This makes my script to run on all the pages, increasing the load to the server on every page load. So, how to restrict this js to be loaded only where the block is visible? Any help is much appreciated.

Using hook_block you can show the js wherever the block renders.

function hook_block($op = 'list', $delta = 0) {
   $block['content'] =
   switch($op){
     case 'view':
      switch ($delta) {
        case 'header_block'://block name
        //here you add that js
          drupal_add_js(drupal_get_path('module', 'mymodule').'/sample.js');
          $block['content'] = theme('header_theme');
          break;
      }
      break;
   }
}


Create a non admin area form to update user form I'm trying to see if there's an example of a form that isn’t in the admin area and is used to update user details.

Is it possible to create this type of form? Where can I find such an example?

Look at the Drupal core user module, is generates the forms for account editing. Specifically, user_profile_form(), user_account_form(), & user_profile_form_submit() will give you an example of an user-accessible form that updates a user account.


D6 + Services 3 + Appcelerator = Login help! I am in the process of (slowly) converting a community forum site from vb4 to drupal. Before I can make the full switch I need to put together a mobile app similar to tapatalk as a large number of my users post almost strictly from their phones.

I had done a little work previously with Services 2 but only on one project that didn't end up coming to fruition.

I am using D6 and Services 3 on this project and I am having trouble figuring out how to login.

I have set my endpoint to 'api/user' for all user resources. That means my login url would be 'api/user/user/login', correct? Using Poster on Chrome I get a "406 Not Acceptable: Unsupported request content type application/xml" when I try to pass along POST data.

Are there any tutorials or docs out there that I am missing? Any clues on what I might be doing wrong? I am finding it extremely difficult to find much out there for Services 3.

make your endpoint 'api'

THen your login url is, 'api/user/login' POST

And also check to make sure you have allowed application/xml as a value response format at admin/structure/services/list/api/server

Although you might need to wait for this patch to be committed
http://drupal.org/node/1232984


Form field validator Is there a way to validate fields individually like you would've done for the file upload (Eg: file_validate_extension etc)? I want to do something like this:

$form["field_name"] = array(
  "#type" => "textfield",
  ...
  "#field_validate" = array("field_validate_numeric") // or "field_validate_email" or "field_validate_url" etc
);

I know there are new html5 field types but I want to be able to validate textfields.

Also, I need this because I might not know the actual tree structure or field parents and I want to validate the field no matter how the form looks.

You can do this with a callback, so that it will work whereever you use it in the form tree:

Add this to your form element:

'#element_validate' => [[get_class($this), 'validateNumber']],

And put the callback in the form class:

public static function validateNumber(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = $element['#value'];
    if ($value === '') {
      return;
    }

    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

    // Ensure the input is numeric.
    if (!is_numeric($value)) {
      $form_state->setError($element, t('%name must be a number.', array('%name' => $name)));
      return;
    }
}

(for the callback I've used some of the code from the html5 number element)


Send e-mail when a field has a specific value I use the Workbench moderation module for Articles workflow. I would like to send an e-mail when Workbench moderation field has the needs review value.

I tried using the Rules module, but I don't know how to select this field and compare data. How do I get the value of the Workbench moderation field in a rule?

I don't know when you need to compare the field data,But you can probably do a form alter or modify the Workbench moderation module function.

Then create a component instead of rules and use a parameter if needed for field id or data.In action add send email.

Then you can invoke that component in the function you are using like this:-

rules_invoke_component('rules_save_review_field', 'paramval1', 'paramval2', ....);


Altering search form I am trying to alter my search form. I am following tutorial to learn drupal theming.
I want to replace the search button with an image :

function mytheme_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'search_block_form') {
$form['actions']['submit']['#type']= 'image_button';
$form['actions']['submit']['#src']= drupal_get_path('theme','MYTHEME').'/images/search.png';
$form['actions']['submit']['#attributes']['class'] [] = 'btn';
}
}

What i get in my page is the following result :

<input class="btn form-submit" type="image" id="edit-submit" name="submit" value="Search" src="http://mysite.com/sites/mysite.com/themes/MYTHEME/images/search.png">

However i want :

class="btn"

And not

class="btn form-submit"

Did i miss something ?

Thanks !

A much much easier way to do this is leave it at the default style and use CSS to replace it with an image. That is how it is done 9 times out of 10.

Now onto the question at hand, Drupal automatically adds certain classes based on the form type. The only way to remove the default classes is to override the THEME_button function and do it there, for more information see https://api.drupal.org/api/drupal/includes%21form.inc/function/theme_button/6


Is there a way to enable the Gutenberg editor so I can use it with custom blocks? I've installed the Gutenberg Editor module and have it working with various content types, however I'd like to also use it to create content for custom blocks (as in structure > block layout > add custom block). I've tried googling but since Gutenberg uses the term 'blocks' to describe the sub-modular pieces of content it uses, I can't find any reference to the module itself being available as an editor for custom blocks, or another module that extends Gutenberg's functionality to custom blocks (or any block element).

Currently it's not possible. Although Gutenberg module provides a Drupal text editor plugin, like CKEditor, it relies a lot on the node edit form to provide the editing experience.


Best practice for moving content from production server to dev server I have used GIT to build my Drupal 7 site (following these guidelines). In order to move changed content downstream before updating the site – in order not to overwrite new content with old content – I would like to find out what the best practice is for that. I was thinking about using the d2d migration module, but maybe there are more established and proven methods?

How do the professionals do this?

Modifying an existing project without loosing data is a common need.

Use Features

One of the best practice I know, is to use the Features module to deliver all the modifications you have made on the production server. Features allow you to make custom modules containing content type structures, views definitions, and a lot more.

You'll probably also need to use the Strongarm module to be able to retrieve the settings variables of some part (modules configuration for instance).

Those modules really help to deploy modifications on a production site, even using git. You'll find easily some good tutorials about using Features.

The only important part to know is when you start using Features, it's difficult to stop using it. Because it will create and implement custom module containing all the specifications of your website (content types, fields, views, pages, ...). If you disable it / them, everything disappear.

Export modifications

If the modifications on your project are not to complicate (mainly content types structures and views), you can use the export / import possibilities offer by some modules (views for instance).

You can also use Bundle Copy module for the node content types export and import part.

Hard way

After, there is a hard way I use sometimes. It is working only if you did not change the fields settings of your existing content types, and if you just add some (fields and content types).

You can copy in your development server database the content tables of your production server. You have to well know all your content types, and specifically the fields used in them (specially the machine names of the fields).

=> You will lose all the new and modified nodes of your dev server. Then do not hesitate to make a backup of your database first.

If you are in the case, you can copy from the production server all the content tables :

node : the base node table with all the content informations
node_revision : if you want to get back the revisions informations
for each one of your content type fields :

the data table : field_data_[field_name] (ie : field_data_body)
the revision table : field_revision_[field_name] (ie : field_revision_body)

url_alias : The custom path of your content (if needed)
taxonomy tables : if you need to, but it can be tricky
user tables : users and users_roles (if needed)


Changing Drush make default subdir for install profiles I have a drush make file which has a default subdir for projects:

defaults[projects][subdir] = contrib

This places all modules into the sites/all/modules/contrib folder, which is great.

The trouble is, it also places my install profiles into the profiles/contrib folder.  Now when I run drush site-install, it doesn't work because the install profile is in the wrong folder.

Is there any way to tell drush make to NOT put the install profiles into a subdir?

I just tested this and the following works:

projects[my_install_profile][subdir] = ""


Drupal 7 Views, Nested User > Content views filter by exposed date I have a nested View. The outer view is a list of users, and that view has a field which includes a content View of everything that user has created. I have chosen to expose the date of that inner view in the hopes I can have an exposed filter on the outer view to control them. Ideally, I'd choose a month and year in the main view and see how much content, if any, each user has created in the last month.

Since the outer view is not a content view, I can't choose a date filter and hook that into the inner view fields. And I need to show all users regardless of whether or not they have content, so I can't go to a Content > Content nested view. Is there a date filter that's independent of content type that I could choose to inherit the exposed filter from the inner view, or that I could use to send a contextual filter to the inner view?

In the outer view, add a relation
Via this relation add the field filters (for example - field_date)
In the outer view field which references the inner view you can pass arguments -> field_date.

In the inner view -> add contextual filters, which will be field_date.

I hope this gives you some direction.


Drupal 8: Read field value from $variables in preprocess_html I've been wrestling with Drupal 8 for some time now and have run into a little problem.

I want to get a field value from a content type that I can use in my html--front.html.twig.
I can create a new variable that I can use in the twig template i.e

$variables['custom_twig_variable'] = 'Some important value';

Then in my twig template I would simply call this like this

{{ custom_twig_variable }}

The thing here is that I don't now how to "reach" my field value in the array $variables that is passed into the preprocess_html function.

Array (
  [user] => Drupal\Core\Session\AccountProxy Object (
    [requestStack:protected] => Symfony\Component\HttpFoundation\RequestStack Object (
      [requests:Symfony\Component\HttpFoundation\RequestStack:private] => Array (
        [0] => Symfony\Component\HttpFoundation\Request Object (
          [attributes] => Symfony\Component\HttpFoundation\ParameterBag Object (
            [parameters:protected] => Array (
              [_system_path] => node/4
              [_controller] => \Drupal\node\Controller\NodeViewController::view
              [_title_callback] => \Drupal\node\Controller\NodeViewController::title
              [node] => Drupal\node\Entity\Node Object (
                [values:protected] => Array (
                  [vid] => Array (
                      [x-default] => 4
                  )
                  [field_background_color] => Array (
                    [x-default] => Array (
                      [0] => Array (
                        [value] => ff00ff
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
)

How do I read the value of field_background_color?

So your field is on the node?

Then you need to get the node object first.

<?php
if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {

}

Once you have that, you can read your field, assuming it is a text field, like this: $node->field_background_color->value. Make sure to always check if you really have a $node object as done in the snippet above when you're in the global context. You will only have on on node/N, but not on other pages.

There are many questions already about how to access field values, and there are great presentations as well.


Hover a trimmed views field for full text? I have a text field in a views table which I use the Rewrite results -> Trim this field to a maximum length with ellipsis option on. Is it possible and how, so that when I hover this trimmed text I get the full version as a popup or that the view updates to show the full text?

Hate to answer my own bounty question but this works exactly as I want it.

I found a great way to do this with beautytips module. My field is an address (field_address). Add field_address to views and do rewrite->trim with ellipsis BUT exclude from display. Add the same field again this time rewriting the output of the field with:

[field_address]

(I have "Add beautytips js to every page" enabled in the beautytips settings)

+1 zhilevan's answer which is also a very good solution but is sadly missing the roll-back/rollup/close option which would mean very long tables with a few read mores open!


How to position Image field in body content I have a content type that has title, body, image etc. I am displaying the Title, image with caption and body using Manage Display. But here there is no option to align (Left, Right, Center) the image. How to align the image node wise.

To meet the requirement I found INSERT module. This module is placing the image inside the body content but the caption of the image is missing.

Please help on this issue and let me know if anything is unclear.

Try the CSS Injector module and use CSS float property or other properties on the  .class or #id of the image field or body/description/captions.


expose filter work with ajax only on inner pages but work with button submit on front page What I want is to work expose filter with ajax only on inner pages but work with  button submit on front page i.e when I want my expose filter on front page to work like normal form but on inner page i want it to work with ajax

Disable Use ajax in View settings, in THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) function do like this:

function THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form)
  // dpm($form_state)
  if ($form['#id'] == 'MY-VIEWS-FORM-ID') {
    if (!drupal_is_front_page()) {
      $form_state['view']->use_ajax = true;
    }
  }
}

flush the cache.


Why bootstrap sub-theme with sass starterkit is not working? I am trying Bootstrap 7.x-3.6 theme.

But sub-theme for some reason is not working. I did follow the same procedure as described on the Documentation page for Drupal 7.

I am describing here, what I did,

1. Installed fresh drupal 7.50 on localhost.
2. Down loaded Bootsrtap 7.x-3.6 and enabled but not make is default.
3. Sub-theme: I did copy sass folder from the starterkits. Paste in /theme folder and rename with mysubtheme. Rename the file-name sass.starterkit with mysubtheme.info. And inside that changed the 'name'.

Final image of /theme folder

4. Downloding Bootstrap: Downloaded bootstrap file from here as decribed in following image. I did select Sass option. Pasted to /mysubtheme folder, rename with bootsrtap.(even to check, I did try all three options one by one, but same result)

5. Downloaded Jquery update module also and enabled, default version was 1.50.

Now, Till this stage the site shows content but not a basic theme formatting. Comparative image below.

What could be the reason or I am missing something.

Thanks to @JeffBurnz @MarkCornoy and @FreeRadical for their inputs.

The following setting needs to be disable in mysubtheme.info(sass.starterkit A original file). And may be @FreeRadical want to point out same thing by asking "Have you removed the CDN?" in the his comment.

  ; Disable the CDN provider so compiled source files can be used.

  settings[bootstrap_cdn] = ''

After commenting out settings[bootstrap_cdn] = '' it does take the base theme setting.

Any more suggestion appreciated. For now, this solution works.


Appending extra columns to Views table Can anyone tell me if there's a way to use hook_form_alter, or some other approach, to insert an extra column with to a views generated table.

I am trying to insert some buttons which will update node data when a user clicks on a relevant button.

There are multiple ways you can add an extra column or a field to each row of your views output. And you can choose what is best for your use case.

For a Drupal 7 site you can use -

https://drupal.org/project/computed_field
https://drupal.org/project/views_php
for extra fields in plain text, you can refer this answer.

If you need to pass any kind of dynamic context to your custom extra field, say a node id, there are multiple ways to do that too.


How do i ajaxify /Use ajax on Side bar custom menues so that links are loaded to my content div without refreshing page I have a vertical menu on My site ,I want to use ajax to load the Menu link into the content so the page doesnt have to reload,Please how can i go about it ,I tried the ajaxify module it doesnt seem to work properly.

You can use ajax_pages module.

  Features

  Works inobtrusively out of the box
  Requires only minimal theme modifications
  Browser address bar updating using HTML5's history.pushState()
  Full page reloading (page_top, page and page_bottom regions)
  Transparently ajaxifies forms, including GET ones Handles redirects
  Loads additional CSS and JS files as required
  JS/CSS preprocessors and aggregation friendly
  Ajax requests are GET and fully cacheable (also with Boost!)


How do you embed addtional RSS feeds into the  section of your theme I have 5 RSS feeds I am looking to embed into the <head> section of the page. What is the best way to accomplish this on drupal 7?

You can use drupal_add_feed() or if you don't want to have an icon appear
on the page itself

 drupal_add_html_head_link(array(
    'rel' => 'alternate',
    'type' => 'application/rss+xml',
    'title' => $title,
    'href' => $url
  ));


Show node IDs along with titles in Entity reference Autocomplete list I'll like to add this functionality to the autocomplete widget in Entityreference field to show node ID next to the titles in the dropdown list. The reason behind the idea is to differentiate between multiple nodes with same title.

Example:

This is a title (3)
This is a title (2)
This is a title (1)

I know the node ID is shown once a selection is made but I like to show it in the dropdown list in order to pick the right node quickly based on the node ID.

Install the Views and Entity Reference modules, create a new View and Add a Entity Reference Display:

Then Add in the fields the content title and the nid, click in the nid and check Exclude from display, Save and click in the title and go to rewrite the output of the title as [title] - ([nid])

Go to edit the settings of the format and check the title, this will allow you to search by title.

Save the view.

Go to edit your Entity Reference field and select in the Mode Views: .... (like the following image) and select your View (in this case the name is: articles_with_id) and save the settings:

Then go to see the result:

EDIT: This is now working in Drupal 8, at least in the version 8.3.4.


How to translate the menu title? Currently I am working on a multilingual website and have already a multilingual set-up.
Now I have translated menu items and it is working great, however I also want the menu title to be translated.

This is how I get the menu titles:

$menuInfo = menu_load('menu-second-menu');

and I get the title through by $menuInfo['title'];

I print the links with the following code (and the title is displayed above):

print theme('links__system_main_menu', array('links' => $menu, 'attributes' => array('id' => $menuInfo['menu_name'], 'class' => array('links', 'clearfix')), 'heading' => array('text' => $menuInfo['title'], 'level' => 'h3')));

So the links are translated, but the $menuInfo['title'] not and $menuInfo does not contain any translated information.

Any help?

Edit: The issue is I do not know how to get the translated menu title (programmatically) I made in Structure -> Menus -> Second Menu -> click the tab Translate and gave a different Menu title for the different languages. I am using the Menu Translation (sub)module of the i18n Internationalization module.

The only solution I could come up with, to translate the menu title is by using the following:

$menu = menu_load('main-menu');
$menu_title = i18n_string_translate('menu:menu:main-menu:title', $menu['title']);
$menu_desc = i18n_string_translate('menu:menu:main-menu:description', $menu['description']);


How do I create a node using web services and Anonymous user? I have successfully installed the Services module and created a service with which I can retrieve a node or even several nodes (using Views Services)
I've now configured an endpoint, whose purpose is to allow an application to create nodes through a JSON call.

After much messing about I finally configured the following JSON call:

{
"type":"demande-de-rdv",
"uid":"0",
"language":"und",
"status":"1",
"promote":"0",
"sticky":"0",
"title":"JSON Post using http_request",
"body":"Morbi sit amet leo molestie, luctus metus aliquet, pellentesque lacus! Suspendisse at laoreet nulla. Nunc sed tincidunt dolor. Donec condimentum     odio non nisl condimentum, id euismod arcu rhoncus? Nullam sit amet ante convallis, viverra nulla in, laoreet leo. Fusce vitae iaculis libero. Phasellus scelerisque varius augue, quis vulputate sapien vehicula vel. Sed at est at felis dignissim rutrum. Sed porta tristique sapien et viverra. Nunc ac elit tristique, laoreet lacus at, pharetra elit. Morbi sit amet commodo dolor? Donec consectetur justo vel fringilla rutrum"
}

However, when I post the call I get the reply "403 : Access denied for user anonymous", this despite the fact that I have configured the content type to be creatable by Anonymous (and have created a node for the content type in question to test it). I also gave Anonymous all the permissions on the Services module just in case, but it made no difference.

Where i am going wrong?

I have posted to /node and it works for anonymous after granted that permission and cleared cache by the way you don't have to set the field uid and it's not necessary if you set

  $request_url = 'domain/endpoint/node';

// Node data
$node_data = array(
  'title' => 'product testing',
  'type' => 'product',
    "uid" => 0,
    "language" => "en",
    "sticky" => 0
);
//$node_data = http_build_query($node_data);
$data = json_encode($node_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json')
);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);


HTML table in a render array? I dislike the notion of using something like this since it may mean I have to commit my table data straight to HTML sooner than I want to:

$render_array = array(
    'maintable' => array(
        '#markup' = theme_table($table)
    ),
    ...
);

Do I have an option to pass the table data into the render array (as opposed to rendering it immediately to HTML), by chance?

$render_array['maintable'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);


How to print the latest facebook posts? I would like to show the two latest facebook-posts on my Drupal page.
I found these two modules: https://www.drupal.org/project/facebook_pull and https://github.com/mysequel/Drupal-8-Facebook-Feed-Module. Unfortunately there is no working Drupal 8 compatibility yet. The first one is in Dev Status and I can't even get it to work. The second generates an error when activating.

What is the Drupal 8 way to import this data from Facebook?

I had a similar requirement (actually a bit more complicated, as I needed Facebook, Twitter and Instagram posts). I ended up creating my own Drupal 8 module - Social Feed Aggregator (https://www.drupal.org/project/social_feed_aggregator).

The module creates a new Social Post content type, allows you to enable each required feed integration, and set up a cron job to refresh the feed data.

You can then simply create a Views block to show the feed data.


how to change a theme through themekey on the contact page in drupal 7 I made a site in drupal 7 and used themekey (i'm using "nid" for all the pages) to have on every page a different backgrounds, this works perfect. But on the contact page i'm not able to find the way to do this, what are the settings in themekey to set a different background in the contact page.

Thx
Fred

I think setting drupal:path to contact should do the trick.


How to render an image field What is the correct way to render a Drupal 7 image field and show the default image if the field is empty?

If I use field_get_items it will simply return FALSE when the field is empty.

I think best practice would probably be to use field_view_field():

$view = field_view_field('node', $node, 'field_image');
print render($view);

That will render the field as if it was attached to an entity view, and as such will provide the default image if none is available.


EntityFieldQuery causing column not found PDO exception I have a very simple node type set up in drupal, see it here

And I'm trying to get the node id based on the email field (the email is unique to each node, just like the nid). My query looks like this:

$query  -> entityCondition('entity_type', 'node')
-> entityCondition('bundle', 'mail_entry')
-> fieldCondition('field_email', 'value', $email);

But drupal is complaining with:

  "PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_email0.field_email_value'"

I don't really understand what's wrong.

At a guess you're using the Email Field module to provide that particular field?

If so, the column name is email, not value, so your code should be:

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mail_entry')
  ->fieldCondition('field_email', 'email', $email);


Using db_select with subqueries Here's an example raw query of what I am trying to achieve with database API:

SELECT * FROM (
    SELECT
      n.nid AS entity_id,
      n.uid,
      n.title,
      node_body.body_value,
      node_body.body_format,
      'node' AS entity_type
    FROM
      `node` n,
      `field_data_body` node_body
    WHERE
      n.status = 1 AND
      n.type = 'forum' AND
      n.nid = node_body.entity_id
  UNION ALL
    SELECT
      c.cid,
      c.uid,
      '-' AS subject,
      comment_body.comment_body_value,
      comment_body.comment_body_format,
      'comment' AS entity_type
    FROM
      `node` n,
      `comment` c,
      `field_data_comment_body` comment_body
    WHERE
      c.nid = n.nid AND
      n.status = 1 AND
      n.type = 'forum' AND
      c.cid = comment_body.entity_id
) AS results ORDER BY results.entity_id

I have to do this using db_select() because of the pager.

My question is: how can I use db_select() for selecting results that are not from a specific table, but from subqueries like the query above?

Thanks!

First of all, you can prepare a SelectQuery object using db_select(), then use it in place of a table in another db_select(). Example (off-the-cuff, not tested):

$inner_query = db_select('comment', 'c')
  ->fields('c');
$outer_query = db_select($inner_query, 'sub');

Second of all, you can UNION two prepared SelectQuery objects with the SelectQuery::union() method.

$some_query = db_select('comment_table', c)->fields('c');
$union_query = db_select('other_comment_table', o)->fields('o')->union($some_query, 'ALL');

So all the tools you need are there; it'll just take some trial and error to put them all together.


Check to determine if user is member of any group of specific type Our website has three types of groups: area groups, support groups and member organized groups.

While a member can join several or none of the support groups and member-organized groups, we do want each member to be a part of one (and only one) area group.

I'd like to find a way to use rules to check to see if a member is a member of an area group and if not, display a warning/help message to them to encourage them to join an area group. Ideally, I would like to do this several times shortly after they join and then occasionally after the first couple weeks (some people who are in the process of moving to the area may not want to join a group right away and I don't want the messages to get overwhelming for that small minority).

I've been playing around in the rules module to see what I can do, but I'm not sure exactly how to check to see if they are a member of any group of the area group type -- can anyone help me with determining what conditions I have to apply to get it to check this for me? Also can I put a limit (as suggested above) on the amount of times the message shows?

Or in lieu of that, is there an easier way to accomplish this goal of ensuring that all of our members make it into one area group?

Thanks
Heather

I don't think Rules alone will do what you want. You'll want something like

// This hook fires whenever a user account is saved.
// If you want to do it at other times, you'll want another hook.
function mymodule_user_presave(&$edit, $account, $category) {
    // This is an organic groups API function for finding out what group a user is in.
    $user_groups = og_get_groups_by_user($account, 'my_group_type');
    if ( [check for group membership] ) { ... }
}


Restrict user profiles access with hook_menu_alter Following this tutorial I'm trying to restrict viewable user pages (and other tabs created in views).
In particular, users belonging to role coordinator need to view and edit only pages of users associated with them via en entity reference field in core profile, and see an access denied page for others.
I've already queried the db to get all the users id associated with current user and put it in a session var $_SESSION["arUidCoordinated"] that I use in other hooks, but I can't make it work with hook_menu_alter.
Here's the code:

function mymodule_perm() {
  return array('my permission');
}

function mymodule_menu_alter(&$items) {

    $items['user/%user_category'] = array(
        'title' => 'Edit',
        'page callback' => 'user_edit',
        'page arguments' => array(1),
        'access callback' => 'my_module_validate',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
        'load arguments' => array('%map', '%index'),
        'file' => 'user.pages.inc',
      );

}

function mymodule_validate($account){

    global $user;

    $uid=arg(1);
    if (in_array("coordinator", $user->roles) AND in_array($uid, $_SESSION["arUidCoordinated"])){

        return true;

    } else {

     return false;

    }

}

I followed this post toot, but I can't make it work, I get "access denied" on every  user/% page, or failed opening required user.pages.inc and I don't understand where I go wrong...

All the pieces of the original user menu items are defined in modules/user/user.module via the User Module's hook_menu().  The key ones here are (IMHO) user/%user for viewing the user page, and user/%user/edit for editing it, eg pages like user/1 to look at uid 1's user page, and user/1/edit to edit that same page.

So, from a logic standpoint, I am going to assume you want this:

  If a user wants to look at or edit his or her own page, allow them to
  do so.  Furthermore, if another user has appropriate permissions,
  allow them to look at and/or edit these pages as well. But no one else
  should be able to look at any other user's pages (let alone edit
  them).

Ok, so how can we do this.  Let's first look at the original view the user page menu item:

$items['user/%user'] = array(
  'title' => 'My account',
  'title callback' => 'user_page_title',
  'title arguments' => array(1),
  'page callback' => 'user_view_page',
  'page arguments' => array(1),
  'access callback' => 'user_view_access',
  'access arguments' => array(1),
  // By assigning a different menu name, this item (and all registered child
  // paths) are no longer considered as children of 'user'. When accessing the
  // user account pages, the preferred menu link that is used to build the
  // active trail (breadcrumb) will be found in this menu (unless there is
  // more specific link), so the link to 'user' will not be in the breadcrumb.
  'menu_name' => 'navigation',
);

Here we would want to change the 'access callback' to include further logic, so the menu alter would only have to change that, nothing else, eg, something along the lines of this:

function YOURMODULE_menu_alter(&$items) {

  $items['user/%user']['access callback']='YOURMODULE_user_access';

}

and then you could write something like this:

function YOURMODULE_user_access($account) {

  if ($account->uid) { // so we don't try to look at an anonymous user

    $account = user_load($account->uid); // load the full user object (ADDITION:  was user_load($uid) in original post, oops)

    if ($GLOBALS['user']->uid == 1) { // admin super user
      return TRUE;
    }

    if ($GLOBALS['user']->uid == $account->uid) {
      return TRUE; // same user so allow (we will assume blocked users aren't logged in)
    }

    if ( /* whatever logic you need to allow coordinators to access the user is TRUE */ ) {
      return TRUE; // or return $account->status; if you want to take blocked accounts into effect
    }

  }

  return FALSE;

}

So, barring any brain freezes or typos on my part, the above should work for viewing, but I did just type it in freehand, so buyer beware.  But, now, let's look at the original user edit menu item:

$items['user/%user/edit'] = array(
  'title' => 'Edit',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('user_profile_form', 1),
  'access callback' => 'user_edit_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'file' => 'user.pages.inc',
);

And once again, all you want or need to do is change the 'access callback', eg, your hook_menu_alter() is now...

function YOURMODULE_menu_alter(&$items) {

  $items['user/%user']['access callback']='YOURMODULE_user_access';
  $items['user/%user/edit']['access callback']='YOURMODULE_user_access';

}

and yes, since the logic is the same, you can use the same function all over again.

Caveats:  We are totally ignoring Drupal's built in permissions, eg, user_access('access user profiles') and user_access('administer users') in the above.

Also, if you find after doing this you can't load user.pages.inc, Drupal is most probably looking for it in your module's directory instead of the user module's where it sits, so set 'file' => drupal_get_path('module', 'user') . '/user.pages.inc' and you should be set.

Anyways hope this stream of consciousness helps out!


How to add more than 7 links in the shortcuts bar? I just noticed that there is a limit of links to add to the Shortcut bar. Is there any way to change this, I need no limit at all.

It's the shortcut_max_slots() function that makes that decision; fortunately that function wraps around the return of a variable from the database (also called shortcut_max_slots), so you can simply set that variable and be done with it.

There's no way to make it unlimited without hacking the shortcut module directly, so you probably want to go for a high number:

variable_set('shortcut_max_slots', 100);


How do I trigger Infinite Scroll with FancyBox in Drupal 7 I have a gallery of photos which uses Infinite Scroll as the pager.
I am also using the fancyBox module so that when I click each photo it appears in an overlay, with the photos grouped per page so I can cycle through them with the FancyBox overlay.

The problem I have is that I can only cycle through the photos that have already been loaded by the Infinite Scroll (which makes sense as they are the only photos the Infinite Scroll has 'seen'). But what I want is to trigger the infinite scroll to load more photos just before I reach the end of the cycle with the FancyBox overlay so a user can simply use the overlay to cycle through all the photos on the site without having to use Infinite Scroll to load them all first.

Any help with the sort of thing I should be thinking about to try and achieve this?

ugh... sounds like you'll need custom work. But try the Image Lazy Loader Module

  This is a small helper module which will automatically lazyload all images for sites with multiple images, which will make the site load faster.

  All images will only load when it's visible to the browser window.


How can I find (programmatically) which fields have been edited on a piece of content? I want to have a computed field pull in the name and content of a field after it has been edited. I would also like the computed field to contain the content that was edited before edit (if that makes sense?). So what code do I need to find which field has been edited?

I also found this in the node_form drupal api:

// Changed must be sent to the client, for later overwrite error checking.
$form['changed'] = array(
  '#type' => 'hidden',
  '#default_value' => isset($node->changed) ? $node->changed : NULL,
);

Is there a way I access this 'changed' value to check if a piece of content has been changed?

p.s. I am new to drupal and php, so stating your answer in simpler terms with more explination is greatly appreciated.

In the node form submit, you can call node_load($node->nid, NULL, TRUE) for Drupal to retrieve the original about-to-be-overwritten node, allowing you to walk the list of fields, and compare them.

I would use sha1sum(serialize($field)) to compare them, as that makes it easy to do regardless of field type.


click image to play video in iframe Objective - have a blank screen with only an image on it. (a "play video" button) when the button is clicked a video (from youtube) opens in a section on the screen that is maybe 200X300. Ideally this would all be done within ckeditor so the end user can setup and change as desired. (note - I am not sure if iframe is needed, but this is how I was able to do it)

I can get the appearance I want easily by embedding the following code into ckeditor in "source" mode:

But can not figure out how to have a blank screen that shows only an image that opens the video when it is clicked. thanks for any help

You would need to use JavaScript to make this happen. You're not going to have a good time with users doing this in CKEditor though, as they'll likely break this functionality when they use the editor and alter the content in it (the JS will be invisible to them, unless they're in source mode, and they could easily delete it without knowing it).

I have achieved similar behavior using a dedicated field called "YouTube Video Link". The user pastes a link in there and then I have a play button execute that link in an iframe overlay using Fancybox.

The JavaScript (jQuery) that you'd want to use is:

// When a user clicks the link...
$('.video-link').click(function(e) {

  // Don't let the browser open the link like normally.
  e.preventDefault();

  // Capture the link's HREF attribute in a variable.
  var youtubeLink = $(this).attr('href');

  // Set the HTML (the content) of the "video destination div" to = your iframe, including the youtubeLink that the user original saved into this node.
  $('#the-video-destination-div').html('');
});

Where your video link has class="video-link" and somewhere on the page you have a

.

Please add a comment to this answer to help funnel the nuances of what you're trying to do and I can edit my answer to reflect.


On node edit form, how to edit field from a referenced entity? I've got a master entity (node) that users edit, and I've got an entity reference on it. I'd like to be able to edit a field on the referenced entity on that master referencing entity's edit form.

Is there a module for this? Or can somebody just give me a general sense of a good way to accomplish this?

I know I can create a custom form element with hook_form_alter, then use a form_submit function, and then use entity_metadata_wrapper to load and save values.

That seems cumbersome, is there a better way to do this?

You can use https://www.drupal.org/project/references_dialog or https://www.drupal.org/project/inline_entity_form.

The first one will load the referenced entity in a popup, the other will show it as part of the original form.


module_invoke() and the performance I am using module_invoke() many times in the front page to invoke lots of block. Does this effect the site performance? Thank you.

module_invoke() is essentially using three functions: function_get_args(), function_exists() and call_user_func_array(). As it doesn't invoke any database API function, it doesn't influence the performance a lot.
Using module_invoke() allows to write code that is compatible with future versions of the module or Drupal. There is a feature report on drupal.org which asks to use a different schema for the hook names; if that would be implemented (it could happen in Drupal 8), then the code that invokes directly the hooks should be changed.

In specific cases, where (for example) you are invoking the same hook implemented by the same module many times in row, it is possible to change the code to do something similar to:

verify the module implements the hook you need, once, at the beginning
call the hook directly when you need the value returned by the hook

This should be done if the module is really invoking the same hook implemented from the same module many times in row (which doesn't exclude the hook is being invoked in a loop).

To notice that module_invoke() cannot be used when one of the parameters needs to be passed by reference. There are specific functions that invoke hook implementations in that cases (e.g. comment_invoke_comment(), but those functions invoke the hook implemented by all the modules.


Add extra information across cart/checkout/invoice in Ubercart I would like to add extra information in cart, checkout and invoice in Ubercart. Idea is to show discount ammount that was implemented by hook_uc_cart_alter - I want to add above the Total Price, Another value - Discount, and show that discount on all forms.

I can add extra values by appending in hook_tapir_table_alter, but i am not sure if this right way, or is it only for viewing purpouse? Is there other more reliable method ?

Thanks.

there's no other module i know of that exposes this data. i too had to do hook alters to recalculate the total and discounts to have it show in the checkout forms.