Wrapping javascript code conditionally using a cookie I want to include the following code in page.tpl.php only once during first site visit and for subsequently not. I mean this will pop-up an ad only once. I want to set it based on a cookie. How to conditionally include this code based on a cookie? I need the sample code.

<script language="JavaScript">
        var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="15";
        </script>
        <script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>

EDIT:

Will this work in page.tpl.php ? I want add it before </head> so that the js file is included only once in user session.

<script type="text/javascript">
    if(!jQuery.cookie('myCookie'))
    {
    $.cookie('myCookie':'myValue');
    <!-- Javascript tag: -->
<script language="JavaScript">
var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="15";
</script>
<script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>
    }

</script>

This StackOverflow question should contain enough information to solve your issue.

I would go with the one that suggests using setcookie(). $_SESSION information is cleared when the user's session ends, generally at the close of the browser. Here is a recent example of me using cookies to remember an anonymous user's submission of a Webform and redirect them to the completion page if they tried to visit the Webform again:

    <?php
    define('REQUEST_TIME', $_SERVER['REQUEST_TIME']);

    function _mymodule_manage_cookie($nid, $type = 'my_cookie_type') {
      $matches = (bool) $nid == variable_get("mymodule_{$type}_webform_nid", FALSE);
      if (empty($_COOKIE["Drupal_visitor_mymodule_{$type}_submitted"]) && $matches) {
        mymodule_cookie_save(array("mymodule_{$type}_submitted" => TRUE));
      }
    }

    /**
     * Drupal 7 yoink!
     */
    function mymodule_cookie_save(array $values) {
      foreach ($values as $field => $value) {
        // Set cookie for 365 days.
        setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
      }
    }

    function mymodule_cookie_delete($cookie_name) {
      setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
    }
    ?>

You need to put this in a module or in template.php in your theme. You can conditionally include the code in a manner similar to the following:

template.php

    <?php
    function THEMENAME_preprocess_page(&$variables) {
      // THEMENAME_get_first_visit_cookie() would refer to a function
      // you have to write that retrieves if the cookie
      // is set. You could alternatively try just using
      // $_COOKIE['my_cookie_type'].
      if (THEMENAME_get_first_visit_cookie()) {
        $variables['first_visit'] = TRUE;
      }
    }
    ?>

page.tpl.php

    (skip to wherever you want to embed the code)
    <?php if ($first_viist): ?>
      // Paste your code here
    <?php endif; ?>

Now, one more point. The way I just showed you isn't the best way. You should add your Javascript properly using drupal_add_js() in a module or by adding a separate Javascript file in the theme that reacts to a class on the <body> tag and displays your first visit message (or whatever you're doing). You would still need the $first_visit variable to determine whether to add the class or not.


Trying to get my form_alter function to be more specific I'm hiding access to a specific fieldset within the Support Ticketing System module add a ticket page. I use a form_alter preprocess function to find the page's form id as such:

drupal_set_message($form_id);

I discover the ID is:

support_ticket_node_form

... perfect so I do:

function MYTHEME_support_ticket_node_form_form_alter(&$form,$form_state,$form_id){
  $form['subscribe']['#access'] = FALSE;
}

... to hide that but the fieldset does not get hidden.

However, if I do a generic form_alter:

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
    $form['subscribe']['#access'] = FALSE;
}

... That works, the fieldset is now hidden on the page. The only thing I could think of that I am doing wrong is that it seems odd to have form_form_alter as part of the string but one is from the form ID and the other is part of the function so it should be working. Not sure what i am doing wrong. I'm guessing the generic form_alter that works for me could be dangerous as it lacks specificity and could cause issues down the road so I'd like to get this sorted out.

The hook for specific form ID's is hook_form_FORM_ID_alter() (at the moment you're using something more like hook_FORM_ID_form_alter()). You should just need to change the name of the function to:

function MYTHEME_form_support_ticket_node_form_alter(&$form, &$form_state, $form_id) {
  // ...
}

and clear the caches.


Can I use Drupal plugin in managing news? Can I use the plugin of Drupal twitter feed on managing news? Is there a twitter feed for Managing News? Sorry for this dumb question, as I was new on this content management system.

Yes you can use Twitter Feed! with Views & OAuth modules and you have to enable OAuth based access for Twitter, you must register your application with Twitter and add the provided in Twitter setting!


How to pass formatter settings to field theme function? I've created a field by implementing hook_field_info, I've created the widget which works perfectly and I've hit a road block with the formatter.

I've implemented hook_field_formatter_settings_form to add some extra output options but I can't work out how to get those values passed to the theme function when the field is rendered.

Here is a simpified version of my code, it's not all the hooks just the ones related to the formatter and the field's theme:

function test_field_formatter_info() {
    return array(
        'test' => array(
            'label' => t('Test'),
            'field types' => array('test'),
        ),
    );
}

function test_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  foreach ($items as $delta => $item) {

    $element[$delta] = array(
      '#theme' => 'test',
      '#item' => $item,
      '#myextravalue' => $display['settings']['myextravalue'],
    );
  }

  return $element;
}

function test_theme() {
  return array(
    'test' => array (
      'variables' => array('item' => NULL, 'myextravalue' => NULL),
    ),
  );
}

function theme_test($variables) {
    $item = $variables['item'];
    ...
    return $output;
}

The widget, field and formatter are working fine, I just can't work out how to get the formatter settings that were defined by hook_field_formatter_settings_form to the test theme function.

When I $variables variable I only see an array for item. myextravalue is not there!

There is very little information on how to create fields/widgets/formatters for Drupal 7 and I'm pulling my hair out with this.

Your formatter_view implementation looks ok, very similar to image_field_formatter_view().

However, you're info hook seems to be missing default values for your settings, I'm not sure if they are required or not, but try to add them, again see image_field_formatter_info()

Does the field_formatter_settings form work correctly? Does it show correctly in the summary and keeps the values when you edit it again?

Without more information, the only advice I can give you is install devel.module if you haven't already and make extensive use of dpm() to see where you get which information. For example, contains $display the necessary information in your formatter_view() function?

If yes, it could simply be a outdated theme registry that does not yet know about your additional theme argument (if you added later on for example).


Syntax for the various query modifiers I'm using hook_views_query_alter() and am wondering where I can find the syntax for the various query modifiers.

One of the examples I found looked like this:

$query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";

I'm not sure what that syntax is saying. Does it mean order by the node.type field, where nodes with story are first, then page, and so on? Or something else? I need to be able to group on multiple fields (and not all fields are on the initial node (relationships.)

Is there somewhere that all of the available modifiers are documented, including their syntax? By modifiers, I mean $query->orderby, $query->where, and so on.

Your question is 2-fold. 1 part of your question is drupal based, the other is (MySQL) SQL based ...

That line of code is as follows:

$query->orderby[0]: adds an ORDER BY clause fragment to the SQL query string. More could be tacked onto using php such as $query->orderby[1] or $query->orderby[123] ... these just build up an ordered php array of orderby sql clauses ...
The SQL expression FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') is used by MySQL within the ORDER BY clause and takes an additional value of DESC or ASC. That function uses the cardinality of the passed in parameters as a weighted list of values for orderby. You are correct in how FIELD() is ordering the results ....

You may order by any selected field in SQL or by an aggregate function in MySQL. Not all DBMS have the same functionality, for example as seen here the above FIELD() function in MySQL has to be emulated in Postgres:
https://stackoverflow.com/questions/1309624/simulating-mysqls-order-by-field-in-postgresql

So far as I'm aware there is no list of all the functions or values one could order by ...


Clicking any hash/"#" link, even in Seven themed edit page tabs, scrolls to top of page? I have a custom themed Drupal 7 site here. If you click on the left or right arrows in the top slide show or bottom "logo parade", the browser will scroll to that hash tag (undesired). Also, when logged in and looking at an edit page (uses Seven admin theme, not custom theme), clicking on a vertical tab e.g. "Menu settings" will scroll to the top of the page. This is disorienting and disruptive!

What's most troubling is that I can't reproduce this issue on the local test version of the site. The home page slide show and logo parade cause no scrolling when clicking around. The edit pages are a dream without unwanted scrolling...

FireBug isn't reporting anything odd. I'm not seeing noticeable differences between the live and local sites. Another Drupal 7 site I have on the same production server is not having this issue. It works great locally. I'm stumped.

This might be unrelated (maybe a related clue!), but for this site specifically I'm also having some odd ajax issues when editing views via Seven theme (and it's working great on my local version). When attempting to add a field to any view I'm getting this message, followed by the overlay instead loading as its own page:

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /admin/structure/views/ajax/add-item/articles/block/field
StatusText:
ResponseText:
ReadyState: 4

Any thoughts on where I should start to troubleshoot this issue? I truly appreciate the assist in advance! :D

Your problem appears to be that the arrows for the slide show and "logo parade" are linked directly to their container <div id="logo-parade"> with the anchor href="#logo-parade", which causes the page to essentially "snap" to the container, since the div id is the same as anchor when called as a hash (you can see in the url that #logo-parade gets appended).

This could be caused because of a portion of javascript is not being called/run properly which should trigger the carousel without needing to use anchors.

Since your problem doesn't occur in development (you can test this by clicking on one of the arrows and making sure that in your URL bar you don't see #logo-parade appended) it leads me to believe that perhaps a file hasn't loaded correctly on the server, or perhaps the .htaccess rewrite has something to do with it


Uploading file, parsing and displaying data For a site i am building right now, there is one component that I would want the user to upload a file, where it will be parsed (currently a python script, but can be ported to something else). The data from the parser will then be used populate a node.

what will be the best way to go around doing this?
rules to start the parsing and feeds to import the data?
a custom php page?
or a custom mod to generate the display i want from the file uploaded in the same node?

need some guidance >,<

I would create a new url where files can be uploaded. This is done with a implementation of hook_menu.

If you want to use Feeds you first need to upload the file and have it converted to rss/csv/opml etc and then use Feeds to map against a node. I would go with a custom module instead so that you can create nodes straight away instead of a "two step operation".

You can find out how to create a form that handles file uploads here. In the submit function for your form you would need to programatically create nodes from the file upload. This can be done in several ways but one is by using Entity metadata wrappers, which I find easy to work with. You can find out more about that here.

This all might sound like a lot of work and I didn't suggest a contributed module but I think in your case it would be more work to first convert the data to something readable by Feeds for example.


Displaying uid on user/x/ and user/x/edit page I want to display the uid (read-only) of the user on both the user/x and user/x/edit page.

By using the function below I managed to show the uid on the user/x/edit page.

function my_module_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    if (arg(0) == 'user') {
        $form['uid_read_only'] = array(
            '#markup' => 'User id : ' . '<b>' . arg(1) . '</b>',
            '#weight' => -500,
            '#disabled' => TRUE,
        );
    }
}

How do I show the uid on the user/x page (view state)?

Implement hook_user_view() to show the uid on the user/x page.


Rules Looping for Multiple User References I have a Rule which checks to see if a "Reviewer" CCK User reference field has been changed. If it has been, it loads the referenced user and add the "Reviewer" role. This works perfectly however it only works for the first value in the field, so adding multiple reviewers becomes a problem.

I can see in the "load a referenced user" action that is says "Note that if the field has multiple values, only the first user will be loaded." So I assume this has come up before...

Is there any way around this for Rules 1.x on Drupal 6? I need to Loop this for each set value in the field array but I cant find the best way to do so...

You could write you're own condition. See http://drupal.org/node/298486.


What is the different between an install profile and a drush make file? I am just getting into using drush and excited about using drush make and installations profiles. What is the different between a drush make file and an installation profile and do they /can they work together?

Drush make...

  Drush make is an extension to drush that can create a ready-to-use drupal site, pulling sources from various locations. It does this by parsing a flat text file (similar to a drupal .info file) and downloading the sources it describes. In practical terms, this means that it is possible to distribute a complicated Drupal distribution as a single text file.

Note that it doesn't install/set up the site for you - it merely downloads and prepares the required files in the specified locations.

Install profiles...

  Installation profiles provide specific site features and functions for a specific purpose or type of site. They make it possible to quickly set up a complex, use-specific site in fewer steps than if installing and configuring elements individually.

Once you've used Drush Make to download all the files relevant to your project, you go ahead and install Drupal as normal (whether through the UI or with Drush), except you choose your profile during installation.

The code in the profile enables required modules, sets up initial configuration for those modules and the core system, perhaps installs demo content (think Commerce Kickstart), adds menus, sets variables, etc.

Using Drush make to install a profile would be a good question/answer to look at to get an idea of how they can integrate together.


How would I add a class with the same name as the header? I'd like to add a class with the same name as the header, in order to keep similar header columns the same size. Basically, the code is generating multiple tables, some of which have the same header items, and some of which do not. All columns with the same header value will take the exact same styling.

$string .= theme('table', array('header' => array_values($headers[$group]), 'rows' => $results));

$string is '' at the beginning of this, and I want to add the class to the values in $header - so ideally it would look like this:

Header

You'll want to consider doing this in PHP, by overriding the theme/output markup for each Table Header, specifically using the theme_table() override function to add a class attribute to each table header argument.

Simplified code sample

$table_headers = array(
      array(
        'class' => array($node->title), // Adds 'class' HTML attribute.
      ),
      // More code goes here to define the table headers...
    );


debugging an array while creating custom rule I am trying debug a custom rule I am creating. In my helper function I am calling an array I want to work with. I want to dpm the contents of the array so that I can see what is available, but it is not working. To check that there wasn't a problem with my array. I set up a new one inside the helper function.

$array = [
      "foo" => "bar",
      "bar" => "foo",
  ];

and then try to dpm the array:

dpm ("array: " . $array);

but all that is shown in the status message is:

array: Array

I have been trying other methods of printing the array like print_r but haven't had any success with these either. How should I be printing my array?

You can only have a string (not an array) as the second argument to dpm().

Try:

dpm($array, "array: ");


Dynamically add destination fields to migration - importing data when fields on destination entity are not know I am trying to import content from JSON from an API call. This API call has different source data depending on what the call is.
For my migration from this JSON, there are set fields that I have coded into the YAML migration file under the process section. The issue I am running into is, some of the fields change, so I need a way to dynamically add these fields to the process section if they exists. Is this possible with Migration?
I think there must be some way to do if with derivers, but I am struggling at how to implement this.
Any insight would be greatly appreciated!

I think you could try to implement something similar https://www.webomelette.com/dynamic-migrations-using-templates-drupal-8. This is a good example of dynamic migration.


How to add extra option to the existing drush command? I'm trying to add extra option to the existing command as below:

/**
 * Implements hook_drush_command_alter().
 */
function MYMODULE_drush_command_alter(&$command) {
  if ($command['command'] == 'features-revert-all') {
    $command['options']['cleanup'] = dt("Remove non-existing components from the database after revert.");
  }
}

However it seems it doesn't work as expected and drush fra --cleanup fails.

Then the help command doesn't show this option either.

What's the proper way of adding such option, so drush can understand it and can be available for further parsing via drush_get_option?

This is done with drush_help_alter rather than drush_command_alter. See the example Drush policy file, reproduced in part below:

function policy_drush_help_alter(&$command) {
  if ($command['command'] == 'updatedb') {
    $command['options']['token'] = 'Per site policy, you must specify a token in the --token option for all commands.';
  }
}


Drupal Node Display Main Image or Video not both We have a content type that in addition to the body field it has a field for Image and another field for Video.

Both video and image are currently displayed at the top of the node, in Node > Manage Display. But if there is already a value for video field, that should be all that needs to display. Unless the video field has no value in which case, display the image field.

In other words, we want to have a condition where the image field is hidden IF there is a value for the Video field. If no data is present for video filed, display image.

Does anyone have an idea of how this can be accomplished?

This should work:

{% if node.field_video is not empty %}
  {{ content.field_video }}
{% else %}
  {{ content.field_image }}
{% endif %}

If the field is populated with a value, render that field. Otherwise, render the image field.


What is the advantage of the APC module? I had the APC PHP extension enabled it it seems to work well. I had 0.0% misses and not much fragmentation.
Then I installed the APC module with:

$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';

in settings.php. After that the fragmentation becomes enormous and I can't see any performance loss when I disable the module again, but with it is actually enabled I get annoying messages when I use drush. So what exactly is the advantage of using that module?

Using APC with PHP and the APC module are two totally different things.

APC for PHP caches the opcode for files.  Essentially, when PHP executes a page, it compiles all of the code into opcode.  APC caches this, so the next time a file gets used, it can skip the compilation step.  This can cause tremendous speed increases in a complex PHP application like Drupal.  Running Drupal without APC enabled is a bad idea.

The APC Module is an alternative cache backend for Drupal.  Out of the box, Drupal caches data in the database.  The APC Module lets Drupal cache the data in the APC user cache.  As with everything, tuning APC is essential to getting this to work well.


How to print the path alias without "/" in views I would like to print the path of a node in a view, but without the "/".

With "Content:path" the trailing slash before the alias is always there.

ie:

path-of-node

in stead of
/path-of-node
Any suggestions, pls?

If you have a custom module of your own, you can use the function below.
To find the exact structure of the data you want to modify, you can use dpm or just simply print_r.

function hook_views_pre_render(&$view) {
    if($view->name == "MY_VIEW"){
        foreach($view->result as $key => $r){
           $view->result[$key]->path[0]["rendered"]["#markup"] = substr($view->result[$key]->path[0]["rendered"]["#markup"], 0, -1);
    } //if
 } // function

As for a direct way, I was trying and I think I even post a question, but to no success. Surely it is much simpler but don't know how to.


Drupal.attachBehaviours() on Block that got rendered via ajax call i'm rendering a form and using an alter hook for changing the form to submit via ajax. This works like a charm. ( Drupal 8 webform with webform_ajax )

Now i want to render the form via ajax into the content. This also works.

Because the content is not there on page load i have to re-apply the drupal behaviours.

This is the thing i can't get to work.

Here's the code i use:
Form.js

(function ($, Drupal) {

  'use strict';

  var $modal = $('#modal');
  var url = $('.block-system-main-block > article.node').attr('about');

  Drupal.behaviors.formInModal = {
    attach: function (context, settings) {
      $(context).find('.js-engagement-link').once('js-engagement-link').each(function () {
        var targetForm = $(this).data('target');

        $(this).click(function(){
          $.ajax({
            url: '/contact_bridge/webform/' + targetForm
          }).done(function(response) {
            $modal.find('.modal-content').first().html(response);
            $modal.foundation('open');
            Drupal.attachBehaviors($('#modal')[0], settings);
          });
        });
      });
    }
  };
})(jQuery, Drupal);

Form alter:

public function formAlter(array &$form, FormStateInterface $formState, $formId) {
  $webformSubmission = $formState->getFormObject()->getEntity();
  if ($this->isAvailable($webformSubmission->getWebform())) {
    $ajax = $this->getAjaxProperties($formId);
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
    $form['actions']['submit']['#ajax'] = [
      'callback' => '\Drupal\webform_ajax\Controller\WebformAjaxController::ajaxSubmission',
      'wrapper' => $formId . '_wrapper',
    ]
  }
}

I tried many different calls to attachBehaviours, nothing seems to work. The alter hook is applied to the form and the ajax wrapper is there.

-- edit1 --

Here the code on the backend side for rendering the block:

<?php

namespace Drupal\contact_bridge\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\webform\Entity\Webform;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 *
 */
class ContactBridgeController extends ControllerBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManger;

  /**
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('renderer'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(
    EntityTypeManagerInterface $entityTypeManager,
    RendererInterface $renderer
  ) {
    $this->entityTypeManger = $entityTypeManager;
    $this->renderer = $renderer;
  }

  /**
   * @param string $webformid
   * @return \Drupal\Core\Render\HtmlResponse
   */
  public function getWebformBlockHtml($webformid) {
    $webform = Webform::load($webformid);
    $renderArray = $this->entityTypeManager()->getViewBuilder('webform')->view($webform);

    $html = $this->renderer->renderPlain($renderArray);
    return HtmlResponse::create($html);
  }

}

And the routing:

contact_bridge.webform:
  path: 'contact_bridge/webform/{webformid}'
  defaults:
    _controller: '\Drupal\contact_bridge\Controller\ContactBridgeController::getWebformBlockHtml'
  requirements:
    _permission: 'access content'
    webformid: ^[a-zA-Z0-9_]+

Can somebody tell me what i'm doing wrong?

Thanks in advance.

Ok, there are a few things that need to be done:

Create a custom ajax command
Create the JS to handle that custom command
Return an AjaxResponse from getWebformBlockHtml(), that contains that custom command from step 1
Ajaxify the response when your ajax is complete

You can do that as follows:

Step 1 - Create a custom ajax command

namespace Drupal\[MODULENAME]\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class MODULENAMELoadFormCommand implements CommandInterface
{
  protected $form;

  public function __construct($form)
  {
    $this->form = $form;
  }

  /**
   * Implements Drupal\Core\Ajax\CommandInterface:render().
   */
  public function render()
  {
    return [
      'command' => 'MODULENAMELoadFormCommand',
      'form' => $this->form,
    ];
  }
}

Step 2 - Create the JS to handle that custom command

Add the following to your JavaScript that you're loading on page load:

Drupal.AjaxCommands.prototype.MODULENAMELoadFormCommand = function(ajax, response)
{
  $modal.find('.modal-content').first().html(response.form);
  $modal.foundation('open');
  Drupal.attachBehaviors($('#modal')[0], settings);
};

Step 3 - Return an AjaxResponse from getWebformBlockHtml() that contains that custom command from step 1

use Drupal\Core\Ajax\AjaxResponse;

public function getWebformBlockHtml($webformid) {
  $response = new Ajaxresponse();

  $webform = Webform::load($webformid);
  $renderable = $this->entityTypeManager()->getViewBuilder('webform')->view($webform);

  $rendered_form = \Drupal::service('renderer')->renderRoot($renderable);
  $response->setAttachments($renderable['#attached']);

  $response->addCommand(new MODULENAMELoadFormCommand($rendered_form));

  return $response;
}

Step 4 - Ajaxify the response when your ajax is complete

Modify your original Ajax Call to look like this:

$.ajax({
  url: '/contact_bridge/webform/' + targetForm,
  success:function(response) {
    var ajaxObject = Drupal.ajax({
      url: "",
      base: false,
      element: false,
      progress: false
    });

    // Simulate an AJAX response having arrived, and let the Ajax
    // system handle it.
    ajaxObject.success(response, "success");
  }
});


How to dpm() an object value? If I run dpm($form); I get an array containing objets. Now I need to just dpm() the uid of the node object.

How do I do dpm() to isolate an object value?

I tried with dpm($form['#node']['uid']); but not working.

Please look the capture to make my question clear:

You would use:

dpm($form['#node']->uid);

As you rightly say the #node variable is an object, and object properties in PHP are accessed using the -> operator.

Have a peek at the PHP Objects documentation for a few more details.


Filter unpublished nodes, even for Admin How can I filter out unpublished nodes in a view even if the user viewing it is an administrator?

Sound like you just want to switch the filter you are using from

Content: Published or admin
Filters out unpublished content if the current user cannot view it.

to

Content: Published
Whether or not the content is published.


Tracking number of attempts via Form API I'd like to track the number of times a user has failed a form validation.

It doesn't necessarily matter if the end user has access to the variable, or even the ability to manipulate it client side, as the purpose is to provide additional help to the user by detecting when they might not be in trouble.

At this point I think I'm leaning towards adding a hidden field and incrementing that value, but I'm interested to know if there's a cleaner method that does prevent access and manipulation in my quest for knowledge :)

Thanks for any advice.

UPDATE

As per tunic's advice below, I'm trying the $form_state route but this doesn't appear to be persisting. In my form validation function I have:

// Track the number of attempts.
if (!isset($form_state['mymodule']['attempts'])) {
  drupal_set_message('attempts not set');
  $form_state['mymodule']['attempts'] = 0;
}
$form_state['mymodule']['attempts']++;
drupal_set_message($form_state['mymodule']['attempts'] . ' attempts');

However repeatedly submitting a form with errors results in the following output each time:

attempts not set
1 attempts

SOLUTION

Having difficulty arguing with $form_state I instead went for the core flood module as suggested below, with the following code, in my validator:

function mymodule_booking_register_online_form_validate($form, &$form_state) {
  if (form_get_errors()) {
    form_set_error('', 'There was a problem registering your online account, please try again.');
    flood_register_event('mymodule_booking_register');
  }
}

And then to handle the result of this event, back in my form definition:

function mymodule_booking_register_online_form($form, &$form_state) {
  if (flood_is_allowed('mymodule_booking_register', 5, 3600)) {
    ...
  else {
    drupal_set_message('You have incorrectly entered your personal details too many times. Please call us on 12345678 to ask for your user code and then enter it in the form below.');
    ...
  }
}

Just use a variable insider $form_state.

In validate function

if ($validation_failed) {
  $form_state['error_count']++
  $form_state['cache'] = TRUE;
}

Then, in your form function just check $form_state['error_count'].

$form_state will be persistent between page petitions while validation fails thanks to $form_state['cache'].

You can also check for errors using form_get_errors().


media library thumbnails missing for txt and pdf The http://drupal.org/project/media module cannot display the thumbnails of txt and pdf files in my installation. I'm not expecting a thumbnail of the actual txt or pdf content of course but a generic placeholder.

Display as list:

Display as thumbnail:

Note that:

no missing file (404) requests are being tracked in firebug
this also affects the media popup file chooser from within content editing
changing the theme doesn't solve this problem
inspecting the "empty thumbnail" with firebug doesn't show anything useful, the <a /> is empty.

Using 7.x-2.x-dev instead of 7.x-1.1 solves this.


Which Foundation 6 files need to be uploaded to my host in order to make my Drupal 8 custom theme working with full capabilities I installed Foundation 6 into my themes/custom/mytheme folder using foundation new. I get my starter kit, all good and ready to go.

I am not sure which files I need to upload to my host in order for my sites full capabilities.

I track my whole Drupal 8 website using Git.

With the installation of Foundation 6 there comes a .gitignore file. In this .gitignore file it ignores:

bower_components
node_modules
npm-debug.log
css

But when I want to commit my Foundation 6 custom theme to the server I need files inside bower_components folder? Or do I mis something here?

When you look at Foundation 6 example index.html they load:

bower_components/jquery/dist/jquery.js
bower_components/what-input/what-input.js
bower_components/foundation-sites/dist/foundation.js

What do I have to do with the Foundation .gitignore file exactly?
And which javascript files do I have to attach to have a good working Drupal 8 and Foundation 6 theme to start building my theme on?

The .gitignore file that is downloaded with Foundation 6 is tied to just the Foundation framework - if you're planning to track the whole Drupal site, you can safely delete it and just use the one that comes at the Drupal root.

In the past I've just tracked everything (and committed everything) in the framework up, including the bower_components folder.

My [theme_name].libraries.yml file looks like this:

global-styling:
  version: 1.x
  css:
    theme:
      stylesheets/fonts/stylesheet.css: {}
      stylesheets/foundation-icons/foundation-icons.css: {}
      stylesheets/app.css: {}
      stylesheets/print.css: { media: print }
  js:
    bower_components/fastclick/lib/fastclick.js: {}
    bower_components/foundation/js/foundation.min.js: {}
    bower_components/foundation/js/foundation/foundation.topbar.js: {}
    js/app.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

homepage:
  version: 1.x
  js:
    js/jquery-ui-1.11.4.custom/jquery-ui.min.js: {}
    js/wcreek-slider.js: {}

The js is my own theme's js folder, and you can see I'm including some bower_components files.  I'm using the default jquery that shipped with Drupal 8, but I'm using Foundation 5.  You might want to rather include the version of jquery from the bower_components.

Also I would recommend that you set your Drupal administration theme to be different from your Foundation theme (I usually set it to Seven) so there's no conflict between Foundation and the Drupal admin tools, like views, etc.

You might be able to use jquery_update module to specify a lower version of jquery for the admin theme (I haven't tried this in Drupal 8 yet). This might be needed if you are using the overlay module.


Problem with loading translation of JS file via ajax I've got an ajax call that loads some info and a js file with something like Drupal.t('CLOSE HISTORY')

That string, although properly loaded in the database, does not get translated when loaded through ajax.

Are there any issues translating js files that are loaded through ajax?

Any ideas are appreciated!

Answer was simple - the js translation file that drupal generates was "stuck". Seems to have been a browser caching issue.


Hierarchical select breaks custom js I am building a case tracker on top of Open Atrium. My case node has some custom fields, and the "Case" category is a hierarchical select taxonomy field. I have another field called level which is dynamic and expected to change when the value of hierarchical select field input changes with custom JavaScript.
It works fine, but when the hierarchical select makes an AJAX update of the node form, the custom Javascript code stops working. I checked the Firefox JS error console, and Drupal recent log, but I could not find any error. For some reasons the hierarchical select doesn't work well with my custom JavaScript code.

Do you have any suggestion on how to fix this problem?

Are you using the live() function in jQuery to bind your behaviors? Drupal behaviors are triggered on page load and after every ajax request. If your behavior only needs to be called once then you can use the add class processed trick. It is explained here.


Using the same form more than once per page with AJAX callbacks I have a small email signup form made from extending FormBase that takes an email address and submits it to a mail service. I need to change the submit to AJAX so I can flash a success or error message.

I want to show this form more than once on a page. Once in a CTA near the top of the page, and there is a slightly different styled version in the footer.

When I added #ajax to the submit button, only one instance of the form seems to be affected. Here is the whole form:

$info = $form_state->getBuildInfo();

$form['#prefix'] = '
';
$form['#suffix'] = '
';
$form['#attributes']['class'][] = 'hl__single-input-form__form';

$form['title'] = [
  '#type' => 'label',
  '#for' => 'edit-email-address',
  '#title' => 'Stay in the know',
  '#attributes' => [
    'class' => [
      'hl__label',
      'hl__label--inline',
    ],
  ],
];

if (!empty($info['args'][0]) && $info['args'][0] == "show_tagline") {
  $form['tagline'] = [
    '#markup' => '
Sign up for email updates from MySite
',
  ];
}

$form['email_address'] = [
  '#type' => 'email',
  '#size' => NULL,
  '#required' => TRUE,
  '#attributes' => [
    'placeholder' => $this->t('Email'),
    'class' => [
      'hl__input',
      'hl__input--inline',
      'js-is-required',
    ],
    'data-twig-suggestion' => 'newsletter_signup_email',
  ],
  '#prefix' => '
',
];

$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Sign up'),
  '#attributes' => [
    'class' => [
      'hl__button',
      'hl__button--small',
      'hl__button--inline',
    ],
    'data-twig-suggestion' => 'newsletter_signup_submit',
  ],
  '#suffix' => '
',
  '#ajax' => [
    'wrapper' => 'hl__single-input-form',
  ]
];

The block in the footer that pulls the form just has this build method:

  /**
   * {@inheritdoc}
   */
  public function build() {
    return ['form' => $this->formBuilder->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup')];
  }

The preprocess for the Paragraph that outputs the form when being themed:

$variables['signup_form'] = \Drupal::service('form_builder')->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup', "show_tagline");

How can I support having this form on the page more than once, both with the same AJAX action on submit? Also, how can I avoid overwriting the wrong wrapper with an AjaxCommand?

edit: validateForm method:

/**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $email_value = $form_state->getValue('email_address');
if (empty($email_value) || !\Drupal::service('email.validator')->isValid($email_value)) {
  $form_state->setError($form['email_address'], $this->t('Please enter a valid email address.'));
}

if (mailchimp_is_subscribed('XXXXXXX', $email_value, TRUE)) {
  $form_state->setError($form['email_address'], $this->t('You are already subscribed to our newsletter.'));
}
  }

Define a class property for a sub id and append it to the form id:

class MyForm extends FormBase {

  public $sub_id = '0';

  public function getFormId() {
    return 'my_form_' . $this->sub_id;
  }

  ...
}

You can append this sub id to the wrapper as well, if you want to have different wrappers for each form:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $wrapper = 'ajax-wrapper-' . $this->sub_id;
    // use $wrapper for #ajax and div container in buildForm()
    ...
  }

Then set a different sub id for each instance of the form.

For example in a block the first instance:

$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\mymodule\Form\MyForm');
$form->sub_id = '1';
$build['form'] = \Drupal::formBuilder()->getForm($form);

and the second in preprocess:

$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\mymodule\Form\MyForm');
$form->sub_id = '2';
$variables['form'] = \Drupal::formBuilder()->getForm($form);


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

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

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

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

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

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

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

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

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

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

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

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

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

      break;

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

  return $output;
}

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


how to get the values of entity reference fields of a content type in a node page? There is a content type in my website called singer and every singer may have name and some other information. there is another content type called songs and every song has two fields: (1) File (2) name. I also created an Entity Reference field in songs which links the song to a singer. obviously every singer may have any number of linked songs.

I listed the singers in a page and it must display every singer information and songs when the user click on any of the singers. this is my template.tpl.php

function MyThere_preprocess_page(&$variables)
{
    if (isset($variables['node']))
   {
        switch ($variables['node']->type)
        {
        case "singer":
            $suggest = "page__node__singers";
            $variables['theme_hook_suggestions'][] = $suggest;
            $variables['name'] = t($variables['node']->field_singer_name['und'][0]['value']);
            break;
        }
    }
}

I can get value of singer fields (using kpr()) but I don't know how to get the value of songs fields that are linked to a singer.

thanks

You can try this thing

// $node represents the node object
// field_songs is the field used in content type to reference field.
$wrapper = entity_metadata_wrapper('node', $node);
$songs = $wrapper->field_songs->value();

Now in $songs you will have each songs object and you can print what ever information you want to print from it.


Issue with the features Module I am experiencing an error when creating some nodes of a particular content type on my site: It triggers a 500 error when users try to save the node. When I look into the log error this is the message displayed:

  Notice: Trying to get property of non-object in _MO_events_is_event_page() (line 461 of /var/www/Server_Name/htdocs/MO/sites/all/modules/features/MO_events/MO_events.module).

Does anyone have any ideas as to what may be the cause?

Here is the Code on line 461

function _MO_events_is_event_page() {
  $is_event = &drupal_static(__FUNCTION__);

  if (NULL === $is_event) {
    $menu_item = menu_get_item();
// If the current menu router is a node of type event or virtual_conference we're on an event page

     //Line 461:
    $is_event = (TRUE === isset($menu_item['page_arguments'][0]) && TRUE === isset($menu_item['page_arguments'][0]->type) && ('event' == $menu_item['page_arguments'][0]->type) || 'virtual_conference' == $menu_item['page_arguments'][0]->type);
          }

          return $is_event;
        }

That error means that $menu_item['page_arguments'][0] isn't an object in the context in which that code is run. It's probably happening during a redirect where the page isn't node/123, and so there's no node object available.

You can fix it by adding a bit of error checking (I've taken the liberty of using menu_get_object() instead of menu_get_item(), it's a more standard way of getting the current node object):

function _MO_events_is_event_page() {
  $is_event = &drupal_static(__FUNCTION__);

  if ($is_event === NULL && $node = menu_get_object()) {
    $is_event = $node->type == 'event' || $node->type == 'virtual_conference';
  }

  return (bool) $is_event;
}


Pathauto alias programmatically? My custom module enables my custom token that allows me to create user paths from one of 3 fields: user:name, or if exists first name + last name, or if exists pageurl field.

this token really gives me the strings like:

Katherine Resette - if page url field is not filled

Mike Nukle - if page url field is not filled

mybeautypage - if page url field is filled

This custom token is: [user:user_pageurl]

and I use this token in Pathauto Patterns on User Paths: [user:user_pageurl]

it does not create strings like:

example.com/katherine-resette and

example.com/mike-nukle

it use just this line as it is:

example.com/Katerine Resette

Please help me to fine my code with pathauto alias create ?

the code from my module user_pageurl.module is this:

     /**
 * Implements hook_token_info().
 */
function user_pageurl_token_info() {

  // Add tokens.
  $user['user_pageurl'] = array(
    'name' => t('Page URL'),
    'description' => t('Defines string for user page address based with priorities
                        (if filled, 3 - high priority, 1 - low priority) : 1. login, 2.fields First name and Last name, 3. field Page URL'),
  );

  return array(
    'tokens' => array(
      'user' => $user,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function user_pageurl_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

 if ($type == 'user') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'user_pageurl':
          $user_pageurl = user_pageurl_token_replace($data, $options);
          $replacements[$original] = $sanitize ? check_plain($user_pageurl) : $user_pageurl;

          // pathauto clean
          module_load_include('inc', 'pathauto', 'pathauto');
          $replacements[$original] = pathauto_clean_alias($replacements[$original]);
          break;
      }
    }
  }

  // Return the replacements.
  return $replacements;
}

 /**
 * Implements hook_token_info().
 * user_pageurl token might contain 1 of 3 user fields
 * 1: user:name - login
 * 2: first name + last name - if exists any
 * 3: pageurl field - if exists - highest priority
 */
function user_pageurl_token_replace($data, $options) {
  //dpm($options);
  $language = $options['language']->language;

  //high priority pageurl token - user:field_pageurl
  //dpm($data['user']->field_pageurl);
  if (isset($data['user']->field_pageurl[$language][0]['safe_value'])) {
    $pageurl = $data['user']->field_pageurl[$language][0]['safe_value'];

    return $pageurl;
  }

  //medium priority pageurl token - user:field_first_name user:field_last_name
  if (isset($data['user']->field_first_name[$language][0]['safe_value'])) {
    $first_name = $data['user']->field_first_name[$language][0]['safe_value'];
    $pageurl = $first_name;
  }
  if (isset($data['user']->field_last_name[$language][0]['safe_value'])) {
    $last_name = $data['user']->field_last_name[$language][0]['safe_value'];
    $pageurl = $last_name;
  }

  if (isset($first_name) &&  isset($last_name)) $pageurl = $first_name . ' '. $last_name;

  //low priority pageurl token - user:name
  $pageurl=$data['user']->name;

  return $pageurl;
}

I do not understand why pathauto takes the string as it is and do not transform it replacing uppercases, spaces and so on...

You have to prepare the string yourself, manually. You can use the pathauto_cleanstring() helper function that will remove all characters you wouldn't want in the URL (e.g. spaces).

Here's an example:

// The function we need is in the pathauto.inc file.
module_load_include('inc', 'pathauto');
$clean_title = pathauto_cleanstring($string_you_want_to_clear);

Hope this is what you were asking about.


How do I change the default value for a filter? I want to customize the default value for a filter in view through some custom code.
I have tried the below answer and its not working for me.

if ($form['#id'] == 'MY_EXPOSED_FORM_ID') {
// Modifications go here.
// example: (change the field name to yours)
// $form['field_adv_cat_1_tid']['#default_value'] = 'All';

}

How to change views exposed filter default value

And I tried these settings also.

$form_state['input']['field_program_tid'] = '44';
$view->filter['field_program_tid']->value = "44";
$view->exposed_input['field_program_tid'] = "44";

Anyone help me in this?

you can try using hook_form_alter in your custom module.

     function yourmodule_name_form_alter(&$form,&$form_state,$form_id){
//print $form_id to get correct id of the exposed form
    if($form_id == 'views_exposed_form'){
      $form['field_program_tid']['#default_value'] = '44';
//you can unset "all" if you don't need it
      unset($form['field_width_value']['#options']['All']);

     }
    }


Why is my functional test not matching my manual testing? I have a Drupal 8 module for banning users based on country.

In it, I have the following test.

public function setUp() {
  parent::setUp();
  $this->drupalLogin($this->adminSitesUser);
}
public function testCompleteBan() {
    // node/1.
    $this->addBanNode("Read only page");
    // node/2.
    $this->addBanNode("Complete ban page");
    $this->drupalGet(IP_BAN_ADMIN_FORM_PATH);
    $edit = array(
      // Set the United States to Read Only
      // 0 = no action / 1 = Read Only / 2 = Complete Ban.
      'ip_ban_US' => 2,
      // Set the test IP address to a known Google US address.
      'ip_ban_test_ip' => '66.249.84.22',
      // Configure the paths for read-only and complete ban.
      'ip_ban_readonly_path' => '/node/1',
      'ip_ban_completeban_path' => '/node/2',
    );
    $this->drupalPostForm(IP_BAN_ADMIN_FORM_PATH, $edit, t('Save configuration'));
    $this->assertOptionSelected('edit-ip-ban-us', 2, 'Complete ban set correctly in country list table.');
    // Should be redirected to complete ban page after logout.
    $this->drupalGet('user/logout');
    $this->assertUrl('node/2');
  }

However, I get an error on the last line (assertURL()):
"Expected 'http://d8.dev/node/2' matches current URL (http://d8.dev/). Value 'http://d8.dev/' is equal to value 'http://d8.dev/node/2'."

It seems as if the page is not redirected on logout the way it is when manually testing with an extremely minimal installation and using the exact same settings (including permissions)/workflow as the tests.

Note all the form-based tests are working as well.

Any idea why this is not working in D8? (It works fine in D7.)

The assertion failure looks as though the testing framework isn't following the double redirect (from /user/logout to <front> and thence to /node/2). Maybe explicitly request the front page after logging out?

Ie.

$this->drupalGet('user/logout');
$this->drupalGet('<front>');
$this->assertUrl('node/2');


Scheduled unpublished content and media that is under content moderation Let's say you have a need for the following:

Content is created with content moderation, with various states.
After a set amount of time, the content is deleted or archived.
The user can set when media (using the media module) can be unpublished.
When the media is unpublished, it's truly gone from the system. Meaning, if you already knew the path of the file before (like example.com/site/default/files/blah.pdf), then after it has been unpublished, it can no longer be accessed because it's gone from the file system.

Playing around with content moderation, I can get it to published in a scheduled manner, but unpublishing seems to not be as straight forward. And media, well, that seems to stick around forever unless you truly delete it.
What am I missing? If this isn't a part of the contributed modules, what other options are there?

It should be no problem for a module to implement a cron hook to unpublish content and media after a set amount of time.
Concerning the media files, if you want that they can no longer be accessed after unpublishing the media entity you have store them in the private file system configured in settings.php. See
https://www.drupal.org/docs/8/modules/skilling/installation/set-up-a-private-file-path
The public file system example.com/site/default/files can be accessed through the web server directly without Drupal being involved.


How to create a Rule to create a new entity of type Comment and a body with tokens? Using drupal 7 and the Rules module, I'm trying to "create a new entity" of type comment. What it's strange, is that although all the other fields accept tokens, "the main body text" doesn't.
Tokens are considered as simple text.

Anyone experienced this and know how to solve it?

Have a look at Comment # 10 of the Rules (support) issue titled "Access and Set Comment extra fields ". It includes a Rule example that looks like so:

{ "rules_test" : {
    "LABEL" : "Comment bot",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "zzz",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : {
                "value" : "This text will be replaced in the next action.",
                "format" : "filtered_html"
              }
            }
          },
          "PROVIDE" : { "entity_created" : { "new_comment" : "New comment" } }
        }
      },
      { "data_set" : {
          "data" : [ "new-comment:comment-body:value" ],
          "value" : [ "node:field-status" ]
        }
      }
   ]
  }
}

The clue to solve your issue (= work around?) is to use that last Rules Action starting with "data_set".


popup window in drupal I want a module to load in pop-up window. Ex. i have a module where the page callback will be a form. when user clicks on a link in my website. only the form has to load in the popup window like the lightbox 2 functionality.

i will generate a form in my custom module and i want the form to be displayed in the front-end of the site in a light box.. without other regions(header,footer,right,left) of the page.

Check out the Popups module, it may be what you are looking for.


Taxonomy page by views with two arguments? I'm not sure if I have understood correctly how views override taxonomy page. What I would like to do is to let taxonomy page have two arguments and each of them are taxonomy terms from different vocabularies. For example,  I have two vocabularies  and  like below. Node can be tagged with multiple terms from  but just with one term from

<Color>
 Blue
 Red
 Grey

<Car>
 GM
 BMW
 Toyota

I would like to make URLs like this.

/Blue/GM
/Blue/BMW
/Blue/Toyota
/Red /GM
/Red /BMW
/Red /Toyota
/Grey/GM
/Grey/BMW
/Grey/Toyota

And when user taxonomy link on node page view for example,
If the node is tagged with "Blue" "Red" "GM"

Click "Blue" takes to /Blue/GM
Click "Red" takes to /Red/GM
Click "GM"  takes to all the node list of "GM" maybe URL /GM

I've been playing with taxonomy views but still can't figure out hot to achieve this.

Based upon my read of your question there may be several things to address here.

View is not overriding your URL.  The address you have in the URL should be unique and intended to call the view just as if it is any other piece of content.  Do not have more than one piece of content with the same address, can only confuse things. Ignoring aliases for a moment, that means you cannot create a view with the path of taxonomy/term/tid, but you can create one called taxonomy/term/tid/facts. adding the fourth level of the URL makes it a unique address.
You are not defining a taxonomy page with terms from two vocabularies. To provide the content you desire you should create a view with the desired URL name.
A taxonomy page has a URL of taxonomy/term/tid. You can provide it with an alias, but that can confuse your thinking.  The first thing Drupal always does with an alias is convert it back to the original path.  So anything that uses the URL, such as Views will not see the alias, it only sees the original path. That means that that if the paths you desire, such as red/gm are aliases, they will not be seen by the view.
A view can have multiple paths using the % wildcard.  If you created a view with a path of /cars/%/brand Then your view will be called by Drupal for any value placed in the % location of the path.
A view path should always have a static name for the first and last positions of the path.  In your examples above for red/GM you basically have an URL of %/%which would be assigned to just about everything.

To create your desired View content you may want to try the following:

Define two vocabularies for brand and color, and/or anything else you want in the categorization.
Create a content type that includes fields for these two vocabularies and give the content URLS following the formula similar to  `cars/%(color)/%(brand)/
Create a view with a path something like cars/%/%/view The word 'view, in the path can be anything you desire.
Define the view to display whatever content you want.
Create two contextual filters, the first defined to read a term from the color taxonomy and the second to read the brand.  Views will use the value of the first % for the first contextual filter and the second % for the second filter.

That should get you started, although I suspect you will have at least one more round of questions before it works for you (It always does.)  There are a lot of previous questions on this site whose answers will help solve the details for you.  There is also an excellent video series 'Taming the Beast' that can show you everything you need to know about views.


Is there a setting to add a suffix and prefix to a list(integer) field like there was in Drupal 6? I am in the process of migrating a Drupal 6 site to 7. Several of my content types have a field called "Rating" which was an integer field in D6 that used a <select> to choose a value 1-10.

In the process of migrating to D7 this field was converted to a list(integer) field. On the old site I was able to add a suffix of "/10" to this value in the field's settings so the field would always render as "#/10". However, in Drupal 7 there is no longer a place to set this suffix on the field's setting page.

Does this setting exist anymore for this field type? If not, do I have any options for adding this suffix outside of creating a custom "field--field-rating.tpl.php" template?

You can do it with Simple Field Formatter module, see the below screenshot

Which allows site administrators to easily control the display of
field values with following features

  Prepend the field value with specified text/HTML
  Append the field value with specified text/HTML
  Reverse the Field Value
  Trim the Field Value
  Convert the field value to lowercase letters
  Convert the field value to uppercase letters
  Convert the first character of the field value to uppercase
  Convert the first character of each word in the field value to uppercase (7.x-1.x-dev)
  Replace some characters with some other characters in the field value (7.x-1.x-dev)
  Link the field value to node(7.x-2.x-dev)


Add Checkboxes to a views listing of titles I am looking to pull in a views listing of events by title into a entity form.

I need help figuring out how to add checkboxes to the views listing of title. This way if someone checks the box when the form submits it will show in the form submitted information that they are interested in that event. Then I need to add that listing to the form.

Thanks

It can be done. You have to build a view -> Entity view and pull in your fields.
Then in the form create a field -> Entity Reference -> Check boxes/radio buttons -- under Entity selection -> Views: Filter by an entity reference view -- then pull in the view you created.

Easy Peesy when you figure it out.


Link a Page to another Page using Views and taxonomy I have a Page created using a View using a Content Type called Sectors, which displays rows of images with a title underneath the image. The Sector content type has the fields - Title, Image, Sector Category (uses a Taxonomy). A Sector can have many Projects.... so.....

When the user clicks on the Sector Image or Title, i want my site to go to another Page which is created using a View and display all the Projects belonging to that Sector using the Sector Category field (which is a field on both Sector and Projects content type, passed to it from the previous Sectors page), to select all the Projects that are held in the Projects Content Typle - which has fields Title, Image, Sector Category.

How can I link the 2 views?

You first need to create your other page, using Views, with a path pattern similar to the following:

projects_by_sector/%tid

This page can then be configured to display only content of type Projects and the fields you need (Title, Image, Sector Category, etc). Most importantly, you need to configure a contextual filter with the following configuration:

For the "Content: Sector Category" field
"Provide default value"
"Raw value from URL"
"Path component" => 2 (this follows from the example URL above)

Now back in your existing Views page for the Sectors list, you need to do some field rewriting. This can be done in a number of ways, the easiest would be to add the Sectors Taxonomy reference again as a field and do the rewriting on that field. You can do these using the following steps:

Add the "Content: Sector Category" field
Save with the default configuration
Rearrange your fields and move the new field below/after the "Content: Title" field. This is important so that the replacements token [title] will be available for the rewriting.
Hide the "Content: Title" field by selecting "Exclude from Display" on its configuration
Configure the new "Content: Sector Category" field
Select "Plain text" as "Formatter"
Expand "Rewrite Results"
Select "Rewrite the output of this field"
Enter the following in the "Text" textarea to use the title of your sector
[title]
Select "Output this field as a link"
Enter the following as the "Link path"
projects_by_sector/[field_sector_category-tid]

This is a rough idea, you need to tune your views page accordingly, but the end-result should be what you asked for. Hope this helps!


How to hide the title field in create content (Drupal 6)? I have a type of content that I won't use the page title,
I will have to use a taxonomy field (the titles will repeat), because it's a restaurant list with auto-complete.

Can I do it with hooks or something?  I could copy some content from other field into the title if it's gonna be mandatory at submit..right?

How can I do it?

The Automatic Nodetitles module in conjunction with the Token module is perfect for this.  From the project page:

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

  Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.


How to hook into "visiting the website"? My main problem is very similar to How to grant userpoints to users who perform a login 5 days consecutively?. As Mike correctly notices in his answer on that question, his solution will not work for users who leave their browser logged in. Therefore, I do not want to hook into a login, but into "visiting the website" (i.e. accessing any page).

I am fine with both Rules and custom code. In the first case, which Rules event can I use? For performance reasons, it is in both cases desirable that the hooking takes place as few times as possible (in the best case once a day per visiting user). Is restricting the visited page to a particular one, say, the homepage the only way to achieve that?

Using Rules Event "Drupal is initializing" (within "System") for sure will do the job:

It doesn't depend on login (can be used for any role).
It applies to any path (a node, a view, etc).

Should you want to do so, you can also add any desired Rules Conditions (eg to only consider selected paths, eventually using RegEx expression also).

Make it right before you make it better

I'm not sure this is the only way your question can be answered, but I do know that this Rules Event (Drupal is initializing) will do what you're asking for, which is to hook into "visiting the website" (i.e. visiting any page) (as in your question).

But, using this Rules Event also comes with a price: it will case this rule to be triggered on every page request (which is a pretty similar to your visiting any page). However, if this price is too high, maybe you want to consider any (or all?) of these compromises:

Add Rules Conditions such as "only for users with selected roles" (eg: authenticated, so that for Anonymous users the Rules Actions are not triggered).
Instead of any page, you only take into consideration something like "viewing content" (for which you know there are less expensive Rules Events available).


Second ajax button not working on user profile form I have added a custom button which has an ajax callback with the following code to the user profile form.

$form['validate_2'] = array(
          '#type' => 'button',
          '#value' => t('validate 2'),
          '#ajax' => array(
            'callback' => 'example_validate',
            'wrapper' => 'validate-settings',
            'method' => 'replace'
          ),
          '#name' => 'user_validate_2',
          '#id' => 'user-validate-2',
          '#weight' => 10
        );

But when I click on it, it gives me ajax error in popup saying

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /system/ajax
StatusText: n/a
ResponseText:
( ! ) Fatal error: Call to undefined function user_profile_form_validate() in /includes/form.inc on line 1520

In my ajax callback I'm simply displaying the $form_state array. Any idea what I'm doing wrong?

The form's own submit button is not with ajax.

function example_validate($form, &$form_state) {
dsm($form_state);
}

If Drupal can't find one of its core files it's nearly always because you're trying to use it in a context in which it wouldn't be automatically included.

For example when you use the user profile form normally, the menu item makes sure the file containing the form functions is included.

For your example the missing function is in user.pages.inc, so:

form_load_include($form_state, 'inc', 'user', 'user.pages');


How can i check if css class exists on page and add new one to the body something like:

function mytheme_preprocess_html(&$vars) {
  //if css.class exists on page{
  $vars['classes_array'][] = 'my-class';
 //}
}

... All i want is to add class to other elements if there is custom views (module:views) on my landing-page

function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}

or

if ($('body.mydivclass').length > 0) {
  $('body').addClass('new-class');
}


How to set value to auto-complete field after form submission? I have a dependent auto-complete form field in my custom module. After submission the form the auto-complete field shows above the result output. Now I want that submitted value should become default value after form submission.
I tried like this:

'#default_value' => isset($form_state['values']['keys']) ? $form_state['values']['keys'] : '',

but not getting any value. I also tried like this:

'#default_value' => isset($_REQUEST['keys']) ? $_REQUEST['keys'] : '',

but still unable to get any value. someone please help.

Finally I found the solution myself. I simply got a value from URL like this:

'#default_value' => (arg(3)!= 'none') ? arg(3) : '',


Bulk language assignment In the past I created hundreds of nodes in a specific language.
Finally, the website will have only one language and I think it is best to set them all to unassigned language for development reasons.

How I can change the language in bulk?
Is there any module for that, or some SQL queries to run directly at the database?


Views 3 vertical reading list When displaying a view of all the terms on my site in asc order, they read from A-z down.  Apply a grid-2 to each row, and they read as so:

A B C D E F G
H I J K L M N
O P Q R S T U

This is difficult reading in my opinion.  I would like them to read as so:

A D G J M
B E H K N
C F I L O

Is it possible to achieve a vertical list like this?

Could you try changing the ordering for the grid to be vertical and not horizontal. I am assuming that the you are using a grid as the format for displaying your data in the view.


User anonymity while using user_external_login_register()? I am using D7 and implementing my own 3rd party authentication against campus LDAP by hook_form_alter()ing a user_login_form to my use own custom user_login_authenticate_validate() which eventually calls user_login_external_register().  As general examples see these blog posts for this technique:

blog entry 1

blog entry 2

But using this method, or even the D7 LDAP module; I see Drupal eventually calls user_login_external_register() with $username and $password.

I dont want to store ANY $username or $password in Drupal as this is considered private student campus data. So, can anyone suggest a mechanism provide dummy user $username and $password for thousands of users logging in? What can I stuff into $username or $password to be able to know that if a student logs in 2 weeks from now they have the same Drupal account they used 2 weeks ago.

All I can think of is generating thousands of custom PHP uniqid()'s and provisioning 1 per each user just prior to calling user_login_external_register() by stuffing faux $username and $profile into the $edit or $account before Drupal creates the account and after the authenication by the 3rd party.

Any feedback and thoughts appreciated.

Would it be sufficient to hash the username and/or password through something like sha1()?

You then wouldn't be storing campus data locally, as the hash is one way.  You'd still be able to check against it later as Drupal would store the hashes.


drush make on local gitweb raw url I moved a git repo from github to local gitweb and want to access the raw build make file

http://git.mycompany.com/?p=workflow.git;a=blob_plain;f=build-workflow.make;h=170f5329b413bea0efb1ec33bebdc1549403cc3e;hb=HEAD

opening that url in browser is fine:   raw code same as in github

But drush make complains about missing core and api entries.

So I checked with wget and it saves a `index.html?p=workflow.git' which is a complete html page.

How is that supposed to work on gitweb ??

So I found the solution : the shell is interpreting the semicolons and cuts the URL so it has to be quoted. Here for example http://sourceforge.net/apps/trac/sourceforge/ticket/9358 it is explained.

my drush cmd should be:

drush make "http://git.mycompany.de/?p=workflow.git;a=blob_plain;f=build-workflow.make;h=170f5329b413bea0efb1ec33bebdc1549403cc3e;hb=HEAD"


responsive menu toggling module? I was curious after stumbling upon this particular construction of a responsive menu.

How was this responsive menu toggle menu created? is it via a module or just pure css / javascript?

http://picturefill7weblinc.h011.attiks.com/node/1

It uses the Responsive Bartik theme. I can see from the CSS that it uses CSS media queries and from the project description that it uses JavaScript (Html5shiv, Respond.js and Selectivizr.js).


Postfix server and Simplenews module interaction I send newsletters from my Drupal-7 website to all its registered users, using Simplenews module. As this number grows, I want to be able to track the number of successful and unsuccessful sends.
In my site, there is a postfix server installed, whose logs may give me a hint on how many mails were not delivered.
Although, the log file is a chaotic file -300.000 rows or even more- and the mails might be about something else, like registration for example.
I want to be able to track better how many of the newsletters were successfully delivered, in integration with my postfix server.
Or if you can suggest a better way to achieve that.
Thanks a lot!

You could try to add a [Reply-To:] header to your mails. Maybe your postfix will send the non-delivery notifications to this address.


How to modify field group markup? field_group.module defines a function as follows:

function field_group_pre_render_accordion_item(&$element, $group, &$form) {
  $element += array(
    '#type' => 'markup',
    '#prefix' => '
format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '">' . check_plain(t($group->label)) . '

classes . '">',
    '#suffix' => '
',
    //'#attributes' => array('class' => array($group->format_type)),
  );
  if (!empty($group->description)) {
    $element['#prefix'] .= '
' . $group->description . '
';
  }
}

Which is an instance of field_group_pre_render_<format-type>.

What I want to do is change that prefix code from an h3 to a div. But I'm not sure what the appropriate function/hook would be to use.

The Field Group API defines a hook_field_group_pre_render function but the $element argument in this function doesn't supply the #prefix element - so I'm not sure.

Ideally I could just totally override the function field_group_pre_render_accordion_item in my own code...

Implementing hook_field_group_pre_render_alter() seems the way to go, it's called just after field_group_field_group_pre_render() which calls field_group_pre_render_accordion_item() and receives the correct info.

It should be like this:

function mymodule_field_group_pre_render_alter(&$element, $group, &$form) {
  if ($group->format_type == 'accordion_item') {
    $element['#prefix'] = '
format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '">' . check_plain(t($group->label)) . '

classes . '">';
    if (!empty($group->description)) {
      $element['#prefix'] .= '
' . $group->description . '
';
    }
  }
}

Remember to implement it in a module, as a hook_*_alter() implemented in a front-end theme may not be discovered while flushing cache via drush or in the back-end theme.


How to display data without html on ajax call? How to display only content on ajax hit without html markup?

what i am trying to do i have to show data on button click in profile dashboard(custom page) ,for this i have created controller file .

class OutstandingPaymentPending extends ControllerBase {
  // callback for learning portal access
  public function GetPendingPayment() {
    /* TO DO
     * Making api dynamic via configuration
     */
    global $base_url;
    $user_id = \Drupal::currentUser()->id();
    $psid = '';
    $psid_request = \Drupal::request()->get('ds');
    if (!empty($psid_request)) {
      $psid = $psid_request;
    }
    else {
      $psid = get_psid_by_user_id($user_id);
    }
    // Get outstanding data from api
    $url = OUT_STANDING_API . '?PSID=' . $psid;
    //$url = OUT_STANDING_API . '?PSID=00002449846';
    $access_token = API_ACCESS_TOKEN;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('AccessToken:' . $access_token));
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    $rows = array();
    $result = json_decode($response);

    $result = trim($result, '"');
    if (trim($result) == 'No data found') {
      $rows = array();
    } else {
        $outstanding_result = json_decode($result);
         $course_count = 1;
        $rows = [];
        if (!empty($outstanding_result)) {
        foreach ($outstanding_result as $key => $value) {
          //if ($outstanding_result->ResponseCode != 401) {
          $rows[] = array('course_name' => $outstanding_result[$key]->CRSNAME,
            'course_validity' => $outstanding_result[$key]->VALIDITY,
            'course_type' => $outstanding_result[$key]->COURSETYPE,
            'course_installment_date' => $outstanding_result[$key]->INSTDT,
            'course_total_outstanding' => $outstanding_result[$key]->TOTALOUTSTANDINSTAMT,
          );
          //}
        }
      }
    }

    return array(
      '#theme' => 'pending_installment_template',
      '#installment' => $rows
    );
  }
  }

My ajax code is:

//ajax for showing installment payment pending block on click
$(document).on('click', '#gettoptracks', function (e) {
    e.preventDefault();
    $.ajax({
        url: "/outstanding-payment-left",
        context: document.body,
        success: function (data) {
            $("#show-pending-payment").html(data);

        }
    });
    // your statements;
});

On clicking ajax based button its rendering entire page along with data with all html, so js files and css rendering two times in same page .

how i can show only data instead of entire page html which is rendering on page.html.twig?

I have done this in a custom controller before. You don't want to return a render array, because Drupal will take the default action.

Instead, you want to render it to HTML (string) and return that back. Something like this:

$rendered = $this->renderer->renderRoot($build_array);
$response = new Response();
$response->setContent($rendered);
return $response;

As far as the Javascript, here is a generic example using fetch (in a twig file):

You also likely don't want to cache the render array either. You can also greatly simplify the API fetch code by using Guzzle (Client) instead of curl.


How to print link text in twig? I've attached file to a node with Media module. I have custom templates/file/file-link.html.twig file, which is rendering the download link with {{ link }} tag.

{{ devel_dump(link) }} outputs this:

I need to print File name as pure text without any link rendering for some cases.

I've tried {{ link.text }}, {{ link.text.string }} and other options, but none of them gave me what I wanted.

Maybe this is a render array and you need to use link['#text'] here (sorry if I'm on the wrong track).

Edit: If {{ link.text }} worked on subsequent tries, then my answer is definitely wrong, and the reason for your problem was probably related to caching or something.


Call multiple hook inserts from different modules? Is it possible for two modules that interact with one another to both call hook_insert()?

I have a node type that calls ModuleA_insert() when the user hits the 'save' button.
Module B is a custom comment-like module that gets injected into a form. In module B, I have a ModuleB_insert(), but it never runs.
I am trying to keep module A from having to deal with the inserts/updates from module B.

I can get module B to insert by using hook_nodeapi(), but it would be easier if I could get hook_insert() to work, meaning module A and module B's data and actions are separated from each other - not to mention the overhead cost of having hook_nodeapi() run and check every time.

Rule of thumb: Don't call hook_anything() in other modules. :-)

If you call node_save($yourNode) then the node API will invoke hook_insert() in the module that implements that node type, if the node is being inserted. Otherwise hook_update() gets called for updates.

If you need to act on an insert for any type of node, and it sounds like you do, then you want to implement hook_nodeapi().

Examples has a node project and a nodeAPI project, so you can figure out which you need.


Add arguments to custom submit I added an extra submit-function to my form:

$submit = array('_check_value_public_catalog');
$form['actions']['submit']['#submit'] = array_merge($submit, $form['actions']['submit']['#submit']);

So the form looks like:

array
  0 => string '_check_value_public_catalogue'
  1 => string 'node_form_submit'

But I would like to pass some arguments to my _check_value_public_catalog function. How do I do this?

You can't as such but you can store the values in the form somewhere and pick them up in your submit handler:

function mymodule_my_form($form, &$form_state) {
  $form['saved_value_1'] = array(
    '#type' => 'value',
    '#value' => 'The Value'
  );

  $form['#submit'][] = 'mymodule_my_form_submit';

  return $form;
}

function mymodule_my_form_submit(&$form, &$form_state) {
  $saved_value_1 = $form_state['values']['saved_value_1'];
}

Exactly the same principle applies if you're doing this in a form alter hook.


Update failed on Metadata module, any easy fix? I am very sorry to bring a rather nebulous question here but need any and all help I can get:  for the first time, I've had a "White Screen of Death" issue when trying to update a module.  I believe it was the "Metadata" module but I don't even remember for sure.  I had a previous backup of the database and site files/folders from a day ago, so I didn't make one this time.  Followed the Drupal tool for downloading, installing, and...presto....White Screen of Death.

Trying not to panic, I reverted to the older backup.  Which I hoped would solve the issue.

Yet it did not.

So my question is whether perhaps (fingers crossed!) there's additional steps I need to take once a backup is in place to get things working again.  I tried truncating every "cache_..." line via PhpMyAdmin, but it didn't help.  I tried the "update.php" in the URL hoping it was (maybe) just an index.php issue.  Again...no dice.

I've seen a long page about WSOD possible issues but don't want to just muddle around doing that if I don't know what I'm doing, which I don't.

Are there any suggestions for quick, simple things I've either forgotten or could try to get this working again?  And if I can't, can I manually copy files and folders over somehow and try again?

Thank you all in advance for any help.  I really appreciate it.  Stay healthy out there!

So the solution here was that the backup (done by my ISP) did not fully restore.  I think they forgot to recursively restore and just did the main Drupal root.  Once I asked them if they were sure they restored recursively and there was a long pause (a few hours, at which point the site started working again) they came back and said they'd missed a few files.

So luckily that solved it.  I did not need to configure anything or run any update.php or such.  Just restored the entire Drupal directory and all subdirs and such, and a database restore to match.  That fixed it.  Whew!


Link field to content In my view I have 4 fields including an image. I want to link a field other than image field to the content but there is no such option as for the image field i.e "Link to". How can I get this option?Or is there any other way to do this?

you can rewrite the output of that field and make it a link. Rewrite works for all fields - some fields do offer a link output in their settings though and might be the better option if available.

Steps to take:

add a path to the content and exclude it from output.

rewrite the output of the field you want to add a link to.


How to get a field in a exposed filter criteria as an autocomplete? In a view the field which has widget autocomplete does not get
an option to select as dropdown or autocomplete in exposed filter criteria.
I have a field in a content type which has following properties.
Type : entity reference
widget : autocomplete
How can I set a exposed filter criteria field as autocomplete ?

You can use Views Autocomplete Filter for getting autocomplete exposed filter in views. Module page says :

Add autocomplete functionality to the views filter text fields.

 - It works for node titles or cck text fields.
 - The autocomplete results are actually the view results, so they are view related.

But the field which you will expose & use autocomplete should be in the views result fields as well.


How to fix broken file.module function 'file_ajax_progress' without hacking the core and patching after every update? When site has enabled page cache and anonymous user tries to upload a file, he cannot see upload status progress. He see only message "Starting upload...". Bug was reported in June 2012, has a working patch and I have a question:

How to fix broken file.module function file_ajax_progress without hacking the core and patching after every update? Should I do some function override by custom module?

This is all working code together:

/**
 * Menu callback for upload progress.
 *
 * @param $key
 *   The unique key for this upload process.
 */
function file_ajax_progress($key) {
  $progress = array(
    'message' => t('Starting upload...'),
    'percentage' => -1,
  );

  $implementation = file_progress_implementation();
  if ($implementation == 'uploadprogress') {
    $status = uploadprogress_get_info($key);
    if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
      $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
    }
  }
  elseif ($implementation == 'apc') {
    $status = apc_fetch('upload_' . $key);
    if (isset($status['current']) && !empty($status['total'])) {
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
      $progress['percentage'] = round(100 * $status['current'] / $status['total']);
    }
  }
  // Mark this page as being uncacheable.
  drupal_page_is_cacheable(FALSE);
  drupal_json_output($progress);
}

Patching core is not the same as hacking core.  Many of us have patched versions of Drupal in the wild (eg, using Secure Pages).

You need to work out how you want to manage this between upgrades.

On sites where I don't track Drupal's repo, I keep a directory of patches next to the DOCROOT.  Before I upgrade, I check on whether the patch is needed or not.  I then drush pm-update drupal and apply patches.

On sites that I have built with git, I can typically build the site in its own branch, apply patches, and then upgrade core versions by merging the latest tag and doing the database updates.


Is there any way to change home page on small screen? I want to change the home page for small screen. Is there any way to set the front page according to the screen size by using hook_preprocess_page() or any other?

To actually answer your question (Is there any way to set the front page according to the screen size). No. Especially as you mentioned that you don't want to use JavaScript in a comment to Inizio.

The server by itself has NO idea of the screen size of the client, so the only way to get that info back would be using JavaScript (either implementing drupal.settings or some kind of custom AJAX callback). Any module that you use would alos have to utilise JavaScript.

If you want to change the frontpage based on DEVICE, then that's more realistic, with something like Mobile Detect, Browscap, WURFL (or something similar) but again - not foolproof.


Strategy for organizing category pages with Views and Panels I have created a vocabulary and using a 2 level tree for organizing content into categories.
Each category and sub-category will have it's own page, where a view block will list the teasers from the content types linked to the filtered term(s).

Now I can go and create a View block for each category, but that just doesn't seem to be proper. I'm new to Views and I have been reading a lot but I'm still not at ease with best practices on using  Views.

Should I create just one single View and make a Display for each category or there's a better way to do this?

I'll be using Panels to lay out the category pages. Do I have to create 1 page for each category/subcategory and add the corresponding view to it? Is there's a better Panel's usage strategy, that permits to skip the use of multiple page panels ?

I'm using D7, Views 3.3, Panels 3.2

I don't know if you figured this out already, but I'll give a quick answer.

The magic you need: arguments / contextual filters. You want to have just one Views block that takes term IDs as arguments (in a contextual filter), so it will filter on the term present in the url. Instead of a regular views block, you can also use a Views content pane (for tighter integration with Panels).

As for Panels: you need one panel page to override the taxonomy system path. When you enable Page manager (part of CTools) some page override templates are provided, just activate the taxonomy one.

Add a variant (you can optionally add a selection rule if you want this override to only work on terms of one vocabulary) and add your Views block. Since this is a taxonomy system path, term IDs are already available as arguments for the view block (Panels is also excelent for manipulating which arguments the page will provide).

Page manager, Panels and Views are complex so it's a good idea to understand how it works. I recommend checking out NodeOne's Learn Page manager screencasts (especially Views content panes), and maybe also parts of the Views series (especially contextual filters).


Location / distance based calculated field in views results? Modules in use:

Drupal 7.12
Views 3.3
Location 3.x-dev
(and lots more of course)

I have a pretty standard view which has a user entered proximity filter for distance from a zip code, used to shows stores near a certain location (your standard dealer/store locater search). I would like to add a calculated field (or something) to show how far each store is from the entered zip code. This field would only be used in the view, and would not need to get saved to the node it represents, since this distance will change depending on the entered zip code.

Can anyone point me in the right direction?

Thanks!

I guess I should have looked through the module better. Here's the answer (tip: it's built right in!):

Go to your view (it needs to be a node based view I think)
In the "fields" section choose "add"
In the search box type "distance" and then choose the "Location: Distance / Proximity" field
Choose miles or kilometers to suite your needs
Then choose "Use Distance / Proximity Filter" from the drop down list (assuming, like me, you have an exposed filter in your view for users to enter a distance and a zipcode)
Adjust the label if you'd like, then click "apply"
In the "sort criteria" section, choose "add"
In the search box type "distance" and then choose the "Location: Distance / Proximity" field
Then choose "Use Distance / Proximity Filter" from the drop down list (assuming, like me, you have an exposed filter in your view for users to enter a distance and a zipcode)
Choose descending (most likely, anyway) and if you want to expose it, then you can click that check box also

And that does it!


Views exposed filter block shows twice I have a view with two page displays both of which share (defaults) an exposed filter block. I've set the exposed filters to show as a block on both displays. I think used the standard block UI to display the proper filter block on the proper URL for each page display.

However, now just the correct filter block shows twice on each of these two pages.

Cache extremely cleared.

Try to switch to Garland theme to see if the problem still occurs, if not, it maybe a theme problem.


Listing entity fields I wonder if there is a good, and easy way to get all fields of an entity.

I have a taxonomy vocabulary. Its terms have a special field I want to make list in a select box in one of my modules, so that users can select a special value of the term. Therefore, I need a way to list the possible fields for this term.

The function you are looking for is field_info_instances().

  Retrieves information about field instances.


How can I prevent users from inputting URLs into a field? I'm pretty sure this is a dupe of a question from a couple weeks ago but I've been searching for about 15 minutes and I can't find it (somehow forgot to favorite it).

I want to prevent users from inputting their e-mail addresses or URLs into a text field.  How can I automatically reject such submissions?

On the Plain text input filter, there is an option to Convert URLs into links, which also converts e-mail addresses into links.  But what I want to do is remove all URLs, including e-mail addresses, that would be converted via this option.  Is that possible?

The Field validation module let you set up your own regexp or PHP code to validate (or not) what user puts into a text field.  However to reject e-mail addresses, your validator must be clever enough to not only recognize regular e-mail addresses such as spammer@example.com but also obfuscated e-mail adresses such as spammer(at)example.com.

Added note (about filtering): If, instead of rejecting input that do not validate, you want it filtered by having email addresses and links removed (or replaced with some string indicating redaction), you can use the Plain text input filter as a starting point, and just replace the code that currently turns email-adresses and URLs into live links, with code that redacts these things instead.  Then, just rename the result of hacking the code, and add it to your configuration as a custom filter.


Superfish menu is not responsive for mobile screens i'm using drupal 7 and superfish 7.x-1.9, the problem is when i reduce the browser, the menu is not responsive, it still be the same nothing moves, i'm working on it for hours now and nothing

Please any help on configurations ?

Here a screenshot of the desktop menu :

And here the same menu with browser reduced on width :

Superfish has a pretty extensive settings/configuration area, all of which, do take away any necessary programming for menus, and make setting up a complex menu simple.

You are probably missing a mobile declaration somewhere in the settings/config, I would read up on the Superfish documentation here: https://www.drupal.org/node/754652

This also has other useful links that may assist with your situation.


How to associate User data with custom module? I'm thinking about a custom module where I need to save additional data (like user logs from other software, customer data, etc.) that'd go into a custom module user table.
How would I associate that with the user? Just the user ID?
Or is there anything else that I might want to save for uses that I might not yet know (Views, Domain Acess, Panels, Context, ...) or can I get all required data just be joining the UserID everywhere?

As usual there are plenty of ways to do something with Drupal.
Of course it would be possible to create a content type and import it via Feeds but sometimes (in case it might become plenty of data) it could be better to use a different approach.

So far it seems I'd go with MongoDB, the appropriate module and get the data into the DB using JSON and try to relate that to the current user if or where needed. Due to the amount of data and the visualisation it seems to be better to go the Document DB way.