Posting in Ruby leads to a 403 error I am writing a Ruby script to ingest content into Drupal 7. This is on my local machine. I'm using the Services module and its rest service to GET and POST. I could log in and grab the csrf token and the cookie information but I get a 403 error when I try to post a new node. I checked my local apache access and error logs. There were no errors listed and the access log only reports the status. This is my code so far:

require "rest-client"
require "json"

node = create_node(node_hsh)
node_json = JSON.generate(node)
response = RestClient.post('localhost/drupal/restfulapi/node', node_json,
:content_type => :json,
:accept => :json,
:headers => {:cookie => cookie, 'x-csrf-token' => csrf_token}
)

I'm not sure where else to look? I would really appreciate any pointers. Thanks.

I figured it out. Posting this for documentation: I had to pass the cookie after the user had logged in to do a GET on the token (localhost/services/session/token) for the Services module. Once I had the token, I could pass the cookie and the token to do a POST of the resources. I also switched the gem from rest-client to Faraday because I could customize my headers better. Also, the logging functionality was more verbose in Faraday which was helpful in debugging.


Language Block customization: I need to display either English link or the other language link (not both) I have a bilingual project and the language is being switched from the language block. It actually displays now: English and Spanish.

I need to have just one language link displayed: English when on Spanish language and Spanish when English.

Thank you!

Usually the current language link gets an "active" class. You can use CSS to hide all other links and display only the active link.

This can also be done by overriding theme template files or functions.


Drush module version Is there a way for drush to print out what module version for a module that is currently enabled?

I'm not looking for trying to find what version of drush is.

I end up doing it the janky way:

drush dl mymodule --select and then seeing which version is installed.

Or drush pm-list | grep mymodule

For Drupal 7 and earlier, try using drush pm-info module. It may give you what you want.

For Drupal 8 and later, the pm commands are mostly deprecated.  To get module information, you would use composer show drupal/module.


Questions about the imagefield of CCK How can I include the text between the label of image field and the upload button?
How can I remove the text "maximum file size" of the image field in some content types? I want to remove the text "maximum file size" but I want to keep "allowed extensions."

assuming that you are talking about the 'edit form', you can use css to control the visibility of these fields in this way:

/*---------------------------this rule is to hide the text"maximum file size"and "allowed extensions"*/
div#edit-field-cl-namefiled-upload-wrapper div#edit-field-namefiled-upload-wrapper div.description{
display:none;
}

/*---------------------------this rule is to move your descriptionnear to the field to upload.here you can add the "allowed extensions.." text*/
div#edit-field-namefiled-upload-wrapper > div.description{
margin-top:-70px;
position:absolute;
}


How do I clear the cache for a single node? In my module, I can call cache_clear_all() (D7) or drupal_flush_all_caches() (D8), and this would clear the cache for all the nodes.

Is there a way to clear the cache for a single node?

What I need to do is setting up a module that, when it selects a story on a list, it changes the value of a node field. Right now, I change the field value by updating the database table containing that value, but I need to clear the cache for the value to be updated across the site.

Is there's a better way to update a node than directly changing the database table?

If you have the node object, use

use Drupal\Core\Cache\Cache;
...
Cache::invalidateTags($node->getCacheTags());

That's better than to assume the cache tag identifier will be 'node:' . $node->id() forever.


CKeditor stripping allowed style attribute I've installed Colorbutton to my Drupal 8 site.

I have enabled the button for Full HTML and For Basic HTML

I have allowed the attribute <span style> in the Basic HTML allowed attributes area.

I have defined a set of hex value colors.

When I edit a page the button appears and I can change font colors in the editor correctly, however, saving the page strips the attributes leaving only clean <span> tags...

what else am I suppose to do?

There is a simmilar question here, however in relation to colorbotton the documentation/README that comes with the module specifically states that we should be allowing <span style> in the allowed tags? Is their readme incorrect?

The extension appears to add the color by adding the attribute style="color:#fff"> How can I allow it to do this successfully?

Your problem comes from the "Limit allowed HTML tags" option. According to this post (for Drupal 7, but the same logic applies on D8), setting this option triggers XSS filter in order to remove dangerous tags.

As for Drupal 8, it uses the core Filter module and calls filterXss() method in \Drupal\editor\EditorXssFilter\Standard class. First line of this method is:

$dangerous_tags = ['script', 'style', 'link', 'embed', 'object'];

Hence, your style tag will always be removed with the "Limit allowed HTML tags" option set.

If you really wish to use inline style, you have to either:

unset the "Limit allowed HTML tags" option (which I do not recommend depending on the kind of users you give access to "Basic HTML" text format)
or use "Full HTML" text format

Best solution would be to rely on classes and styling in CSS stylesheets and inline styling should be used sparingly.

Hope this helps.


How to stop twig debug from breaking HTML when inside tags? Originally this was in a views field rewrite but i have since moved it to

views-view-fields--[view name]--[machine ID].html.twig

And behaviour seems to be the same:

 {{fields.title.content}}

This renders fine when twig debug is set to false in development.services.yml
When twig debug is turned on, the markup becomes badly broken.

I.e.

HTML does not support  inside tags, which seems to be the core issue.
Is there a workaround to this, or it's just a limitation of Twig debug?

You can apply |render|striptags|trim twig filters:

{{ fields.title.content }}

  If you want to save (not delete) for example div or img tags you can also write:

  {{ fields.field_image.content|render|striptags('
, ')|trim }}

Seen here https://www.drupal.org/node/2672656#comment-11821896


Is there a standard Drupal way to link to 3rd party configuration forms? I am writing a custom module.  On my module's configuration form I would like to provide links to relevant modules' configuration forms; e.g. the cron configuration form.

Is there a standard Drupal way to encode such links?
For instance is there a Drupal function that takes the menu path (eg. 'admin/config/system/cron') and provides an actual URL?

Thanks!

For instance is there a Drupal function that takes the menu path (eg.
  'admin/config/system/cron') and provides an actual URL?

Definitely!

print l(t('Cron configuration'), 'admin/config/system/cron');

Will print an a tag as follows:

Cron configuration

to the configuration with paths resolved correctly (works well when you have installed Drupal in a sub folder as well - just use the Drupal path).

If you are putting your own text, most likely that you are using t() function.
Example:

$form['warning']['#makup'] = t('You need to make sure that you have setup a working !cron',
  array('!cron' => l(t('Cron configuration'), 'admin/config/system/cron')));

l()  -  Generates the anchor link (text)

url() -  Returns URL for a given Drupal path (l() calls this function to get the correct link)

See function reference for more configuration (absolute URLs, prevent using aliased path, etc)


using entity reference fetch different fields automatically using entity reference, i am able to relate to nodes with one another. Thats great. The user while entering their blog has an option to relate it to nodes of my custom content type. This works great. Now i want that once the user has selected the node to be related to, the blog should not only show the title of the n node but also other fields from that referenced node. How can i achieve this?

Regards

On the content type that has the reference-field, on the "Manage Display" section, you can choose if you want "Label" or "Rendered entity", which will output the full node.


Use custom marker when specific checkbox is checked I am building an events page. The page is using Gmap, Locations and Views modules.

In the content type "Events", I have set a checkbox for "Featured Event", I want these events to stand out in the map, so I would like to use a different marker in the map if the event is a "Featured Event".

Please let me know how to do this. Thanks in advance

I would use CSS for this.

Add your featured checkbox field
Add a views-row class, in the format settings, with the replacement pattern of the value for the checkbox

Now I can't remember if GMap will add that class to the marker rows too. If it does not, I would advise you to override the template for the view and in the class section, add $fields['field_featured'], making sure that there is a space before it

Using that class, you can style it however you want using CSS and/or JS

Hope that helps!


Get "previous" and "next" buttons on view The view I want to create consists of two parts:

An overview page with all the products, that is sortable using Draggable Views.
The url given by /collection/
A specific page that is shown when a user clicks on a product in the overview.
The url given by /collection/[title]

Now I want prev / next buttons on the product page, based on the order given by Draggable Views.

I've searched for a couple of hours but cannot find anything that will do the trick. Can someone point me at an option or function that accomplishes this?

Thanks in advance!

This module might be able to do the trick Views navigation

  This module adds next and previous links on content pages when
  accessed from a view. It is intended for dynamic and/or paged view
  results, where the result set changes according to exposed filters,
  current user access rights,...


How do I create a link that redirects to a destination after completing an action? I'm trying to create login/logout options for menus that are parts of groups on my page. The thing is I want each menu to have that login/logout select redirect the user to the group page, not the user profiles. How would I go about setting this up in the path setting of the menu?

Have a look at the Login Destination module.  From the project page:

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.


Overriding a specific view mode html.tpl.php template How can I override the html.tpl.php template for only the "teaser" view mode of the "Article" content type?

I found this on the Drupal 7 Template (Theme Hook) Suggestions page on drupal.org page, but cannot see how to drill down to a specific view mode for a single content type.

  html.tpl.php base template: html.tpl.php The following are some examples of how you may override the base template:

  html--internalviewpath.tpl.php
  List item

  html--node--id.tpl.php

  See html.tpl.php in the Drupal API documentation for more
  information.

Will I need to implement a page preprocess hook to accomplish this?

As I am sure you know, the teaser view is only/mostly used when a list of nodes are put together, eg, the promoted to front page listing, a View listing, etc.

So, let's say you have a View page listing the most recent Articles, and it's sitting at www.yourhost.com/recent/articles, you could override the html.tpl.php there by creating a html--recent-articles.tpl.php file in your theme and modifying it accordingly.

Views itself also allows the use of node templates when a node is presented in a listing; if that is what you are needing or requiring, the template files there are along the lines of node-view-VIEWNAME.tpl.php.


Attempts at client side rendering? What attempts are there (successful or otherwise), to move the heavy work in templating to client side javascript?

If I understand your question, the only projects that I am aware of are

jQuery Mobile (I am pretty sure this is abandoned)
Backbone
Node.js

There is a related discussion in Using Javascript frameworks like Backbone with Drupal and some of the work for Spark could probably count, too.

I don't have direct experience with any of these, but I am in the early process of determining whether Backbone is a good fit for a particular project.


How to use NOT EXISTS condition? I have 2 tables:

|users |       |users_roles|
--------       -------------
| uid  |       |uid| rid   |
--------       -------------
|  1   |       | 1 |   3   |
|  2   |

For the authenticated users the role is missing in users_roles table. User with uid=1 is an admin. I want to write the following query in Drupal DB API:

SELECT
        uid
FROM
        users
WHERE
        NOT EXISTS(
SELECT
        NULL
FROM
        users_roles
WHERE
        users_roles.uid=users.uid
)

I tried with this code, but don't know, how to write the query for notExists condition.

$query = db_select('users');

$query->addField('users', 'uid');

$query_exists = db_select('users_roles');
$query_exists->addExpression('NULL');
$query_exists->condition("users_roles.uid=users.uid"); //<- how to do this. Doesn't work.

$query->notExists($query_exists);
$result = $query->execute();
foreach ($result as $record) {
        var_dump($result);
}

Why not use a simple db_query()? In many cases, this is a perfectly adequate way of doing things; you can still use named parameters, and you can build your query as you'd like. It actually performs (very) slightly better than a db_select() anyways (see: http://drupal.org/node/1067802 and https://drupal.stackexchange.com/a/1205/26).

The only reason to not use a db_query() for a particular select query is if you need the query to be easily extended or changed by some other module.

$result = db_query('SELECT uid
  FROM users
  WHERE NOT EXISTS(SELECT NULL
    FROM users_roles
    WHERE users_roles.uid = users.uid
  )')->fetchCol();

Anyways, your particular query is a little more complex than normal, but can still be done using D7's DB API. See:

http://drupal.org/node/1001242#comment-3921430
Database query with notExists ($query->condition('', $subquery, 'EXISTS');)


Delete button not working on forum comment I am using the AJAX Comments module.
For forum I am using the Advance Forum module.
In forum topic  I have some post replies, my issue is when I am click on delete button on forum comment a popup is shown with message:

  You are not authorised to access this page

I have assigned the permission so any one can delete their own comment.

I don't know what is the issue because on other content type comment its working fine but only on forum comment its not working.

There is a bug report about this

According to one of the comments written by Ravathi.M

  i am also having the same issue the comment wraper class is
  missing.for the initial execution.then i have added the
  ajax-comment-wraper class by custom js code.now it is working fine

Looks like the solution is that you need to add the ajax-comment-wraper comment-wrapper-[post#] class name to your forum comments.

Go to /sites/all/modules/advanced_forum/styles/naked folder and replace the advanced-forum-naked-post.tpl.php with this code:

<?php

/**
 * @file
 * Theme implementation: Template for each forum post whether node or comment.
 *
 * All variables available in node.tpl.php and comment.tpl.php for your theme
 * are available here. In addition, Advanced Forum makes available the following
 * variables:
 *
 * - $top_post: TRUE if we are formatting the main post (ie, not a comment)
 * - $reply_link: Text link / button to reply to topic.
 * - $total_posts: Number of posts in topic (not counting first post).
 * - $new_posts: Number of new posts in topic, and link to first new.
 * - $links_array: Unformatted array of links.
 * - $account: User object of the post author.
 * - $name: User name of post author.
 * - $author_pane: Entire contents of the Author Pane template.
 */
?>

<?php if ($top_post): ?>
  <?php print $topic_header ?>
<?php endif; ?>

<div id="<?php print $post_id; ?>" class="<?php print $classes; ?> ajax-comment-wrapper comment-wrapper-<?php print str_replace('post-','',$post_id); ?>" <?php print $attributes; ?>>

      <?php print $date ?>

      <?php
      // This whole section is for printing the "new" marker. With core comment
      // we just need to check a variable. With Node Comment, we need to do
      // extra work to keep the views caching used for Node Comment from
      // caching the new markers.
      ?>
      <?php if (!$top_post): ?>
        <?php if (!empty($new)): ?>
          (<?php print $new ?>)
        <?php endif; ?>

        <?php if (!empty($first_new)): ?>
          <?php print $first_new; ?>
        <?php endif; ?>

        <?php if (!empty($new_output)): ?>
          <?php print $new_output; ?>
        <?php endif; ?>
      <?php endif; ?>

    <?php /* End of posted on div. */ ?>

    <?php if (!empty($in_reply_to)): ?>
     <?php print $in_reply_to; ?>
    <?php endif; ?>

    <?php /* Add a note when a post is unpublished so it doesn't rely on theming. */ ?>
    <?php if (!$node->status): ?>
      <?php print t("Unpublished post") ?>
    <?php endif; ?>

    <?php print $permalink; ?>

 <?php /* End of post info div. */ ?>

      <?php if (!empty($author_pane)): ?>
        <?php print $author_pane; ?>
      <?php endif; ?>

      <?php if (!empty($title)): ?>

          <?php print $title ?>

      <?php endif; ?>

        <?php
          // @codingStandardsIgnoreStart
          // We hide the comments and links now so that we can render them later.
          hide($content['taxonomy_forums']);
          hide($content['comments']);
          hide($content['links']);
          if (!$top_post)
            hide($content['body']);
          print render($content);
          // @codingStandardsIgnoreEnd
        ?>

      <?php if (!empty($post_edited)): ?>

          <?php print $post_edited ?>

      <?php endif; ?>

      <?php if (!empty($signature)): ?>

          <?php print $signature ?>

      <?php endif; ?>

  <?php /* End of post wrapper div. */ ?>

      <a href="#forum-topic-top" title="<?php print t('Jump to top of page'); ?>" class="af-button-small"><?php print t("Top"); ?>

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

  <?php /* End of footer div. */ ?>

<?php /* End of main wrapping div. */ ?>
<?php print render($content['comments']); ?>

Since the forum post and the 1st comment have the same number 1 you will notice that clicking reply will affect the node post as well. Therefore, you will need to use jQuery to modify or remove the 1 from comment-wrapper-1 of the forum (node) post.


Is it a security issue to put CSRF token in drupal settings? I have an application where I created a REST resource to update a field on the user object to store bookmarked items.

When you do a post request to a rest resource you are required to use a header with X-CSRF-Token.

You can get this by making a call to "/session/token".  But I'm wondering if it's OK, if you have a "bookmarks" widget on all pages to include the token in drupal settings.

Or is this some kind of security issue?

Is it better to make a call through javascript to get the token, rather than have it in the drupal settings?

Or as long as you're logged in, having the csrf token in drupal settings is not a problem?

/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$vars) {

  // Add CSRF token to page for authenticated users.  Token
  // is required by rest resources on POST requests.
  if ($vars['logged_in']) {

    $route = \Drupal::routeMatch()->getRouteObject();
    $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

    if (!$is_admin) {
      $vars['#attached']['drupalSettings']['user']['csrf'] = \Drupal::csrfToken()->get(CsrfRequestHeaderAccessCheck::TOKEN_KEY);
    }
  }
}

Drupal.settings, and other global variables, will be available to cross-origin scripts that happen to be injected (possibly maliciously) into the site. The same applies to any other part of the document body, like meta tags or JSON script tags.

Sensitive tokens should ideally be stored in a place that is restricted to same-origin scripts, which includes cookies and localstorage: https://stackoverflow.com/questions/34782493/difference-between-csrf-and-x-csrf-token

(This shouldn't normally be critical, because script injection shouldn't be possible in the first place, and is a severe vulnerability by itself. But it's probably still a good idea to rely on multiple layers of security.)


Autoselect parent taxonomy if child is selected How can I have the parent taxonomy be automatically selected when one of its children gets selected? It would be a convenience if the parent is selected automatically in the backend for every child selected.

Right now, if I select a child and not the parent, then search or browse for the parent term, child terms under that parent are not brought back. This doesn't seem right.

similar question here: Check parent term when checking subterm

but if you need check all child when parent checked, you need some changes in JavaScript file


How to hide node field if value is x? Hiding a node field works great by default when the field is empty.

But I wonder how to hide a field when viewing a node if the value of a field is for example 3.

For now, I just need it for integer field.

Any suggestions?

Views Conditional or Conditional Fields can help you reach your goal .

  Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
  with fields in views. Conditions include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the condition.


List style article in drupal 7 I'm trying to create a content type that allows me to post multiple images from an external database in this sort of style: http://www.newageman.co.uk/14-time-travelling-celebrities

In an ideal world this is what I would like my group of fields to look like in the article creation screen.

Any idea how I would achieve this using best practices? To post articles like this I'm currently using a piece of php code but it's confusing for my contributors, so would like to use fields. I've never made a module or custom field before.

Essentially I am trying to recreate what this PHP does:
The input

<?php $folder = ''; ?>
<?php $location = ''; ?>
<?php
$title01 = '';
$content01 = ''; ?>

The output

1. <?php echo "$title01"; ?>

<img src="/sites/default/files/foldered_images/<?php echo "$folder"; ?>/<?php echo "$location"; ?>_01.jpg" />

<?php echo "$content01"; ?>

You can create a multiple-value field collection field.

In the "field collection item" entity type, you can create the fields for the image and body text.

Afaik, the built-in image field type does not really work with external images. This problem is discussed here: Linking image field to an external URL

And now for the output.

Under "manage display" of the field collection item, use Display suite, with ds_extras enabled. Choose "Reset" as the layout (which will disable all divs that wrap the field collection item). Then create a ds custom field using token, and use it to put the other fields into your custom html.

Or alternatively, override field-collection-item.tpl.php in your theme, or better, override field-collection-item--field-xyz.tpl.php. I am not sure which exact template suffix to use to target the specific field collection item type. You should play around a bit and then we can update the answer based on your findings.


how to be the last hook_page_alter called? If you implement hook_page_alter in your own module, your hook will be called somewhere between all the other modules.

I am trying to undo something another module is doing in hook_page_alter. Somehow my hook is called before the other one.

How can I become the last hook to get called ? Or, what is the first hook after hook_page_alter that still uses $page ?

To make your hook last called you can make use of hook_module_implements_alter
like the following:

function MODULENAME_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'page_alter') {
    // Move MODULENAME_page_alter() to the end of the list. module_implements()
    $group = $implementations['MODULENAME'];
    unset($implementations['MODULENAME']);
    $implementations['MODULENAME'] = $group;
  }
}


Assigning custom class to nested menu UL elements I'm trying to theme my menu to alter the default UL classes. So far I'm working with the following function:

function theme_menu_tree($variables){
  return '
' . $variables['tree'] . '
';
}

This works great but I need to apply a different class to the UL inside a parent item. Right now I get

Item

Link1

Link2

How can I target the second UL to give it a different class using the theme_menu_tree function?

This kind of issues should be managed by CSS, but if you realy need to override the theme_menu_tree() and define a custom ul class there, you can do that with the help of custom global variable created in theme_menu_link().

Not sure if it's "the right way" to do that, but works:

/**
 * Implements theme_menu_tree__[MENU NAME].
 */
function YOURTHEME_menu_tree__[MENU NAME]($variables) {
  global $level;
  $class = ($level == 1) ? 'my-class' : 'my-class-for-depth-' . $level;
  return '
' . $variables['tree'] . '
';
}

/**
 * Implements theme_menu_link__[MENU NAME].
 */
function YOURTHEME_menu_link__[MENU NAME]($variables) {

  $element = $variables['element'];
  $sub_menu = '';

  // set the global variable in order to use it in hook_menu_tree()
  // I called it "level" to avoid confusing with the $depth
  global $level;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $level = 1; // set the level as first for each list with submenu
  }
  else {
    $level = $element['#original_link']['depth'];
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}


Add View To page.tpl I hope that you could help me out with this. After much time ive finally managed to work out how to takeover the space that my breadcrumb was taking up. With this bit of space i thought about adding a banner in there or a welcome message. I dont want my site to look 'tatty' so the banner idea was soon forgotten. A welcome message would be nice but it will be going through all my site and im sure that folks will get a bit sick of it.

I was hoping to add a View of random quotes in there. You can see the 'spot' i mean on my frontpage here-
http://onlinebanter.com/

As i type this though i'm a wondering if i could make that spot a block region? Then i could have a welcome message on the frontpage and then use it as a region to add helpfull advice for differant sections of my site. also i could add a random quote view for within nodes etc.

Could anyone offer me advice on either adding a view to a page.tpl or creating a block region in the wee spot ive found?

All help appreciated.

thanks

You can open your theme's .info file and add regions[my_region] = My region. Now open your page.tpl.php and do print $my_region (the name of the variable corresponds to the regions array index - see the first sentence) where the region should be rendered. After this make sure to clear your Drupal's cache so that it picks up the new region and the modified page.tpl.php.

Views can generate block displays. After you created the block display, you can use the Drupal's default blocks interface to put the Views block into the region you created, or better yet use a module like: Context which gives you more control over when to show which blocks in what region and when not to...


How can I display empty text for an empty CCK field that is output in a node template I am using a node-content_type.tpl file to control the content display of a certain content-type. I am rendering the fields like so:

print $node->field_name[0]['value'];

I want to display some empty text if the field is empty so it doesn't show up blank. Is there a way to set empty text for all of the field of a content type so I don't have to check every field individually? Can I do this in a preprocess function in my theme's template.php file?

You could use an if statement, to check for value, and if not print something else:

<?php
  if (!isset( $node->field_name[0]['value'] )) {
    print t('My empty text');
  } else {
    print $node->field_name[0]['value'];
  }
?>

But I think that if you print the whole field  you don't need to do this. Use something like:

<?php print $node->field_name_rendered; ?>


Ajax button in list to delete row entry - submit function is called instead of callback I have a themed table on a form. To delete entries in this table I render buttons for each row having a special idx and an ajax callback for each button.

The buttons are rendered perfectly, but when I click on the button, the standard submit routine is called instead of the assigned callback routine. Is there anything I missed?

// build header for table
$pheader = array('Name','Action');
// build data array for table
$aPersonsTable = array();
foreach ($aPersons as $key => $value) {
  $form_button['button'.$key] = array(
    '#id' => 'del-p-'.$key,
    '#name' => 'del-p-'.$key,
    '#idx' => $key,
    '#type' => 'submit',
    '#value' => 'Delete',
    '#submit' => 'delete_auction_person_ajax_callback_submit',
    '#attributes' => array('class'=>array('ajax-processed')),
    '#ajax' => array(
      'callback' => 'delete_auction_person_ajax_callback',
      'progress' => array('type' => 'none'),
      'effect' => 'fade',
    )
  );
  $deleteButton = drupal_render($form_button['button'.$key]);
  $row = array($value['dname'],$deleteButton);
  $aPersonsTable[]=$row;
}

$form['persons']['ptable'] = array(
  '#theme' => 'table',
  '#header' => $pheader,
  '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
  '#disabled' => TRUE,
  '#title' => 'Users currently assigned',
  '#empty' => t('No users assigned yet!'),
  '#prefix' => '
',
  '#suffix' => '
',
);

Remove the '#submit' => 'delete_auction_person_ajax_callback_submit', it does not seem necessary. Adding ajax-processed class on the button doesn't seem necessary either. The function delete_auction_person_ajax_callback receives $form and $form_state, and will tell you what input was clicked that triggered the callback, from there you can do whatever it is you need to do.

I built a lot of tables this way, but I don't think I had the form items as a submit type. If I recall, I used buttons.


How to use not in in drupal views 3 I'm using Drupal 7 with views 3.

I need a list of students who have due payments in a view. The students who have paid the fees are stored in a new table. Now I want to show the students which are not in other table. How can I have this is views 3

EDIT Better explanation of query

I am using views 3 to get a list of students who have due payments. The students who have paid the fees are stored in a new table. Now I want to show the students which are not in fees paid table. How can I have this is views 3.

My Table structure is:

I have a table structure for fee details as

fid
name
description
currency
fee
instalments
created

This fee schedule has N no of instalments and storing in a cross ref table as

iid
fid
instalment_no
amount
payable_by

This fee schedule has associated students and are storing in a cross ref table as

fid
uid

The table structure for paid students who has paid fees.

pid      Payment ID serial
fid      Fees ID details
iid      Instalment No
uid      Student who has paid the fees
paid_on  Payment date

Thanks in advance for your help.

My suggestion: You could make this a great deal easier for yourself if "Has payed" a field on the User entity instead.

Answer to your question: You need to expose the custom table to Views, by telling Views that it exists and what type of data there is in it. The canonical way of doing that is with hook_views_data, although the Data module claims to be able to do this automatically.

Once you have the data in Views, you create a View based on "User", and add a "Filter" to remove all users in the "Payed" table.


Using Bootstrap theme and anonymous user, ajax form submit results in "call to undefined function bootstrap_form_process" Context

We have a subtheme based on the Bootstrap theme and we're rendering a form inside of a modal. The submit button uses an ajax callback to handle form submission.

Problem

When logged in as an admin in Chrome, the form submits perfectly.

When logged out (accessing the site as an anonymous user) in Chrome, submitting the form results in a 500 Server error.

The server logs are reporting "Call to undefined function bootstrap_form_process()".

Research

It seems that this might be related (https://www.drupal.org/node/2156371) but I'm not sure what to do to fix it.

I have a hard time following issue discussions on drupal.org. I have a decent amount of Drupal knowledge, but still struggle to figure out what they are saying.

Things I've Tried

Some people in the thread linked above got around the issue by setting max_input_vars to 2000, so I gave that a shot. It didn't help.

I thought maybe I needed to increase it even more, so I set it to 5000, but still no change. I then switched it back to the default 1000.

I also tried adding "drupal_static_reset('element_info');" to my theme's template.php file, but it didn't seem to do anything.

This is similar to https://www.drupal.org/node/2369635, i.e. you need to include /path/to/bootstrap/includes/process.inc in your codebase.  The easiest way IMHO is in a hook_init() somewhere.


Do I need RDF enabled on a normal site? When you install Drupal 7, you notice that RDF is enabled by default. Now... I have a website called 7 Tutorials and I am wondering if RDF is useful, considering the content shared on the website.

I read a bit about it and learned that the "Resource Description Framework" is the standard for encoding metadata and other knowledge on the Semantic Web.

I admit I did not research much about it and I am not sure I fully understand its use cases but, it sounds to me RDF would be useful only to websites which share data in a structured way. Is this correct? Would I have anything to gain by enabling RDF on my website? (e.g. help with SEO).

As far as Google is concerned if your website is well structured it will be easy for crawlers to crawl your website.Morever Google Rich snippets uses RDF and it needs every site to be RDF structured if you want to enable rich snippets for your website.

Drupal 7 rich snippets and RDF

  So Unless you have any problem with RDF module enabled why you need to
  disable it?


Views : how to combine fields in exposed filter using is between operator In a view showing commerce products, with exposed filters, I need to make a slider filter for commerce_price field. This is easy with exposed filters (is between operator) and BEF module, but ...

commerce_price field is retrieved in the view by its relationship to Product variation type, and I've got 2 different Product variation types for the same product display :

  And

This means you can make a slider for each one, but this makes no sense for end-user to have 2 prices slider !

And by default Views 3.x  Global: Combine fields filter doesn’t provide "is between" operator, it only works with strings and operators like equal to, begins...

How can I filter the values of both relationships in a single slider for that Price field ?
Is there a Views setup way or a module to do that? If not, how can I add a custom filter to my view using API ?

This is a "smoke and mirrors" situation, in which you want the end user to experience one thing when the code is doing something completely different.

I would do a little bit of jQuery trickery.  First, I would expose all 4 fields (the high and low for each of the 2 fields) as text boxes.  Then, I would use the jQuery UI slider (which ships with Drupal Core) to update the high and low values as the user changes them.  Of course, the jQuery should hide the actual text boxes as well.  This will give you the effect that you are looking for.

Finally, if you wanted this to be ultra simple in the event that Javascript fails, you can use a form alter to hide one of the pairs of text boxes and then, when the form is submitted or the view loaded, populate the values for the other filter programmatically.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'THE-FORM-YOU-WANT-TO-TARGET') {
    // you'll have to look through the $form array for the field you want
    // I suggest installing Devel and running dsm($form);

    $form['YOUR-FORM-ELEMENT']['#default_value'] = isset($_SESSION['max']) ? $_SESSION['max'] : 1000;
    // Do this for all the applicable form elements...

    // Finally, tell Drupal that you want to see the form when it is submitted.
    array_unshift($form['#submit'], 'MYMODULE_filter_submit');
  }
}

function MYMODULE_filter_submit($form, &$form_state) {
  $_SESSION['max'] = $form_state['values']['YOUR-FORM-ELEMENT'];
}

You'll have to double-check to see what the variables actually look like.  I suggest installing the Devel module and putting dsm($form); and dsm($form_state); at the beginning of the functions.

Lastly, any time that you add a hook, don't forget to clear your cache or Drupal won't find it.


How to create a list of paragraphs not linked to a node Is there a way to create/edit several paragraphs (from within a UI) and use them grammatically by after.

Here is my use case:

I have a paragraph type made of 3 fields:

Unit Source : taxonomy term reference (Kg, g, piece, box of
tomatoes,...)
Unit target : idem
Conversion factor: floating number

And I would like to encode some data like

Unit source = box of tomatoes
Unit target = kg
Conversion factor = 3

(A box of tomatoes is equal to 3kg of tomatoes)

I would like to be able

1- to encode through a UI a list of those conversion data

2- to be able to call them in some other function by after.

No, this is not possible. By concept paragraphs are always tied to a parent entity, just like normal fields. If it can exist on it's own, better use a node instead.


Rate widget won't display I am trying to use the rate widget in Drupal 7, and everything looks like it should work correctly, however it isn't displaying.

I'm on one of the node types it should appear under, it does not show up.

I used to have Fivestar installed, could that be an issue?

Here's a screenshot of the nodetypes I've selected

Any help would be appreciated, I can't find anything I've done wrong or that would prevent it from showing up.

I was just having the same issue.  Using a custom tpl.php for the node seems to fix it.

Cheers,


Migrate plugin migration_lookup : dynamic migration id "node_a_migration" is the migration ID of nodes of type "node_a"
"node_b_migration" is the migration ID of nodes of type "node_b"
I'd like to use either "node_a_migration" or "node_b_migration" as a migration_lookup depending on other field value.
The source (not a drupal site, entities of content A and content B can have the same id, because stored in different tables) :
[
  ['entity_type' => 'content_a', 'entity_id' => 123],
  ['entity_type' => 'content_b', 'entity_id' => 123],
]

The migration config :
process:
  pseudo_field_migration_id:
    plugin: static_map
    map:
      content_a: node_a_migration
      content_b: node_b_migration
    source: entity_type
  field_entity_reference:
    plugin: migration_lookup
    migration: '@pseudo_field_migration_id'
    source: entity_id

There is no error when running the migration, but the field_entity_reference is not populated.
It works if I manually replace '@pseudo_field_type_id' by node_a_migration
Any idea how to make it work ?
Thank you!

As @Hudri suggested, I've created my own process plugin (extending MigrationLookup plugin):
my_module/src/Plugin/migrate/process/CustomMigrationLookup.php

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\Plugin\migrate\process\MigrationLookup;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * @MigrateProcessPlugin(
 *   id = "custom_migration_lookup"
 * )
 */
class CustomMigrationLookup extends MigrationLookup {

  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // We set the migration id based on the field configured in "migration_id_source"
    $this->configuration['migration'] = $row->getDestinationProperty($this->configuration['migration_id_source']);
    // We continue with the standard migration_lookup process
    return parent::transform($value, $migrate_executable, $row, $destination_property);
  }

}

The migration config :
process:
  pseudo_field_migration_id:
    plugin: static_map
    map:
      content_a: node_a_migration
      content_b: node_b_migration
    source: entity_type
  field_entity_reference:
    plugin: custom_migration_lookup
    migration_id_source: 'pseudo_field_migration_id'
    source: entity_id


Programmatically create node using feeds I'm creating nodes from XML using the Feeds module (great module BTW).

function boardgamegeek_menu() {
  $items['games/add/%/%'] = array(
    'title' => 'Boardgamegeek add game',
    'description' => 'Boardgamegeek add game',
    'page arguments' => array(2, 3),
    'page callback' => 'boardgamegeek_add',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function boardgamegeek_add($objectid, $title) {
  $node = new stdClass();
  $node->type = 'boardgame';
  $node->title = $title;
  $node->feeds['FeedsHTTPFetcher']['source'] = 'http://www.boardgamegeek.com/xmlapi/boardgame/' . $objectid;
  node_save($node);
  /*
  // This does an import
  $myFeed = feeds_source('game_importer');
  while (FEEDS_BATCH_COMPLETE != $myFeed->import());
  */
  return 'http://www.boardgamegeek.com/xmlapi/boardgame/' . $objectid;
}

When I run this code, a node is created with a title field value from $title (that's exactly what I want). The import doesn't start automatically, and when I start the import myself, another node is being created without any title.

I would like to update the node I created...

The feed_nid and the entity_id should be the same. The feed_nid is the node id from the node I created, the entity id is the node id feeds created.

Any ideas?

From the description what I understand is that you are trying to create a node with all the contents from the feed except the Title which you have set manually.

You have created a feed which would run when you create a node of the type "boardgame" with an HTTP Fetcher.

The way feeds work in this case is when you create the node with the attached feed. It creates a node for the feed itself and also creates additional nodes with the contents in the feed. So in effect the feed is not meant to update the node executing the feed but to create additional nodes from the feed itself. And I guess that is happening without any issue in your setup.

To achieve what ou want to do you can install the following module

Feeds Self Parser

What this does it to update the node being created from the feed it self and not create another node instead.

Note : You might have to clear cache for the module to work other wise you might get an error FeedsMissingPlugin_feeds_form in drupal_retrieve_form()

This way you dont really need to create a module just create a node with the with the title entered and the url as well. But if there is some other reason from creating the module then yes that would work fine as well.

Second option is to not use the feeds module itself. Just parse the xml manually and add the required fields and call the node_save() function. This would mean you wouldn't have to run the feed script after you create the node it would be done automatically by just calling the url. and it will also take you off the overheads of using the feeds module.


Search module for taxonomy terms? Having browsed through drupal.org with no results for D7, let ma ask the public: does anyone know of a Search module that would extend the search by taxonomy terms?
I have a very taxonomy-intensive site, where each taxonomy term has a rich description field, as well as its own term page. I want user to be able to find not only nodes but also taxonomy terms.

I'd highly recommend using Search API with which you can create an index and custom search from any entity including Taxonomy terms. You can then customize your search page using Views.


Why doesn't a form immediately call its submission handler? I have a form which is called from a page function. The page initially makes some external calls to get #default_value data which gets passed to drupal_get_form(). When the form is submitted, the page function gets called before the submission handler. Why is that? I don't get it and I don't want that to happen because it then connects to an external data API for no reason.

Does anyone know of a good place to find the calls order for a default submission handler? I'm unable to debug this.

There is an AJAX update when the form inputs refresh, but I don't see how that matters.

To understand this, we should step back a bit in look at how forms are used regardless of what CMS (if any) is in use.

All <form> tags have an action attribute which define what page the browser should send the data to. If action is left blank (or missing) the browser will assume it should send the data to the same URL it is currently on. In this scenario the URL will be loaded to get the form and then again to send the data.

This is how the Form API works (by default). When you define a URL (using hook_menu I presume) that presents a form to the user, the browser will use the same URL to load and send the form.

The menu router in Drupal has to be run first so it can determine what page to display. Only after that does Drupal see that it has a form and then run the submit callback. In other words, you cannot change the order of these functions.

You can provide an #action attribute in your Form API implementation which (combined with a new hook_menu entry) should let you separate your form load/submit functions.


Vanilla Javascript Firing Twice I have some simple dom manipulation I want to make using javascript without jquery. I can't seem to figure out how to prevent this code from firing twice.

Almost all examples I find use jQuery, but I do not want to add jQuery just for this. I'm trying to use es6 with babel here.

((() => {
  Drupal.behaviors.node_page_filters_sales = {
    attach: (context, settings) => {

      const usaButton = document.querySelector('[data-sales-switcher="83"]');
      usaButton.style.border = '6px solid orange';
    }
  };
})());

This code works, but it is run twice. Once when there selector queried does not exist, giving me a typeError, and one when it does, executing the code as expected.

It seems like it's related to BigPipe. If i turn that off, things seem to work as normal, firing once. But I obviously want BigPipe turned on. I'm clearly missing something that needs to be done when dealing with it.

For a little more detail, this is in a custom module. The custom module creates a block plugin. The javascript (snippet above) is part of the custom module's library that's attached to the block template.

UPDATED CODE EXAMPLE

The inline style was just for testing purposes. I'm attempting to check multiple buttons and add/remove classes based on a variable. See below.

// Determine default region.
let defaultLocation = '83';

if (defaultLocation === '83') {
    document.querySelector('.tid-83').classList.add('active');
}

I also notice that the javascript works as expected and is only executed once if I'm not logged in. When logged in, it fires twice.

I don't think you can force javascript to only run once. In addition to big pipe, any lazy loader, ajax form update (consider entity reference fields), or other ajax functionality on the page can trigger javascript to run again.

This is the issue that jQuery.once() addresses, and the reason it is used. It adds a class on the element, then executes on elements that do not have the class and adds the class. I expect you could reproduce this with something like the following.

const usaButton = document.querySelector('[data-sales-switcher="83"]');
if (!usaButton.classList.contains('node-page-filters-sales-once') {
  usaButton.style.border = '6px solid orange';
  usaButton.classList.add('node-page-filters-sales-once');
}


How to lock a piece of content form being edited by specific roles? I'm using Drupal 7. Right now, all users can create certain content. the way I have it set it is that all content has to be approved by users of the "editor" and "administrator" roles. Once the content is edited and approved I want to lock out the author so that he can not edit it anymore.

I've not used it, but the Content Lock module might fit your needs!

EDIT AFTER COMMENT

What you could do then is utilise Taxonomy Access Control using the following method:

1) Add a Taxonomy vocabulary called "Locked" (or something like that)

2) Add two terms to that vocabulary - Locked and Unlocked

3) Set the permissions for authenticated users to be able to add/edit the content, but do not allow them to set the taxonomy terms.

4) Set the permissions using TAC so that if a node has the term of Unlocked, it is still editable, but as soon as that term gets changed to Locked, then authenticated users cannot edit that node.

5) Once the content has been submitted and approved, the user with the Editor or Admin role sets the term on the node to Locked.   This will prevent the user from being able to access the edit page for the node.

It sounds much more complicated than it really is.  You'll see what I mean when you get to the settings page for TAC.


How do I set start date with the core date field? I need set the start date (e.g. now +1) for my date field. How can I do this on Drupal 8.1.x?

When you create your field, you have the option of setting a default value.  Set the Default Value to Relative Date and then ender "+1 day" into the textfield, and proceed with setting up the field.

When you create new entities with that field, it will default to the current time +1 day, which you can then change if needed.


Add jQuery to exposed filter form on drupal 7 I've been searching around how to add jQuery to Drupal 7, but i couldn't make it work.
Here is my steps:

Step 1: I create a javascript file and put into my module under js directory.

Step 2: I added the file to my module .info

 scripts[] = js/xxx.js

Step 3: The contents of the xxx.js

(function ($)
{
  Drupal.behaviors.mymodule =
  {
    attach: function(context, settings) {

    $("#edit-field_a",context).change(function(){
      currentValue = $(this).val();
      alert(currentValue); // no fire at all
      if(currentValue == 'a')
        {
            $('#edit-field_b').val('All');
        }
    }

}
};

})(jQuery);

All the fields are on exposed filter form.
I wish to do something like the value of the field_b select list changed based on field_a select list.

What did i miss? Is my jQuery correct?

Updates: Previous js is wrong, corrected here.

 (function ($)
{
  Drupal.behaviors.mymodule =
  {
    attach: function(context, settings) {

    $("#edit-field_a",context).change(function(){
      currentValue = $(this).val();
      alert(currentValue); // no fire at all
      if(currentValue == 'a')
        {
            $('#edit-field_b').val('All');
        }
    });

}
}

})(jQuery);

Do like this:

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'FORM-ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/js/SCRIPT.js' => array(
        'type' => 'file',
        'group' => JS_LIBRARY, // or JS_DEFAULT, JS_THEME.. read this -  https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
      ),
    );
  }
}


Need a hook a little later then hook_node_insert I am working on a module to unzip the contents of my file field after I have submitted the node.  I originally tried to do this in hook_node_insert but this did not work for me because my file field has a custom file path and at the time of hook_node_insert the file is still in the default upload location and it is then moved to the custom file path at some later point.

I also though maybe I could implement my unzipping code hook_file_move (which gets called when the file is moved to the custom file path) but it seems that there is no way to verify that the node type from hook_file_move.

Is there some better hook to implement this unzipping code where I can both verify the type of the node and late enough in the content creation process that the file will have been moved to the location of the custom path.

Did you try to make your module's weight higher, to make sure your hooks get executed after all other modules' ? The documentation states that node_insert is called after file_attach_insert so it might be worth a try.


Can www.example.com/node/123 be used as a canonical url? We are sharing some of our content with partners and want to include a canonical reference to the pages on our Drupal site.

I like the idea of using www.example.com/node/$nid for the simplicity of it, but I don't know whether it is acceptable for a canonical url to be redirected (as is commonly done with clean urls, path_auto, redirect, etc)?

Permanently redirecting the canonical URL is allowed, but discouraged by RFC 6596:

  To better ensure that applications properly handle the canonical link relation, administrators ought to consider the following guidelines:

  […]

  Avoid designating the target (canonical) as:

  […]

  The source IRI of a permanent redirect (for HTTP, this refers to 300 and 301 response codes defined in Sections 10.3.1 and 10.3.2 of [RFC2616]


How to set image as background I am using bartik theme. I have an image that I like to use as background of the home page only. Admin > appearance > Bartik > settings > I see different colors to set as background. Can I have an image as background instead of the color for the home page. And for other pages I can use a color.

Thanks.

D

unless you want to add it to a theme setting so that it can be adjusted by UI, the simplest way is probably to override page--front.tpl.php in your theme template directory, and manually add the html to create the background.

For more info on page template naming, see here.


How to display comment form and comments per node in a view I am trying to display comments + comment form per node in a view of nodes following this answer. So I'm trying full content display with row style options, which works perfectly on another site I am working on, but on this one, I don't have the "Display comments" toggle box

So I have reinstall the site and disable every thing I could : contrib modules / themes and templates / custom code / libraries / fields & comment fields / all content types trying with new ones / uninstall & reinstall comment modules / combination of permissions for all/just admin in view-post-skip options. Still nothing.

Anyone has seen this before?

Check if you've comment module installed, if yes, also check if you've comments enabled for that content type


Add 'Top product' field to products Ubercart I'm trying to filter products on the homepage of my webshop (Views module). I want to add small ribbons to my products like: New,Top,Sale.

I made everything with the Views module but I think need to add a field to the Product content type but don't know what I need to choose, if I edit the product there should be a checkbox so I can edit if this product is New,Top,Sale or not.

The default product and all product classes are a node content type that can have fields added to it. Go to Structure > Content types > Product > Manage fields to add your checkbox fields. The field will then be available in any node view for display or filtering.


How to view several Colorbox images simultaneously after click on wide screen? Usually I see only one big overlay image after click thumbnail with Colorbox.

Is there Colorbox settings to view several overlay images simultaneously on wide screen after click?

You need to choose per page gallery in colorbox formatter settings like in screenshot :


Views are disappearing randomly; always needing to flush caches I am writing a module that has 2 views in code. At first, I pasted the code that was exported from views directly into hook_views_default_views() like so...

function MY_MODULE_views_default_views() {
  $views = array();

  // Copy and pasted code from views export here...

  $views[$view->name] = $view;
  return $views;
}

After installing the module, the only way to get the views to show up would be to run cron and then flush the caches. I tried just running cron, or just flushing caches, and it would only work if I ran them both in that order. Once the views showed up, I could go along with things fine for a little while, then randomly the view would disappear again. I could not figure out a pattern to why they would disappear. Flushing caches would mostly fix it. Sometimes I had to flush caches two or three times or run cron and flush caches to get the views to appear again.

I searched around for some help and was able to find this post... A whole view disappears. This seems to be a similar problem. The function is too long and each view needs to be split into separate files. Okay, I did that and now my code looks like this...

// Files located in "my_module/views":
my_module.view_1.view
my_module.view_2.view

/**
 * Implementation of hook_views_default_views().
 */
function MY_MODULE_views_default_views() {
  $views = array();
  $files = file_scan_directory(drupal_get_path('module', 'MY_MODULE'). '/views', '/.*\.view$/');
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }
  return $views;
}

This is a nice solution as it makes adding new views very easy and clean. However, I am having the exact same experience as before. After installing the module, it still takes a cron run and a cache flush for the views to show, which they eventually do, but then they still disappear randomly. The only way to get them back is to flushes the caches (sometimes several times), or run cron and flush caches.

I'm feeling pretty stuck here. If anyone would be so kind as to offer some guidance, that would be most appreciated. Thank you.

Thank you so much to kladria on IRC #drupal-support for helping me through this one!

After using a debugger to step through the code, I saw that my implementation of hook_views_default_views() was not being called. The problem I was having was that the function was in the wrong file. Originally, I had the function "MY_MODULE_views_default_views()" in the file "My_MODULE.views.inc", and it is supposed to go in "My_MODULE.views_default.inc". That "_default" made all the difference for it to be auto-loaded correctly.

So far, there has been no more needing to flush caches, and the views haven't disappeared. I'm pretty sure this did the trick.


Filtering my products on drupal commerce I have imported 5.000 products to my drupal-commerce website.I want the user to be able to navigate fast on all of these products,so I just figured out that I need to make somehow a filter or a search that when the user chooses/selects some of the features of the product the result will be only the products with these features.How can I manage to do this on Drupal 7 and Drupal Commerce(Commerce kickstart?)

You can do it in the view.

Select a filter criteria for example "size", then click on expose filter.

This permit you create a custom search box as well clicking on "exposed filter in block" under Advanced in view.

First part of a tutorial http://www.youtube.com/watch?v=9-sKG1bplx0


After DB backup and restore: Call to undefined function user_access() in ...includes/menu.inc This question pertains to a Drupal 7 multi-site install. As a test for some future backup/migrate bash scripting that I am doing for work, I made a backup/dump of my test site postgres DB. I then dropped the DB and recreated it with the same (old) name. I then restored the DB from my backup. I did not touch any files. I thought everything had worked out well, except I have an error that I cannot figure out:

  Call to undefined function user_access() in .../includes/menu.inc on line 634.

Things I've tried:

As a sanity check, I made sure that User module was in my core files and that user_access was defined in user.module
Checked out the restored database in pgAdmin, made sure that user 0 (anonymous user) was still there
Truncated any table starting with '_cache':

Truncate table prefix_cache;
Truncate table prefix_cache_block;
Truncate table prefix_cache_bootstrap;
Truncate table prefix_sessions;
Truncate table prefix_cache_field;
Truncate table prefix_cache_filter;
Truncate table prefix_cache_form;
Truncate table prefix_cache_image;
Truncate table prefix_cache_menu;
Truncate table prefix_cache_page;
Truncate table prefix_cache_path;

Checked the system table and disabled, checked and re-enabled various modules including user module via the 'status integer' value/col. (I'm not sure if this is the way to enable and re-enable modules in the DB).
Tried to install Drush on my server but file permissions are very restrictive. It seems that Drush has limited abilities. Drush can only clear its own cache even after I setup an alias for the site in question.
Created a 'modules' directory inside of the site's multi-site directory and copied the user module out of core and put it there.
Tried the export using utf8 as the encoding of the DB and re-importing (no change in error)

Here are few tips:

make sure your Drupal core has all the files in the right place (especially user module),
upgrade your Drupal core to the latest version (drush fr && drush up drupal)
clear all your caches (drush -y cc all), including your memcached (killall memcached),
rebuild your registry by using Registry Rebuild,
if you're using modules which are implementing drupal_bootstrap() (such as Secure Site), disable them,
try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem,
use XDebug and generate a trace file to analyse the code execution,
or use IDE debugger, breakpoint on the failing line and check why the function doesn't exist,
test it on different environment/machine,
eventually restore your database from the point where it was working before.


Client-Side Equivalent of drupal_set_message with javascript I've got javascript that notifies the user of actions and errors, and I'd like to use the existing Drupal messaging. Is this built in to Drupal?

Alternatively, (I'm fairly new to Drupal and am not very familiar with the modules available) if this is available as a module, I haven't been able to find it. Does anyone know of a module?

UPDATE: To clarify, I'm trying to set a Drupal message from the client-side (JavaScript), on a page that has already rendered. This is a very AJAXy page with tonnes of functionality that sometimes requires messages be shown to the user.

Is there is a provision in the Drupal client-side API for setting messages?

I don't see JS API for dispaying messages even in D7. Maybe because all you need is DIV with classes like messages,status warning or error. You can see how drupal works with it in file /misc/tabledrag.js.
When you drag rows in tables drupal shows you a warning message with this code:

$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');


Add separate div after a form All I want to do is add a new <div>, ideally just after a <form> element.  I have a self-written module that generates a payment form, using some routing, like this:

mymodule.applications.payment_form:
  path: '/payment/{submission}'
  defaults:
    _form: '\Drupal\mymodule\Form\PaymentForm'
    _title_callback: '\Drupal\mymodule\Form\PaymentForm::getTitle'
  requirements:
    _role: 'authenticated'
    _custom_access: 'Drupal\mymodule\Form\PaymentForm::access'
  options:
    parameters:
      submission:
        type: entity:webform_submission

The PaymentForm class has a standard buildForm() method, and it's easy to add render arrays to the $form build form elements and other decoration etc. But those are all within the <form> tag.

The payment form is displayed in the main page content block.

I've been trying is HOOK_preprocess_HTML in my mymodule.module file and looking at $vars.

$vars['page'] contains the various regions: sidebar_first, content, secondary_menu etc.

$vars['page']['content'] consists of:

'mysite_page_title' => array(13)
'mysite_local_tasks' => array(3)
'mysite_help' => array(3)
'mysite_local_actions' => array(3)
'mysite_content' => array(12)
'#sorted' => boolTRUE
'#theme_wrappers' => array(1)
'#region' => string(7) "content"

mysite_content is a block - and I can't see how I can modify it from here...

I've also tried HOOK_block_view_BASE_BLOCK_ID_alter, which in this case is system_main_block (for the page content).

function mymodule_block_view_system_main_block_alter gives me a $build array with a #block element, but I don't see how I can find the <form> elements in there either and place something afterwards…

Anything else I can do?

There might be hundreds of ways to add this markup in Drupal. The two simplest that came to my mind are:

1) Add a suffix to the form tag in form build or form alter:

$form['#suffix'] = '
Suffix to form
';

2) or add the markup in a form.html.twig below the form tag:

{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

  A div container after the form

For the second solution you might also need to add a theme name suggestion.


How to use Drush in remote server? I'd like to use drush methods in the remote server.
As far as I know I have to install Drush in the remote server.
But my server provider tell me that Drush has many conflicts with other modules that the server is already running. How do you manage to use Drush in remote server? Is my server provider answer acceptable?

It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed.  This is possible because the Drush commands drush rsync and drush sql-sync work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.

In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias.  Otherwise, Drush will try to use Drush on the remote system to look up these values.  See example.aliases.drushrc.php for more information.

Note that it is really useful to be able to at least run drush updatedb on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster.  The Resources page on drush.org lists some hosting providers that are Drush-friendly.


In Drupal Commerce, what Rules need to be set to go directly to checkout after Add to Cart button is clicked? On a fresh drupal commerce install, clicking on add to cart brings your back to the same page. What is needed in Rules to have it go straight to checkout after clicking on the Add to Cart button?

Since this isn't built into Drupal commerce itself, you have to create a new custom rule (admin/config/workflow/rules). The event would be called:

After adding a product to the cart

and then the action would be:

System > Redirect Page

URL should be: checkout


Can't update nodes / node unpublishes itself This problem has been bugging me for some time now and I haven't been able to find this issue online anywhere else.
My Drupal 7 website has a very simple photo gallery, using a custom node type called gallery with image upload fields.
One or two of these nodes (but not all) have started behaving very strangely. When I upload new images, the files appear to upload successfully and the thumbnails appear, but immediately I get a message directly above the field on the edit page saying "Gallery (node title) has been updated." Normally this message would only appear after submitting changes using the save button.
When I click 'Save', I get the following message:
"The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved."
At this point, the node unpublishes itself, and the changes I make are not saved. The only way to publish the node again is by using the /admin/content interface.
I have noticed that nodes that have many images are the problematic ones. One such node has 160 images.
This behavior only happens with the gallery node type. I have tried creating a new node type with the same fields and recreating the node from scratch, but the same thing happens. I have tried using the image widget and the multiupload widget.

This seems to be a common problem when exceeding the max_input_vars on saving nodes. Which might seem your problem regarding the 160+ images on the node.
First, check your server logs for anything related to this error.
Then update php.ini (check for max_input_vars)  to an amount that suits your needs.


How to make sure that drupalSettings value gets updated on the JavaScript end? Have an ajax callback function within which the data gets generated dynamically based on the custom input from form fields.

//ajax callback submit
$form['action'] = [
'#type' => 'button',
'#value' => $this->t('Submit'),
'#ajax' => [
'callback' => '::getData',
'wrapper' => 'table-data',
'method' => 'replaceWith',
'effect' => 'fade',
];

//ajax callback function
public function getData($form, FormStateInterface &$form_state) {
$table_data = $this->getTableData($form_state);  //getting the data dynamically
$form['section']['#attached']['drupalSettings']['table_data'] = $table_data; //assigning the data to drupalSettings
dpm($table_data); //to check if the assignment is updated
    return array($form['table_markup'],$form['section']);   //$form['table_markup'] is a markup used to display data in the table
   }

//javascript code
(function ($, Drupal, drupalSettings) {
    Drupal.behaviors.display_data = {
    attach: function (context, settings) {
        alert(drupalSettings.table_data);
        var table_data  = drupalSettings.table_data;  //inconsistency noticed in this assignment
    }
};

})(jQuery, Drupal, drupalSettings);

Now whenever I click on the submit button, the $table_data gets updated and assigned to the drupalSettings dynamically, but passing its value to the javascript seems to be behaving inconsistent, meaning the drupalSettings.table_data within javascript does not get updated but shows the previous set values.

For it to work correctly I have to reload the page, change the form inputs and submit.

I've realized it may have to do with the cache and tried to avoid it by setting the routing.yml file as below:

  options:
    no_cache: 'TRUE'

Not sure how to use cache tags here, as I do not have any tags defined
Tried to rebuild the form within the callback which didn't work either.
The form input fields does not get cleared even after reloading the page and I'm confused why this happens even after the no_cache is set to true?

Tried using 'delete' on javascript end, which didn't work either

Is there a suitable approach to make sure that the variable from drupal php, received on the javascript is always an updated one?

In this case instead of returning HTML (aka the form render array) your AJAX callback method needs to return an AjaxResponse object (see API docs). The AjaxResponse object should contain at least 2 commands, one for updating your HTML (the processed form) and other to update the drupalSettings object. A possible response could be like

public static function ajaxCallback(array $form, FormStateInterface $form_state) {
  // Assuming the $form variable is either the updated render array or rendered output.
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('#wrapper-id', $form));
  // The $data variable is an assoc array with he same keys you passed during the build under #attached key.
  // If you don't want to merge the settings but instead replace it, remove the second argument.
  $response->addCommand(new SettingsCommand ($data, TRUE));
  return $response;
}


How to increase password length while creating account on a drupal website? I'm using Drupal 7, is there any configuration on drupal to make users choose passwords with more than 10 characters (for example) when they're creating accounts ? For now, any user can choose username, and a password can contain only one letter and it's not safe.

Thank you.

Sounds as if you need the Password Policy module.

From the project page:

  This module provides a way to enforce restrictions on user passwords by defining password policies.
  A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.


How to compare text input with a user password stored in the database? I've been trying to compare password values using a custom form.

Actually I want to show a relogin form after a particular amount of time. So I have created a custom form with two fields – email and password. And now I want to compare the password input from my custom form with the user's password stored in the database. If the passwords are same, then the user will be allowed to access the site agin.

I can't compare the hashed password with the custom form password. I know we can't compare the password values, because the password in the database is hashed.

Is any other way to compare them?

The only advisable approach would be to use user_check_password:

$account = user_load(123);
$valid = user_check_password($password_from_form_submission, $account);
if ($valid) {...}

If you desperately need to do it manually, just copy the parts of that function that make sense for your requirements.


drupal http_request give solr parse exception typing a WS uri into the navigator return the json correctly

but the same adress in $url

 $result=drupal_http_request( $url );
 var_dump($result->data);

gives a parse exception

  Cannot parse 'docid:(7000': Encountered \"\" at line 1, column
  11.\nWas expecting one of:\n ...\n ...\n ...\n \"+\" ...\n \"-\" ...\n ...\n \"(\" ...\n \")\" ...\n \"*\" ...\n \"^\" ...\n ...\n ...\n
  ...\n ...\n ...\n ...\n \"[\" ...\n \"{\" ...\n ...\n \"filter(\"
  ...\n ...\n ","code":400}

it must have smthg to do with whitespace or some special characters
because it works with docid:(7000) but not docid:(7000 OR 7001)

How to somehow encode the url so that the solr WS server is happy with my request?

the same url works with drupal 8 code

   use GuzzleHttp\Client;
      $client = new Client();
      $response = $client->request('GET', $url);

i found out I have had to urlencode the bracket part of my url for it to work

urlencode('(7000 OR 7001)'


entity translation of menu i have set up entity translation and everything is working. except for menus. I have a translation set defined for a menu item in "main-menu" and have 2 languages set up for a menu item. However, now both show up in the main menu regardless of which language i am in.

any clues?

its possible my custom menu tree may have something to do with it?

in page.tpl >

$pid = variable_get('menu_main_links_source', 'main-menu');
$tree = menu_tree($pid);
$tree = str_replace(' class="menu"', '', $tree);
$main_menu = drupal_render($tree);
print $main_menu;

Fixed with i18n_menu_translated_tree

$tree = i18n_menu_translated_tree($pid);

as an alert for the next guy, there is some development to move towards i18n_menu_translated_menu_link_alter()
http://drupal.org/node/1693074


Turn off template suggestion for specific fields I have the problem, that the theme / template suggestion comments destroy the html when they are outputted as values.

{% set img_uri = "fields.img.value"%}

{{ dpm(img_uri)
style="backround:url({{ createMyImagePathCustomTwigFunction(img_uri) }});"

Results in:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/views/views-view-field.html.twig' -->
public://img/person/joshua-ness-117255-unsplash_0.jpg
<!-- END OUTPUT from 'core/themes/stable/templates/views/views-view-field.html.twig' -->

<!-- END OUTPUT from 'core/themes/stable/templates/views/views-view-fields.html.twig' -->

..as wrong uri.

I know that I could dive deeper into the rendered array to find other versions.

However:
To change production templates in general only for enabling a developing environment seems wrong to me.

Better would be a hook that would remove field tpl suggestions in general as I don't need them.

I know I can write handler functions... that is what I do in the moment.

But cleaner would be to turn the suggestions off for views fields. How this can be done?

As it seems, that there is no solid alternative that works for field values I have written a Twig-Filter which returns the value via this php function:

public function removeHtmlComments($string) {

  $output = preg_replace(array('/<!--(.|\s)*?-->\s*/', '/\t+/', '/\n+/', '/[\r\n]/', '/[\n\r]/'), '', $string);

  return $output;
}


Show pages with a specific template when user is logged-in I would like to know if there is a way to show an existing node with a custom template if user is logged-in or has a specific role.

I have tried with a custom module route.

custom_module.presentation:
  path: '/node/1'
  defaults:
    _controller: '\Drupal\custom_module\Controller\myController::custom_presentation'
    _title: 'presentation'
  requirements:
    _permission: 'access content'
    _user_is_logged_in: 'TRUE'

In the page controller, I used the following code.

public function custom_presentation() {
        $myVariables = array();

        $build = [
            'description' => [
                '#theme' => 'my_custom_template',
                '#scriptVars' => $myVariables
            ]
        ];
        return $build;
    }

It doesn't work, though. What is the correct way of doing it?

The most basic way of providing a custom template for a node that meets certain criteria, is using theme hook suggestions.

You can for example add a custom theme suggestion by implementing hook_theme_suggestions_HOOK_alter() in a custom module. There you can check whether your criteria are met and add a custom theme suggestion, if they are:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {

  if (
    // Do your checks here, e.g authenticated user?
    \Drupal::currentUser()->isAuthenticated()
  ) {
    // Add your custom template here. The following
    // example would apply to 'my-node.html.twig'.
    $suggestions[] = 'my_node';
  }

}


How do I manage core and module updates along with config management between environments? I've set up a dev site, a test site, and a public site. Dev and Test are in two separate virtual machines (VLAD) and Public is on a shared Dreamhost account. I've successfully used the Configuration management tool to get all three of these environments in sync by installing it once, then copying the files (git) from one to the other environments, and exporting/importing the database information. Now it is time for me to update something like Drupal core from 8.0.3 to 8.0.4 and I am unsure exactly how that should happen with relation to getting that update on the other two environments. So, the main question is: how should I migrate/deploy/manage the upgrade between environments taking into consideration the need for UUID and CMI to stay intact?

Should I update one environment, lets say dev, using whatever chosen tool I have handy (like drush up --security-only or download the new version, and hit update.php in the browser, etc.) then copy those files from dev to test and re-export/import the database info? Or, should I update each of them individually? I suppose the thing I'm most worried about is will that break configuration management? Maybe I don't need to export/import database files and instead just export/import config changes after updating drupal or some contrib module into the dev site.

I've read what feels like 50 different posts about CMI and how to use it and how Drupal 8 makes some of this so much better and I totally agree about the information that actually gets managed by that tool but I can't seem to find information about how to deal with upgrading core and modules between these different environments. If I'm just not reading the right doc or blog post correctly and you can point me to one that is great. If you can answer directly here that is great too. And, maybe I'm just not "getting it" so please feel free to set me straight.

My question may be similar to the one posed here but it isn't exactly worded the same, so, again, I may just be missing the easy answer here.

Yes, the referenced issue is related but I think this deserves a separate answer.

I agree this situation isn't fully satisfactory, but it's not too much of a problem.

In most environments, it won't be possibly to avoid manual configuration changes on production entirely. For example, contact forms are configuration (and not just a single file but 3 + 2 * number_of_fields) and users will likely create new ones without going through staging.

That basically means that you have to live with the situation that there can always be changes on production that are different from what happened on staging/dev. And that you have to treat the configuration on production as the master, unless you're deploying specific changes.

My process for deploying configuration changes usually looks like this:

Do the changes, commit them to a feature branch.
Export the configuration from production and commit it to whatever branch you use for that (for me, that's usually a branch called "production")
Merge your changes into that. Resolve conflicts if necessary.
Deploy the code to production.
Verify the configuration changes, make sure that ther are only known changes that know you prepared for deployment.
Import the configuration.

Module updates add the additional problem of update functions. If you have those, you need to run them between steps 4 and 5. Usually, those aren't a big problem unless they create new configuration with new UUID's. Then you have a problem if you want to import the same configuration entities from the staging config since those would have different UUID's and it would lead to deleting and re-creating them. You have to merge back the changed configuration from production before you can do that.

In general, I'd recommend to not mix module updates with feature/configuration deployments. Do module updates first, export the configuration again, then deploy again with new configuration.

Note that enabling new modules isn't affected by this, unless the module is installed by an update function. But if you deploy new modules through an updated core.extension module list, the config system supports that explicitly by taking the new configuration from your configuration export and not the module's clean default installation. So it's perfectly supported to enable a module on staging, customize its default config (not just simple configuration but also views and so on) and then deploy it to production.


How do I update jQuery to the latest version I can download? I'm using Drupal 7, which uses jQuery 1.4 as default? How can I update it to the latest version (currently 1.7)?

One way is to install the dev version of jQuery Update, which gives you the option to use jQuery 1.7 (by visiting the settings page at http://mysite.com/admin/config/development/jquery_update).

Beware though, currently it's known to break JavaScript elsewhere in the site (for example the widget dropdown on a Manage Fields page will no longer work). If you're prepared to fix up that, and any other small annoyances, this is probably your best bet. You should also note that using the dev version of a module isn't without risks, as the chances of it having bugs is a lot higher than using a specific release.

If you want to do it manually then you'll have a lot of core javascript code to rewrite to make your site work as expected; jQuery changed an awful lot between version 1.4/1.5 and 1.7 so a lot of the core Drupal javascript code simply won't work with it.

If you want to just drop in a version of jQuery 1.7 then you could probably implement hook_js_alter(), unset the core jQuery file, and add your own in it's place:

function MYMODULE_js_alter(&$js) {
  $path = drupal_get_path('module', 'MYMODULE') . '/path/to/jquery.1.7.js';

  // Copy the current jQuery file settings and change
  $js[$path] = $js['misc/jquery.js'];

  // Update necessary settings
  $js[$path]['version'] = 1.7;
  $js[$path]['data'] = $path;

  // Finally remove the original jQuery
  unset($js['misc/jquery.js']);
}

Once you've done that, open up Developer Tools/Firebug and you'll see all the changes you're going to need to make to get the rest of the site JS to work :)

UPDATE

The latest version of jQuery update (7.x-2.3 at time of writing) will now allow you to update jQuery to v1.8. Very cool.

The jQuery Multi module is another option, thanks to goron for pointing that out in the comments. As he also notes, this module has a stable release and won't break any existing javascript.


Video.module: Rendering playablefiles programmatically I am trying to pull the "playablefiles" URIs from the array for a video field (hereafter: field_video).

Here's a look at how the array is set up.

I'm trying to pull a list of the files by this method, which seems to be in error:

  foreach($node->field_video['und']['0']['playablefiles']) {
    echo $node->field_video['und']['0']['playablefiles']['uri'];
  }

Can anyone tell me what I'm doing wrong here?

There are a few things that could do with attention...

A foreach statement needs an as keyword to keep a reference to the current object in the iteration (the docs explain it better than that, it's worth having a read). This error should throw an exception.
From the looks of the array each 'playablefile' is an object (not an array) so you need to access its members with -> not []. If the interpreter makes it this far this should also throw an exception.
You can also make use of the API and make your code language safe using the field_get_items() function

The resulting code should be:

$field_items = field_get_items('node', $node, 'field_video');
foreach ($field_items[0]['playablefiles'] as $file) {
  echo $file->uri;
}


Merge Users from Prod to Staging/Dev I have users registering on my prod environment, but I also have accounts created internally on my staging environment. Is there a drush command similar to  sql-sync or Drupal module that will simply merge the user table without overwriting all users and credentials?

go through the discussion on https://groups.drupal.org/node/177179. You will get to know the answer of your question


Apache Solr Framework with Views (for Facet Search) What I want

I want to use the Apache Solr Search to:
1. built a Global Search with a customized Search Results Display
2. built a Facet Search for specific content types

Problems

Currently I'm trying to use the Apache Solr Framework Module:
https://drupal.org/project/ApacheSolr

So my first question: As far as I can see, this module has no native integration with views, right?

As a result I installed the "Apache Solr Views Integration" Module:
https://drupal.org/project/apachesolr_views

But when I create a view of the new typ "Apache Solr .." I am experiencing different problems:
1. Not all fields are available (for the facet search I only need to display specific fields)
2. It is not possible to filter the Content Type (needed for the facet search)
3. It is not possible to set the ouput to "rendered entity" (needed for the global search!)

Does anybody know to achieve the result that I want? What are your expieriences with the Apache Solr Framework? How do you integrate this with views?

I have typically achieved this type of thing using the Search API module which provides ability to select which fields are indexed and thus exposed to Views in turn along with Apache Solr integration.

The Search API provides a great base onto which to build very powerful search applications.


How do I access the variables posted in a page callback? Ok I don't know why I am having such a hard time getting my mind around how to do this. How do you access posted values in your page callback? Something in Drupal seems so hard. All examples just call drupal_get_form() but what do I do if I want to display the form and any results from the submit?

function stock_quotes_menu(){
    $items['stock-quotes'] = array(
     'title' => variable_get('market-summary-title', 'Stock Quotes'),
     'access arguments' => array('access content'),
     'page callback' => 'stock_quotes_page',
    );

    return $items;
}

function stock_quotes_page() {
    $symbols = isset($_REQUEST['symbol']) ? strtoupper($_REQUEST['symbol']) : '';
    $out = "<pre>".print_r($_REQUEST,1);
    if ($symbols != '') {
        $start = NULL;
        $pos = strpos($symbols, ",");
        /*if($pos == false){
            $start = date('Y-m-d');
        }*/
        $quotes = stock_quotes_fetch_yql_quote($symbols, $start);
        $out = print_r($quotes, 1);
    }

    $form = drupal_get_form('stock_quotes_get_form', $symbols);
    $build['snippets'] = array(
      '#type' => 'node',
      '#title' => '',
      '#prefix' => drupal_render($form),
      '#markup' => $out
    );

    return $build;
}

function stock_quotes_get_form() {
    $form['symbol'] = array(
      '#title' => t('Symbol(s)'),
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#description' => t('Enter Symbols or Symbols seperated by , to get quotes'),
      '#default_value' => !empty($form_state['values']['symbol']) ? $form_state['values']['symbol'] : 'Enter A Symbol',
    );

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

    return $form;
}

By default, Drupal looks for two functions on form submission (for forms generated with the Form API): {$form_name}_validate() and {$form_name}_submit();

For what you are trying to do, you need to implement the submit handler, do something with the form values (store to session, database, etc) and then go to page that will display the values of the form.  I've mocked up a quick and dirty module so you can see a couple different approaches:

function mymodule_menu(){

  $items = array();

  $items['sample_form'] = array(
     'title' => t('Sample Form'),
     'access arguments' => array('access content'),
     'page callback' => 'drupal_get_form',
     'page arguments' => array('mymodule_sample_form'),
  );

  $items['sample_form/success/%'] = array(
     'title' => t('Sample Form | Success'),
     'access arguments' => array('access content'),
     'page callback' => 'mymodules_sample_form_success',
     'page arguments' => array(2), //pass value of field_two to callback function
  );

  return $items;
}

function mymodule_sample_form($form, &$form_state){

    $form['field_one'] = array(
      '#type' => 'textfield',
      '#title' => t('Field One'),
    );

    $form['field_two'] = array(
      '#type' => 'textfield',
      '#title' => t('Field Two'),
    );

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

    return $form;
}

function mymodule_sample_form_submit($form, &$form_state){

  //This is where you process and store submitted values.
  //Lets use variable_set to store the value
  variable_set('mymodule_field_one', $form_state['values']['field_one']);

  //Ok, lets now redirect the user to the success page and pass field_two as an argument
  $form_state['redirect'] = url('sample_form/success/'.$form_state['values']['field_two'], array('absolute'=>true));
}

function mymodules_sample_form_success($field_two){

  $output = 'Value for field one: '. variable_get('mymodule_field_one').'
';
  $output .= 'Value for field two: '. $field_two.'
';

  //Lets display the form again, rebuilt.
  $output .= drupal_render(drupal_get_form('mymodule_sample_form'));

  return $output;
}


How to get row weights from a form before saving? I have form with an image upload field which saves multiple images. User can reorder and crop images in that form. Reorder using default drag option.

My requirement is to create a PDF of images in current order when user clicks on submit button.
I am taking the image uri from field values by loading node. So the order will be the saved order. I am creating the PDF inside hook_insert.

How do I get the row weights before saving the node, so PDF can be created according to current order of images?

You don't need to do anything special to get the row weights for the images.

The "weight" or list order of the images is stored in the delta value.

e.g:

$node->field_images[LANGUAGE_NONE][0]['fid'];
$node->field_images[LANGUAGE_NONE][1]['fid'];
$node->field_images[LANGUAGE_NONE][2]['fid'];

The delta value is 0, 1 & 2 representing the first, second and third images respectively.

Also, if you're using one of the node API hooks, e.g hook_node_insert, you won't need to load the node, it should already be passed as a parameter there.


hook_menu_alter() is not working I have implemented hook_menu_alter() in a module I have created. I have printed something inside that function call but nothing shows up, though the function hook_init() is executed from the same module. The output of hook_init() shows up in the page, but not from the hook_menu_alter() even after clearing the cache.

Does anybody have any idea regarding this issue?

function mymodule_init(){
print "here";
}

function mymodule_menu_alter(&$items) {
print "I am here";
return $items;
}

hook_menu() and hook_menu_alter() are not always invoked; they are invoked only when Drupal rebuilds the menus, such as when a module is enabled, disabled, and updated, or when the Drupal cache is cleared.

Anatomy of hook_menu reports the following sentence:

  hook_menu() is called rarely, such as when modules are enabled. If you edit a module’s hook_menu(), you must visit admin/build/modules for the changes to take effect.

The function that invokes the implementations of hook_menu() and hook_menu_alter() is menu_router_build(), which contains this code (the code is for Drupal 7):

function menu_router_build() {
  // We need to manually call each module so that we can know which module
  // a given item came from.
  $callbacks = array();
  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);
  list($menu, $masks) = _menu_router_build($callbacks);
  _menu_router_cache($menu);

  return array($menu, $masks);
}

The function is called by menu_rebuild(), which is then called by:

drupal_flush_all_caches()
menu_enable(), the implementation of hook_enable()
menu_uninstall(), the implementation of hook_uninstall()
12 other functions, and 1 method

drupal_flush_all_caches() is invoked by system_modules_submit(), which is the submission handler for the module page where modules are enabled, and disabled; every time a module is enable, or disabled, the menu is rebuilt, and both the menu hooks are invoked.


How to assigned specific "comment" view mode for specific "node" view mode? In "Article" content type i have three view mode in "Manage Display" namely "teaser", "default" and "abc".

Similary in "Comment Display" i have two view mode namely "defalut" and "xyz".

Eg: When i see "abc" node page where i am listing comments, that time the comment should be display with my "xyz" view mode not the "default" one.

function custom_node_view($node) {
    return node_view($node, 'abc');
}

You could use hook_entity_view_mode_alter() to switch it on the fly.


How to add a new join table by using a hook view? How should we alter a query of a view by using the hook_views_query_alter, by adding a new join table.

I tried

 $join = new views_join();

but it seems to be for drupal 7 not 8.

Please help.

Here is a solution to add a join table to an SQL query in views.

Let's consider a view for a Person entity. We want to add a join to a PersonTag entity. Person has an id field (the primary key);
PersonTag has a person_id field that contains the PersonTag ID.

In your module_name.module, you would add this hook_views_query_alter() implementation.

function module_name_views_query_alter($view, $query) {
  if ($view->id() == 'views_id') {
    $definition = [
      'table' => 'person_tag_field_data',
      'field' => 'person_id',
      'left_table' => 'person_field_data',
      'left_field' => 'id',
    ];
    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('person_tag_field_data', $join, 'person');
  }
}

After clearing the cache, you could check the SQL query used by the view and notice INNER JOIN is added to the query.

module_name is the name of your module, views_id is the ID of your view, person_tag_field_data is the table name for the PersonTag entity, and person_field_data is the table name for the Person entity.