Recover a deleted user's content A few weeks ago a site admin canceled a user account on one of my Drupal 7 sites and clicked on "Delete the account and its content." That user had created about half the content on the site in different content types and uploaded files.

So we lost about half our content.

I have backup (a mysql dump) of the site from before account was removed and all the uploaded files, and I'm sure the user wasn't active in the time between the backup and the removal.

Is there an easy way to recover the content from that one user? I cannot just restore the database from the dump, since that will wash away any changes since then.

It depends on how complicated your content/site structure is, authored by the user account that got deleted, but it can be fairly easy if it's just nodes and sum such content.

Use which ever migration method you're most comfortable with. Migrate module is popular, but Feeds may be more user-friendly? Don't hang on module reviews here ;)

One way to go about it is to create a separate dev instance of your site by copying the live Drupal folder, and restoring the database backup that contains your deleted user and content. Like a time machine viewing your site at a moment in the past :)

You can use Views to list all content from that user, export it as CSV, or some other parsing case. Views gives you a nice overview of what's there so you can check you got everything. You can output post times, statuses, references to other entities...

Then build Feeds importer for what you exported. Test the import on yet another dev instance of your site, the copy of the current db. TEST everything thoroughly before importing to a site that matters, this should be obvious. Migrations are notoriously tricky and long affairs.

You could go as far as to restate the user with account history etc with some more magic, but it seems you only need the content so it will probably easier to just assign authorship to another user or anonymous if it doesn't clash with permissions, or create a completely new user, you can name it the same as the old one but the ID will be different.


Removing part of string retrieved from $_SERVER["REQUEST_URI"] in webform default value field I'm trying to figure out if doing this is possible. I'm not very good at php so I'm trying to avoid having to create a module or something else to do this.

What I am trying to do is this:
In the default value field for a section in my webform, $_SERVER["REQUEST_URI"] to return the URL that the form is on, however, the entire URL is retrieved. (/cms/?q=content/82245940-initial-services) I want to cut out the non-identifying part of the URL so that I'm left with 82245940-initial-services. Is there a way to code this into the default value field(1 line), or do I need to create special code to do this?

Something like this:
$_SERVER["REQUEST_URI"-"http://example.com/cms/?q=content"]

If you'r working with drupal you should use drupal_get_path_alias()

$path = drupal_get_path_alias();
$value = str_replace('content/', '', $path);


How do I sell points using a new product type? With the Drupal commerce module, I created a new product type I use for selling points to my customers. The product has a custom field named “points” (field type integer) where I specify the amount of point to sell.

On checkout I want to grant the points to the user (with the Userpoint module). I want to do this with rules.

The problem is that I can’t retrieve the field “points” in action rules. I tried adding the “entity has field” condition, but I am not able to retrieve the field from the commerce order.

The action is grants points to a user.

How can I achieve this?

To answer your question in order to give you a solution. That people can "top" up here is maybe an alternative.

Drupal Userpoint Feature request

  Remember to use dev version.

Commerce Userpoints

What about something like this ?

1) Rule

Event: on payment completed
Action: loop through the order line-items. Each line-item has an action to call the next component with parameters of order and the line-item.

2) Component

Parameters: order, line-item
Condition: data comparison line-item:type is Product (to expose line-item:commerce-product)
Action: call next component with parameters of order and line-item:commerce-product

3) Component

Parameters: order, product
Condition: data comparison product:type is Product (to expose the product:field-points-to-add)

Action: add userpoints, number to add being
product:field-points-to-add


Single page site - drupal 7 I am trying to add multiple pages to my home page (about, contact), I assumed I do this in page--front.tpl. How to I call or pull in page nodes into my template?

Seems like something perfecly suited to Panels.

An Overview of Panels
The Panels module allows a site administrator to
create customized layouts for multiple uses. At its core it is a drag
and drop content manager that lets you visually design a layout and
place content within that layout. Integration with other systems
allows you to create nodes that use this, landing pages that use this,
and even override system pages such as taxonomy and the node page so
that you can customize the layout of your site with very fine grained
permissions.

Just create a panel page with the content you want displayed in a list, and then make this panel page your front page.
There are loads of tutorials/help on the project documentation page if you've never used it before.


Behavior of taxonomy-term classified paths We have customer who insists that there is a setting/method that will order the listing-page for taxonomy attributed event-type by date ascending. My exploration has lead me to the .../admin/config/search/path/patterns settings in Taxonomy term paths. We are using the default: [term:vocabulary]/[term:name].

However I can not find a setting that will allow for date-ordering. Is there such a setting? The behavior of the site is that the ordering is done by the initial-post date.

I've advised that this can be done w/ View.

/admin/config/search/path/patterns is an admin page for the module Pathauto, URL alias - Patterns. And the default pattern for Taxonomy terms just happens to be [term:vocabulary]/[term:name].

You can also see that each "vocabulary" of taxonomy terms can have it's own pattern.

To confirm if Views is handling the display of any of the taxonomy terms pages we need to find a view that takes over the default Taxonomy term path and is already enabled. Meaning, the modules View and Views UI must be enabled. If only Views is enabled, enabling Vies UI at this point makes this easier, plus we will need it later to change the "Sort criteria". With install of the of the Views module the Taxonomy term view is created. This view has a path of 'taxonomy/term/%' the same as the Taxonomy modules default path and when the view is enabled it overrides the Taxonomy module's handling of the display of the taxonomy terms pages.

For a final conformation that this taxonomy vocabulary's term pages are being handled by views lets look at the final HTML that is out generated.

For a views generated page you will see a few key classes in the content's wrapping elements (unless heavenly custom themed).

vs the generated page you will see from the taxonomy module.

Bonus tip: The classes added by the view let us know the machine names of the view being used. view-id-taxonomy_term tell you the "taxonomy_term" view is using used, while view-display-id-page tell you it is the "page" display in current view.


get content which user likes When a user registers in my site, the registration form asks the user on which type of food he likes, the user choses one or more from a taxonomy terms.

A user can also create content and tag them from the same taxonomy terms on the registration from.

Now I want to create a view that gets all food "content" the user likes based on what he chose in the registration form or profile.

I would approach this by building a view that has relation to current user selected taxonomies. Then listing content according to that.


How to always require email verification before accessing a page? I have a custom page defined by hook_menu.

I want signed in users to be required to verify their email every time they want to access it. The page will have buttons on it that would allow someone to export all the data related to the account.

I've looked around for existing modules that could provide this. This looked the most promising: Email Required. However this only happens on their first visit to the page. So once the accounts email is verified the user would always have access to it.

How can I have people verify their email every time before allowing them to access the page? It would be good if the verification link in the email expired after a period of time if it isn't used for security.

Any pointers are much appreciated.

Because the page I was creating was actually a form, I found this module got me out of trouble password_require

Although strictly speaking my question didn't specify it was a form. Other than mentioning buttons.

Hope it helps someone


Added menu link not showed in menu configuration I have a very weird problem. If I add a new menu item, I can do it without any error in the menu configuration page, but the item isn't showed in the menu in this page neither in the menu. If I check menu tables in mysql, the items are added. If I try to add another item, I can create a child of the other in the menu structure, but the item isn't showed.

There are a couple possibilities for why your menu link isnt showing.

Have you checked that the menu being rendered is the same as the one you added the link? Typically, menus are rendered via Drupal's block layout settings. (Admin > structure > block layout) You can check that the menu rendered on your site is the same as the one you are adding the links to.
If using the Menu Block module, check that your menu block settings aren't set to display a fixed level of the menu or fixed trail.
Is the link you've added to a page or view on the site that has permission restrictions? This sometimes happens when trying to add custom admin routes.

If the settings above are correct, try flushing the drupal caches when updating menu links before checking on the front end.

In the case none of the above works, and you are on a development instance of the site, try switching to a standard theme (like Bartik) to quickly determine if somethingin your theme is preventing the links from rendering.


Why is there a convention to use test-specific namespaces for unit tests? My team and I have noticed that the Drupal convention is to create a separate namespace for unit tests (as opposed to the namespace define by, lets say, the custom module we are testing).

If they shared a namespace then we could, for example, easily override a function like t() for our tests. I know there are lots of ways to handle things like the t() function, but this convention of creating a new name space eliminates this particular option. Can anyone speak to why? What is the benefit?

There are few reasons why tests are in different namespaces.

Drupal have several different types of tests

WebTestBase (WTB), aka simpletests or integration tests
BrowsertestBase (BTB), integration tests (all WTB will eventually be replaced by equivalent BTB)
KernelTestBase (KTB), a barely bootstrapped version of Drupal, not an integration test but a lot more than a true unit test
JavascriptTestBase (JSTB), an integration test that is Javascript aware
UnitTestCase and PHPUnit_Framework_TestCase, unit tests

Note that integration are also called functional tests. I am going to ignore the difference between UnitTestCase and PHPUnit_Framework_TestCase right now and lump them together as unit tests.

The five different test types are all in different namespaces so the test discovery process can find them and place them into five groups.  The test runner allows the various test groups to be run together, and also invoke them properly during runs.

For example, if making a big change, you can run all unit tests locally as a sanity check (running all of the take about a minute on a normalish local machine).

Tests associated with a particular module are also in the modules namespace, so you can easily run all tests for that module, and they won't be discovered if that module is disabled.  For example, integration tests take along time (usually between 30 seconds and 4 minutes each).  You can just run all of the Field UI tests at ones if you are doing work there.

The test runner also allows you to run all of the tests in a particular directory.  This allows you to target a particular core subsystem that isn't in a module.  For example, you can run all of the database kernel tests at once this way.

Some subsystems also define their own test bases.  For example, the migration system defines its own test bases to centralize common functionality and to to have a common setup.

Tests also make frequent use of traits to share code between different types of tests.

The particular case you mention is an oddity.  In a perfect world, the t() function wouldn't be used in object oriented code; the injected translation service would be used which could then be mocked in unit tests instead of needing to use shenanigans like shadowed globals.


Variable to check if the page is of some other Content Type The variables $page and $teaser are very helpful but is there a way to check if I'm in a different kind of Content Type? For example, if I made a content type named Products, what can I type in my template file page.tpl.php which will display HTML only if the page being viewed is of type Products?

Place this in your theme's template.php, replacing 'THEMENAME' with the name of your theme:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['some_html'] = '';
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['some_html'] = '
Hello world!
';
  }
}

And use this in your page.tpl.php:

<?php print $some_html; ?>

Alternatively, if you want to keep the HTML string in your template file, I would do this in template.php:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['print_extra_header'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['print_extra_header'] = true;
  }
}

And use this in page.tpl.php:

<?php if ($print_extra_header) : ?>
THIS GETS PRINTED
 <?php endif; ?>

Make sure to clear the cache after creating the THEMENAME_preprocess_page function, otherwise Drupal will not know it's there and it will not run.


CSS changes not taking effect in customized styles folder I am trying to size the banner in a Jackson theme on my site to fit to the 960px wrapper size have in customized folder in sites/all/themes/mytheme/styles/mytheme.css but no matter what I do the length won't change, only the height which makes no sense at all.

I have tried flushing the cache several times but still no changes take effect.

The code in jackson styles.css is

#banner-wrap {
   background: transparent url(../images/main-sprite.png) repeat-x scroll center -90px;
   height: 133px;
   overflow: hidden;
   width: 100%;
}

I have successfully changed the height but if I change width from 100% to 960px it does nothing.

Make the changes to the style.css file which is in Jackson theme folder. Not under mytheme

Use

#banner-wrap {
background: transparent url(../images/main-sprite.png) repeat-x scroll center -90px !important;
height: 133px !important;
overflow: hidden !important;
width: 100% !important;
}

Add this in to style.css file
Flush the cache once.


views_get_current_view returns null I have placed the following function in my .module file to get the information of current view. But it returns null

public function buildForm(array $form, FormStateInterface $form_state) {
    $record = array();
    $view = views_get_current_view();
}

I have added use Drupal\views\Views; in the top.

What could be the reason to return null. Am i missing anything?

views_get_current_view() seems to be from the early days of procedural code and I don't know how this can be used in connection with form building in D8.

You can get the current view from the current route, if this is what you are looking for:

use Drupal\views\Entity\View;

  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  if ($view_id) {
    $view = View::load($view_id);
  }


Migrate with Cloud Files fopen:Too many open files I'm using migrate to import 2800 blog posts. Each have a header image which is getting imported. I'm using Rackspace Cloud Files as my CDN so the system is copying the image files up to Rackspace Cloud Files, but after it's been running for awhile I start getting this error:

  (/home/drupal/html/sites/all/libraries/rackspace/php-cloudfiles/cloudfiles.php:608)
  Invalid response: (curl error: 35) error:02001018:system
  library:fopen:Too many open files: Failed [error] to obtain valid HTTP
  response.

What is causing the problem?

I believe there is a bug in the rackspace cloudfiles api which causes connections to not be closed properly. In normal, web-based, circumstances this isn't a problem because at the end of the processing all of the connections are closed and you never usually open enough connections to have a problem.

However, I'm running the migration via drush from the command line which means the process isn't ending for a VERY long time after A LOT of connections and eventually I hit the limit for the max number of open "files."

This isn't a perfect solution, but it works even if it's hackish.

class MyArticleMigration extends BasicExampleMigration {
    public function __construct($rangeStart = 0) {
        parent::__construct();

        // code to set up the query where I pull my source data from the database.
        $query->range($rangeStart, 35);

        // rest of the code...
    }
}

class MyArticle0Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(0);
    }
}

class MyArticle1Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(200);
    }
}

class MyArticle2Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(400);
    }
}

// etc...

Then on the command line I just run:

drush migrate-import MyArticle0Migration
drush migrate-import MyArticle1Migration
drush migrate-import MyArticle2Migration
drush migrate-import MyArticle3Migration

etc...


D7 - syntax in Field template My D7 content type has a field for an MP3 file. I want the field to display as an image which the user can then right click to download the file ie like this. My field template file looks like this:

var_dump($items) =

<?php var_dump($items); ?>

print_r($form) =

<?php print_r($items); ?>

<?php echo $items[filesize]; ?>
<?php echo $items['filesize']; ?>
<?php echo $items["filename"]; ?>
<?php echo $items['url']; ?>
<?php echo $items['uri']; ?>

<a href="<?php echo $items['url']; ?>">

The result is here.
Can anyone please tell me why the orange box is empty / not printing out, and the correct syntax re the green box to make the image link to the MP3 file URL instead of the page URL?

Thanks...

I think your are printing wrong the array $items. It should be something like

print $items['#file']->filename;

The same is happening with the image issue.


Capture amount on order state change I would like to know if it is possible to capture payments by subscribing to order transition events.

Example:

Transaction mode: Authorize only
On order placed - Capture some amount (application fee)
On order validated - Capture outstanding amount

Thank you!

I've managed to create new payment and modify authorisation amount. Here is what I have so far:

public static function getSubscribedEvents() {
  $events = ['commerce_order.place.post_transition' => ['captureFee', -50]];
  return $events;
}

public function captureFee(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  if ($order->bundle() != 'training') {
    return;
  }

  /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */
  $payment_gateway = $order->payment_gateway->entity;
  $payment_gateway_plugin = $payment_gateway->getPlugin();

  $payment_storage = $this->entityTypeManager->getStorage('commerce_payment');

  // Load first order payment
  $payments = $payment_storage->loadMultipleByOrder($order);
  $first_payment = current($payments);

  // Only proceed if payment is not captured
  if ($first_payment->isCompleted()) {
    return;
  }

  // Default fee amount
  $fee_amount = new \Drupal\commerce_price\Price('50.00', 'USD');

  // Get fee amount from product variation
  if (isset($order->getItems()[0]->getPurchasedEntity()->field_app_fee) && !$order->getItems()[0]->getPurchasedEntity()->field_app_fee->isEmpty()) {
    $fee_amount = $order->getItems()[0]->getPurchasedEntity()->field_app_fee->first()->toPrice();
  }

  // Create fee payment
  /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
  $payment = $payment_storage->create([
    'state' => 'new',
    'amount' => $fee_amount,
    'payment_gateway' => $payment_gateway->id(),
    'order_id' => $order->id(),
  ]);

  // Capture fee payment
  if ($payment_gateway_plugin instanceof OnsitePaymentGatewayInterface) {
    $payment->payment_method = $order->payment_method->entity;
    $payment_gateway_plugin->createPayment($payment, 'capture');
  }
  elseif ($payment_gateway_plugin instanceof ManualPaymentGatewayInterface) {
    $payment_gateway_plugin->createPayment($payment, TRUE);
  }
  else {
    return;
  }

  // Subtract captured amount from authorized amount and save first payment
  $first_payment_amount = $first_payment->getAmount();
  $first_payment->setAmount($first_payment_amount->subtract($fee_amount));
  $first_payment->save();

}

I have "training" bundle that is limited to 1 item per cart. This is the result with variation price set to $2,100.00 and $45.00 fee.


How do you theme a pager in a specific View? I have a few views, but each view would have a pager that would be themed differently. How do I go about targetting the pagers of each View for theming?

each view has own class like .view-id-name
so this class or id you can use to CSS your pager for each view


Need help with Views and Glossary I'm following along on the blog post "Use Views to Create an Alphabetical List of Taxonomy Terms" by Kristin Brinner http://getlevelten.com/blog/kristin-brinner/drupal-tutorial-use-views-create-alphabetical-list-taxonomy-terms and my sample does not produce the results as she shows.

Part 1 & 2: I successfully created a new view selecting taxonomy terms (create as Grid), then grouped terms alphabetically (add Taxonomy term: Name, label it "Grouping", exclude from display, rewrite to max length = 1), then under Grid-Settings use "Grouping"

Part 3, Create a Views page for each letter of the alphabet: I can't see these results, but I presume I did this correctly, using contextual filters,  (Glossary, Character limit 1)

Part 4, Create A-Z list (create a block that will display the list of first letters in a cute list above the grouping grids) isn't working. Here is what the tutorial says should be the result:

I followed along exactly with the tutorial except When the filter value IS available, the tutorial says Specify validation criteria, Basic Validation, Hide View and I do not have Hide View available.

I don't have an option to Apply, only Save. My content continues to look the same as it did previously in the exercise, i.e. like this (graphic omitted because I don't have enough clearance on this site)

However when I put "S" into the Preview with contextual filters, I get
(graphic omitted because I don't have enough clearance on this site)

So, it looks like it's almost working. Ideas? TIA

You can find validation in Contextual Filter. I am attaching screen shot for the same.

However you can also use the glossary view which is provided by Drupal.


Module to Automatically Create URLs from Article Titles for Drupal 8 I am wondering if there exists a module that would automatically create "nice" URLs using titles of posts in Drupal 8. I am aware of aliasing; however, if there is a lot of posting activity on the site,  it can become a substantial time sink.

Example: (something along these lines would suffice)

Title of a post:

  How to create neat URLs in Drupal 8

corresponding URL:

  www.example.com/how-to-create-neat-urls-drupal-8

Yes, just use the Pathauto module with Token. Pretty straightforward.


Execute jquery function if Ajax callback form complete I got a custom ajax callback which replaces my checkbox options based on the select option.

Now after the checkboxlist get's updated i need to execute a jquery function on those checkboxes.

How can i execute this custom jquery function after the callback is done, so after the checkboxlist is updated.

Form element:

        $widget['select_box'] = array(
            '#type' => 'select',
            '#title' => 'Select bussen',
            '#options'  => $options,
            '#validated' => TRUE,
            '#default_value' => '_none',
            '#attributes' => array('class' => array('select-province')),
            //The callback
            '#ajax' => array(
              'callback' => 'ajax_select_callback',
              // 'wrapper' is the HTML id of the page element that will be replaced.
              'wrapper' => 'replace_select_div',
            ),
        );

        //Form element wich get updated
        $widget['select_box_2'] = array(
            '#type' => 'checkboxes',
            '#title' => 'Select bussen',
            '#options' => ...,
            '#prefix' => '
',
            '#suffix' => '
',
            );

Ajax callback function:

    function ajax_select_callback($form, $form_state) {
      // The form has already been submitted and updated. We can return the replaced
      // item as it is.
    return $form['line_item_fields']['field_bussen_select']['und'][0]['select_box_2']

    }

Jquery function i run on the checkboxes:

    jQuery("input[type='checkbox']").change(function () {
        jQuery(this).parent().siblings('ul')
            .find("input[type='checkbox']")
            .prop('checked', this.checked);
    });

I think if found the answer at :https://drupal.org/node/171213.

Section: JavaScript on your AJAX form

"Attach jQuery to Drupal.behaviors, that way it can be run anytime new DOM elements are inserted. One example, if you're using AJAX in Views, each time a section of the page reloads, it will reload/run jQuery."

Didn't test it, because i don't need it anymore :), but still good to know!


Goto page in webform or submit I've got a Drupal 8 webform with a multi page wizard. I know that it is possible to "jump" to a specific page if I implement hook_webform_submission_form_alter() and add my own submit function to change the formState current_page to my desired page. But I want to check a value from a previous page and if the value is value_a I want to submit the form. If it is value_b I want to go to page b and if its value_c I want to go to page c.

$pages = $formState->get('pages');

if ($formState->get('type') === 'value_b') {
    $pageName = 'page_b';
    gotoStep($pageName, $pages, $formState); // this is my custom function to go to the desired page
} else if ($formState->get('type') === 'value_c') {
    $pageName = 'page_c';
    gotoStep($pageName, $pages, $formState); // this is my custom function to go to the desired page
} else {
    // SUBMIT FORM. HOW TO DO THIS?
}

I switched to the latest dev release ob the webform module and could skip the wizard pages depending on previous values without having to code anything. Thanks for the tip @jrockowitz ;)


MAC -> Drush higher bootstrap level? Since a couple of days now, i switched from a ubuntu machine to a macbook pro retina for my development works.

I installed XAMPP on it, without to much trouble.
But I have been struggeling with drush for quite some time now, and I am hoping to find a little help here.

Drush partially works...
I can download Drupal, download modules etc.
I CANNOT enable the modules, perform sql-cli commands (however sql-connect DOES work?!).

The error i get is:

Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                                           [error]
The drush command 'en token' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with
the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.28
 Site URI               :  http:// default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database username      :  root
 Database name          :  drupal_site
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /Users/myusername/drush/php.ini /Users/myusername/drush/php.ini
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/XAMPP/htdocs/drupal_site
 Site path              :  sites/default

Now I have been googling around for this for days and found numerous topics, stating all kinds of things (change your settings.php file to use 127.0.0.1 instead of localhost => did not work)

One thing i would like to add is that i discovered that my OS runs a different php version as the XAMPP instance?!

Ps: My drupal_site is fully functional! Just drush won't work with me.

Any help would be very much appreciated!

Best,

Your drush is using system php, whereas Drupal is using XAMPP's. This reliably creates drush problems.

Look into XAMPP and figure out where its php binary is and then set your path accordingly in .bashrc or whatever other shell init files you have sitting around.

Check your progress with drush status, in particular what it reports for the database connection.


sort a view by Most Viewed, Most Favorited, Latest I have view which contains all nodes of a content type(article). default sort criteria of view is recent nodes. But i have three links Most Viewed, Most Favorited, Latest.I have to sort this view by clicking on these links .

I am making a node favorite by using flag module .

How can i achieve that .

Please Help.

Create three different views, Most Viewed, Latest, Most favourite with display type block.
For sorting by views, You need to enable statistics module.
For sorting by latest, use post date sort filter in views.
For sorting by favourite, flag module has integration with views. You can able to create a filter to sort by number of flags.
Use Quick Tabs module to group above three different view blocks as a single block and display it where ever needed.


Drush pm-update strange behavior I have a bunch of sites running both on Drupal 6 and Drupal 7 on my server. Every site has its own folder (ie. I don't use multisites feature). I created a small script to run drush pm-update on every site.

All of this is working okay, but I noticed something strange. Often when I run, either manually or via the script above mentioned, the drush pm-update finds a update for a version of a module or core in one site, but not for others.

I tried to clear drush cache but it showed no result.

Have anyone seen this behavior and has a hint of what it is? I'm curious about it :-)

Update: Now I think it's related to this issue https://drupal.org/node/952394

The thing is, every Drupal site has a variable, in {variable} table, called update_last_check that stores the last time the site had a update check. This variable is mostly update by Drupal cron. It happens that, in some of my sites, this date is too small to need a new check, so Drush skipped it and considered the site up to date. So, in other words, if you want to ensure there's a new update, you should first run a drush cron and then run a drush pm-update.


My login form seems to have disappeared I'm developing a custom theme and even though I have placed the "user login" block in a region, I can't find it and now I'm locked out.

My site is on Drupal 8.

The login block is "a" way to get logged in. Another solution to get loged in is to navigate to an URL like /user/login.

So try that, and see what happens then. Of course, if you get logged in, hurry to move that disappeared block to some region that for sure you now is OK. To QA test it, use another browser before logging out again ...


How to send comma separated taxonomy term (as link to taxonomy term url ) from preprocess to twig file as single variable? According to my requirements I have to use views preprocess and views-view.html.twig

function MYTHEME_preprocess_views_view(array &$variables) {

  $aliasManager = \Drupal::service('path.alias_manager');

    if (isset($variables['rows'][0]['#rows'])) {
      $nodeValues = [];
      foreach ($variables['rows'][0]['#rows'] as $value) {

        $nodeValue['created'] = $value['#row']->_entity->created->value;
        $nodeValue['external_url'] = $value['#row']->_entity->field_url->uri;
        $nodeValue['title'] = $title = $value['#row']->_entity->title->value;
        $nodeValue['nid'] = $title = $value['#row']->_entity->nid->value;
        $nodeValue['tid'] = $value['#row']->_entity->field_topic->entity->tid->value;

        // section referenced to node
        $nodeValue['section'] = $value['#row']->_entity->field_topic->entity->name->value;

        $topics = "";
        foreach($value['#row']->_entity->field_topic2 as $val){
          $topics != "" && $topics .= ", ";
          $topics .= $val->entity->name->value;
        }

        $nodeValue['topics'] = $topics;

        $nodeValues[] = $nodeValue;

      }

      $variables['node_values'] = $nodeValues;
    }

 }

In twig file :

{% for value in node_values %}

 {{ value.title }}

            {% if logged_in %}
                {% if 'premium' in user.getroles %}

{{ value.created|date(format='y-m-d H:i') }}

{{ value.topics }}

                {% endif %}
            {% endif %}

    {% endfor %}

Out put is like below :

Everything is working fine but I need to create Links of terms in above screenshot. And in code its TOPICS in preprocess function.

I have tried various ways to create it as link but that does not work as it just print a tags as html but not links. Please suggest.

Thanks!

I have solved this like below :

It was always considered as string so I have to send topics in from of array like below:

$topics = array();
foreach($value['#row']->_entity->field_topic2 as $val){
  $topics[$val->entity->tid->value]= $val->entity->name->value;
}

And then in Twig I made links from them and it worked.

    {% for key,item in value.topics %}
        {{item}}
        {% if not loop.last %},{% endif %} # for adding commas after each term
    {% endfor %}


Creating child nodes when creating parent I'm trying to implement creation of child nodes programmatically in hook_submit when creating parent nodes according to the parent node field value. Here is the idea.
Parent node: field_stages (unlimited count). I want to create new "stage" nodes when I've added new parent node and save a reference to these child nodes in parent, although the references should not be editable and visible in add/edit form and node view. How it can be implemented in drupal?

Your main problem here is you won't be able to create a reference to the created node in a form submit as the node id hasn't been created yet. I'm not actually sure at what point it becomes available in the node process either. hook_node_save is still too early and it's the last node specific hook you can do this with.

I would skip trying to do this programmatically and use rules and entity reference field. Have your rule fire after a new node is saved. then have it create a new entity (node) and set data value (entity_reference) to the newly created node. much easier to maintain than code.


Reducing file size of styled images I always thought styled images are smaller than original ones in file size. So the main reason for styling was to reduce the file size. But today I noticed it isn't always the case. For example:

I downloaded an image abcd.jpg from facebook and then uploaded it to my Drupal website.

Originally the image was 405.3 kB which is 2048px X 1536px.

After downloading the same image from my drupal website the image is 698 kB which is 1100px X 845px.

Style Effect:(Scale width 1100)

And when I checked I found the same in most of the cases. Can anything be done about it without compromising image quality?

It's in the nature of image compression that compressing an already compressed image can result in larger filesize. The image-toolkit (be it GD or image magick) can not know on what level the image is already compressed and will try to make the best of it (following the quality setting that No Sssweat describes). So you may want to try to set this to 100% to prevent repeated compression.

Further reading:

Efficient Image Resizing With ImageMagick
In search of the most optimized image in Drupal 7


how do I create multiple modules that both add to the output of a node? We have a content type called "sales_order" which contains order data for online sales.

I have created a custom module that adds a form to the node that allows a user to generate shipping quotes. I do this by creating this function which adds my form to the node:

function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

if ($node->type=='sales_order' || $node->type=='sales_orders')  {
    switch ($op)
    {
        case 'view':

            $form .= drupal_get_form('mymodule_form',$node->nid);
            $node->content['form'] = array
            (
                '#value' => $form,
            );
        break;
    }
}

This works great, but, now I want to add an additional form for another shipping provider. So I created a new module doing the same thing but when I enable both, it only outputs the form for the first module and not both?

I think I am misunderstanding how this is supposed to work.

How should I get multiple custom modules to add content (a form) to a node?

PS I know I could easily integrate both providers into a single module but I would prefer to keep them separate for now.

If you're using $node->content['form'] for both modules, that would be why. Instead do $node->content['module1_form'] and $node->content['module2_form'].

This is because each function is getting passed the same node object and $node->content['form'] is being overwritten between the two modules.


How to customize a node--type.html.twig template? I activated the devel and devel kint modules. I also activated twig debugging, so, I can know which are templates used by Drupal.

So, I created a content-type named album that contains a field named tracks.

Now, I want customize this content type, so I created node--album.html.twig in templates folder of bartik, which works so I can begin to customize this template.

Now, I have to know which are variables used by this template. In comment section of node--album.html.twig I can read that content variable can be used to display content of page. I also read I can use subset of content, such as content.field_example to display a field.

OK, so if I want to modify rendering of field_tracks I can use content.field_tracks. Before using this variable I wanted to know all content variable, so I've written [[ kint(content) ]] in content section of this file. I rebuilt the cache, and I seen that content is an array, not an object as suggested in comment section of node file.

So, if I print [[ content.field_tracks ]] it returns nothing.

If I use kinkt() without parameters it breaks drupal and point me to core/install.php.

The same as I use d() without parameters.

At this point I am confused: there is a way to modify node--type twig templates without creating a file for each field?

Here is some examples

Render the whole field markup

{{ content.field_text }}

Get just the value of the field

{{ content.field_text.value }}

Get a field value from authors object

{{node.uid.entity.field_gender.value}}

For field above you can get the machine name of the field as you see it for example in admin/structure/types/manage/page/fields

For multivalue fields look at some examples here

Read more about how to find more variables here


How do I get block relationships for a content type? As part of a migration from drupal 7 to drupal 8, I currently have a rather original node display method that I'm trying to reproduce to Drupal 8, but without success.
Currently on Drupal 7, this method is filled by a custom preprocess that I try to remove in favor of views / entity reference.

Here is the procedure:
I have a node type that contains tags (field_tags), with for example the vocabulary 'news' from the 'Users terms' term. And basic content (title, body...).
I would like, via an already existing block having a field tags and value 'news', recover all the nodes with the tag 'news'.

Recap of entities I have tried:

Node:
- title
- body
- field_tags / value: 'news' (reference to "User terms")

Views name 'flow':
- display: content
- contextual filter: 'Content: Has taxonomy term ID' > 'Display all results for the specified field'
& Content: Nid
- relationsips: nothing, because I can't add a entity reference to a block

Block name 'block flow' :
- title
- field_tags / value: 'news' (reference to "User terms")

I would like when I create a block type 'block flow' with 'news' tags, get all node type that containing the 'news' tag.

I can't get it working because the views relationships don't allow me to reference the field 'field_tags' from my block (only content or taxonomy available).
We have a theme preprocess who can do that but I would like to know if there is a workaround ou any contrib module doing that.

Why I don't create a block from the view? Because in our process, we don't give access to the views of our contributors.

Finally, I got this working by creating a simple view "custom block".
Then, I created 3 relations, one for my node content, one for my content tags and last one for block tags

After that, we just need a contextual filter : Content: Has taxonomy term ID' > 'Display all results for the specified field

And that's all.


How can I show a field on click? In node.html.twig, I want to show a field when I click on it, as what the Field Value Loader (Show field on click) module does, but this module doesn't have releases for Drupal 8.

How can I do this?

node.html.twig

{{ content.field_something.value }}

Show

custom.js

(function ($) {

$('.field-something').hide();
$('.show').show();

$('.show').click(function(){
    $('.field-something').fadeIn(2000);
    $('.show').hide();
});

}(jQuery));

Your Theme's style.css

.field-something { float: left; padding-right: 5px; }
.show { color: blue; cursor: pointer; display: none; }

Example DEMO


show related taxonomy blocks I wanted to show related taxonomy content in my page and I found this:

http://www.metachunk.com/blog/adding-related-content-view-drupal-7

and it worked perfectly. I wanted to know how it worked basically i.e the 5th step i.e

  Configuration on this filter: -> When the filter value is NOT in the
  URL: -> Provide default value -> Type: Taxonomy Term ID from URL ->
  under that, check the box "Load default filter from node page, that's
  good for related taxonomy blocks." -> now check the boxes of the
  taxonomies you want involved here

He says get Taxonomy term ID from URL and then says Load default filter from node page, that's good for related taxonomy blocks.

Basically what is it doing here ??   Is is trying to tell to block here that get the term ID from the given URL page's term ID selected?

It basically means that when you include the view as block on a node page, it will get the term id from the page's taxonomy terms (magically) even though the term id is not really on the page's URL path.

I agree that the description for that option is really confusing.


What's the purpose of $item in taxonomy_field_is_empty($item, $field)? Please explain:

taxonomy_field_is_empty($item, $field)

$field - this is name of field

$item - what is it ???

I want to use on my function for check if tags field empty in node we don't show other articles, show otherwise.

With the help of @Clive

I think that's not the way, taxonomy_field_is_empty is an implementation of hook_field_is_empty(), which is used to

  Define what constitutes an empty item for a field type.

$item is:

  An item that may or may not be empty.

An item is the data for a specific field entry, so what you'd find in, for example, $node->field_tags['und'][0] in your code example.

If you have access to the $node variable and your field is named field_tagsyou can do this:

//Recover all the items
$items = field_get_items('node', $node, 'field_tags');
//If there is not a tag, then do something
if (count($items) == 0) {
  echo "field empty";
}

Or

//If there is not a tag, then do something
if(count($node->field_tags[LANGUAGE_NONE]) == 0) {
  echo "field empty";
}


How to add views exposed filter blocks into views I am trying to move a views exposed filter into a custom block, and then add it back to the views header. The reason for this is because I would like to intersperse the filter with other blocks/markup in the views header. When I selected the option to turn the filter into a block, it does show in the Block UI, but not as an option to add to the view header.

Is this possible in views?

Add the following function in your template.php

function THEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

then in your views header render the block like so

<?php print THEMENAME_render_block('<moduleName>', 'delta', array('title' => t('Filter Title'))); ?>

For this you must have views php module enabled if you want to render the block from views header or else you can use tpl file to render the block in the header as @rooby suggested.


Add CCK form with overlay or colorbox I have a CCK form. When users submit the form, and add new content, I would like the form to be viewed in an overlay that allows the form to use all of the browser window's area in a similar manner as colorbox or lightbox.

The reason for this is to provide more screen space for the large form. I have most blocks hidden for this content type, but there is still other page elements and menus ect taking up room.

Also, I am using the multistep module. This means the content is created before submitted. After the first step, the path is no longer /add/[…]. Multistep also provides a block for the form index and progress bar. If I only display the node in colorbox (which is installed and used for other features) then I miss out on the multistep block.

If I only display the node in colorbox
  (which is installed and used for other
  features) then I miss out on the
  multistep block.

A "quick-and-dirty" solution that I can think of, is to embed the multistep block in the node using the Insert Block module. Notice, that if you are using D7, you can check this, which is a community submitted port of the module.

If this is not what you need, please add a couple of screenshots of the form and the multistep block so that we can understand exactly what you are trying to do here.


Exclude content referenced by content whose author is current logged in user I try to solve question - answer scenario with views.
2 content types: question and answer. (answer is connected to question by entityreference)
User can check themes of interests (taxonomy) in profile and a view is displayed in his profile with relevant questions. Creating this view was simple: I made a user view with UID as contextual filter and added a entity reference relationship and taxonomy term:content with term. Then it is easy to display list of relevant questions.

Problem: I want to filter out questions already answered by current user. In other words - to filter out all questions which are referenced from answer content type and answer's author is current user.

I tried to add new relationship - content referencing content from xy field, tried to add contextual filter - node author. None of this seems to work.
EDIT: adding contextual filter user:author with excluded option works ONLY if there is reference (answer) made by current user. If other content(answer) by other user is referencing the content(question), it shows the question in the list again. Of course, because context filter only removes current user's nodes.

I need views to exclude content by other users as well. Does someone know answer to this? thank you

Try this,

Add a contextual filter of Content: Author uid.
Under "WHEN THE FILTER VALUE IS NOT AVAILABLE", select "provide default value", and then select "User ID from logged in user".
Under MORE, select "Exclude".
Save.

P.S. This should work. Haven't tried myself.


After submit form open a view I am using the custom module to create a block wich contains a form. I added this form in a node of a custom content type. When I click to submit, I want to open a view wich contains another form and I will create it in the same module.

this is my code

function my_module_block_info() {
$blocks['visit'] = array(
    'info' => t('Visit'),
    'cache' => DRUPAL_CACHE_GLOBAL
);
return $blocks;
}
function my_module_block_view($delta = '') {
$block = array();
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
    $nid = arg(1);
}
switch ($delta) {
    case 'visit':
        $block['content'] = drupal_get_form('visit_project', $nid);
        break;
}
return $block;
}
function visit_project($form, &$form_state, $nid) {
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
);
$form['actions'] = array('#type' => 'actions');
$form['actions'] = array(
    '#type' => 'submit',
    '#value' => t('Visit'),
    '#attributes' => array('class' => array('general_button')),
    '#submit' => array('_visit_project_details')
);
return $form;
}
function my_module_menu() {
$items['my-page'] = array(
    'title' => 'Title of my page',
    'page callback' => 'project_details',
    'access callback' => TRUE,
);
return $items;
}
function _visit_project_details($form_state)
{
   $form_state['redirect'] = 'my-page';
}
function project_details() {
    return '
ok in details of '.$_POST['id'].'
';
}

Can you help to go to my-page after submit form and still reading the $_POST?

Thank you

Below code is redirecting to my-page

<?php

function my_module_block_info() {
$blocks['visit'] = array(
    'info' => t('Visit'),
    'cache' => DRUPAL_CACHE_GLOBAL
);
return $blocks;
}
function my_module_block_view($delta = '') {
$block = array();
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
    $nid = arg(1);
}
switch ($delta) {
    case 'visit':
        $block['content'] = drupal_get_form('visit_project', $nid);
        break;
}
return $block;
}
function visit_project($form, &$form_state, $nid) {
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
);
$form['actions'] = array('#type' => 'actions');
$form['actions'] = array(
    '#type' => 'submit',
    '#value' => t('Visit'),
    '#attributes' => array('class' => array('general_button')),
    //'#submit' => array('_visit_project_details')
    '#submit' => $form['actions']['submit']['#submit'],
);
$form['actions']['#submit'][] = '_visit_project_details';
return $form;
}

function my_module_menu() {
$items['my-page'] = array(
    'title' => 'Title of my page',
    'page callback' => 'project_details',
    'access callback' => TRUE,
);
return $items;
}
function _visit_project_details($form, $form_state)
{
   //$form_state['redirect'] = 'my-page';
   drupal_goto('my-page');
}
function project_details() {
    return '
ok in details of '.$_POST['id'].'
';
}


Creating quicktabs prorgammatically: code worked in D6 not in d7 I created a custom quicktabs module in drupal 6 that adds a block, and it is working just fine. Before moving it over to drupal 7, I edited the module and info files accordingly, but the module displays no block on admin/structure/block and the version of the module doesn't appear on admin/modules.

I have added the feeds and their blocks are displaying content and the bids are identical in both versions of the site.

I have read this and this and even tried this, but haven't found the solution. I have run cron and cleared cache when you would be expected to.

If I add a print_r($tabs) I get an array with all of the array pieces as designated below for the right days.

quicktab_custom.info file

name = quicktab custom
description = custom quicktab block for event data
core = 7.x

quicktab_custom.module file

/**
 * Implements hook_block().
 *
 * We want to define a quicktabs block.
 */
function quicktab_custom_block($op = 'list', $delta = 0, $edit = array()) {

switch($op) {
// 'list' shows the items in admin/build/block admin page
// we alsohave: configure, save, view
case 'list':
  $blocks['quicktab_custom_quicktabs'] = array(
    'info' => t('events this week'),
    'cache' => BLOCK_NO_CACHE,
  );
  return $blocks;
  break;
case 'view':

  switch ($delta) {
    case 'quicktab_custom_quicktabs':
     $today = date('D');

      //set tab content
      $tabs[] = array(
        'title' => t($today),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-14',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +1 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-15',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +2 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-16',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +3 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-17',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +4 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-18',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +5 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-19',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +6 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-20',

      );

      $quicktabs['qtid'] = 'quicktab_custom_quicktabs'; // machine readable name
      $quicktabs['hide_empty_tags'] = TRUE;     // hide tabs that are empty
      $quicktabs['default_tab'] = $today;   // set the default tab
      $quicktabs['tabs'] = $tabs;       // all tabs with content
      $quicktabs['style'] = 'Navlist';      // tabs theme -- originally set to Sky
      $quicktabs['ajax'] = FALSE;       // ajax or not
      $block = array('subject' => '', 'content' => theme('quicktabs', $quicktabs));

      return $block;
      break;
  }
 }
}

According to this comment on the hook_block() docs,

  Drupal 7 doesn't use anymore hook_block(), but it uses a set of new hooks; see Converting 6.x modules to 7.x for more details.


Is there an hook to modify programmatically the thumbnail shown from the video module? I'm using the video module and i need to show a different thumbnail if the user who is watching the node is a guest or a logged on user (if the user is a guest i want to display a standard thumbnail). Is there an hook to do this?

you could just modify the template to show a different thumbnail for anonymous users. You can use the Theme Developer module to find the right template to modify.


Change name of a tab for a specific content type I have a content type Organizations which is an OG Group. I would like to change the default tab name "View" only for this OG group(or content type). Tab tamer module helps with it but it does not allow the change of the name of tabs for a specific content type.

I use sky theme(an Adaptive theme). I wrote the following code in the theme template file,

function sky_preprocess_page(&$vars) {
  if ($vars['node']->type == 'organization') {
    foreach($vars['tabs']['#primary'] AS $index => $tab) {
      if($tab['#link']['title'] == t('View')) {
        $vars['tabs']['#primary'][$index]['#link']['title'] = t('Organization Home');
      }
    }
  }
}

But this doesn't help too

You can use hook_menu_alter() to change the name of tabs for a specific content type. For example:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  unset($items['node/%node/view']['title']);
  $items['node/%node/view']['title callback'] = 'MYMODULE_view_tab_title';
  $items['node/%node/view']['title arguments'] = array(1);
}

function MYMODULE_view_tab_title($node) {
  if ($node->type == 'organization') {
    return t('Organization Home');
  }
  return t('View');
}

Remember clear Drupal cache.


Two sort criteria. How to display first those with a specific List (float) selection i have a View that provides a list of products(content type Product). This view has two sort criteria. The one is the "SKU" and the second is "New product". The "New product" is a List(float) field and the available options are N/A, Yes and No.

The view must show first the new products and then all the rest. New products are considered those that they have selected the option "Yes".

Is this possible? Any idea?

Thank

You can do it using views_query_alter. Find out what are the key values being stored from your list and then use them accordingly in the code below.

function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'shop' && $view->current_display == 'page') {
     $query->orderby[0] = array(
           'field' => 'CASE table.type WHEN '1' THEN 1 WHEN '0' THEN 2 WHEN
            ELSE 3 END');
  }
}


Format of the JSON returned by the Services module I have a big doubt about the JSON format the Services module (for Drupal 6) generates.

When I view the XML, all is OK.

<result is_array="true">
 <item>
  <nid>9</nid>
  <vid>9</vid>
  <type>producto</type>
 </item>
</result>

When I view the JSON, I see this:

[
 {
  "nid": "9",
  "vid": "9",
  "type": "producto",
 }
]

What I really is something like this:

[
 {
  "item":{
    "nid": "9",
    "vid": "9",
    "type": "producto",
  }
 }
]

How do I do this? Is there any configuration in the Services module that I can use to change the output, or do I need writing code?
I know the function to render JSON output.

You should implement hook_services_request_postprocess_alter().


Events Tickets Profit for the comany I am trying to create an event ticketing system with drupal 7 and would like to insert the company's commission to it.
In simple explanation.
If event planner ticket price is $x
Company commission rate is 15%

The planner to choose whether the customers pay for the commission + ticket or the planner pays upfront.

Is there any module that support something like this?

If you're looking for a pct fee on top of your order, you've got a couple of options, the quick and dirty one is to create a fake tax of the percentage you want, see http://www.drupalcommerce.org/user-guide/tax-configuration, another option is to multiply the amount by 0.15 or whatever quantity on the rules event you choose.

For fixed fees you can check Commerce Fees

You've got also commerce discount and commerce coupon that do the exact opposite operation, so you can check how to add and modify stuff in the checkout, if you're looking for a more advanced solution.


Rewrite field for a specific row? I see that in views the Rewrite the output of this field option affects all rows. Is there a way, using php or something, to rewrite the output of row #4 only?

Put this code in your theme's template.php file:

function THEME_preprocess_views_view_fields($vars){
  dpm($vars);
  if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] == 4){
    $vars['fields']['title']->content = 'blahblah';
  }
}

Clear the cache.

Replace VIEWNAME, DISPLAY and 4 with your appropriate values.

Then inspect the $vars['fields'] with dpm output and rewrite the output how you want for the field in question. You may use 'raw' value, but remember to sanitize.


Error line appears when using drush 7.x.5.9 -- 32-bit executable? I keep getting the line "/[~]/drush/drush: line 49: /sw/bin/tput: Bad CPU type in executable" in drush 7.x.5.9 on OS X 10.9.2 Core 2 Duo. I think it's related to a 32-bit executable running on a 64-bit-capable processor. Any ideas? It has only happened since I upgraded to 5.9.

Try running tput cols from your shell.  Drush is running this command to determine how many columns wide your terminal is.  You could convince Drush not to call TPUT if you instead export COLUMNS 80 (e.g. in bashrc), but it's probably better to figure out what's wrong with your tput executable.  This is possibly related to an installation problem that is independent of Drush.


Adding a button to a form that links to an external URL I am trying to add another button to a user login form.  I am able to get the button to show up, but not to link to an external URL (example.org in the code below).  Code I am using is below:

<?php

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['change_pass'] = array(
      '#type' => 'button',
      '#prefix' => '
',
      '#suffix' => '
',
      '#value' => t('Change Password'),
      '#weight' => 1000,
      '#submit' => array('MYMODULE_change_pass_submit'),
      '#limit_validation_errors' => array(),
    );
  }
}

function MYMODULE_change_pass_submit($form, &$form_state) {
  drupal_goto('https://example.org', array('external' => TRUE));
}

Any thoughts?

You should use $form_state['redirect'] to redirect in form submit instead of drupal_goto
,I mean

function MYMODULE_change_pass_submit($form, &$form_state) {

  $form_state['redirect'] ='https://example.org';
}


Custom Apache Solr search per usertype (Profile2 Module)? I have a site that enables you to register either as a "Care giver" or a "Patient". The patient has a different profile (Profile2 module) with options such as the type of care they need, the amount of money they can pay a care giver, etc.

The care giver profile has a work profile (much like a resume).

What I want to accomplish:

Create a custom "Search patients" search for the care givers
Create a custom "Search care givers" search for the patients.

How do I limit apachesolr to a profile2 search?

Checkout the Search API module - this was developed to solve problems exactly like this. With Search API, you can configure multiple search engines, define the datasource it pulls them from (ex. Apache Solr) and then use its built-in views integration to create custom search sets (ex. for care givers pull only from these entities / content types, and show only these fields).


Issues with namespaces and Migrate module migrating XML content In the Migrate module I noticed that one reason I could not import an XML file was because it contained namespaces.  Removing namespaces from the XML file and Migrate class allowed me to import the content without issue.

In trying to fix this issue I came across this post which brought me to this patch for the xml.inc file (used to import xml sources) in the Migrate module.  Unfortunately it was for an outdated version of the module so I had to manually apply it.

The patch does not seem to work as I still get this error when attempting to migrate (the same error I was getting before applying the patch):

  Migration failed with source plugin exception: Passed variable is not
  an array or object, using empty array instead

I think I have tracked down where the issue is appearing in the xml.inc code, as this function, &xml, does not output $this->currentXml which should be a simplexml_load_file:

/**
   * Load and return the xml from currentUrl.
   *
   * @return SimpleXMLElement
   */
  public function &xml() {
    if (!empty($this->currentUrl)) {
      dpm('start grab url/xml');
      dpm($this->currentUrl);//it is grabbing this url ok
      $this->currentXml = simplexml_load_file($this->currentUrl);
      dpm($this->currentXML);//it is not loading the file properly it seems
      dpm('end grab url/xml');
      if (!$this->currentXml) {
        Migration::displayMessage(t(
          'Loading of !currentUrl failed:',
          array('!currentUrl' => $this->currentUrl)
        ));
        foreach (libxml_get_errors() as $error) {
          Migration::displayMessage(self::parseLibXMLError($error));
        }
      }
      else {
        dpm('register namespace');
        dpm($this->registerNamespaces($this->currentXml)); // this then fails
                                                           // to load since
                                                           // $this->currentXml
                                                           // is not populated,
                                                           // which is most
                                                           // likely generating the error
        dpm('endr egister namespace');
      }
    }
    return $this->currentXml;
  }

Here is the output when migration is run:

Is there something that would be stopping a simple php function such as simplexml_load_file to run here?  Or could this possibly not even be the issue?  There is currently an open issue with the Migrate module for this issue,  though there is not much activity on it.

A few things had to be changed.

public function &xml() {
    if (!empty($this->currentUrl)) {

      // $this->currentXml = simplexml_load_file($this->currentUrl);

      // simplexml_load_file wasn't explicit enough, change to file_get_contents
      // then explicitly call it a new SimpleXmlElement.

      $xml = file_get_contents($this->currentUrl);
      $this->currentXml = new SimpleXmlElement($xml);

      if (!$this->currentXml) {
        Migration::displayMessage(t(
          'Loading of !currentUrl failed:',
          array('!currentUrl' => $this->currentUrl)
        ));
        foreach (libxml_get_errors() as $error) {
          Migration::displayMessage(self::parseLibXMLError($error));
        }
      }
      else {
        $this->registerNamespaces($this->currentXml);
      }
    }

    return $this->currentXml;
  }

However, the major issue was this function in xml.inc:

protected function getElementValue($itemXML, $xpath) {
    $value = NULL;
    if ($itemXML) {
      $result = $itemXML->xpath($xpath);
      if ($result)
        $value = (string)$result[0];
    }
    return $value;
  }

The if($itemXML) needs to be changed to if($itemXML->asXML()), like so:

protected function getElementValue($itemXML, $xpath) {
    $value = NULL;
    if ($itemXML->asXML()) {
      $result = $itemXML->xpath($xpath);
      if ($result)
        $value = (string)$result[0];
    }
    return $value;
  }

After applying the patch manually and changing the simplexml_load_file and the if statement in the above functions, the import works successfully with namespaces.

I re-rolled the patch mentioned earlier with my changes: https://drupal.org/comment/8260027#comment-8260027


How to Begin a French Version of My Site? I have an English site at the moment. I'd like to start a French version of it, but I get a bit confused when I look at the options out there. I am running Drupal 7.

Here's what I'd like:

When you go to example.com, it is in English. When you go to example.fr, it is in French.
There should be an option to switch from English -> French or French -> English, redirecting to the appropriate domain.
Some nodes on the English side will not have equivalent nodes on the French, and vice-versa. Some will, and some will not.
I wonder if it's possible to have different settings per site? For instance, I have a social media module that has icons for following on Twitter/Facebook etc. I'd like to have the French site show the links to the French versions of those, like my French FB page.

What would be the best way of doing these things?

Drupal support multi-language websites and creating a multi-language site is very easy.

You can configure a Drupal website to use a language other than English and you can configure a site to use multiple languages.

If your site requires the interface to be displayed in multiple languages or if you need to customize the interface of a single language site, the first step is to enable the multilingual capabilities of Drupal.

You can also configure a Drupal site to allow your users to switch languages and you can translate content into multiple languages.

Helpful Resources:

Multilingual Guide Tutorial
Building a Multi-Language Site
How To: Basic Internationalization Setup
Translating Site Interfaces
Translating Content Contributed Modules for Localization and
Internationalization
Core Modules for Localization and
Internationalization
Cookbook: Build a Non-English D7 Website
Localization API
Internationalization (i18n) module
Book: Drupal 7 Multilingual Sites (Kristen Pol)

Videos:

Building a Multilingual, Multidomain Drupal Site
Multilingual Site Setup and Management
Multilingual Module Madness! Which i18n Modules Do You Really Need?

Getting Started:

Localized Drupal Distribution: A small distribution to install Drupal with user interface translations pulled automatically from localize.drupal.org. It is suggested you use this distribution to start off with Drupal if you'd like to set up a localized site.
Internationalization: This is a collection of modules to extend Drupal core multilingual capabilities and be able to build real life multilingual sites.
Internationalization (i18n) Submodules: A collection of submodules that provides extended multilingual support for Drupal. Each module addresses a specific functionality.
Apache Solr Multilingual: The goal of this project is to cleanly extend Apache Solr Search Integration to provide: better support for non-English languages, support for multilingual search, cross-language information retrieval (CLIR), and an easy-to-use administration interface. Apache Solr Multilingual does not replace Apache Solr Search but is based on it.
Related Modules: A list of additional contributed Drupal 7 modules that extend Drupal's multilingual features


How can I reorder active menu items programmatically? I have an 'audience' menu which has 4 links. When a user visits one of these links, it becomes active, and I want to push it to the front of the menu item list. Outcomes would like like;

Pitchers | Catchers | Hitters | Coaches
Coaches (active) | Pitchers | Catchers | Hitters
Catchers (active) | Pitchers | Hitters | Coaches
Hitters (active) | Pitchers | Catchers | Coaches

How can I accomplish this programmatically? I can't seem to find the right theme_ or hook_ api function to pull this off.

I've tried this, and changing the '#original_link' weight didn't seem to make a difference (note, I have other things going on here):

function apple_menu_link__menu_audience_gateway(&$vars) {
  $element = $vars['element'];
  $submenu = '';

  if($element['#original_link']['in_active_trail'] == TRUE) {
    $element['#original_link']['weight'] = 50;
  }

  if ($element['#below']) {
    unset($element['#below']['#theme_wrappers']);
    $submenu = '
' . drupal_render($element['#below']) . '
';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '
' . $output . $submenu . '
';
}

Also, I'm using Panels, Panels Everywhere, Page Manager, and MiniPanels — this could inform the ultimate solution.

Thanks all.

You need to use hook_menu_alter.

Make sure you declare the function with the & in front of items argument, this is what allows the function to modify the $items array passed to the function:

function MYMODULE_menu_alter(&$items)

In your function you can access every menu item in an array structure like so:

   $items['node/%/edit/schedulenew'] = array(
            'title' => 'Schedule1',
            'access callback'=>'user_access',
            'access arguments'=>array('view cssswitch'),
            'page callback' => 'cssswitch_schedule',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
            'weight'=>4,
        );

If you just redefine the 'weight' property, it will allow you to re-order your menus.

Be sure to clear your cache after each menu changes, or go to the menu page, load the menu edit page and save it, this also rebuilds the menu.


How to add html head link tag when a specific block is loaded I have a custom block with its own twig template file.

I want to add an html head link tag when this block is loaded.
ex: <link rel="import" href="test.html">

In the twig template I can use attach_library to add css/js to , but I don't know how to add html imports in twig.

Is it possible to achieve this using mytheme_preprocess_block function, or any other hook?

I can add the html head link tag in mytheme_page_attachments_alter but I don't know how to limit this to only when my custom block is loaded.

Thank you.

See NodeViewController::view():

  $build['#attached']['html_head_link'][] = array(
    array(
      'rel' => $rel,
      'href' => $node->url($rel),
    ),
    TRUE,
  );

You can add html_head_link #attached elements anywhere, including in your block, and it will bubble up and be added to any page that shows your block.


hook_form_alter not running if cache enabled I have enabled the cache in Administer->Development->Performance. I have changed user profile form using hook_form_alter. But the code inside hook_form_alter strops automatically after few days. I thinks, it may be cache issue.

Everything I did in hook_form_alter is not running. I changed the submit button value. I added a custom Save and Continue button.

My Sample Code is below :

if($form_id == "user_profile_form" && $user->uid == 1) {
    $userid = arg(1);
    if(is_numeric($userid)) {
      drupal_set_message("Current User Id on site: ".$userid);
    }
   }

Attached screenshot :

Messages set by drupal_set_message() goes thorough message router and may end up displayed on another page than the one you set them. If you want to add informative element to your form, use markup Form API element instead.

if($form_id == "user_profile_form" && $user->uid == 1) {
  $userid = arg(1);
  if(is_numeric($userid)) {
    $form['info'] = array(
      '#markup' => t("Current User Id on site: !uid", array('!uid' => $userid)),
      '#weight' => -9999,
    );
  }
}


Metatags generated from views results I'm using the Metatag module to include appropriate Open Graph, etc. tags to delineate site content as it is shared on social media sites. The front page of our site is a Views Page, feature only the most recent piece of content. We would like some of the info from this featured node to be included in the meta tags for the home page of the site.

What I'm wondering is -- How can I include meta tags specific to the first result from a View?

Alternately, can anyone suggest an alternative approach to either featuring the most recent piece of content on the home page that would solve this problem?

Thanks!

Found this thread, which was very helpful:

Metatags and Commerce - pass taxonomy metatags to commerce product view

I adapted that approach to have metatag generate the tags from the first entity returned by the view:

/*
 * Implement HOOK_views_post_render to run code for each view render
 */
function THEME_OR_MODULE_views_post_render(&$view, &$output, &$cache) {
  // check for a particular view and view display page
  if ($view->name=='YOUR_VIEW' && $view->current_display == 'YOUR_VIEW_DISPLAY') {

    // retrieve the first node in the view
    $entity_type = 'node';
    $entity = entity_load($entity_type, $view->result[0]->nid);
    $language = entity_language($entity_type,$entity);

    // Generate metatags output
    if ($tags = metatag_generate_entity_metatags($entity, $entity_type, $language, 'YOUR_ENTITY_DISPLAY_MODE')) {
      list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
      $instance = "{$entity_type}:{$bundle}";

      // register the term's metatags
      metatag_page_set_metatags($instance, $tags);
    }
  }
}

Here is alternate code which doesn't rely on the Metatag module, and allows for more finely tailored meta tags based on view results:

function HOOK_preprocess_html(&$vars) {

    // only operate on the front page
    if ($vars['is_front']) {

        // get the view results
        $view_results = views_get_view_result('YOUR_VIEW_NAME','YOUR_VIEW_DISPLAY_NAME');
        // load up the first node
        $node = entity_metadata_wrapper('node',$view_results[0]->_field_data['nid']['entity']);

        // get some data
        $title = $node->label();

        // some fields may require more processing
        $description = trim(drupal_html_to_text($node->field_description->value()['safe_value']));
        $image = image_style_url('YOUR_IMAGE_STYLE',$film->field_image->value()['uri']);

        // generate and output the meta tags
        $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' =>  'og:title',
          'content' => $title,
        )
        );
      drupal_add_html_head($tag, 'og_title');

        $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' =>  'og:description',
          'content' => $description,
        )
        );
      drupal_add_html_head($tag, 'og_description');

        $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' =>  'og:image',
          'content' => $image,
        )
        );
      drupal_add_html_head($tag, 'og_image');
    }
}


Access to $content['links'] from page.tpl.php in D7 I understand how to print node fields and custom fields in the page.tpl.php files but how would I go about adding the $content['links'], (or I suppose $content['comments'], but I am really just looking for the links) like it is in the node.tpl.php?

I took a look at the node object and I don't see it in there. I would like to ultimately have the node links printed in two places, and one of the places is easiest to access from the page.tpl.php.

Well it looks like it can be pulled off with (in the page.tpl.php files):

$links = node_view($node);
print render($links['links']);

Anyone know if there is a better approach?


How to attach a library to a page controller that returns a plain Symfony response? I created a custom module with a page controller that returns a Symfony response (Symfony\Component\HttpFoundation\Response). The thing is I don't want to render my custom theme in this controller, just the theme_base template in this module.

$build = array(
  'page' => array(
    '#theme' => 'theme_base',
    '#content' => $content,
    '#owner' => $owner,
    '#cache' => [
      'max-age' => 0,
    ],
    '#attached' => array(
      'library' => array(
        'my_module/library_name',
      ),
    ),
  ),
);

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new Response();
$response->setContent($html);

return $response;

I tried attaching the module library to $build, or including it directly in Twig template but this doesn't seem to work.

Any ideas why this is not working? Or is there maybe another way I could do this?

Thanks!

After rendering of $build the attachments have bubbled up to $build['#attached'] and you can add them to a response, which implements AttachmentsInterface, for example an HtmlResponse:

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new HtmlResponse();
$response->setContent($html);
$response->setAttachments($build['#attached']);
return $response;

To place the libraries on the page you have to enclose the page in an html render element

$build = [
  '#type' => 'html',
  'page' => [
     // content with attached libraries
  ],
];

or implement the placeholders where the attachment will end up in a custom template, see template_preprocess_html().


Upload a file to Drupal server from (external) desktop client application (in c#) I have an application written in Winform (dotNet) and I would like it to Upload File to Drupal 7.
I'm newbie in Drupal. Can somebody help me please?

You may want to create something with the Services module. The services module gives you an easy way to add REST / XMLRPC services to your drupal site. http://drupal.org/project/services

See also the documentation: http://drupal.org/node/736522


views_get_view is returning some outdated version of the view When I created some_view, its Items Per Page was limited to 10. Naturally, views_get_view('some_view') was resulting in 10 nodes.

I have since changed some_view's Items Per Page to unlimited, and cleared all caches. However, views_get_view('some_view') still results in just 10 nodes.

The preview of some_view shows more than 10 nodes, so the view works as expected. It has only the Default display mode.

Although clearing all caches should have cleared any view caches (right?), I also tried views_get_view('some_view', TRUE), which is supposed to ignore the cache. To no avail.

So, where could the view returned by views_get_view be coming from?

views_get_view('some_view') doesn't actually execute the View, it just retrieves the specification for the View.

How are you executing the view?

From the comment on your question, I see that you're doing:

$view = views_get_view('some_view');
$view->execute();
print_r($view);

On this thread, merlinofchaos (the primary author of Views) recommends the following sequence:

$view = views_get_view('some_view');
$view->init_display();
$view->pre_execute();
$view->execute();
print_r($view);

which is roughly equivalent to this:

$view = views_get_view('some_view');
$view->preview();
print_r($view);

...except that the later also renders the view as HTML, which, if you're not going to use that rendered HTML, is wasteful.


Add a message to messages array using theme process or preprocess function For testing purposes, I'm trying to manually add a message to the $messages array, in either process or preprocess page function. To be clear, I first tried using

template.php -> mytheme_preprocess_page (&$vars) {}

but then I realized there's no $messages array there, so instead I am doing it via process.page.inc.

The code I have tried, which is not working is:

function mytheme_process_page(&$variables) {
    $variables[messages][] = 'new test message';
    kpr($variables);
}

I have tried some variations on this, but nothing worked.

$messages isn't an array of messages; it's the rendered output of theme_status_messages(). From the point at which you're looking to add messages (template_process_page()), Drupal has already processed all the messages it's going to render.

If you're looking to print some debugging messages you can do something like this:

function MYTHEME_process_page(&$variables) {
  drupal_set_message('new test message');

  //This will overwrite any previous messages that were to be rendered
  $variables['messages'] = theme_status_messages(array('display' => null));
}


Why does webform module uses $node->webform as a property? Why does webform module uses $node->webform as a property instead of $node->type['webform'] or something like that?

because webform is not integrated to drupal entity concept

check entity form module that is integrated with drupal entity
https://drupal.org/project/entityform


Drush command 'omega-wizard' could not be found I want to create a sub-theme with Omega using drush but I get a couple of errors.  I've been trying to solve these problems for a bit now and I need some help.  I'm using OS X and XAMPP as my local web server.

When I change directories into my site:

/Applications/XAMPP/htdocs/joshvocal/sites/all/themes

and run drush omega-wizard I get these errors:

The drush command 'omega-wizard' could not be found.  Run drush cache-clear drush to clear the commandfile cache if you[error]have installed new extensions.
Drush was not able to start (bootstrap) the Drupal database.
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See
drush topic docs-aliases for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

I think the problem has something with drush not being able to connect to my database.

I've tried:

Changing my settings.php file from host: localhost to host: 127.0.0.1
Creating a symbolic link with /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock /var/mysql.sock

When I run my drush status this is what is looks like:

I think this is what it should somewhat look like:

I want to know how to fix these errors and be able to run drush omega-wizard to create a sub-theme on omega.

Thank you for your time,

Josh

Add -d option so that command looks drush -d omega-wizard. You will see debugging information showing what causes problems.


What's needed to get Views data export working with a Block view? I have been successfully using the Views data export module to export "Page" data to CSV.

However, when attempting to do the same thing from a "Block" view, the path (required by VDE) spec'd for the CSV results in page not found. The Block does not have a specific path associated as it is included in a content page.

Does anything special have to be done to get VDE working with a Block view?

I'm one of the maintainers of the module - I run the firm that built it https://www.computerminds.co.uk/articles/views-data-exports

I've just done a quick test locally and I can't seem to replicate the issue, I have a view with a single block display to which I add a data export.  I assign a path to the data export display and attach it to the block display - and it all seems to be working fine.

Could I ask which version of the Views Data Export module you are using?


How to suppress one specific warning? I have one specific warning in Drupal 7 from the workbench module which I do not want to display. All other warnings should not be changed.

For now I edit the workbench module by comment the specific line which is not the way it should be solved for final.

I tried to use disables messages wit a specific regex but this is not working. I think because it is a warning and not a message.

I prefer to use hook_page_alter but cannot find the specific warning in the $vars array.

Any suggestion for this or what approach and possibility is there to solve this?

Solved it in Hook_preprocess_page(&$vars) {

  $all_warnings = $_SESSION['messages']['warning'];
  foreach ($all_warnings as $nr => $messageinfo) {
      if (strpos($messageinfo,"do not have permission to moderate") != false){
        unset ($_SESSION['messages']['warning']);
      }
  }


How to get image titles and source out of a view? I'm struggling hard to understand how drupal views work. With views i assembled a new front page which takes images from certain content types.

Now i'm writing a module to get the image data out of the view.

My Problem:
where can I find the images: when i write

views_get_view('viewsname');

I get an array of values but not the images.

How can i get the images out of the view properly?

If you are wanting to get Views results to use programmatically, check out the views_get_view_result() function.  If you do something like:

$result=views_get_view_result('viewname');

you can then loop through $result, which is an array of objects relating to each row, and the tried and true:

drupal_set_message('<pre>' . print_r($result, TRUE) . '</pre>');

will give you all the information you are working with.


Are there hook_functions to handle submissions from the webforms module in Drupal 6? I'm asking this question as a possible way to handle another issue I possted about ("Moving webform uploads to a non-public folderspace"). Is there a hook_function that I can use to handle the submission of a webform in Drupal 6. That is, can I use a hook to relocate a file uploaded through a webform and update the database entry to mark that upload files new place?

Take a look at these three hooks.

hook_webform_submission_presave() - which is called before saving.
hook_webform_submission_update() -  which is called after the submission is stored in database
hook_webform_submission_actions() - which provides a list of actions that can be executed on a submission.


How do I translate the Webform module form? I really see no way of translating the Webform module. Is anyone else facing this issue?

I know it is possible with locale (for the same node), or creating another node, but I really want to use the first option.

The Webform front-facing form was given the ability to be modified (and thus translated) in this issue: Make Webform multilingual (i18n) aware through contributed modules. That enhancement is already included in the latest versions of Webform, but that improvement is merely at the API-level; Webform module doesn't provide any translation abilities itself.

The add-on module that provides translation abilities for Webform is called Webform Localization, but it is currently only available as a sandbox project here: http://drupal.org/sandbox/GDrupal/1407100

The author of the module just recently (2 weeks ago) received the green-light to turn the module into a normal fully-promoted project, which will make it more easily accessible on Drupal.org.

The Webform Localization module provides two modes of translation, one that uses separate nodes and syncs certain webform settings between the nodes; and one that uses a single node and makes the strings available to translate through the i18n_strings module. The single-node approach is also what I've been advocating and I've tested that it works with this module. Only the single-node approach keeps all of the results from all languages aggregated together, with separate nodes the results are separate for each language.


How can I use the field_ui_table element in a custom module? How can I use the field_ui_table element in a custom module? Is it even possible to use it?

The following code doesn't show anything.

$form['menu_builder']['list1'] = array(
  '#type' => 'field_ui_table',
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No content available.'),
  '#attributes'=>array('id'=>'menu-builder-table'),
);

Looking at theme_field_ui_table(), the function that renders the field_ui_table element, and field_ui_display_overview_form(), a form builder that uses that form element, I can say that:

Neither #options nor #rows is used from the rendering function
Leaving out those two element attributes, the code you shown contains just the declaration of the table; it still needs to define the elements to render in the table, which the render function expects to be a list of fields.

The code adding the fields to be listed as rows of the table is quite complex.

  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $display = $instance['display'][$view_mode];
    $table[$name] = array(
      '#attributes' => array(
        'class' => array(
          'draggable',
          'tabledrag-leaf',
        ),
      ),
      '#row_type' => 'field',
      '#region_callback' => 'field_ui_display_overview_row_region',
      '#js_settings' => array(
        'rowHandler' => 'field',
        'defaultFormatter' => $field_types[$field['type']]['default_formatter'],
      ),
      'human_name' => array(
        '#markup' => check_plain($instance['label']),
      ),
      'weight' => array(
        '#type' => 'textfield',
        '#title' => t('Weight for @title', array(
          '@title' => $instance['label'],
        )),
        '#title_display' => 'invisible',
        '#default_value' => $display['weight'],
        '#size' => 3,
        '#attributes' => array(
          'class' => array(
            'field-weight',
          ),
        ),
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
          '#title' => t('Label display for @title', array(
            '@title' => $instance['label'],
          )),
          '#title_display' => 'invisible',
          '#options' => $table['#parent_options'],
          '#empty_value' => '',
          '#attributes' => array(
            'class' => array(
              'field-parent',
            ),
          ),
          '#parents' => array(
            'fields',
            $name,
            'parent',
          ),
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array(
            'class' => array(
              'field-name',
            ),
          ),
        ),
      ),
      'label' => array(
        '#type' => 'select',
        '#title' => t('Label display for @title', array(
          '@title' => $instance['label'],
        )),
        '#title_display' => 'invisible',
        '#options' => $field_label_options,
        '#default_value' => $display['label'],
      ),
    );

    // ...

  }

Yes, it is possible to use that form element, using the correct data. Since it has been written for a very specific purpose, it's easier to write code for a custom form element, if the task is not showing a table with the same degree of complexity. If the code is then used for a single form, it's even easier to create a custom table in a form.


"An AJAX HTTP error occurred" when sending an email via VBO (view bulk operations) An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=42348&op=do StatusText: OK

Running Drupal 7, using amazon SES to send emails. Get the above error message every time I send an email via VBO which is bizzare because the message response code is 200, the status is OK and the email is successfully sent.

Any idea why I might be getting these errors?

As per this issue on VBO, you likely have a separate module that is stuffing up AJAX.

Try turning your custom modules off and then back on one by one to find the problem.  If it happens with your custom modules all off, try it with contrib modules.


Override site's registration restriction on accepting invite We have a custom module that uses the invite module to send invitation to non users. Our site is set to allow registration only by administrator to avoid spam. When the invitees accept the invite they cannot register as its not allowed by the site. Is there a way to override registration restriction when invitees try to register?

We are looking into duplicating registration form on another route then routing the invitees to register there instead of default route.

Any other suggestions to handle this situation?

This is a bit hacky, but it could be done with the following:

  my_website.com/admin/config/people/accounts

  Who can register accounts? - Visitors

  Install https://www.drupal.org/project/redirect and add redirect /user/register to a basic page which says something like "Sorry, to register you need an invite. Please contact us to receive an invite."

Invited people can now log in to site but there is no way for people to access the user register page, as that page will redirect.


Stylize Field based on Boolean value In Views showing as a table, I have 3 fields, field_checkbox1, field_checkbox2 and field_checkbox3,  and values set to either Yes or No.
I need to add color to them, if the checkbox is set to Yes(on, checked, "1" or any other value that denotes a positive value that Drupal recognizes) the border of its  should be set to "2px solid #00ff00".
*****************************EDIT******************************

Which css file (there are 6) governs class="views-field views-field-field-checkbox1 green"? How Macro do I have to get?

Add class to views (Advance -> Class) and then through css, do something like this:

.className .Alpha["value=1"]{
      border: 2px solid #0f0;
}
.className .Alpha["value=0"]{
     border: 2px solid #f00;
}

Value may slightly differ and you can simply check it through "inspect" of your browser's contextual menu.