Ajax InvokeCommand with custom Callback Primary tabs View(active tab) I tried to do a what described in https://api.drupal.org/comment/56868#comment-56868, but for Drupal 8.

Drupal.behaviors.corsFileAutoUpload = {
  attach: function (context) {
    $(context).find('input[type="file"].s3fs-cors-upload').once('auto-s3file-upload').on('uploadToS3', Drupal.s3fs_cors.uploadToS3);
    },
}

To invoke this from PHP, I used the following code.

$response->addCommand(new InvokeCommand($selector, 'uploadToS3');

But I got an error from core/misc/ajax.js line number of 1266, as the method for the element is not available. On inspecting eventlistener in Chrome, it was very well visible and I was also able to fire it from Browser Console.
I am missing something here. How do we call a custom jQuery function using InvokeCommand?

In the JS side try with this:

(function($) {
  $.fn.uploadToS3 = function() {
    // Your code here.
  };
})(jQuery);

the PHP part looks ok to me.

What's your selector, where you're trying to trigger the method ?? This won't be available according to your error. I guess you have an event/method mixup.

To trigger a custom event do something like:

new InvokeCommand('html', 'trigger', array(
  'your_bound_event',
  array('param1', 'param2'),
)));

And in your behavoir:

$(document).on('your_bound_event', function(ev, param1, param2) {
  console.log('hit');
});


I'm new to object oriented php. Trying to query database but not getting any results I am trying to query a table in my DB and am not able to get any results back.  Here is the code I am using:

function get_agent_info($agent) {
        $query = db_query("SELECT * FROM tls_connect_stage_timer WHERE '".$agent."' IN ('start_processing_agent' || 'end_processing_agent')");
        $rows = array();
        foreach ($query as $result) {
            $rows[] = array(
                $result     -> applicant_id,
                $result     -> stage,
                $result     -> event_start,
                $result -> event_end,
                $result     -> start_processing_agent,
                $result     -> end_processing_agent,
                $result     -> start_request_ip,
                $result     -> end_request_ip,
                $result     -> gwf,
            );
        }
        print_r($rows);

    }

I have already used a method like this to get info:

$results = db_query("SELECT * FROM tls_active_applicants WHERE `".$searchParams."`='".$input."'");
$rows = array();
                 foreach($results as $result){
                    $rows[] = array(
                        $result -> first_name,
                        $result -> last_name,
                        $result -> gwf,
                        $result -> visa_type,
                        $result -> current_stage,
                    );
                 }

The second one works fine, where with the first one, if I print_r($rows) it returns an empty array.  Why is the foreach loop starting in the first example but not the second?  I've tested the query, and it works fine. Also any links that could help me understand how the foreach loop is working would be greatly appreciated.  I assumed that since it's saying $query as $result, I would be able to pull a single value saying something like $query->stage but that didn't work.  I'm assuming because there are several entries I would need to do something like $query[0]->stage but I don't really know how that works when it comes to calling properties..

I won't address your question specifically...because you're doing it wrong, and that should stop here :)

This is very, very bad:

db_query("SELECT * FROM tls_connect_stage_timer WHERE '".$agent."' IN ('start_processing_agent' || 'end_processing_agent')");

You should never concatenate data into an SQL string, you'll leave yourself ripe for injection attacks.  This one is even worse:

db_query("SELECT * FROM tls_active_applicants WHERE `".$searchParams."`='".$input."'");

As you're liable to injection attacks from both the field name and the argument.

If you want to use dynamic field names you should use the SelectQuery class, accessible via db_select(). E.g.

$values = array('start_processing_agent', 'end_processing_agent');
$query = db_select('tls_connect_stage_timer', 't')
  ->fields('t')
  ->condition($field_name, $values);

$rows = $query->execute()->fetchAll();

You'll need to make some changes to the above for your specific query, but that's the general idea.

You are messing things up. Build a query with db_select. https://drupal.org/node/310075


The missing phpmailer module I updated a site with "Composer update --with-dependencies"
and encountered the following problem:

User warning: The following module is missing from the file system: phpmailer in drupal_get_filename()

Then I ran: composer require drupal/phpmailer.

Terminal returned:

Using version ^3.0@beta for drupal/phpmailer
./composer.json has been updated

And

Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

But the Status Report still showed that phpmailer module was missing.

So I attempted running "drush en phpmailer -y"

And it returned:

phpmailer was not found.                                             [warning]
The following projects provide some or all of the extensions not     [ok]
found:
phpmailer
Would you like to download them? (y/n): y
This codebase is assembled with Composer instead of Drush. Use       [error]
`composer update` and `composer require` instead of `drush
pm-updatecode` and `drush pm-download`. You may override this error
by using the --pm-force option.
phpmailer was not found.                                             [warning]
Unable to download some or all of the extensions.                    [warning]
There were no extensions that could be enabled.                      [ok]

What can I do to fix this?

There is a module for that: https://www.drupal.org/project/module_missing_message_fixer

And you can try drush or devel according to the doc here https://www.drupal.org/node/2487215

Use Drush

drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='module_name';"

When done, clear the site's caches (e.g. drush cr).
Also make sure that the CMI folder is cleansed of the broken uninstalled module. There may be some yml files left over and / or some system config. (this is all not the best way to do things as a FYI. However with Drupal 8 being so young, things don't go as planned always).

Use Devel

Enable Devel module and go to /devel/php. This will allow you to run some PHP code and you can execute the following:

$query = \Drupal::database()->delete('key_value')
    ->condition('collection', 'system.schema')
    ->condition('name', 'module_name')
    ->execute();


How to insert ® value in database I am inserting users from drupal6 to drupal7 using a custom script. I am using db_insert function.
In one of the D6 entry I am getting ® mark in a field and because  of this that particular value become blank in D7 database.
D6:  imatter®    ->   D7:

Anyone has any idea about how to insert this value in database?

Collation is same in both database: utf8_general_ci
And in phpmyadmin its look like same as above, means no html code for ®

In the case that your insertion script is not capable of handling UTF-8 encoding (it sounds like this is the case), you can get around this by inserting this character as 7-bit HTML entities (i.e. &#174; or &reg;) provided the field where it appears is going to be rendered as HTML (and not as plain text).  Just do a search and replace and replace all occurences of ® with &#174; in the source text file.

If this workaround doesn't work (because the field is supposed to be plain text, or for some other reason), you must do two things:

Make sure your file containing these characters is UTF-8 (not ISO-8859-1 or some other encoding incompatible with UTF-8).
Make sure your insertion script is capable of handling UTF-8 (db_insert is, but I don't know what other components you use).

Try utf8_encode before store you variable

$username=$olduser.'®';
$newusername =  utf8_encode($username);

or Drupali method

$username=$olduser.'®';
$newusername =   drupal_convert_to_utf8($username,'utf-8');


How to display an image in a Views RSS feed I am trying to display an image in a Views RSS feed.

I have added the following fields to my View: field_image,
field_title, field_twitter (These fields come from my node).
I then set all fields to "Exclude from display".
I then create a new field in Views called "RSS Content".
I then place tokens for all the fields (from step 1) into "RSS Content".
Finally, I go to "Views >> Show >> Settings". In the drop down menu for "Description field", I select "RSS Content".

When I look at my RSS feed, the image field is displayed like this:

    <description>
&lt;img src=&quot;http://example.com/sites/files/nodes/content/images/intro/two-hearts-1312984-1280x960_0.jpg&quot; /&gt;
</description>

How do I get the image to display properly, instead of the image tags being escaped?

First add the Media RSS namespace to your views-view-rss.tpl.php

<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?> xmlns:media="http://search.yahoo.com/mrss/">

Then add the  tag to your views-view-row-rss.tpl.php

<media:content url="<?php print image_style_url('my_img_style_id', $node->field_image['und'][0]['uri']); ?>" type="image/jpeg" medium="image" height="800" width="600" lang="en" />

Lastly make the field data available to your theme's template

function mytheme_preprocess_views_view_row_rss(&$vars) {
  $view     = &$vars['view'];
  $options  = &$vars['options'];
  $item     = &$vars['row'];

  // Use the [id] of the returned results to determine the nid in [results]
  $result = &$vars['view']->result;
  $id   = &$vars['id'];
  $node   = node_load( $result[$id-1]->nid );
  $vars['node'] = $node;
}

Original article: https://blog.sam-thompson.info/images-in-drupal-rss-feed-without-additional-modules/

wrap it on CDATA  tags.

CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be.


How can I avoid to return HTML markup for access denied? I've developed a custom controller that serves as a simple endpoint, POST method.
This controller has custom access control.
Custom access is done by looking for a header in the HTTP request, by making the controller object a service as well.
Everything works great. Except that when I return AccessResult::forbidden() .. I get the HTML of the access denied page .. and I don't really want that .. I'd like to return just a short bit of JSON.
What can I do to return something that is JSON, and not the Access Denied page HTML, for this particular route, when the access() method returns AccessResult::forbidden() ?
I've read that appending ?_format=json to the url works, and in my case it does. Is there anyway to achieve the same result without adding this url parameter?

If you look into ParagraphAccessControlHandler you will find something similar.
Implement something similar in your Access callback.
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {

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


How to update cart after deleting line items? I have an Application (app) node that when it gets created (hook_node_insert) I add line items (based on info in the app) to my cart. This works great.

Step 2 now is that when I add a new app, I would like to empty the cart (or remove the line items) before adding the new line item (so there is effectively only ever 1 item in the cart).

If I try to do $item->delete() or $cart->delete() before I add the new line item (in my node insert hook) then I get this error:

  Drupal\Core\Entity\EntityStorageException: A cart order for type
  default, store 1 and account 1 already exists. in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 847 of
  core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php).

If I delete the line items after I add the new line item; then the cart almost looks correct. It shows only my new line item and the subtotal is the amount of my new line item; but the Total shown is the combined Total of the new line item added to the old line items (which have been successfully deleted).

My guess is there is something I need to do to "refresh" the cart after adding and then deleting line items?

instead of using $item->delete() this works:

  $cart_manager = \Drupal::service('commerce_cart.cart_manager');
  foreach($items as $item) {
    //$item->delete();
    $cart_manager->removeOrderItem($cart, $item, TRUE);
  }

the 3rd parameter is 'save cart' and setting it to TRUE updates the cart Total.


Always show next page link in pager function mythemename_pager_next($text, $limit, $element = 0, $interval = 1, $parameters = array()) {
  global $pager_page_array, $pager_total;
  $output = '';

  // If we are anywhere but the last page
  if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
    $page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);
    // If the next page is the last page, mark the link as such.
    if ($page_new[$element] == ($pager_total[$element] - 1)) {
      $output = theme('pager_last', $text, $limit, $element, $parameters);
    // The next page is not the last page.
    } else {
      $output = theme('pager_link', $text, $page_new, $element, $parameters);
      //$output = '

';
    }
  }

  return $output;

}

How to make NEXT PAGE link visible on last page? For example we have 3 pages and i am on the 3rd page and i should see NEXT page link. Please assist to me with function above, thanks!

The line

if ($page_new[$element] == ($pager_total[$element] - 1)) {

Will never fire because of the earlier line:

if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {

So if the current page is equal to (or higher) then the last page it will skip the whole code.

Try removing that line (and the corresponding closing bracket }).
I hovever don't know if it will keep working then because the following function seems to be assuming it can never load a pager higher then the current page. So prepare for some unexpected behavior.

$page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);

You need to redeclare two functions

theme_pager_previous
theme_pager_next


How to group facets (Facet API) by day for date fields? How to group facets (Facet API) by day for date fields?
Currently I have a custom date field indexed by Search API Solr.

I want to group this values by day, for example:

Friday 26 june
-08:30
-08:45
Saturday 27 june
-08:30
Sunday 28 june
-08:30

Use the numeric_groups module. It is a sandbox project.


Menu callback rendering node xxx I want to render node/7 on /mymodule/info. I don't want to use path to cover it. What callback function shall I use?

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

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => ?????????,
    'type' => MENU_CALLBACK,
   );

  return $items;
}

You have to call the same callback issued from node/%node menu i.e. node_page_view :

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

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => 'node_7',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function node_7(){

include_once(drupal_get_path('module','node') . '/node.pages.inc');

return node_page_view(node_load('7'));

}

Try

function mymodule_menu() {
  $items = array();
  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => 'rendernodeseven',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function rendernodeseven() {
    print_r(node_load(7));
}


How to show loader image before popup screen of color box module in drupal 7 I used color-box module in my current drupal project for showing user details in popup after click user image. It will take some time to show details so I want to show loader images before this. I tried to override this using drupal.behaviors but cannot get proper output. If any idea how to handle this situation then please help me for same.

Thank you.

Hope this will help you,

You can use Colorbox Callbacks

onOpen : Callback that fires right before Colorbox begins to open
onComplete : Callback that fires right after loaded content is displayed

jQuery.colorbox({
........
  onOpen:function(){
    //show loader
  }
  onComplete:function(){
   //hide loader
  }
});


Programmatically do something when a node is updated I want to do something when a node gets updated. To keep it simple, lets say display a drupal message.
hello_world.routing.yml
hello_world:
    path: /node/{node}
    defaults:
        _controller: Drupal\hello_world\Controller\HelloWorldController::hello_world_entity_update
    requirements:
        _permission: 'access content'

Not sure if the path should be /node/{node}/edit instead.
HelloWorldController.php
<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloWorldController extends ControllerBase {

  public function hello_world_entity_update(Drupal\Core\Entity\EntityInterface $entity) {

    drupal_set_message(t('Something @var just happened.', array('@var' => 'cool')));

  }
}

Since hook_node_update() was depreciated, I assume we now have to use hook_entity_update().
I am not getting the message upon updating a node, what I'm I missing or doing wrong?

Update

Just so I don't confuse anyone.
I was brainwashed into thinking I needed a routing file and a
controller. All the D8 examples out there use them.
Since I was not creating any pages,
turns out I did not need a routing.yml file nor a Controller.php file
nor the /src folder. All I had to do is approach this like Drupal 7,
all that I needed was the .info.yml file and a .module file
to put the hook.

Hooks are still implemented as global, procedural functions; you need to declare them in the .module file just like Drupal 7, not in a controller class:

function MYMODULE_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // ...
}

The system will move to OO in Drupal 9.

It's also worth noting that hook_ENTITY_TYPE_update() also exists, so you can still use hook_node_update():

function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  // ...
}

There are lots of hooks are available for node.

You can inherit in template.php file and write down your code.

you can use hook_node_update in template.php


webform date popup format I have a webform with a popop date the problem is the date in the textbox is shown in the format

2014-7-30

it need it to be

30/7/2014

how can I change this?

I use webform 7.x-3.20 it doesn't give text box option for date field rather it show select list except for year. If in your case it showing textbox make sure the configuration is as followed.

You can create new date format under date and time settings, Go to admin/config/regional/date-time/formats

Add new format in the form j/n/Y it will show date as 30/7/2014.

Under webform date field setting choose the Default value timezone to "Website timezone"

P.S If you want to reorder select boxes then see: Re-ordering the elements of a Drupal Webform Datepicker


How to change the text of the "checkout" button in Drupal commerce cart? How can I change the text of the "checkout" button in Drupal commerce cart?

I need it to be "continue" instead.

thanks

   function rooms_form_alter(&$form, &$form_state, $form_id) {
      dsm($form_id);  // print form ID to messages
      switch ($form_id){
            case 'views_form_commerce_cart_form_default':
                $action['#value'] = 'continue';
            break;
      }
    }

By using the hook_form_alter() function, you can change the text of the buttons. It would be something like

$action['#value'] = 'continue';

Please provide us with more code so I can work out a decent example.

//exact code goes here

/*
I have also removed the update cart button here as I dont need you, you must have that code if you want it.
*/

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

  if (strpos($form_id, 'views_form_commerce_cart_form_') === 0) {

    // Only alter buttons if the cart form View shows line items.

    $view = reset($form_state['build_info']['args']);

    if (!empty($view->result)) {

      // Unset update cart button as we dont need it.
      unset($form['actions']['submit']);

      //Change the name of checkout to - Delivery
       $form['actions']['checkout']['#value'] = t('Delivery');
       $form['actions']['checkout']['#submit'] = array('memento_checkout_form_submit');

      // Change any Delete buttons to say Remove.
      if (!empty($form['edit_delete'])) {
        foreach (element_children($form['edit_delete']) as $key) {
          // Load and wrap the line item to have the title in the submit phase.
          if (!empty($form['edit_delete'][$key]['#line_item_id'])) {
            $line_item_id = $form['edit_delete'][$key]['#line_item_id'];
            $form_state['line_items'][$line_item_id] = commerce_line_item_load($line_item_id);

            $form['edit_delete'][$key]['#value'] = t('Remove');
            $form['edit_delete'][$key]['#submit'] = array_merge($form['#submit'], array('commerce_cart_line_item_delete_form_submit'));
          }
        }
      }

    }
    else {
      // Otherwise go ahead and remove any buttons from the View.
      unset($form['actions']);
    }
  }
}


adding yet another domain to multi-site but this time symlink not working Have no idea what's going on here. I'm trying to add another new domain to my multi-site but keeps directing to apache test page - not install.php.

Have many subdomains installed now and one new domain added to root one but this next one is giving me problems for some reason. Everything has been done same way. Set up in server to point to IP; separate database created; name of domain in sites folder created with default.settings.php copied to it as settings.php and chmod 644 then a symlink from the /var/www/html folder to the sites one but as I say just keep getting apache test page. Not found if try going to install.php. This is happened to me before but don't have a thorough understanding why...i am suspecting has something to do with database- not sure.

This has nothing to do with your database. At this point you have probably a problem completely unrelated to Drupal. Instead your Apache is not aware of your Drupal installation.

Here is a list of things you should check:

Is that domain we're talking about pointing to your server (or do you see the test page of a different one): compare IP by ping yourserver.com

If it's a "testdomain" you might want to add an entry to /etc/hosts

Is your virtual host configured correctly?

Did you set a ServerName or a ServerAlias
If you were setting up a new VHost, did you enable it (sudo a2ensite yourhost for instance)
Did you restart Apache/reload configuration after doing this (sudo service apache2 reload)?
Did you configure your VHost/your root directory to follow symlinks?
Have you set NameVirtualHosts?

Are your symlinks pointing to the right folder?

Do you get the contents of your settings.php by typing cat /var/www/html/sites/symlink/settings.php in a terminal or an error?

As an example:

<VirtualHost *:80>
  ServerName yourdomain.com
  ServerAlias sub1.yourdomain.com sub2.yourdomain.com # etc ...
  DirectoryIndex index.php
  DocumentRoot /var/www/html
  <Directory /var/www/html>
    AllowOverride All
    Options -Indexes FollowSymLinks Multiviews
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Again, it's most probably not Drupal related. It would be if you'd see a different one of your multisites or Drupal complaining about something but since you got the Apache test page you might want to ask on a different board (serverfault) and provide some more information (OS, directory structure, current host configuration and so on) if my checklist didn't help you.

I just worked it out but thank yu for above important list of reminders.

Was symlinking to sites folder instead of drupal folder- knew it was something simple.

So logical and yet totally passed over my head ;o


How can I retrieve the current node ID on a custom route? I have a new route and the yml file looks like this:

rsvplist.form:
  path: '/rsvplist'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'

From the module root directory, I have src/Form/RSVPForm.php, and inside is where I have the build form function that looks like the following:

public function buildForm(array $form, FormStateInterface $form_state) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->nid->value;

    $form['email'] = [
        '#title' => t('Email Address'),
        '#type' => 'textfield',
        '#size' => 25,
        '#description' => t('We will send updates to the email you provide.'),
        '#required' => TRUE,
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('RSVP'),
    ];

    return $form;
}

When I clear the site cache and refresh the page: mylocal.com/rsvplist, I see the following error:

Notice: Trying to get property 'nid' of non-object

I initially used the following code to get the node

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;

If I change the last piece of code to this:

$nid = $node->id();

I see the following error:

Error: Call to a member function id() on null

How can I get the node id when am on the new route?

Reference here

Your route doesn't have a parameter called node, so therefore $node is null.

In order to make node available as a parameter you have to be on a route that has node as a parameter.

So to add the node parameter to your route, you can do like this:

rsvplist.form:
  path: '/rsvplist/{node}'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'
    _entity_access: 'node.view'
    node: \d+

And then you can add the $node parameter to your buildForm method, like this:

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  // Your form.
}

Since I added node: \d+ to your form, $node is now the loaded entity in the buildForm method.

You can try code

rsvplist.form:
  path: '/rsvplist/{nid}'
  ....

use Drupal\node\NodeInterface;
....
$nid= \Drupal::routeMatch()->getParameter('nid');
$node = Node::load($nid);


How to scale uploaded image in ckeditor I am using CKEditor, and am having a problem with the scaling of the images during edit.  When I upload and insert them into my editor, if the image is very large, it displays that way in the editor, making it very hard on the user.

I have formats defined for these image styles, which set the class attribute to a CSS class.

Is there a way to get images in the editor to adhere to the CSS of their format, so the page layout during edit resembles what it will look like after being saved?

In the latest version of the ckeditor library there is the new Enhanced Image plugin.
This plugin allows you to resize the inline image by dragging the image corner.
Go to ckeditor building website ( http://ckeditor.com/builder) and select the Enhanced Image plugin (image2) and also deselect the standard Image plugin from the build.

I was able to do this with the Picture module.


How can I use Drush to determine if a module is being used or not in a multisite architecture? I have a multisite architecture that has over 30 sites.

In one specific site search_api_solr version 7.x-1.0RC5 is installed, and I can see that it's enabled and being used in the module list.

In the common sites/all/modules folder search_api_solr 7.x-1.0-rc2 is there. When I do drush pm-list | grep search I can see that it's listed but "Not Installed."

Does this mean that none of the 30+ sites is using this module and it's safe to delete it? Or is that command simply telling me that it's not being used by the default install?

If the latter, how can I use Drush to tell me what specific sites are making use of modules in the common sites/all/modules directory?

EDIT:

@greg_1_anderson

I tried your solution with:

drush @sites pm-info search_api_solr --field=status

On each line of the output after hitting y I get something like:

.appdrupal#mysite.example.com >> blahblah : some.description

looks like the above output is 3 columns. Possible values for that 'blahblah' column seem to be numerous (requires, required by, type, title, description, version, date, package, 'group', files.. etc, etc..) nothing to denote if it's enabled)

I can see a couple times in the 'blahblah' "status", but it's not singled out. Ultimately this creates 1000s of lines of output. I tried to add | grep status but it hanged (I gave it 120 seconds).

Drupal is 7.26 and Drush version is 5.9 - thoughts?

This works in Drush 6.x and later:

$ cd /path/to/drupalroot
$ drush @sites pm-info MODULENAME --fields=status
You are about to execute 'pm-info devel' non-interactively (--yes forced) on all of the following targets:
  /path/to/drupalroot#default
  /path/to/drupalroot#other
Continue?  (y/n): y
.path.to.drupalroot#other   >>  Status   :  enabled
.path.to.drupalroot#default >>  Status   :  enabled

You need to either set up Drush aliases, so you can run your command against all of the multisite's individual sites at once (as Clive suggests) or you can cd into each individual site (on D7, usually drupalroot/sites/A_SITE/) and run the command so it's checking using that individual site's configuration and not the default site's configuration (which is usually at drupalroot/sites/default/.


Show a block within node content (field template) based on context/taxonomy? I've created a block using Views that I want to display only on nodes that have a specified value for a taxonomy field (no taxonomy info in the URL). The catch is that I want to display it within the main content (between certain fields), not above or below the main content. I've tried doing this in various ways, but none of my attempts have quite gotten what I needed.

Using one method, I managed to use pre-processing functions and the specific field template for the field (field--body--story.tpl.php) to get the block to show up in right place, but it showed for all the nodes of that content type. I tried evaluating for other fields' values within mytheme_preprocess_field, but those field values don't seem to be available within that function? (They don't show at all using dsm($vars) on the page, I think because the display of that field is hidden.)

Using another method, I used the Context module to get the block to show up only on the nodes of that content type that had that field set to the desired value, but then I could only get it to show above or below the main content, not between specified fields within the main content.

I'm new to Drupal (but am otherwise an experienced web developer), so I'm probably over-complicating this and/or not understanding some major concept. I'm sure there is an elegant way to do this, but I just can't get it (at all, much less elegantly). What am I missing?

you can do what i did before :

-1 install computed field module and enable it.

-2 you have to call the specific views that you want in computed field like this way

<?php
$view = views_get_view('your_views_name');
$view->set_exposed_input();
$display_id = 'default';
$view->set_display($display_id);
$view->render();
$entity_field[0]['value'] = ($view->preview());
?>

Did you tried Entity View Attachment (EVA) and adding a PHP Condition (that returns true only on your desired case) to the view? Then you add that whenever the condition is NOT satisfied the view doesn't display anything.

Maybe it would be the way to go.


How to add a 'flag link' in an email? I want to add a 'flag link' in an email. I have an event content type, and every time a new event created, the users get an HTML Email. I have a flag that the users can flag this event if they want to attend. I want to embed the flag link in the email, so that the users click the link and redirected to the flag confirmation page.

I've tried that with flag_create_link() in the email-template but it has two problems that makes it unusable in an email. First, I'm getting 'Bad token' error if click the link in the Email. Second, the URL generated is a relative URL, so I had to manually change the URL in browser to test, which got me to the first problem.

Is there any proper way to embed a flag link in an Email? So that, the user can click and directed to the confirmation page of the flagging, or login page if he's not already logged in.

UPDATE:

I've changed the link type to 'confirmation form' and that solved the first problem. I'm not getting 'Bad token' error anymore. However, the link path is still relative.

With the following code I managed to create the flag link to embed in the email body:

global $base_url;
$flag_url = $base_url . base_path() . 'flag/confirm/flag/my_flag/' . $nid;

You can try to strip any tags getting in your way:

strip_tags ( string $str [, string $allowable_tags ] )

http://my1.php.net/strip_tags


Customizing the node create form using a template file I have created a template file for my content type, but I don't know how to get form design in that page.

My content type name is wallpaper, and I created the page--node--add--wallpaper.tpl.php template file. How do I access the node title, or the node body, in the template file?

If you want to design the form then use hook_form_alter you will get form array. If you want to design the node page then user node--content_type.tpl.php.

node.tpl.php is the base node template.

If you look at the source code you can find all variables to render values in that .tpl file.

Available variables:

$title: the (sanitized) title of the node.
$content: An array of node items. Use render($content) to print them all,
or print a subset such as render($content['field_example']). Use
hide($content['field_example']) to temporarily suppress the printing of a
given element.
$user_picture: The node author's picture from user-picture.tpl.php.
$date: Formatted creation date. Preprocess functions can reformat it by
calling format_date() with the desired parameters on the $created variable.
$name: Themed username of node author output from theme_username().
$node_url: Direct URL of the current node.
$display_submitted: Whether submission information should be displayed.
$submitted: Submission information created from $name and $date during
template_preprocess_node().
$classes: String of classes that can be used to style contextually through
CSS. It can be manipulated through the variable $classes_array from
preprocess functions. The default values can be one or more of the
following:

node: The current template type; for example, "theming hook".
node-[type]: The current node type. For example, if the node is a
"Blog entry" it would result in "node-blog". Note that the machine
name will often be in a short form of the human readable label.
node-teaser: Nodes in teaser form.
node-preview: Nodes in preview mode.

The following are controlled through the node publishing options.

node-promoted: Nodes promoted to the front page.
node-sticky: Nodes ordered above other non-sticky nodes in teaser
listings.
node-unpublished: Unpublished nodes visible only to administrators.

$title_prefix (array): An array containing additional output populated by
modules, intended to be displayed in front of the main title tag that
appears in the template.
$title_suffix (array): An array containing additional output populated by
modules, intended to be displayed after the main title tag that appears in
the template.

Other variables:

$node: Full node object. Contains data that may not be safe.
$type: Node type; for example, story, page, blog, etc.
$comment_count: Number of comments attached to the node.
$uid: User ID of the node author.
$created: Time the node was published formatted in Unix timestamp.
$classes_array: Array of html class attribute values. It is flattened
into a string within the variable $classes.
$zebra: Outputs either "even" or "odd". Useful for zebra striping in
teaser listings.
$id: Position of the node. Increments each time it's output.


How to set/display select options in selectbox using form-api I have created a form to allow users to enter some details but I also need to display some mysql data into that form. The contents and fields of the form are displayed in a tabular format. I just want to know the right way to display mysql data in one of the table columns along with the form fields.
How can i display select options in selectbox using form-api ?

You can make use of theme_table to make a table view.
You can use form-api inside the table as you wish.

Sample code for creating table.

$header = array();
$rows = array();
$rows[] = array(
    array('data' => 'Head1', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head2', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head3', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head4', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head5', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head6', 'colspan'=> 6, 'header' => 1),
);
$rows[] = array(
    array('data' => 'SubHead6-1', 'header' => 1),
    array('data' => 'SubHead6-2', 'header' => 1),
    array('data' => 'SubHead6-3', 'header' => 1),
    array('data' => 'SubHead6-4', 'header' => 1),
    array('data' => 'SubHead6-5', 'header' => 1),
    array('data' => 'SubHead6-6', 'header' => 1),
);

return  $output .= theme('table', $header, $rows);

To make a select box with db values you can try this

$query = "SELECT * FROM {tablemanme}";
$query_result =  db_query($query);
while (($data = db_fetch_object($query_result )) !== FALSE) {
  $opt[$data->id] = $data->name;
}

$form['select'] = array(
    '#type' => 'select',
    '#options' => $opt,
);

Good luck.

You can check on this link

http://public-action.org/content/drupal-7-form-api-drupal-7-multi-step-form-fapi-table-report

It gives you complete idea of displaying data in tabular form


Contextual filters exclude option missing I've downloaded the drupalcommerce kickstart but when adding a contextual filter to my view, the "exclude" option is missing.

when I expand the "more" at the bottom the only options are: Allow multiple values and administrative title

do I have to enable the option somewhere before I can access it?

I'm trying to make a list of nodes of the same type, excluding the current node...

The exclude option is a part of the views_handler_argument_numeric handler that comes with views.  If it's not there, it likely means your filter is operating on something other than a numeric argument.  What you have is "Indexed Node: Node ID".  If you create a filter on "Content: Nid" instead then you should see the option.

Also see https://www.drupal.org/node/733686 .

In the configuration screen for your Conceptual filter, go to the bottom and click on More, then select Exclude. There is no other way that I know of, and there is no option to activate it.

Make sure that the install of the Views module is clean and the most up to date version, and run update.php to make sure that all updates have been done. then look for it again.


Media + WYSIWYG or ICME + CKeditor I need to build quite feature rich set of tools for file & media management both for embedded and stored files in a new D7 project. Media will be added to both fields and in the WYSIWYG and File manager is a must.

In the past I have always been working with a combo of CKeditor, IMCE, CKeditor Link, FileField Sources.

However there seems to be a lot of buzz around TinyMCE via the WYSIWYG module and Media modules. In short what am I missing out on with these new projects? They seem to have a big overlap on the above and was wondering if people have experience with both...

Should I be looking to change my toolset to WYSIWYG / Media combo?

Pantheon is now offering Panoply, a distribution built on Panels that features TinyMCE via WYSIWYG as well as the media module already set up and ready to go.  You can register for a free account with them and test out a pre-built version of Drupal with the modules already set up in a fairly intelligent configuration.

Disclaimer: I'm a Pantheon customer, but I really do think that trying out this distro is a great way to see a hands-on example of what can be done not just upon installing a bunch of modules but after someone has taken the time to polish up the site.

I see no inconvenient in using WYSIWYG rather than install TinyMCE by hand. TinyMCE and CKEditor are the only which support IMCE integration using IMCE Bridge module. You should use these 4:

WYSIWIG module
TinyMCE or CKEditor
IMCE
IMCE Bridge


How to make payments on recurring product automatically(RESOLVED) I have drupal 7 and commerce modules. I'm using Stripe payment system with module commerce_stripe. Customer's card details are stored in file (commerce card in file).
Site sells recurring products.

My question is:
can I make payments on recurring products automatically without user agreement?
And if I can how should I do it?

Thanks in advance.

UPDATE

Found how recurring entities and card on file work. After user bought subscription first time his card data saves into file to use it in later payments. When user should pay for subscription again cron commerce_recurring_cron should run. This cron checks recurring entities and if it's time to pay creates an order with status pending.

When this cron runs once again it charges payments and necessary amount of money debited from users account.

So everything I need is processed and my customer is happy.

If you're using the Card on File module, that means you're storing tokens that point to card data stored securely by the payment gateway itself. What you then need is to combine that with Commerce Recurring or the Commerce License suite to create the schedule for recurring charges and Commerce Dunning to react to payment failures.

Storing credit card details isn't very safe and allowed unless you have an application which is PCI complied and as well the hosting.

Anyway, as you are using Stripe, you should have a look at this: https://stripe.com/subscriptions


Override field value in view? I have a content type for events. There is an optional field where the user can provide a link that overrides the default link to the event.

For all of our internal events, the link should take website users to the node of the event. However, for events that are held elsewhere by third parties, the link should take the website user to whatever external link is official for that event.

I'm having difficulty creating a single link field in a view that is the value of the external link, unless there no value, in which case it falls back to the node link.

I can make a re-written field that is [override_link][path], but that always shows the path, no matter what. I only want the path when there is no override_link value.

This is in a Drupal 7 site.

The easiest way IMO to do this is to use the views field template. Here is a very detailed and helpful tutorial on DO. You can find the field template's name in the views theming tab under the advanced tab.

In terms of implementation for your use-case, the field's $output in the template would be empty if there is no link, and then you can change $output to be the link to that node (which you should be able to access with $row->nid).

I don't think this is the best solution, so becarefull. I always use Views PHP. This module adds a "Global PHP field" in the views fields, where yo can use PHP to return the value that you need. In this Global PHP field, you will have access to data of others fields as an array in $data variable.

Check this.

Hope this help.


How do I add javascript to a node or block I've made a cost calculator script and want to use it on my Drupal 7 site.

I heard to use drupal_add_js, but I don't know in what context.

Use a function in the template.php file: yoursite.com/sites/all/themes/YOUR_THEME/template.php

Add JS file in a block:

function YOUR_THEME_preprocess_block(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
}

Add JS file to one page or node:

function YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
  }
}

Add JS file to a content type:

function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

Add JS file to a view:

function YOUR_THEME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

As mentioned by @Pierpaolo Cira, you could always replace MY_THEME with MY_MOUDLE. To get the path to your module you would have to use drupal_get_path('module', 'my_module').

Note: MY_THEME and MY_MODULE needs to be lowered case if your module or theme name is lowercased. (E.g. MY_THEME would be replaced with zen if zen)

Source

if your script is saved as .js you can add it like that in html.tpl.php:

<?php drupal_add_js('location/of/my/script/my_script.js'); ?>

more info  here

OR

<script src="location/of/my/script/my_script.js"></script>

in your block or node body (make sure that you select format that does not filter JavaScript i.e. "PHP code")


How to set Class for a particular image style? I'm trying to add a CSS class to a particular image style, in Drupal 8. For this purpose, I'm trying to set up a template, but am open to all solutions since I know I lack knowledge (I've been teaching myself this stuff over the past couple of months).

Specifically, I want all images with the style machine name 'feature_main_960_x_640_' and field machine name of 'field_image' to include the following class during 'Full content' view mode. I would like this class to be added to the img tag.

The purpose: to have my articles' feature images to be centered when the full content is being viewed.

Specifications:
Drupal 8, theme is Bootstrap 3, using Display Suite module.

I've used Display Suite to add the Bootstrap 3's 'center-block' class. The class is added before the img tag, in a div. This doesn't center the image. I could only get the image to center when I manually added 'center-block' within img. I also used the Field Formatter Class module for this purpose and it also added the class to a div rather than img: so the problem persists.

So far, I've taken a sledgehammer to the problem and used the following template to apply the class to all images but would like to be precise in application, as mentioned above. This is the template I used:

image.html.twig

{% set classes = [
  theme.settings.image_shape ? theme.settings.image_shape,
  theme.settings.image_responsive ? 'img-responsive',
  'center-block',
] %}
<img{{ attributes.addClass(classes) }} />

Any solution?

In Drupal 8 you can do this with hook_preprocess_image in your themes mytheme.theme file.

/**
 * Implements hook_preprocess_image().
 */
function mytheme_preprocess_image(&$variables) {
  if ($variables['style_name'] == 'my_custom_image_style') {
    $variables['attributes']['class'][] = 'my_css_class';
  }
}

I found very simple solution. just add your custom bootstrap 3 style.css...will work as you want..applied over usps tracking site to look

.img-responsive{
  margin-left: auto;
  margin-right: auto;
  display:block
}


Exposing webform submissions for Views, but not giving anonymous users permission to view all submissions I have a webform set up in Drupal 8 and am trying to create a View that displays certain fields from form submissions. The webform and the view seem to be set up fine and are working.

The problem comes in when I want the view to be visible for anonymous users. I seem to be stuck with two options, neither of which are ideal:

Option 1: Anonymous users can see the page created in Views, but there are no fields on it.
Option 2: Anonymous users can see the page with the fields, but I have to grant the "View any webform submissions" permission, which then gives them access to view (and download) on the webform page itself.

Can anyone help me with an option 3, where the fields are visible in this View, but without granting the "View any webform submissions" permission to anonymous users?

You will have to give following permissions to anonymous users from permissions page. admin/people/permissions

View any webform submissions

Allows viewing all webforms and submissions.


How do I send a variable value from my form to another page using the POST method? In the first page I have the following code:

$form['message1'] = array(
  '#markup' => $this->t('Check Your Details once again !!'),
);

$form['candidate_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Candidate Name:'),
  '#required' => TRUE,
);

$form['Back'] = array(
  '#type' => 'submit',
  '#value' => t('Back'),
);

$form['submit']= array(
  '#type' => 'submit',
  '#value' => t('Proceed To Pay'),
);

return $form;

function submitForm(array &$form, FormStateInterface $form_state){
  drupal_set_message($this->t('@candidate_name! Wow! Nice choice! Thanks for telling us!', array('@candidate_name' => $form_state->getValue('candidate_name'))));
  $form_state->setRedirect('second_page');
}

In the second page I have the following code:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Candidate Name:'),
    '#required' => TRUE,
  );

  $form['Back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
  );

  return $form;
}

How can I get the first page candidate name into the second page candidate textfield?

This is how I send information from one form to another.

In the first page:

use \Drupal\Core\Url;

function submitForm(array &$form, FormStateInterface $form_state){
  drupal_set_message($this->t('@candidate_name! Wow! Nice choice! Thanks for telling us!', array('@candidate_name' => $form_state->getValue('candidate_name'))));

  $params['query'] = [
    'candidate_name' => $form_state->getValue('candidate_name'),
  ];

  $form_state->setRedirectUrl(Url::fromUri('internal:' . 'second_page', $params));
}

In the second page:

public function buildForm(array $form, FormStateInterface $form_state) {
  $candidate_name = \Drupal::request()->query->get('candidate_name');

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Candidate Name:'),
    '#required' => TRUE,
    '#value' => $candidate_name,
  );

  return $form;
}

EDIT: For POST method I never see it before, but you can create in the first page a session var and use this var in the second var after the redirection. Take a look in Storing Session Data with Drupal 8.

SECOND EDIT: It seems that the correct way todo this is with PrivateTempStore, if you go to see the CommentAdminOverview in Core you will see this:

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
      ...
      $info = [];
      /** @var \Drupal\comment\CommentInterface $comment */
      foreach ($comments as $comment) {
        $langcode = $comment->language()->getId();
        $info[$comment->id()][$langcode] = $langcode;
      }
      $this->tempStoreFactory
        ->get('comment_multiple_delete_confirm')
        ->set($this->currentUser()->id(), $info);
      $form_state->setRedirect('comment.multiple_delete_confirm');
    }
  }

In this page you collect the comment id that you want to delete and made a redirect, and the comment deletion happens in comment.multiple_delete_confirm (ConfirmDeleteMultiple) that have the following code:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->commentInfo = $this->tempStoreFactory->get('comment_multiple_delete_confirm')->get($this->currentUser()->id());
    if (empty($this->commentInfo)) {
      return $this->redirect('comment.admin');
    }
    /** @var \Drupal\comment\CommentInterface[] $comments */
    $comments = $this->commentStorage->loadMultiple(array_keys($this->commentInfo));
  ...
  }

So, we don't have a POST method from one form to another in Drupal 8 but this can be solved in this way.

You can set the information in session if it is related to single user.
Hope it helps.


How do I remove the underscore a view adds to a rewritten link? I am using fields, one has a link, rewriting the link as shown below sending the datetime to webform in the URL. All fields display as they should. When hovering over the link, the URL shows extra space at the end of each field as an underscore as follows. The underscore is not in the datetime field.

  2018-05-14T15:39:15-0400_

As seen above the underscore is added. Webform wont prepopulate the datetime field element with the underscore. When manually writing the value, webform correctly prepopulates my webform.
The link is /appt_testform?apptdatet={{ field_apptdatet }}&body={{ body }}, which becomes /appt_testform?apptdatet=2018-07-15T18%3A00%3A00-0400_&amp;body=Testing%20the%20appt%2C%20test%20and%20recommend. The underscore after 0400 should not be there.

I see an underscore is added to other fields, which accept values where the datetime will not. I am trying to do this without using hook_form_alter().

After testing on 5 servers using different 8.x versions
When importing using feeds module CSV file,
If the content field is date and time..imported using feeds then View linked to webform to prepopulate it will add the underscore as shown in the original question.
If a field is timestamp (unix number in CSV) after importing, the view rewrite results link does not have the underscore added. I don't know why, however, my site works using the timestamp field type. On all the servers.

This issue happens when the field value is rendered with HTML (which is appended by Drupal date formats).
In your View, edit your time field and make sure to use Custom formatter rather than any of the predefined ones, and provide the custom pattern in 'Date/time format' field. And then underscore should go. Check this useful answer.
In my case I was struggling with underscore appended after Year value (mysirte.com/tag/1994_), and when I created custom format and used 'Y' the underscore disappeared, see picture:


Drupal installation in nginx subdirectory I have a new application that will be made of 2 frameworks yii and drupal 7

Yii framework will be in the root (/)

and drupal will be in a sub directory called admin (/admin)

I have a problem how to config it in nginx,drupal doesn't work,it gives me access denied,or just the home page and no link works

This is my configuration file in nginx

server {
        listen 80;
        server_name demo.example.com;
        root /home/www/example;
        index /index.php;

        location / {
                if (!-f $request_filename) {
                        rewrite ^(.*)$ /index.php?q=$1 last;
                        break;
                }
        }
        location /admin {
                root /home/www/example/admin;
                index  index.php index.html;
                try_files $uri $uri/ @rewrite;
        }
        location @rewrite {
                rewrite ^/(.*)$ /admin/index.php?q=$2 last;
        }
        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include        fastcgi_params;
                index /index.php;

        }
         location ~ /\.ht {
                deny  all;
        }

}

I had a similar scenario, but in my case I didn't need to define again the root folder for the Drupal installation as you do on location /admin.

In my case I only needed to add the nginx directives for the Drupal path:

location /admin {
    try_files $uri $uri/ @rewrite;
}

location @rewrite {
    rewrite ^ /admin/index.php;
}

If Drupal is in a subfolder, probably all you need is:

root /home/www/example/admin;

as compared to

root /home/www/example;

Where "example" is the base site and "admin" is the Drupal folder.


How to change default "Create" label? I want to change the 'Create' label for a specific Content type.
I made a new content type called 'Bid Offer':

I want to show this to the users as 'Make Bid Offer' instead of 'Create Bid Offer'

Any help appreciated

Put the following code into a custom module.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bid_offer_node_form') {
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
  }
}

or

function mymodule_form_bid_offer_node_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
}

To change the URL, you can just set a path alias and alias node/add/bid-offer to make-offer or whatever you fancy should you need to.

Just for reference:

hook_form_alter()

hook_form_FORM_ID_alter()

EDIT

Following on from your comment, please try the following code (I've used it recently so I know it works):

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bid_offer_node_form') {
    drupal_set_title(t('Make Offer'));
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
  }
}

or

function mymodule_form_bid_offer_node_form_alter(&$form, &$form_state, $form_id) {
    drupal_set_title(t('Make Offer'));
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
}

Reference:

drupal_set_title()

Create bid_offer module with title callback returning node form. It should look like this (I didn't check it live!)

function bid_offer_menu_alter(&$items) {
  unset($items['node/add/bid_offer']); //unset core add path
}

function bid_offer_menu() {
   $items = array();
   $items['create/bid_offer'] = array(
     'title' => 'Create bid offer',
     'title callback' => 'bid_offer_title',
     'title arguments' => array(1),
     'page callback' => 'bid_offer',
     'page arguments' => array(1),
     'type' => MENU_CALLBACK,
     'access callback' => TRUE // You can customize this
   );

function bid_offer_title($type) {
  drupal_set_title(t('Make bid offer'));
  }
  return t();
}

function bid_offer($type = null) {
     if($type->type == 'bid_offer') {
       module_load_include('inc', 'node', 'node.pages');
       global $user;
       $new_node = new stdClass;
       $new_node->type = 'bid_offer';
       $new_node->language = LANGUAGE_NONE; //localization
       $new_node->user = $user->uid;
       $new_node->name = (isset($user->name) ? $user->name : '');
       $form = drupal_get_form('bid_offer_form', $new_node);
       return $form;
     }
   return drupal_not_found();
}

After that you're be able to create your bids from http://yoursite/create/bid_offer

You can change

'type' => MENU_CALLBACK

to MENU_NORMAL_ITEM for visible menu.

Important! Do not afraid of creating module. I'm not developer, just Drupal enthusiast and if you think logically you can make it.


Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs? I am trying to pass URL parameters and access them in a preprocess function. I have done a fair amount of research but did not find an answer. It works if I do the following /example?id=1, but that's quite ugly and non-SEO friendly. Clean URLs is much better.

Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs?

Yes, the arg() function can do this.

https://api.drupal.org/api/drupal/includes%21path.inc/function/arg/6.x

At the end of Drupal's .htaccess file, you can see how Drupal makes those URLs work by rewriting them to ?q= if they are not real files or directories. Without this, they would cause a 404 too.

In http://api.drupal.org/api/function/arg/6 you can see how it handles them.


Avoid duplicate hits in two separate Views I'm using Views to generate a number of lists, e.g. Newest articles and Popular articles.
Now, often newest articles will also be in the Popular articles list.

So when I'm using both views on frontage, I would like to prevent, that the same article is shown on both lists.

So basically skip articles in Popular list, if they also are available on Newest list.

This is not trivial to accomplish, and will in most cases require coding.

First of all, it's necessary to determine in which order the lists should be evaluated. One of them needs to take priority. The gist of the solution, is that in some way, you need to feed the hits from the first list, as arguments to the second list.

In Views, you can add a Contextual filter, or Argument, depending on your version. These arguments can be set to "exclude" their matches, and it's also possible to allow "multiple arguments per filter".

The high priority View can be left as it is, but the low priority View should be configured so that it takes several entity-id's as arguments, and excludes those from the result. The real difficulty for most is going to be in passing arguments between these two Views.

In code:

$first = views_get_view('most_important_view');
$second = views_get_view('less_important_view');

// Get results, but don't render them.
$first->preview('machine_name_of_display');

// Append together a list of node id's to a string.
$nodes_to_exclude = '';
foreach($view->result as $node) {
  $nodes_to_exclude .= $node->nid . '+';
}
// Remove the trailing +.
$nodes_to_exclude = rtrim($nodes_to_exclude, '+');

$second->execute_display('machine_name_of_display', array($nodes_to_exclude)););
return $second->render();

If you are not comfortable using the above code, there is a module called Viewfield that allows you to call a second View from a primary View. But unfortunately I'm not aware of a way to configure this to pass several arguments on, but just a single one, so I'm not sure if that's helpful.

I think the best way to achieve this is use selection rules (I'm not completely certain if you can filter by those properties but I think you can). I'm not really sure how you are going about defining "new" and "popular" but if is something that can show in the selection rules you can use that to filter.


Adding Vue.js to my theme with Webpack not working I am trying adding Vue.js into my Drupal 8 theme with my Webpack setup (which I had already working).

It's all compiling fine with Webpack, without errors after my npm script npm run build.

In my index.js I have:

import './styles.css';
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

In my App.vue I have:

<template>
  <div id="app">
    <HelloWorld msg="Coming Soon: Near-Earth Objects"/>
  </div>
</template>

<script>
  import HelloWorld from './components/HelloWorld.vue'

  export default {
    name: 'app',
    components: {
      HelloWorld
    }
  }
</script>

<style>

</style>

In my ./components folder I have HelloWorld.vue

First I am trying now to render my Vue component inside header.html.twig like

<hello-world></hello-world>

My thoughts are, by the element  in page.html.twig I can show, arrange and position all my Vue.js components where I want. Is that correct?

But why is my component not showing up?

Update:

I figured out. My webpack.config.js is splitting Vue into /themes/custom/my_theme/dist/vendors~main.bundle.js. By this setting:

config.optimization = {
      splitChunks: {
        chunks: "all"
      },

What is the purpose of this? Isn't it better to compile it all into the same file main.bundle.js?

I recommend looking into the Decoupled Pages module which can make integrating Vue.js simpler.


Is it possible to use an Image Style in a text field? Image Styles is a great feature in Drupal. Is it possible to apply a preset Image Style to an image that is brought into a long text type field that uses WYSIWYG in Drupal 7? That is, for use in the basic node, not in a View.

Currently, we're using the IMCE WYSIWIG bridge to insert images in the textfield, and there seems to me no way to indicate what preset Image Style to use.

It depends on what you mean by "possible" :-).

The Scald module (integrates with the WYSIWYG CKeditor) uses something called "contexts" that in turn makes use of the preset image styles.  So it is certainly possible to do this if you use Scald to insert images into WYSIWYG.

Scald has a drag'n'drop UI that allows you to place an image (or "atom" in Scald-speak) into WYSIWYG. When you do that, you can set its legend (i.e. caption), context and alignment (see sample dialog below):

In this case, the "Context" is set to "Full page". which I have associated with the preset Image Style known as "Large 480x480".

Below, you can see the markup that is generated by Scald as a result of this, and you can see that it links to the image using the path:

public:://styles/large/public/thumbnails/image/fredespenbenth.jpg

the styles/large path is indeed the image cache for the preset "Large 480x480" image style.

This is the caption that will appear under the image..

Now, as you can see, Scald is doing this, so it must be possible.

And you can (to some extent) do the same thing without Scald by inserting similar markup "by hand" or with the help your own custom module.  But Scald has in place additional magic to regenerate that style of the image in the image cache if it does not exist.  If you do this just by inserting the markup, you can't be sure that the image exists in that style, so you have to use other means to make sure the image cache is populated with the styles you actually use.  (For example sniffing for URLS pointing into the cache in hook_preprocess_node(), and regenerate those that are missing.)

Yes, this can be done with the module found on:
https://www.drupal.org/project/image_filter


Commerce-Marketplace : Members tab in store's page doesn't show up After this clean install :

Drupal 7.28
Commerce 7.x-1.9
Commerce-Marketplace 7.x-1.0-beta2 (same issue with current dev version)
ECK 7.x-2.0-rc3+15-dev

I create a new store but can't see the "Members" tab as seen on the demo site (I also tried the direct URL "commerce_store/store/{ID}/people", no error but I stay on store page).

Here is a screenshot

And the demo site

Do I miss a step to activate the store members management tab/pages ?

Thanks for your help or direction to solve this.

Problem resolved after this update : https://www.drupal.org/node/2284457#comment-8962135


How to know when to use $config or $settings overrides in settings.php? I want to be able to disable certain options of modules on non-production environments.

For example:

Disable XMLSitemap from running
Set "Read Only" mode for Search API indices to TRUE
Set robots.txt string to

User-agent: *
Disallow: /

How do you know whether you should override $config or $settings in settings.php?

Would it be:

$config['search_api.index.acquia_search_index']['readonly'] = TRUE;

or

$settings['search_api.index.acquia_search_index']['readonly'] = TRUE;

Also, how can you confirm if these overrides are working? Is there an admin overview page that lists these things?

From settings.php, regarding $settings:

Settings:
$settings contains environment-specific configuration, such as the files
directory and reverse proxy address, and temporary configuration, such as
security overrides.
@see \Drupal\Core\Site\Settings::get()

From settings.php regarding $config:

Configuration overrides.
To globally override specific configuration values for this site,
set them here. You usually don't need to use this feature. This is
useful in a configuration file for a vhost or directory, rather than
the default settings.php.
Note that any values you provide in these variable overrides will not be
viewable from the Drupal administration interface. The administration
interface displays the values stored in configuration so that you can stage
changes to other environments that don't have the overrides.
There are particular configuration values that are risky to override. For
example, overriding the list of installed modules in 'core.extension' is not
supported as module install or uninstall has not occurred. Other examples
include field storage configuration, because it has effects on database
structure, and 'core.menu.static_menu_link_overrides' since this is cached in
a way that is not config override aware. Also, note that changing
configuration values in settings.php will not fire any of the configuration
change events.

Your question is not clear, but dev and stage environnemnts have differents settings.php, so you can modify your config in each file as you like, $config contains all globals variables to drupal, and in same time are config variables in data base ...


field template for a specific content type I've read from http://drupal.org/node/1089656 that I can create a template for a field in specific content type as field--field-name--content-type.tpl.php.

I have a custom content type "festivals_events" and a cck field "field_description".
So, I created a template "field--field_description--festivals_events.tpl.php".  But it is not working.

I tried to replace _ in field name with - as suggested in Template Suggestion, http://drupal.org/node/1089656, to become my template name file name as "field--field-description--festivals_events.tpl.php"
This too is not working.

I think it is definitely can be used as it is mentioned in Template Suggestion.
What is wrong with me?

Thanks in advance.

Try "-" in the contact type name like field--field-description--festivals-events.tpl.php

[Edit]
You may also need a template suggestion in your theme.

function mytheme_preprocess_field(&$variables) {
    if($variables['type'] == 'festivals-events'){
        if($variables['element']['#field_name'] == 'field_description') {
            $variables['theme_hook_suggestions'][] = 'field__field_description__festivals_events';
        }
    }
}

for me it worked great (field--field-name--content-type.tpl.php.). Drupal 7.26

But, first add in template.php

    function ThemeName_process_page(&$vars) {
  if (!empty($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

  this also works with node-content-type.tpl.php


How to add Cancel button to Batch operation? How to add Cancel button to Batch operation?
Is this even possible?

There is no good way to interrupt a batch process, afaik. There used to be a hackish trick in Drupal 6 though, see http://drupal.org/node/894222. Maybe if you can figure out how that worked, you can make Drupal 7 do the same.

Define your operation like this:

$batch = array(
  'title' => t('Exporting'),
  'operations' => array(
    array('my_function_1', array($account->uid, 'story')),
    array('my_function_2', array()),
  ),
  'finished' => 'my_finished_callback',
  'file' => 'path_to_file_containing_myfunctions',
);

http://api.drupal.org/api/drupal/includes!form.inc/group/batch/7


$form_state->setRedirect not working after a $form_state->setResponse In the submitForm of a custom form, I have this:

$sFileName = 'sites/default/files/_private/bulletins/' . $form_state->getValue('adherent')[1] . ".pdf";
$response = new BinaryFileResponse($sFileName);
$response->setContentDisposition(
  ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  'bulletin.pdf'
);
$form_state->setResponse($response);

This triggers the download of a pdf document and it works.
Then, I try to execute:

$form_state->setRedirect('<front>');

and that is not working!
In FormState::setResponse documentation, I read « If a response is set, it will be used during processing and returned directly. The form will not be rebuilt or redirected ».
I guess it is why my redirection to  doesn't work...

How can I do it anyway?

short answer RedirectResponse;

use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('/where-ever');
$response->send();


Removing divs added by render and node.tpl.php I'm trying to build an HTML5 template for Drupal 7, and I'm quite particular about clean code. I want full control over the HTML and CSS which for the most part I get using my own custom theme. In other words I have an HTML5 and CSS set I want to use exactly as is in Drupal. I'm not too clued up on how the whole pre-process function thing works.

When I use 'print render($page['content'])' in my page.tpl.php file it adds

And then when I add 'print render($content)' in the node--custom.tpl.php it adds

I don't want any of these divs. How do I get rid of them?

The div ids and classes you see inside $page['content'] comes from region.tpl.php > block.tpl.php > node.tpl.php
Drupal content passes through these template files, each step adds some divs.

Step One

region.tpl.php file contains  the code as follows

       <?php if ($content): ?>
  <div class="<?php print $classes; ?>">
    <?php print $content; ?>

<?php endif; ?>

now if you make changes in this file it will effect all the regions of your page. If you want to control only the content area, create a new file name it region--content.tpl.php in that file paste only

<?php if ($content): ?>

    <?php print $content; ?>

<?php endif; ?>

This will get rid of div created for only content region.

Step Two

Make a copy (if we make changes in block.tpl.php all the blocks will be effected) of block.tpl.php and name it block--content.tpl.php and remove or change the divs. Without the divs the file will contain the following code to output content.

<?php print render($title_prefix); ?>
    <?php if ($block->subject): ?>
      <h2 class="block-title"<?php print $title_attributes; ?>><?php print $block->subject ?>

    <?php endif;?>
      <?php print render($title_suffix); ?>
      <?php print $content; ?>

This will get rid of div created by bock.tpl.php

Step Three

Now edit the node.tpl.php file to remove or change the divs. Without the divs the file will contain the following code to output content.

          >">

    <?php print $user_picture; ?>

    <?php if ($display_submitted): ?>
      <?php print $date; ?> — <?php print $name; ?>
    <?php endif; ?>

        <?php
          // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
       ?>

    <?php if (!empty($content['links']['terms'])): ?>
      <?php print render($content['links']['terms']); ?>
    <?php endif;?>

    <?php if (!empty($content['links'])): ?>
        <?php print render($content['links']); ?>
      <?php endif; ?>

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

This will get rid of all div and classes. Now you can wrap the content with your own divs.  Please let me know if it works for you.

What works perfectly for me is: strip_tags(render($var));


Colorbox images in grid I installed colorbox module and I'm showing images as thumbnails. Each image is in on new line. Is it possible to set it that images will be in the grid similar as here?

I have exactly the same settings as here but don't see any settings to view images as grid, but I have a feeling I saw this somewhere else, but don't remember where.

thank you

You can use CSS rules to position the images like you want.

Another options would be to use views to display the images, which has built in support for displaying items in a grid.

If you want a more detailed answer, you should provide more info in your question.

This Drupal module is what solved my issue:

  The Grid Field Formatter module provides a simple way to override the display of multi-value fields to show as a grid/table with a certain number of columns.


How do I turn off maintenance mode? Does anyone know how to turn off maintenance mode for brainfx?  I tried http://www.website.com/?q=user/login but that gives me a blank page (no html source or anything).  I tried the following query.

UPDATE `variable` SET `value`='0' WHERE 'name' = 'maintenance_mode';

It didn't affect any records.

I tried to find a $conf['maintenance_mode'] variable in the project, but it doesn't exist. Adding that $conf['maintenance_mode'] = false; in setting.php didn't do anything either.

How do I turn off maintenance mode?

Using Drush, you can run drush vset maintenance_mode 0 to disable the maintenance mode on a Drupal 7 site.

In my case, Drush was not working and I could bring back the site by doing this:
Add the below line in docroot\core\lib\Drupal\Core\EventSubscriber\MaintenanceModeSubscriber.php
\Drupal::state()->set('system.maintenance_mode', FALSE);
Run the site again for 2-3 times (clearing the cache) and it is up again.
Remember to take out this line once your site is up


Add fields to user roles I'm using Drupal 7 to create a project linking organizations to volunteers. My initial approach is to use profile module to create different profiles for each role (volunteer & organization). Is it possible to create new fields which would attach only to a selected role?

This is a great example use-case for the Profile 2 module.

As listed on the project page:

  Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)

Sounds like a good idea to collect all fields in one entity. You could then have a enumerator-field, where you could choose entity-sub-type (organization or volunteer). That would be needed in case the author had authority to create both.
You can use User Role Field to hide the fields that the author is not allowed to see.
You can use Field Permissions to restrict access that the author and viewer is not allowed to access.
You can use also hide or show fields dependent on values of other fields with Conditional Fields. The dependee field would then be the enumerator-field.
You could probably use Computed Field to add extra logic dependent on sub-type.

I like to use taxonomy for enumerator, but it could be a text list instead.

You would probably also like to group the subtype specific fields together in a drupal.org/project/field_group

This pattern could just as well be applied on contenttypes. I think I will try it out.

In Microsoft Sharepoint, ContentTypes has had inheritance for years. I wonder if it will come in a future Drupal version.


Why form redirects to encoded url when having GET params? I have a simple form with 1 select and I want it after the form submit to redirect to the same URL, but with added GET params.

So in a form submit I added:

$form_state['redirect'] = url(arg(0).'/'.arg(1).'/'.arg(2), array(
  'query' => array(
      'brand' => $state['values']['brand'],
      'categ' => arg(2)
)));

Which redirects to wrong encoded url:

  /produkty/vlasy%3Fbrand%3D118%26categ%3D27

But It works well when I use drupal goto (this is not recommended):

  drupal_goto(arg(0).'/'.arg(1).'/'.arg(2), array(
      'query' => array(
          'brand' => $state['values']['brand'],
          'categ' => arg(2)
  )));

  /produkty/vlasy?brand=118&categ=27

Why is it so?

You just need to adjust the param value from a string to an array for $form_state['redirect']

It is in the documentation for drupal_redirect_form

  $form_state['redirect'] determines where to redirect the user. This can be set either to a string (the path to redirect to), or an array of arguments for drupal_goto().

Example:

$form_state['redirect'] = array(
  arg(0) . '/' . arg(1) . '/' . arg(2),
  'query' => array(
        'brand' => $form_state['values']['brand'],
        'categ' => arg(2)
  )
);

Use urldecode() function.

$redirect_url = url(arg(0).'/'.arg(1).'/'.arg(2), array(
  'query' => array(
      'brand' => $state['values']['brand'],
      'categ' => arg(2)
)));
$form_state['redirect'] = urldecode($redirect_url);

Output: /produkty/vlasy?brand=118&categ=27


Drupal 7: Two submit buttons and custom field validation I have a custom user registration form (D7). I added two custom submit buttons inside THEME_form_alter

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up')
  );
  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up & Take Survey')
  );

These render fine and both handle the registration equally well but when submit2 is clicked I want to redirect to a webform survey.

I added the following:

function tweakform_user_register_submit($form, &$form_state) {

  if($form_state['values']['op'] == $form_state['values']['submit2']) {
    echo 'Redirect to survey and populate fields with user details';
    exit;
  }

}

I refreshed the cache and this function does not seem to be invoked.

Alex

I'd suggest using the #submit property

For example:

$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Sign Up')
);
$form['actions']['submit2'] = array(
  '#type' => 'submit',
  '#value' => t('Sign Up & Take Survey')
  '#submit' => array('custom_submit_for_this_button')
);

And then:

function your_form_name_submit($form, &$form_state) {
  // your logic for first button here; this is auto-called by Drupal
}
function custom_submit_for_this_button($form, &$form_state) {
  // your logic for second button here
}

$form['actions']['submit2'] = array(
  '#type' => 'submit',
  '#value' => t('Sign Up & Take Survey'), //the missing line in above example
  '#submit' => array('custom_submit_for_this_button')
);


Set value after unpublishing content I'm using drupal 8 and the scheduler module to automatically unpublish custom content after x days have passed.

While unpublishing a boolean field from the custom content needs to be enabled/disabled.

So far I tried rules module after_a_node_has_been_unpublished_by_scheduler with Condition: Entity has field with Action: Set a data value Unfortunatelly the action does nothing.

What else could I try?

You can create your custom code in a hook_cron, and you can handle your verifications following the date of publication.


Can I move the description of a form field between the label and the field? I have a form with input fields such as this one:

'sex' => array(
    '#type' => 'radios',
    '#title' => t('Sex'),
    '#options' => array('m' => t('M'), 'f' => t('F')),
    '#description' => t("We use this to write Mr. or Mrs. in the letters we send you.")
)

By default, this prints the label first ('Sex'), then the radio buttons, and then the description. I would like to print out the label followed immediately by the description and have the radio buttons appear last. How can I achieve this? I know how to load a stylesheet, but in this case it would be nice for the html to appear in the correct order:
<input /> rather than <input />

Edit: The solution proposed by Anil Sagar works, but introduces a bug. Indeed, what I use his solution, it prevents me from giving a description to a checkbox field. In other words, if I write

$form['myCheckbox'] = array(
  '#type' => 'checkbox',
  '#title' => t('My checkbox'),
  '#description' => t("My description")
);

that description never makes it to the HTML. Does anyone know how to fix this?

You need to override theme_form_element in your theme template.php to change the order of the form field description. See below code which will change order for all fields.

If you would like to change for only one field, then add a if condition by inspecting $element array only for your field !

function yourtheme_form_element($variables) {
  $element = &$variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // This function is invoked as theme wrapper, but the rendered form element
  // may not necessarily have been processed by form_builder().
  $element += array(
    '#title_display' => 'before',
  );

  // Add element #id for #type 'item'.
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  // Add element's #type and #name as class to aid with JS/CSS selectors.
  $attributes['class'] = array('form-item');
  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '
' . "\n";

  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }
  $prefix = isset($element['#field_prefix']) ? '' . $element['#field_prefix'] . ' ' : '';
  $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';
   $element_description = "";
  if (!empty($element['#description'])) {
    $element_description = '
' . $element['#description'] . "
\n";
  }
  switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= $element_description;
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

    case 'after':
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
      $output .= ' ' . theme('form_element_label', $variables) . "\n";

      break;

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= $element_description;
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;
  }
  $output .= "
\n";

  return $output;
}

Other way & simple way to solve this problem is use jQuery to change the position. This will help you !

I found this very helpful blog post to fix this problem : http://www.whenwhowhere.com/tech-blog/move-description-field-below-label-drupal-7-form

Basically, in hook_form_alter, you put the title and the description in the #prefix of the element, then unset the title and the description so they don't appear twice ... I tried it and it works perfectly.


Submit form and disable submission button I want to disable the submit button after it is clicked to prevent multiple submissions. I have:

$form['show'] = [
'#type' => 'submit',
    '#value' => $textforsubmitbutton,
    '#name' => 'submit',
    '#attributes' => array("onclick" => "javascript: this.disabled = true;"
    ),
];

but this disabled the button completely. Using "onsubmit" in place of "onclick" doesn't change anything on the button. So maybe I need something like:

    '#attributes' => array("onclick" => "javascript: this.submit; this.disabled = true;"
    ),

How do i fix this?

For those wanting to disable the form submit button on load, try this:

$form['actions']['submit']['#attributes']['disabled']  = 'disabled';

To remove the button in hook_form_alter() simply unset the submit action.

unset($form['actions']['submit']);


Installed Views Module but It did not appeared in Structure I installed a fresh Drupal 7.22 on my localhost and installed Ctools and Views modules.

When i go to Structure i dint find Views link

I also cleared all cache but still same problem.

This is not my first Drupal experience, I created many views.

Here are the screen shots.

You have to enable Views UI in order for it to show up under Admin -> Structure.

If you are still not seeing after enabling Views-UI and IF YOU USING ADMIN MENU module to generate Admin Menus, You have to clear cache.

To do that,

Home Icon -> Flush all caches -> Administration menu
Home Icon -> Flush all caches -> Menu


Cannot load ctools automodal associated menu call from another module I have several modules that make extensive use of the Ctools Automodal modal to activate custom-driven modals. These Link references live in their own module, example_item_modals:

/**
 * Implements hook_menu()
 */
function example_item_modals_menu() {
  $items['product/product1'] = array(
    'page callback' => 'product_order_modal_1',
    "access arguments" => array('interact with orders'),
    'type' => MENU_LOCAL_TASK,
    'modal' => TRUE
  );

  $items['product/product2'] = array(
    'page callback' => 'product_order_modal_2',
    "access arguments" => array('interact with orders'),
    'type' => MENU_LOCAL_TASK,
    'modal' => TRUE
  );

  return $items;
}

We have another module that loads in a User Profile (developed by another third party) and the requirements call for loading some of the products here, and interacting with the modal. Actually displaying the links are done using a tpl.php call to those menu calls with an l().

    <?php echo l("View Product", "product/product1"); ?>

So when we eventually load the template call in this custom user profile module, this link should load and have the necessary logic to fire the modals. Except, its not. Here, it treats it like a backpage link. Is there something I am missing for this link to function as a modal? Do I need to explicitly include the parent module the links are defined with, and if so, what API call accomplishes that? (I looked at module_load_include() but i'm importing settings thrown in the .module, not a .inc file).

I think you need specific class for your link to be preprocessed as a modal link (but i don't know the 'automodal' feature so maybe im wrong)

<?php echo l("View Product", "product/product1", array('attributes' => array('class' => array('ctools-use-modal')))); ?>


How to tell Drupal to look for templates in module directory? I'd like to provide template implementation in my module and allow themes to override it. Basically, I add a suggestion by this simplified code:

function attach_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__test';
}

(I don't want to use hook_theme to add a new theme because I want to reuse preprocess node functions. The theme name are awkward but I don't want to write node_attach_% to avoid confusion with node type.)

Then I use hook_theme_registry_alter() to add module path:

function attach_theme_registry_alter(&$theme_registry) {
  $path = drupal_get_path('module', 'attach') . '/themes';
  $theme_registry_copy = $theme_registry;
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'node', drupal_get_path('module', 'node'));
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  if (!isset($theme_registry['node']['theme paths'])) {
    $theme_registry['node']['theme paths'] = array();
  }
  if (!isset($theme_registry['node']['theme paths'])) {
    $first_element = array_shift($theme_registry['node']['theme paths']);
    if ($first_element) {
      array_unshift($theme_registry['node']['theme paths'], $first_element, $path);
    }
    else {
      array_unshift($theme_registry['node']['theme paths'], $path);
    }
  }
}

However it does not work. That means: the file themes/node--super.tpl.php is not used. It is used only if I copied it to the theme folder.

Maybe this one works:

/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return array (
    'node__CONTENTTYPE' => array (
      'variables' => array( . . . ),
      'template' => 'node--CONTENTTYPE' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'MODULE'),
    ),
  );
}

Important here is the key 'base hook'.

I asked this once on Stack Overflow. Basically, you have to implement hook_theme_registry_alter() to get your path added to the theme hook template path; then, on hook_enable(), you call  drupal_theme_rebuild() to clear the theme registry cache and get your path scanned for templates.


Restrict Menu Item from anonymous users and redirect to Login page I created a simple menu link and need it to be visible for both authorized and anonymous users. But when a unauthorized/anonymous user click it should check authorization and if not it should redirect to login page. How can i do this. Thanks

Create a custom module
In your_custom.module

function custom_init(){
global $user;
$current_path = request_path();
if (!in_array(array('your roles','your roles'),$user->roles) && $current_path=="node/add/yourcontent type" ) {
  // for mutiple row
  drupal_goto('/user');
}
}

Yes you can do this just go to admin/config/system/site-information (if using drupal 7) there you will see a Error Pages title at the bottom of the form there you can see an option as Default 403 (access denied) page. You can mention your login page path within that text box user/login. I hope this works for you


Hierarchy between terms from different vocabularies in Drupal 7? Is there a way to have a hierarchy of terms by reusing the same terms that reside in different vocabularies? There seem to be so many different options for dealing with taxonomies in Drupal 7 that it feels very daunting to figure out...

For example, let's say I want to make a directory of athletes for different sports. I've created 3 vocabularies, each with several terms:

Vocabulary: Sports
* Soccer
* Basketball
* Baseball

Vocabulary: Divisions
* Division 1
* Division 2

Vocabulary: Teams
* Team 1
* Team 2

Each type of sport will be divided into Divisions and then into different teams per Division.

The hierarchy looks like:

Soccer
* Division 1
    --Team 1
    --Team 2
*Division 2
    --Team 1
    --Team 2

Basketball
*Division 1
    --Team 1
    --Team 2
*Division 2
    --Team 1
... and so on for each sport.

Since the terms for vocabularies Divisions and Teams are always the same, I'm thinking it would make more sense to be able to reuse the same terms under those two vocabularies instead of creating the same terms over and over again for each sport, each division...etc.?

Is that even possible and if so, what would be the best way to go about implementing it?

You can make a term reference field on a vocabulary.
So on a the team vocab one of the fields would be "division".
So when you create a new team you would enter the team name and "tag" the division it is in using auto complete or a dropdown.

It is also possible to assign multiple parents to a term.  The easiest way to do this that I have found is with the Taxonomy Manager module.


Routing match everything i want to match in a route a 'random' URL with a random sub path, fox example:

/example/1/a/b/c
/example/c3/s
...

i implement this route in my .routing.yml file

modulo.validator:
  path: '/example/{path}'
  defaults:
    _controller: '\Drupal\modulo\Controller\Controller::check'
  requirements:
    _permission: 'TRUE'
    path: '.+'

I write it following Symfony2 standard but it doesn't works, seems Drupal override requirements in path.

Take look to system.routing.yml

system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

why this doesn't work for me?

Any suggestion?

The reason that the route in system.routing.yml works is that it gets help by an inbound path processor service, which stores the filepath to a query parameter in the request:

PathProcessorFiles.php

<?php

namespace Drupal\system\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines a path processor to rewrite file URLs.
 *
 * As the route system does not allow arbitrary amount of parameters convert
 * the file path to a query parameter on the request.
 */
class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

This service is registered in system.services.yml:

system.services.yml

  services:

    path_processor.files:
      class: Drupal\system\PathProcessor\PathProcessorFiles
      tags:
        - { name: path_processor_inbound, priority: 200 }

And the controller gets the file path from the query parameter added by the processor:

FileDownloadController.php

  public function download(Request $request, $scheme = 'private') {
    $target = $request->query->get('file');
    ...

You can implement the same approach for your route to match everything after /example/.

The Drupal 8 example modules has a few examples of this functionality.

For example in the page_example module you'll see a page_example.routing.yml file with the following

page_example_arguments:
   path: 'examples/page-example/arguments/{first}/{second}'
   defaults:
       _controller: '\Drupal\page_example\Controller\PageExampleController::arguments'
   requirements:
       _permission: 'access arguments page'

And in the controller you have the arguments function that is called:

public function arguments($first, $second) {
    // Make sure you don't trust the URL to be safe! Always check for exploits.
    if (!is_numeric($first) || !is_numeric($second)) {
       // We will just show a standard "access denied" page in this case.
       throw new AccessDeniedHttpException();
    }

    $list[] = $this->t("First number was @number.", array('@number' => $first));
    $list[] = $this->t("Second number was @number.", array('@number' => $second));
    $list[] = $this->t('The total was @number.', array('@number' => $first + $second));

    $render_array['page_example_arguments'] = array(
       // The theme function to apply to the #items.
       '#theme' => 'item_list',
       // The list itself.
       '#items' => $list,
       '#title' => $this->t('Argument Information'),
     );

     return $render_array;
}