Error messages when running "drush verify-makefile" on a generated make file When running the following command, Drush is printing a number of error messages:

drush verify-makefile

There is only one make file in document root and it was created with:

drush generate-makefile drupal-org.make

There were no errors printed with generating the make file. All that is said was:

Wrote .make file drupal-org.make                               [ok]

I am trying to publish a new Drupal distribution on drupal.org. The particular error messages I am receiving are:

The project-level attribute 'custom_download' on project 'datasets' is not allowed. [error]
The project-level attribute 'custom_download' on project 'operations' is not allowed. [error]
The project-level attribute 'custom_download' on project 'quadstat' is not allowed. [error]

My guess is that these modules are not published on drupal.org so they can not be included with the distribution. It seems related to this Drupal.org issue: #1427762

Before I went and created these modules on Drupal.org, I was hoping someone could confirm my theory.

Also the syntax generated for the make file seems to follow YAML (a Drupal 8 convention) even though my Drush version is 8.1.2 and my drupalorg_drush version is 7.x-1.x-dev. My Drupal core distribution is 7.44.

I thought it may be helpful to include the make file too.

core: 7.44
api: 2
projects:
  admin_menu:
    version: 3.0-rc5
  ctools:
    version: '1.9'
  node_clone:
    version: '1.0'
  features:
    version: '2.10'
  field_group:
    version: '1.5'
  field_permissions:
    version: 1.0-beta2
  filefield_paths:
    version: 1.x-dev
  panels:
    version: '3.5'
  jquery_update:
    version: '2.7'
  libraries:
    version: '2.3'
  mathjax:
    version: '2.4'
  node_export:
    version: '3.1'
  nodeaccess:
    version: '1.4'
  text_with_summary:
    version: '1.0'
  uuid:
    version: 1.0-beta1
  views:
    version: '3.14'
  views_filters_populate:
    version: '1.1'
  shiny:
    version: '1.7'
  datasets:
    type: module
    custom_download: true
  operations:
    type: module
    custom_download: true
  quadstat:
    type: module
    custom_download: true
  libraries:
    SlickGrid:
      directory_name: SlickGrid
      custom_download: true
      type: library

There are some other unrelated error messages, but the ones I mentioned are the first that popup.

Thank you for any suggestions provided.

EDIT: Not sure if the solution specified here is cosmetic but it did take care of the above question. I am not too familiar with Drupal project packaging.

This particular error was fixed with only making changes to the make file:

I switched the colons defining Drupal core and the API versions to equals
I changed the name for SlickGrid library to lowercase("slickgrid")

core = 7.44
api = 2

The rest of the make file still uses YAML convention. I wonder if that will cause problems down-the-road.


How to add multiple products to cart at the same time with attributes I have different view blocks that display multiple products on the same page, each product has their own attributes such as product bundle and custom line item, these serves as an option set / criteria of the main product. The results of the options slider will be the value of the customs line item that is hidden.

What I plan to accomplish is to add all these selected products with the selected attributes on the cart at the same time with just one button.

Example:

Product 1:

Product 2:

These are the methods/modules I have tried:

VBO + Rules : https://www.drupal.org/node/1468392#comment-10270105
Commerce Add to Cart Extras
Commerce Ajax Add to Cart + Jquery : Looping through all selected products then clicking the add to cart button by jquery. It works but not that great because sometimes some of the products are not being added. Maybe because of all the ajax request running at the same time?

The first two methods work for the main product only, no attributes of the customs line item and bundle products. I tried including the add to cart form in the view with the VBO or commerce product: quantity field of commerce add to cart extras but it doesn't work maybe because it's a form within a form.

Does anyone have any suggestion on how to make this work?

Thank you in advance!

I suggest writing a custom hook_submit() who will add all the items of your views to the shopping cart.

Something like that should do the job.

 global $user;

 $results = views_get_view_result('view_name', 'block_1');

 foreach($results as $item) {
 // Create new line item:
 $line_item = commerce_product_line_item_new($product, $quantity);

 // Add to current user's cart
 $line_item_added = commerce_cart_product_add($user->uid, $line_item);
 }

Good luck.

Cheers


A deleted image filename is printed to the top of SOME of my nodes Background:

I once had an image file in the site (I think the image was added via an image-field I already deleted).

The problem:

This image filename I described is printed to the top of SOME of my nodes (I should note that these are nodes from different content-types). In some nodes it doesn't appear but in some others it does... Any idea why would this strange beahvior happen?

I already tried to flush all caches - didn't help.

Live examples (Images):

While I don't know the mechanism of the behavior, deleting the SQL file-data from the relevant SQL tables via PHPmyAdmin and then flushing all caches, solved the problem.

Note: There where references to the file in 2 tables (One table deals with files and one deals with the Watchdog).


Drupal users getting blocked automatically I am experiencing a strange problem with my drupal website. On it, there are a good number of registered users. Sometime the users login, but not very frequently. Suddenly I figured out that some of the users (who are relatively old) are getting blocked. I check with blocked users, they said they did nothing. I do not have any idea how they got blocked.

Ok, then I unblock them manually and now they are active. Next day, I find them blocked again. So, now I need to unblock a bunch of users manually which is not the optimal way to deal with the users.

Anyidea? Anybody?

Thanks,

Do you happen to have the Inactive User module installed? This module can be used to block users who are inactive for some time. Otherwise, are you sure that the users are not trying to log in with the wrong password (5 times), which would also block them. It could be possible that someone else is trying to log in with these user accounts and is getting them blocked (I suppose it would be up to you to decide how likely this is based on whether or not your website is fairly high or low profile).


List the hooks that can be used in .install file? I have found only few hooks that can be used in the .install file. They are:

hook_enable
hook_disable
hook_install
hook_uninstall
hook_requirements
hook_update_N
hook_schema
hook_schema_alter
hook_update_last_removed
hook_field_schema

Please tell me if I have left any hooks.

I think you are missing function
hook_field_schema
This hooks are mentioned in the "list" and "number" default module which is in "field" module.


Search for terms by name in admin panel Right now I only see a way to list all the terms of a particular taxonomy in the admin panel. I have to go through pages of terms if I want to locate a term I want to edit. How can I search by a term's name?

You can create view for your needs. Access only to admin role and pin it to "Default Shortcuts" menu.


how to display the machine name of module at /admin/modules? I use Drush to enable and disable module, to do this I need to know the machine name of the module.

At /admin/modules I can see the list of modules, but this list doesn't show the machine name, jut the human readable name.

I created a view to list the machine name of modules but I'd like to have it at /admin/modules. Is there any way to do this?

If you don't mind going low-tech you can just look at the value of the checkbox next to each module; it contains a string like:

modules[Core][aggregator][enable]

In that example, aggregator being the machine name of the module.

If you don't want to go low-tech you'll need to implement hook_form_alter(), loop through the module data in the form and add the machine name somewhere.

For example, the following code will add the machine name in brackets after the title of each module:

function MYMODULE_form_system_modules_alter(&$form, &$form_state, $form_id) {
  foreach (element_children($form['modules']) as $group_key) {
    foreach (element_children($form['modules'][$group_key]) as $module_key) {
      $machine_name = " ($module_key)";
      $form['modules'][$group_key][$module_key]['name']['#markup'] = $form['modules'][$group_key][$module_key]['name']['#markup'] . $machine_name;
    }
  }
}

Screenshot of the results on a blank Drupal installation:


Exposed date filter against >= "today" fails until 5pm Mountain time I added a Date only date field named expires to the user profile.
The expires field has the value 2021-01-08 for a certain user (I checked the database; it has no time component).
In a view, I have an exposed filter that tests the expires field using Operator=Is greater than or equal to with Value type=An offset from the current time and Value=today.
On 2021-01-09 up until 5pm Mountain time, the user with expires = 2021-01-08 is improperly included in the view.
When I refresh the view at 5pm Mountain time or thereafter, the user is dropped from the view.
I tried switching to Value type=A date in any machine readable format and Value=today. This also has a problem, but in this case users aren't included when they should be sometimes (the problem is sort of reversed).
If, as a test, I edit the exposed filter and use Value type=A date in any machine readable format and Value=2021-01-09 (i.e. hardcode the date) then the user with expires=2021-01-08 is not included in the view at any time, as expected.

It appears that today isn't giving me today's date until 5pm Mountain Time. What am I missing?
SOLUTION: Inspired by @Patrick Kenny below, I added this to MYMODULE.views_execution.inc:
function MYMODULE_views_query_alter($view, $query)
{
    if (!empty($query->where[1]['conditions'])) {
        foreach ($query->where[1]['conditions'] as $key => &$value) {
            error_log($value['field']);
        }
    }
}

Testing on 2021-01-13 at 10:17 am Mountain Time with Operator=Is greater than or equal to and Value type=An offset from the current time and Value=today, the output is
DATE_FORMAT(user__field_expire.field_expire_value, '%Y-%m-%d') >= DATE_FORMAT('2021-01-12T17:00:00', '%Y-%m-%d')
Notice the today value of 2021-01-12T17:00:00. WRONG DAY. Off by 7 hours. This confirms the answer by @Patrick Kenny.
HOWEVER, if I change to Value=now (instead of Value=today) and test again, the output is
DATE_FORMAT(user__field_expire.field_expire_value, '%Y-%m-%d') >= DATE_FORMAT('2021-01-13T10:17:02', '%Y-%m-%d')
Notice the today value of 2021-01-13T10:17:02. CORRECT DAY and time.
In my case, switching to now seems adequate to fix the problem because the Y-m-d format is applied, making the comparison work correctly. But I still subscribe to @Patrick Kenny's solution as a general fix.

Since the server timezone, Drupal timezone, and \Drupal::time()->getCurrentTime() are all pointing to the same time, you have probably been bitten by the same bug in Views that I was, Date/time Views filter tries strotime() relative to Unix epoch.
Basically, all relative values like "today" "yesterday - 5 hours", etc. can have timezone issues in Views.  There's another related issue I reported as well.  This bug has yet to be fixed.
In my case, I needed to filter by "midnight of the current day", and Views was giving me incorrect results depending on the timezone.
I fixed it like this (code more or less pasted directly from my site, but it should give you an idea of what you can do):
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if (($view->id() === 'VIEW_MACHINE_NAME') &&
    ($display_id === 'page_1')) {
    $filters = $view->display_handler->getOption('filters');
    if ($filters['field_MY_FIELD']) {
      $user_timezone = date_default_timezone_get();
      $current_timestamp = \Drupal::time()->getCurrentTime();
      $midnight_usertimezone_datestring = MYMODULE_get_midnight_datestring("$current_timestamp", MYMODULE_get_utc_offset($user_timezone));

      $filters['field_MY_FIELD']['value']['value'] = $midnight_usertimezone_datestring;
    }
    $view->display_handler->overrideOption('filters', $filters);
  }
}


how to make a filter on a view be on the result of a select query My content has a field called release year  .  I want to be able to make a searchable view which will show only the unique years in this release date as options as a select .  I don't want to hard code the years or have the user have to type in the year.  How can I do this in a view?

I'm pretty sure Drupal 8 does this out of the box when you expose the field as a view filter. The drupal 8 documentation for Views and it's Filters is clear on how to set this up and I believe a Select list is possible with if your field is an integer or a date limited to a Year component.

https://www.drupal.org/docs/8/core/modules/views/expose-a-filter-to-site-visitors


How can I re-format (not validate) the value of a field that a user inputs into a node? I am using the Addressfield module to allow users to input addresses.  I am then using the Location Taxonomize module to generate a taxonomy based on these addresses.

To make everything consistent, I would like to automatically capitalize the first (and only the first) letter of every word (I know there are exceptions where multiple words should be capitalized, but I am willing to deal with those manually).

How can I implement this?

In Drupal 6, you could do something with the nodeapi() hook, eg,

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

  if ($node->type=='TYPEOFNODE' && $op == 'presave') {
    $node->field_WHICHEVERFIELD[0]['value']=ucwords($node->field_WHICHEVERFIELD[0]['value']);
  }

  // other nodeapi()ing goes here

}

In Drupal 7, you could use the node_presave() hook with similar logic.


How to set an alias to a fields on a db_select? Like it said on the title, as we use alias to fields with a static query, i want to do same thing with a dynamic query

example :

with static select : $sql = db_query ("SELECT my_super_long_field as mslf FROM {super_long_table} as slt")

How to perform same with a db_select query please ?

$sql = db_select ('super_long_table','slt')
->fields('slt',array('mys_super_long_field', 'here i want alias for long fields')

Thank you

Use addField(). Here's an example:

$query = db_select('super_long_table', 'slt');
$query->addField('slt', 'mys_super_long_field', 'mslf');

Arguments passed to addField() are:

Table alias
Field - your long field name will be here
Alias - your short field alias will be here

Read more about it here.


Drupal 7, Custom Content Type... Does an addon that does this exist? I rebuilding my companies intranet... we have what's called a portal. Within the portal is pages. Each portal page is either HTML, a PDF or a Video.

Right now... I'm planning on creating 3 seperate content types. One with Text, one with a custom PDF Object for loading in browser and one for a video. So content types like:

PAGE content Type
* Title
* Image (Icon for content flagged News)
* Text with Teaser

PDF content Type
* Title
* Image (Icon for content flagged News)
* PDF Object (loads PDF in browser)

VIDEO content Type
* Title
* Image (Icon for content flagged News)
* Video Field

FILEVIEWER content Type
* Title
* Image (Icon for content flagged News)
* FileViewer Viewer

Notice... a lot of duplication.

What I'd like to do, and tell me if I'm stupid... is I'd like to have a drop down selector that shows the content type selected, while hiding the rest.

COMBINED CONTENT TYPE
* Title
* Image
* Select List (Three, or more, choices: Text, PDF, Document, Video)
* Text w Teaser
* Video Field
* PDF Field
* Fileviewer Field

It will display the selected content type and hide the others when displayed on the actual node/block. This particular case is simply "Select One type", so I'm not worried about selecting combinations (ie: Text + Video)

I'd just much rather baby one content type... than 3+ content types with near identical layouts.

Question updated. Basically... it's my desire to have one content type instead of 4 (and possibly more). I'm not afraid to make my own custom module, although it would be a learning curve.

The obvious choice for that functionality would be the conditional fields module. It's still under development for D7, but you can check if it already supports your use case, or maybe you could even help the maintainer get the D7 version to a stable state.


Let users choose from pre-defined user set options for creating a node I want to provide the ability for users to make and save a set of pre-defined options when they create a node.

They can then choose from their predefined set of options when creating future nodes.

(At the moment I allow users to create nodes with a custom form, I could possibly switch to the standard add node method but I'd prefer not to, unless it's a lot easier.)

Has anyone on here tried this before? At a high level, how did you go about trying to save user presets?

I find using a custom form always seems to be more work then just using the one Drupal provides to add nodes. Even if they are not quite what you want hook_form_alter makes it easy to modify them to suit your needs.

I would create an unpublished node for each of my 'presets'. This way it is easy for an administrator to update the preset values, but normal user won't be able to see them.

Then using hook_form_alter I would add a selectbox to the top of the node add form allowing the users to choose between any of the presets. You could add an #ajax property to the selectbox that rebuilds the whole form.

Again in hook_form_alter if $form_state['values']['yourselectbox'] is not empty then you can load the values from that node and populate the form with them.

As an example (none of this code is tested but I think should be almost right):

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

    $templates = db_query("SELECT nid, title FROM node WHERE type='my_type' AND status=1")->fetchAllKeyed();
    // TODO: Should maybe add a field to control if this node is a template or not?
    $default_template = 0;

    if(!empty($form_state['values']['templates'])) {
        $default_template = $form_state['values']['templates'];

        $selected_template = node_load($default_template);

        // if your fields have multiple values you will need to loop here
        $form['other_field_1'][LANGUAGE_NONE][0]['#value'] = $selected_template['other_field_1'][LANGUAGE_NONE][0]['#value']
        $form['other_field_2'][LANGUAGE_NONE][0]['#value'] = $selected_template['other_field_2'][LANGUAGE_NONE][0]['#value']

    }

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['templates'] = array(
        '#type' => 'select',
        '#title' => 'Template',
        '#options' => $templates,
        '#default_value' => $default_template,
        '#ajax' => array(
            'callback' => 'change_template_callback',
            'wrapper' => 'whole_form_wrapper',
            'event' => 'change',
        ),
    );

}

function change_template_callback($form, $form_state) {
    return $form;
}

See the examples module - it has loads of good stuff on forms and ajax.


webform save draft after each field update - ajax error for anonymous user I wanted to save webform's draft after each field's update, and i did it with help of this post: Webform save draft after each field update .

But it is only working for logged in user, if i try it with anonymous i get ajax error

"An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /system/ajax
StatusText: n/a"

Does anybody have any idea why is this happening? thank you ..

The save draft functionality has not yet been committed for webform for anonymous users.

According to the post you mentioned, @Stefan in his answer claims he added the functioanlity by incorporating my patch from this issue. (We are testing an updated patch which will be posted to the issue cue within the next couple of days.)


Storing additional data with a node reference What is the best way to store additional data in a Drupal 6 site pertaining to CCK node reference fields?

Suppose that a content type has a repeating node reference. I would like to be able to describe and/or annotate the node reference and describe the relationship between a "Person" content type and a "School" content type (e.g. "person attended school," "person donated to school"), or just have a chunk of text to go along with the relationship.

If you have a repeatable noderef field, you get a table like

CREATE TABLE  `content_field_foo` (
  `vid` int(10) unsigned NOT NULL default '0',
  `nid` int(10) unsigned NOT NULL default '0',
  `delta` int(10) unsigned NOT NULL default '0',
  `field_foo_nid` int(10) unsigned default NULL,
  PRIMARY KEY  (`vid`,`delta`),
  KEY `nid` (`nid`),
  KEY `field_foo_nid` (`field_foo_nid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

I could create a module that maintains a table like the following, which is used to store the metadata.

CREATE TABLE  `mymodule_noderef_metadata` (
  `vid` int(10) unsigned NOT NULL default '0',
  `delta` int(10) unsigned NOT NULL default '0',
  `metadata` longtext,
  PRIMARY KEY  (`vid`,`delta`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

The problem with this is that I would have to do a hook_nodeapi to update the table on both "nsert" and "update" to be able to handle revision rollbacks.  In the particular implementation I am thinking of, there could be a pretty big performance impact of doing this.

Am I overthinking this? Is there a better way to do this?
I searched around for a module that does this, but didn't find anything.

Have you looked at CCK3 for Drupal 6? It's not stable yet, but the package does contain the Multigroup module which may be exactly what you need. A 'multi group' is a group of cck fields which can be repeated just like normal multi-value fields can. This means that you can group a node reference field with a text field and repeat that combination as many times as needed.

If you decide to give it a try, I recommend that you create a test site first to check if Multigroup and the rest of CCK3 is stable enough for your use case and to make sure that it doesn't interfere with other modules you need.


Use views template, In advanced section, there is an option for theming - Theme:Information. Choose template from there or simply use views-view-table--yourviewname.tpl.php.

debug your rows here and add css classes to customize the output as per you want.

Take below code as a reference.

<?php
/**
 * @file
 * Template to display a view as a table.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $header: An array of header labels keyed by field id.
 * - $caption: The caption for this table. May be empty.
 * - $header_classes: An array of header classes keyed by field id.
 * - $fields: An array of CSS IDs to use for each field id.
 * - $classes: A class or classes to apply to the table, based on settings.
 * - $row_classes: An array of classes to apply to each row, indexed by row
 *   number. This matches the index in $rows.
 * - $rows: An array of row items. Each row is an array of content.
 *   $rows are keyed by row number, fields within rows are keyed by field ID.
 * - $field_classes: An array of classes to apply to each field, indexed by
 *   field id, then row number. This matches the index in $rows.
 * @ingroup views_templates
 */
$i = 0;
$cnt = count($rows);
?>

<?php foreach ($rows as $row_count => $row): ?>

        <div class="member-wrapper" id="<?php print $row_count; ?>">
            <?php
            $url = $row['field_profile_image'];
            ?>

<?php endforeach; ?>


Create a new region within an existing one I want to create a new region within an existing region which is by default or is custom made. I have created a custom region called footer_top. I want to create a new region within this region, i.e, a nested region. What should i do...what code should i write in page.tpl.php and how?

Thanks

You can use the region.tpl.php

And add a template_preprocess_region to add the new region variable with in this region.

You can use the following code to add the region variable to the region.tpl.php

$variables['custom'] = block_get_blocks_by_region('custom');

So the over all process would be as follows.

first you would create a preprocess_region function as given below

function theme_name_preprocess_region(&$variables) {
  $variables['region_name'] = block_get_blocks_by_region('region_name');
}

next you would create a region template file called region--region_name.tpl.php

and print the variable $variables['region_name'];


How do I show the current node title in page.html.twig OR in node.html.twig? If I want to show the current node title in page.html.twig (by default it seems to only be available in node.html.twig) I have to create a preprocess function like so:

function theme_preprocess_page(&$variables, $hook) {
  // Set our page title so we can access it in page.html.twig
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['my_node_title'] = $node->title->value;
  }
}

And then I have to overwrite page-title.html.twig by copying it into my current theme folder and commenting out everything.

This doesn't seem "right".  Is there a better way?

The node is already available in the page template thanks to template_preprocess_page, so there's no need for the preprocess function. You can output the title with:

{{ node.label }}

The page title itself is a block, so if you don't need it any more just remove it from the region at /admin/structure/block. No need to copy the template to your theme or alter the original.


Inverse of Drupal contextual filters? Does anyone know how to / know if Drupal 7 Views 3 is capable of using the inverse of a contextual filter to display results?

Basically I want to display a result not involving the logged in user ID. I can get the view to display only the data associated with the user ID using the contextual filter. I just want the opposite of it. I have tried using the current user filter and checking no for the particular relationship but was unsuccessful. If anyone can point me in the right direction that would be greatly appreciated.

Unfortunately no.. This helped but this does not establish the relationship I need.
The data is in two tables. I basically need query like this:

(the first select grabbing all the nid's available)

SELECT DISTINCT n.nid
 FROM node n
  WHERE n.status = '1'
    AND n.type = 'job'
    AND n.nid not in

(the second select grabbing all the nid's that are associated to a specific uid)

(SELECT DISTINCT n2.nid
  FROM node n2
  LEFT JOIN applicationsTable ON n2.nid = applicationsTable.nid
   WHERE n2.status = '1'
    AND n2.type = 'job'
    AND n.nid= n2.nid
    AND applicationsTable.uid ='999');

Oddly enough my query doesn't work as a straight db call so feel free to correct me on that too :P

In settings of the User ID contextual filter, you can exclude this argument/contextual-filter. Expand the last field-set and you'll see it. isn't it what you need to do ?


Check access to existing plugin block I have a programmatical plugin block defined in theme region. I need to check access to this block in my module hook. The following code creates a new instance, but I need to load an existing plugin block from the theme with its custom visibility settings and find out if it is going to be displayed or not.

$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
$access_result = $plugin_block->access(\Drupal::currentUser());

Please advise.

Loading a block should be in theme context, because block visibility configured by theme, here is an example to how load system_breadcrumb_block block in your active theme.

   use Drupal\block\Entity\Block;
    // Get block ids.
        // This will return block ids by theme like the following
        /*  [
              "bartik_breadcrumbs" => "bartik_breadcrumbs"
              "seven_breadcrumbs" => "seven_breadcrumbs"
            ]
        */
        $ids = \Drupal::entityQuery('block')
          ->condition('plugin', 'system_breadcrumb_block')
          ->execute();
        // Get the active theme name.
        $active_theme_name = \Drupal::service('theme.manager')
          ->getActiveTheme()
          ->getName();
        $my_block_id = '';
        foreach ($ids as $id) {
          // Check the if the id start with theme name.
          if (strpos($id, $active_theme_name) === 0) {
            $my_block_id = $id;
          }
        }
        // Load Block.
        $block = Block::load($my_block_id);
        // Get the block visibility array
        // Something like
        //    [
        //      "user_role" => [
        //        "id"    => "user_role",
        //        "roles" => [
        //          "administrator" => "administrator",
        //        ],
        //      ],
        //    ]
        $visibility = $block->getVisibility();
        $currentUser = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        /**
         * TODO: Do your visibility check
         */
        // Example to check if the user has the access by role
        $has_access = FALSE;
        if ($visibility['user_role']['roles']){
          foreach ($visibility['user_role']['roles'] as $role => $name){
            if ($currentUser->hasRole($role)){
              $has_access = TRUE;
            }
          }
        }
        dpm($has_access);


admin menu item not displaying I am developing a module which has an admin menu entry in Drupal 7. The issue I am having is that the menu item is not showing up in the admin menu. I have looked at the docs and scoured google for why this might be happening but nothing I try seems to work.

Here is my hook_menu() implementation:

$items['admin/config/people/accomplishments'] = array(
  'title'            => 'Accomplishments',
  'description'      => 'Configure the accomplishments system.',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('accomplishments_admin_form'),
  'access arguments' => array('administer site configuration'),
  'file'             => 'accomplishments.admin.inc',
  'type'             => MENU_LOCAL_TASK,
);

I have tried flushing the cache and reinstalling the module but nothing works. I do notice that when I specifically go to the url admin/config/people/accomplishments I get a permission denied error - which doesn't make sense to me as I am logged in as user 1 and I have assigned access privileges to the administrator role.

The module I am developing is creating a new entity so I don't know if this might have a baring on this as I have never created an entity before, but I don't think it should.

Any ideas as to what I am overlooking or what the cause might be? I am going crazy here.

It seems that the path your using is "admin/config/people/accomplishments"
Make sure that the users that need to have access to this menu item have sufficient permissions in administering people or use another path

Last make sure you flushed the drupal caches so the changes are applied. Drupal only calculates the menu items once and then it caches them


How to build a dynamic hyperlink within a Page (Panels)? On a Drupal 7 Site with Panels and Tokens I have a content-type for Events. For the "Page" (Panels) of a Event I like to add a hyperlink / button to add the event to the personal Google Calendar. This requires to build a hyperlink with some query-parameters in it. Eg:

My approach is to create a custom block with "Full Html" and add the above snippet. Then add tokens like [node:title] that should get replaced with the node's title etc. Afterwards I add this block to the Events page (Panels). The problem is that the tokens don't get replaced.

Any idea how I can build this links the most easiest way?

Thanks for help,
Marc

Update:
Got one step forward: I don't use a block but a "Custom Content" pane from Panels. Within this replacement is supported. The problem I now have is that the date/time doesn't get formatted right. I use "date" field-type (Date module). Any idea how I can format that date correctly?

You would want to override the template for the content type you're using, in your theme. If you're using a base theme, copy the node template into your theme and then change it there (don't change the base theme directly). More info on phptemplate and theming is on Drupal.org.

If you don't code, doing this in a View would work. Here's what I would do:

Create a content type with plain text fields for all the things you need to make dynamic (if you haven't already done this)
Create a View that only displays one item at a time.
I'm not sure what your setup is exactly like, so it may take some creativity to filter it to display the right one. You might want to try something like References to relate an Event node to your particular node of your new content type, or configure some contextual filters to pick the right values based on the URL of the Event page, or something.
Have your View create a Block and have that Block display on Event nodes
Configure your View to rewrite output of a field and make all other fields excluded from display. Views seems to have the peculiarity of only allowing you to use tokens from fields that were added to the display before the field being rewritted so use the last one added.
????
PROFIT

But that's a ton of work. You're better off going with the phptemplate option.


How do I modify the teaser products display page in Kickstart Commerce? How do I modify the teaser products display page in Kickstart Commerce?

I would like to display smaller product teasers with a "four column" layout versus the default "three column" layout. Is this a task for "views"? Modifying some "css" file? Both?!

Any direction on this would be huge help.

Thank you!

Tom

You'll want to look into Display Suite. Its a great module which allows you to not only create new view modes, but use special layouts for each view mode and content type. If you also have the Omega theme installed, Display Suite will give you some fluid, responsive layouts to choose from as well.

To be clear, Display Suite will create a layout within your page layout. It is specific to the view mode and that content type. I say this because styling might get muddy if you use it too much or inappropriately. That said, it's a great tool :)


How to change the value of a field in its preprocess method? I am trying to figure out Drupal 8's $variables array ...
So I have a MYTHEME.theme file, complete with a working MYTHEME_preprocess_field() function. (I know it works because I use it for other fields that need customization.)
Right now I'm focusing on the title of an article displayed on the front page of my site. I can access it with the following code.
if ($variables['field_name'] == 'title') {
    $title = $variables['element'][0]['#context']['value'];
    // ...
}

What I want to do is replacing all instances of ® (the registration mark) with <sup>®</sup>. However, setting this value in the array to something else does not change it on the site.
Is there something I'm missing? A few sources I found said to alter (or add) the #markup element in the array, but there's a death of information about this online.
How do I change the value of a field? This seems like it should be something basic and easy to do.

In Drupal 8 front page is a view called frontpage if the view is not modified it should show: "Content" by default (instead of fields).  If so the following can be applied to change each node title

function THEMENAME_preprocess_node(&$variables) {
  //for views that show: "Content" (not fields)
  if($variables["is_front"]){
    $variables["label"][0]["#context"]["value"] .= " end of title";
  }
}


Why am I getting a "You are not authorized to access this page." on the Drupal Migrate UI page? I just installed this module on my Drupal 8 site hosted locally on Acquia Dev Desktop. I haven't had this issue with any other modules and this is occurring immediately after I install the module.

Are you logged in? Is your login the superuser? You can always get into your local site w/ drush:

$ cd /path/to/docroot
$ ../vendor/bin/drush uli --no-browser
http://default/user/reset/1/1527085618/[RANDOM_STRING]/login

Assuming your setup uses the drupal-project composer approach. Otherwise, you could use drush w/ a site alias or params.

If you're logged in as the superuser and still have issues, that's indicative of something wrong w/ the routing specification. That shouldn't happen with a contrib module, unless you've made any modifications? If you haven't and the superuser can't access the UI, then I would file an issue w/ the migrate module.


Theming a Field Collection Widget Is it possible to theme the Field Collection widget for just one field? The example I am looking for is a list of text fields. I need some of the text fields to be in two columns instead of one long column, which is the default. I also need to add some formatting guide text for some of the fields. I know I can achieve some of this through CSS, but was curious if there is a hook or something that I could implement that would allow me to change the markup as well? This is in Drupal 7 as well.

Thanks!

Yes it's possible.

You need to go to the Field Collection module directory and copy field-collection-item.tpl.php. Then paste it into your theme directory and rename it to field-collection-item--myfieldname.tpl.php.


How to split up the renderd page in a tpl file? In my D7 template I have a tpl file called:

html--events.tpl.php

  <html class="no-js" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<?php endif; ?>

  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body<?php print $attributes;?>>
  <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

I would like to add a page header image to this page by changing the template.

So therefore I would like to split the rendered content of this page for e.g. like this:

  <?php print $page_top; ?>
  <?php print $pageheader; ?>
  <?php print "
/div>" ?>
  <?php print $pagetitle; ?>
  <?php print $pagemaincontnet; ?>
  <?php print $page_bottom; ?>

However the var $page contains already all the rendered header. How can I split the rendered page into smaller blocks? I tried to replace:

<?php print $page; ?>

into

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

but then got a message : Only variables can be passed by reference

Any suggestion is very welcome.

$page is the rendered content from page.tpl.php - you can't alter it in the HTML template without resorting to nasty string manipulation.

Fortunately your desired output lends itself nicely to being handled in the page template anyway. You won't automatically have the same template name suggestions available, although a theme/module might already make them available in your installation. If not, you can add it yourself:

function MYTHEME_preprocess_page(&$vars) {
  // This condition may need to change depending on your exact needs
  if (arg(0) == 'events' && !arg(1)) {
    $vars['theme_hook_suggestions'][] = 'page__events';
  }
}

Then in page--events.tpl.php you'll have access to the individual elements of the $page array, and you can render them as needed.


Submit to external url via Ajax & get return I need a Drupal form to submit a file to an external server using ajax. I have done the form using Form API and I am able to submit it via Ajax, But the Drupal throbber never stops and I am not able to get the returned value. But in firebug I can see it to be returned.

My Code:

function upload_video_episode($form, &$form_state){

     $form['files'] = array(
        '#type' => 'file',
        '#title' => t('Video'),
        '#description' => t('Upload a file, allowed extensions: mov, mp4, avi, mkv'),
      );

     $form['submit'] = array(
           '#type' => 'submit',
           '#value' => t('Submit'),
           '#ajax' => array(
           'path' => url('http://web.com/test.php', array('external' => true)),
           'callback' => 'upload_video_test',
           ),
      );

    $form['#action'] = url('http://198.199.95.235:8080/dev/test.php', array('external' => true));
    return $form;
}

function upload_video_test(){
    return "Done!";
}

The throbber just keep rotating non-stop.

However, in firebug I can see the form have been submitted and values returned.

Console seems to be showing some error, possibly related to Non-Origin. But in my case the data is already submitted.

Error: Permission denied to access property 'document'

Is what I have done so far correct?
I want to get the returned value and store it in a hidden form field or something.
Or is Drupal Form API not capable of handling external urls?

Any help would be highly appreciated.

Sounds like it's spinning forever because of the js error.

Where is the error occurring? In jQuery library?

If so use an uncompressed version of jQuery and it may be easier to debug.

Maybe even temporarily hack jQuery core to remove error and see if that fixed your problem before spending time figuring out how to fix it properly...


Creating date field with only month and year We are using the Form API in a custom module (and not an entity field), how can we easily set the date widget for just year and month data entry?
I've tried adding a #date_format attribute but no change:
$form['date_needed'] = array(
  '#type' => 'date',
  '#title' => $this->t('Date Needed'),
  '#date_date_format' => 'Y/m',
);

I have also tried  '#date_date_format' => 'd/m/Y' but the date widget still appears asking for YYYY-mm-dd.
Looking at the source code for core/Render/Element/Date.php and stepping though the code, I can see it's picking up this setting.
The drupal.org doc page has a comment that indicate this should work: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Date.php/class/Date/8.2.x
Any ideas?

We can make this in a hook_form_alter.
$form['DATE_FIELD_MACHINE_NAME']['widget'][0]['value']['#date_date_element'] = 'month';
$form['DATE_FIELD_MACHINE_NAME']['widget'][0]['value']['#date_date_format'] = 'Y-m';

However, there is still a problem of this way:  instead of first day of the month, current day will be saved. I cannot figure out how to solve.


Updating core modules independently of core? We have a vendor that is asking us to assist them in updating a core module independently of core.  Is there such a thing?  For example, could you update Views without updating core?  My understanding is that's not doable.

For example, could you update Views without updating core?

First of all, you should check if you could get away with implementing those changes via a hook, event subscriber, or altering/overriding a service.

If not, download Lastest_Drupal_8.zip and unzip only /core/modules/views folder onto your projects /core/modules/views folder.

If you like, you could create a patch for that particular core module using git diff between latest and current version.

Although, I wouldn't recommend to do this to begin with, this is bad practice!, but if there is a really, really, and I mean, really good reason sure.

Caveats:

You'll have to test the core module to make sure all is good.
You won't be able to use composer update unless you find a way to make it run the patch.


How to Update Commerce Product Programatically $product_load = commerce_product_load(456);

 $product_load->uid = $GLOBALS['user']->uid;

 $product_load->example[LANGUAGE_NONE][0]['tid'] = 123;

 commerce_product_save($product_load);

As I am doing this it is not updating commerce product and takes lot of time to load the page.

You may have better luck using entity metadata wrappers' ->set() and ->save() functions.


Drupal 7, form api - file field default_value I've created a formular where the user can upload an image using a file field. In another formular the user is able to change the image he previous uploaded.

So far I was able that the user can upload a new picture or let the field empty and the existing image remains. My question is, how do I show the user in a nice way which file he previously uploaded with the field? Setting a #default_value (@code below) does nothing for me.

//$smallimage = fid of image
$form['smallimage'] = array(
  '#type' => 'file',
  '#title' => t('Image'),
  '#default_value' => $smallimage,
  '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
);

Has anyone a solution/workaround without switching to managed_file?

Thank you in advance

Edit:

As seen in the answers there is no direct solution for the problem. So I've changed the type back to managed_file and gave user1 and node1 the responsibility of being the reference of my files. I'm not happy with that but it works.

No, there's no way to do this. The restriction is with HTML, not Drupal. A file input simply doesn't have the capacity for a default value to be set; allowing such behaviour would introduce a security hole (imagine you pre-filled it with /~/.ssh/id_rsa, auto-submitted the form, and the user didn't have permissions set up correctly). See this post.

If you check the FAPI guide you'll see there's no #default_value available for a file field type.

You'll need to switch to a managed_file element if you need a default value for the field.


How to allow each company section to manage their own content on the Intranet? I have a simple problem of permissions. I work in a company which is divided into different sections. I have to make a Drupal intranet for them.

Each section must be able to manage their own content on the Intranet. The contents of the intranet are always the same, ie the same "content type" with the same "fields". It is necessary that a section could only edit the contents within its section. Thus, "computer" could only create / edit / delete content of "computer". The section of "press" could only create / edit / delete content of "press". All sections can view all content.

I tried different modules. "Field permissions", which lets you field level permissions, is interesting but does not help in this case. "Content Access" allows me to level management content type, but I can do what necesito.Con "Taxanomy Access Control" can define visibility rules, editing and deletion according to the presence or absence of one or more terms a taxonomy. It could be interesting, was not that "computer" should not be able to create content "press", for example.

You could create a content type for each section equal, and each give the required roles. The problem is that they are over 15 and does not seem the most optimal way to do this, because if I have to add a field so I have to do in the 15 (DRY).

I sense that Drupal has a more efficient way of doing this, but as I am new to this CMS I can not find it.

The thing you are looking for is Organic groups. It does exactly what you need.
Further more you may be interested in some solutions already made on drupal. Like Open Atrium or Drupal Commons

Hope it helps.


Drupal Commerce: Calculating a shipping rate: Custom Shipping Price I have a variety of products that have different fixed shipping prices. Each product has a custom field associated with it that contains a decimal price for shipping. Using Flat Rate Shipping, on the event "Calculating a shipping rate", how may I go about bringing in the custom field (scoping) to calculate that shipping price?

It's probably easier to have multiple flat rates, and a conditional rule that the product for that price is in the cart.

Notes:

There's a commerce shipping rules module that has a "cart contains item" condition.
If you could get at the logic behind the prices you could deal with this more easily, like weight based or size based shipping. For hundreds of products it's unreasonable that there's no logic behind it outside of what they want to charge for shipping. What I could think of is a custom module using hook_commerce shipping method alter where the shipping method matched the shipping price in the field. I've written a small module that alters the shipping weight, but that again assumes logic the weight based shipping.


Add "timestamp" type for MySQL I used Drupal 7 and the Data module to import a table into Drupal. I could import the orphaned table, but my table has a column of type "timestamp" which does not show up when I try to edit the schema of the data table. I get the following error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'published': ALTER TABLE {resource_profiles} CHANGE published published INT NOT NULL DEFAULT 'CURRENT_TIMESTAMP'; Array ( ) in db_change_field() (line 2988 of C:\xampp\htdocs\drupal\includes\database\database.inc).

I followed http://drupal.org/node/1466122, and added the timestamp datatype to /includes/database/mysql/schema.inc.

Where can I edit the schema information for my data table?

Like Gian says, you can't have a default value of CURRENT_TIMESTAMP for an int field.

Due to Drupal's database abstraction layer timestamp is not a supported field type.

This is due to not all databases supporting timestamp or now() as a field default value as apposed to mySQL where it is supported. The solution / work around if you're using mySQL is to add a query to your .install that modifies the field default to now() where the field type is int. See the Data Type doc page for further discussion: http://drupal.org/node/159605 or see here for more info on Drupals DB Schema: https://api.drupal.org/comment/48593


How to make nested Quick tab in a view? I am using Quick Tabs for displaying the image gallery.

In views the FORMAT is Quicktab and the fields are Year ,Month ,Title and Images .

I have a gallery based on Year and month.I need to display the gallery based on year(main tab) under the year tab the month tab should be displayed.

e.g :
here under the year i need to display the months entered in the content type.Now in view's Quicktab format option i gave Grouping field Nr.1 as Year.When i tried the Grouping field Nr.2 to Month,the tab is not showing anything or the combination not working.

How can i show the nested tab in Quicktab or can you suggest any alternative ways?

Try this:
 - create the view for the month (with the pictures) [field collection module can help you here]
 - Then you create the view for year and call the MonthView inside

(i know this is not the most advanced response you could get, but my knowledge is basic as i been using drupal since last month)

i hope this can help you.


Search a content type fields based on user inputs I am using Drupal 7.
I need to create a search condition to generate a search result.I have a content type called "properties".It contains around 20 fields like Location,City,Availability,Property type,Category,Price,Nearby Landmarks,amenities etc...

I have a search form to search properties based on
PropertyCategory
PropertyType
City
Location
Price
Furnish  etc...

But drupal generates separate tables for each field type.How can i retrieve data from all table based on any search condition?I have created a view based on this content type "properties".

Do we have any option to generate a single table for a content type?
Could you please give me an idea.
Please help me ,i am stuck on the way and can't move without any help.

Thanks in advance!

harikris.

If you want result from a specific content type then user views with expose filter for search and filter it with the specific content type.
Why do you need single table for all the fields, Either you can use join to fetch data from all the table. You should not write custom code for this kind of functionality best option is to alter the search query or user views with expose filter to provide this functionality.


How to allow users upload images to existing nodes? Let’s say I have created a content type called movies and I want all nodes in movies to have a gallery tab. Inside the gallery tab it should allow users to upload images. How can I do this?

The best / simpler way would be to create a second content type called 'image', and give user the permission to create nodes of type 'image'. You can add a CCK imagefield to provide an image upload field.

Then you will want to be able to store relationships between your movie node and the related images nodes. You can add a node reference field on the image content type. You can populate this field by default with the movie reference. So any image added in the website will be related to a movie.

You can then create a view that will list the images related to your movie ID.


Unable calculate date field using strtotime From this answer, the result will be in text field field_cubagan.

Actually I want the result in another date field, but I choose text field instead as testing purposes because text field accept wide variety of result.

In below codes, the result will be 2012-06-30 10:05:00:

// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);
$integer_items = field_get_items('node', $node, 'field_subscription_period');
$integer_item = array_shift($integer_items);

// Get the field value
$start_rent = $date_item['value'];
$period = $integer_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = $start_rent;

// Save the node
node_save($node);

But under Update the other field, instead of get unmodified result from $start_rent, I want the result become: "Datetime" + "x years" which "Datetime" is from field_date_start_rent while the "x" of the years is taken from field_subscription_period

I'm not sure if strtotime only works on unix timestamp or only on Y-m-d h:i:s format or works on both.

both below codes giving same result 2012-06-30 10:05:00 because in second codes, it converted to unix timestamp, and then converted back to the time format:

$node->field_cubagan[$node->language][0]['value'] = $start_rent;
$node->field_cubagan[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime($start_rent));

below codes will result in unix timestamp 1341050700:

$node->field_cubagan[$node->language][0]['value'] = strtotime($start_rent);

But strange thing is, I always failed when trying to calculate.

In below 3 codes is example where I always get warning and not works (I'm using +1 year as testing purposes):

$node->field_cubagan[$node->language][0]['value'] = strtotime('+1 year',$start_rent);
$node->field_cubagan[$node->language][0]['value'] = strtotime('+1 year',date('Y-m-d h:i:s', strtotime($start_rent)));
$node->field_cubagan[$node->language][0]['value'] = strtotime('+1 year',"date('Y-m-d h:i:s', strtotime($start_rent))");

What actually I've missed and what is the right codes?

I got it. It should be:

// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);
$integer_items = field_get_items('node', $node, 'field_subscription_period');
$integer_item = array_shift($integer_items);

// Get the field value
$start_rent = $date_item['value'];
$period = $integer_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime("+$period year",strtotime($start_rent)));

// Save the node
node_save($node);


Why does Panels output  for some panes and  for others? I'm just wondering what causes Panels Pages (or cTools pages? Never figured out which is which) to output some panel panes in a <section> html tag wrapper, and output the other panel panes in a <div> html tag wrapper?

I would prefer it if they were one or the other, but not both. So I wanted to understand and find out the reason so I could potentially make it consistent.

Theme I use: AdaptiveTheme (Custom Sub-theme with minimal configurations and changes)

Panels "Variant" Layout: AT One Column (Responsive single column panel layout, AdaptiveTheme core)

To the best of my knowledge, Panels contains no instances of <section>. This comes entirely from your theme.

Specifically, I believe it's from at_core/templates/panels-pane.tpl.php which contains the following:

 * Adaptivetheme variables:
 * - $is_mobile: Bool, requires the Browscap module to return TRUE for mobile
 *   devices. Use to test for a mobile context.
 * - $tag: top level wrapper element, section or div.

followed by

 <<?php print $tag . $attributes . $id; ?>>

The relevant logic appears to be

/**
 * Preprocess variables for panels_pane.tpl.php
 */
function adaptivetheme_preprocess_panels_pane(&$vars) {
  // Top level wrapper
  $vars['tag'] = $vars['title'] ? 'section' : 'div';


How can I access language currently viewed in Views Customfield: PHP Code? I'm looking for a way to display some text in a view—information about who posted an article, and a link to read more—in a specific language based on which language for the site the user has selected.

I thought I'd do this with a "Customfield: PHP Code" to make an if statement echoing a string depending on the language.

How do I access this variable, or how do I solve the problem in another way?

The standard way to display text strings in Drupal is using the t() function. You should enter your text in English and it will be translated to the corresponding string in the current user's language.

If you still want to know the current user's language, you can load the user like this:

$user = user_load(uid);

and the language will be available on

$user->language


Getting fields' Attributes in node template I'm trying to rendering node's fields directly inside a node template.

This is my node template file node--homepage.twig.html:

<div{{ attributes }}>

  {{ title_prefix }} {{ title_suffix }}

  <div{{ content_attributes }}>

    <!-- Render field_1 value here -->
    <div{# field_1's HTML attributes here #}>
      {{ node.field_1.value }}
    </div>

    <!-- Render field_2 value here -->
    <div{# field_2's HTML attributes here #}>
      {{ node.field_2.value }}
    </div>

  </div>

</div>

Is it possible to get HTML attributes for each field inside the node template?

The field values in node are the raw data from the database. You should not use them for output. They are great for coding of conditions in twig.

For output use:

{{ content.field_1 }}
{{ content.field_2 }}

These statements will output the fields using the field formatter as configured in the ui.

Edit: Adding attributes

If you need additional attributes add them in the field twig. The methods described in the link you provided in the question are only possible in the same twig your element comes from. If you want to modify the attributes of the node it is the best to do it in the node template. If you want to add attributes to the field use the field template.


D7: file_create_url() usable in node.tpl.php? Can you use file_create_url() inside node.tpl.php? Should I assume you can only use it in the template.php?

$img_src = render($content['field_image']);
$bgimage = file_create_url($img_src);

Using the following code, I am only getting public://science-of-rock_background.png from $img_src.
Is there any reason why it would be blank?

print $img_src;
print $bgimage;

Edit made to avoid confusion:

In my tpl page for this field I am generating the uri.

field--field_image.tpl.php

<?php foreach ($items as $delta => $item) : ?>
  <?php
  print $item['#item']['uri'];
  ?>
<?php endforeach; ?>

file_create_url takes a uri, such as public://science-of-rock_background.png

The revised:

$img_src = $content['field_image'];
$bgimage = file_create_url($img_src);

Would work if your field is only returning the URI.

And, for best practices, should set that up in preprocess_node, otherwise will work in node.tpl.php


How to find out the combinations of Views arguments that have the most Views result I have a node view with 2 arguments in URL my-view/%1/%2.

Both arguments %1 and %2 are Taxonomy Term ID.

I would like to make a page that lists the number of the View result per argument combination and order them by the number of the result.

For example, Something looking like this:

  %1 |  %2  | Resulst
  10 |  20  | 13
  10 |  21  | 7
  13 |  21  | 5

Is there anyway to make this kind of page?

My goal is to find out what the top 20 combinations of the 2 arguments that have the most nodes attached to.

Inside Drupal, this would take some real custom magic. But, let's say for example, you wanted to show

pets/birds,

pets/cats

both birds and cats would be arguments off the main Views page of pets. BUT - if you had a Google Analytics account, which does not understand Drupal arguments, you could easily decipher which page received what number of visitors.

Because Google will never discriminate vs what is a page and what is an argument, you can easily see what would be most popular as a result.


Custom content type which is a check list I am trying to build a new project in which i as admin can easily add or edit a checklist which is used for tracking a days job which i want any registered user to fill out . This is possible either by creating a custom module or using an existing one . I have used Checklist module and Matrix Module . But was not able to achieve my goals. I would like your help to guide in any any direction that you think it is possible and the i will peruse it . If i am not able to achieve my goal i will get back to you asap .

Looks like you are looking for Checklist module:

  Allow administrators on sites to create checklists that must be completed by users of the site.


Creating a view with 2 content of different content types I currently have 2 different content types which are very different from each other. I have also created multiple content using these content types.

I want to create a view which shows only 2 specific contents one below the other. Is this possible? Currently I can only have a view which filters on the two content types but that results in all of the different instances of the content types coming onto the page and not just the ones I want.

The content that I want to show in the view have no relationship with each other, I just want to be able to filter them in using their names.

"2 specific contents" .. if it's very specific / admin decides, add an extra field with code. Fill 2 nodes with something like 'promo' or '1234 Hide this field in the display, so you only see the code when you're editing. In the view, filter on this field (only nodes with this and this code) and voilá.

-edit: in this way you can re-use the view for different codes. Maybe use the URL (like foobar.com/promo shows the 2 nodes with promo in the code field). Tbh, i don't know how to use the URL in Views ;-)


Where to modify the logic that calculates the height of a collapsible fieldset? I'm not sure if this is a theme issue, but I continually get my collapsible fieldsets being 1-2 scanlines too short, causing scroll bars to appear.

This project has heavy use of FAPI, sometimes with collapsible fieldsets inside other collapsible fieldsets, and the vertical scroll bars are eating too much page real estate.

I'm using an unmodified version of Fusion Starter theme, if that helps. And, I'm not a themer, but can usually get by.

I would be perfectly happy modifying the PHP or JavaScript code doing this calculation, if I just knew where it is.

Are you sure it can't be solved by CSS? Try adding some padding.


Feeds Import csv - inline images I'm using the feeds module to import thousands of nodes into my Drupal 6 site (the source is a Drupal 5 site) and after figuring a few things out, it actually works really nicely! I just have one problem though, most of these nodes are supposed to contain inline images, and I'm wondering how to recover them as they don't come with the import...?

Thanks!

If the enable full html does not work try using Feeds Image Grabber


Horrific errors and WSOD I was installing the panels module when all of a sudden my site went to white screen of death with a whole bunch of error messages. (Check this out here: http://graphbyte.co/fuck.png ).

Right before I tried to install panels I had abandoned the process of creating a custom page. I realized I hadn't enabled the panels module, which I needed for this custom page, so I jumped into the modules page and attempted to install it.

I tried deactivating the panel module directly from the database but that had no impact on the situation.

What can I do??? Please helllllp!!

Thanks,

G

OK I found out that that error in particular is due to not having a large enough allowed packet size in your mysql configuration. Here is a bit more info on that:

http://is.gd/pV7c2M

If you're running LAMP, here is how you can create a configuration file and increase your max packet size limit:

http://is.gd/mI3B82


How to correctly check the value of boolean in D7? I have a boolean single check-box field. and inside my node--content-type.tpl.php Idothe following check:

  <?php if($content['field_hide_1st_line_of_the_addre']['und'][0]['value'] == 0): { ?>
    <?php print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', '); ?>
    <?php } else: { ?>
    <?php print t(''); ?>
    <?php } endif; ?>

And it returns loads of "Notice: Undefined index: und in include() (line 80 of node--content-type.tpl.php"

Any idea what is going on?

UPDATE

  <?php if (isset($content['field_hide_1st_line_of_the_addre']['und'][0]['value'])): { ?>
    <?php print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', '); ?>
    <?php } else: { ?>
    <?php print t(''); ?>
    <?php } endif; ?>

is not the doing the check correctly: the Street field disappears forallteasers,while it should only disappear for those that have the boolean check-box ticked.

UPDATE 2
This code didn't work either. Pave me a Parse error: syntax error, unexpected $end

<?php
  if (isset($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'])) :
  if($content['field_hide_1st_line_of_the_addre']['und'][0]['value'] == 0): { ;
    print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
  }  endif;
?>

UPDATE 3

I deleted that old field and created a new identical one.  Tried many things,but it turns out that for some unknown reason it just didn't like the 0 and preferred 1 instead.So I used 1,and just changed the wording of the field from "Hide full address" to "Display full address".  This is the code that worked for me.  If you seeany syntax mistakes,pleaselet me know.

<?php
    if (isset($content['field_hide_address']['#items'][0]['value'])) :
    if($content['field_hide_address']['#items']['0']['value'] == '1'):
    print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
    endif;
     endif; ?>

The error you're getting simply means that

$content['field_hide_1st_line_of_the_addre']['und']

hasn't been set. It might be that the 'und' key is missing, or it might be that $content['field_hide_1st_line_of_the_addre'] simply hasn't been set at all. This can happen if you've added a new field to a content type that already has existing nodes (and probably in other situations too).

To remove the notice, you can just wrap your code in another condition that ensures the array element you're accessing exists. For example:

<?php
  if (isset($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'])) :
    if ($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'] == 0) :
      print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
    endif;
  endif;
?>

I've taken the liberty of replacing 'und' with the constant equivalent (and cleared up a couple of other very minor issues), it's better practice. Even better practice would be to extract this logic out of the template file completely, and instead implement it in a preprocess function.


How to give an 'editor' role rebuild/clear cache permission? I'm setting up an "editor" role for a D8 site. I noticed there's no "Flush all caches" in the Tools menu. I don't see any permission setting related to caches. How to enable cache clearing/cache rebuilding for non-admins?

To access this, they would need the administer site configuration permission.

From system.routing.yml:

system.performance_settings:
  path: '/admin/config/development/performance'
  defaults:
    _form: 'Drupal\system\Form\PerformanceForm'
    _title: 'Performance'
  requirements:
    _permission: 'administer site configuration'


Set author to the node automatically whenever the new user registered and also automatically authenticate the user I have a Drupal site with content type people. In that content type I have a field that contains an email id.

What I want to do is, whenever the new user is registered, I want to compare the user's email with the email field of all the nodes with people as the content type. If these 2 fields match, then set the user as the author of that node.

I don't know how to execute this process.

Can anyone give me a solution?

Create a custom module and  Use below logic hope it will work.

function hook_user_insert(&$edit, $account, $category) {
  $email = $account->email;
  $uid = $account->uid;

  $query = db_select('field_email', 'e');
  $query->addField('e', 'entity_id');
  $query->condition('e.field_email_data', $email, '=');
  $nids = $query->execute();

  foreach($nids as $nid){

    //Update node user
    $node = node_load($nid); // ...where $nid is the node id
    $node->uid    = $uid;
    node_save($node);

   //Add role to user
   $role_name = 'member';
   if ($role = user_role_load_by_name($role_name)) {
     user_multiple_role_edit(array($uid), 'add_role', $role->rid);
   }

  }

}


Passing values in view block to contextual filter on Panelized Node I have a view set up with a contextual filter for year (select list field).  I want to have the ability to have one view and pass the year to the view.

Now I have panelized nodes that I add the views to and I want to pass different years to each view.   In Drupal 7 I used to be able to do this with View Panes.  Is this not possible in Drupal 8?

There is a patch that may add this functonality: How to manually pass an argument to a views block through interface.


How to add custom functionality on per-date base to nodes that use date fields for an event ticket system? For an event ticket system I have created a node type with multiple date fields including start- and end-dates.

-EVENT1-
Date A
Date B - Date F
Date G

- Event2 -
Date B
Date C
Date E - Date G

Now I need to add a boolean field to every date that is inserted into an event node to possible mark it as 'sold out event day'. How is this possible when I want to use the start-/end-date option? I don't want to create a nodetype 'date' and then reference its nodes to an event-node...
Thnx!

In the database (the appropriate table for your date field), you have a column called 'delta' wihch start from 0

In your example
Date A (delta = 0)
Date B - Date F (delta = 1)
Date G (delta = 2)

Your probably can add an hidden (for non-admin user) field in your node type (for example an textfield serialized array) to store the boolean value for each delta. This can be done programmaticly with rule an php algorithm on each node_save. In view you can also get the delta value


Is there a Drupal rating module that lets you rate from 1 - 10? I'm looking for a Drupal module that will let me rate something on a scale of 1 - 10.

It doesn't look like the Fivestar or Rate module would allow that.

Any suggestions?

The VotingAPI module (D6 and D7) offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

Create/Retrieve/Update/Delete operations for voting data.
Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
Via its integration with the Actions module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
It integrates with the Views module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

Rating related modules with a stable release for D7:

Rate (D6 and D7).
Fivestar (D6 and D7).
Voting API Bayesian (D7).
Star Rating (D7, no VotingAPI dependency).
Raty (D7-beta2).

Other rating related modules:

Plus 1 (D6 and D7-alfa2).
Vote Up/Down (D6 and D7-alfa1).
NodeReview (D6-beta1 and D7-dev).
Voting Rules (D6-beta2 and D7-alfa1).
Drupalit (D6).
Decisions (D6, unsupported).

Rating related modules with maintenance/development status 'unknown':

Extra Voting Forms.
UpDown.
Drigg.
Node Moderation.
SimpleVote.
MediumVote.
User Review.
Latest and Greatest.
jRating.
Loves and Hates.


Can i attach a views grid of images in a carousel Hi i'm new to Drupal and this maybe kinda of advance, but how can i achieve a Drupal views of images grid format displayed in a carousel as shown in the image above

Views Slideshow
You could use the Views Slideshow module for this. Here is a quote from its project page:

... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
Potential uses:

News item slideshow (such as the title, image and teaser of the last 5 news articles submitted).
The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
Rotate any image, based on any filters you can apply in views.
Hottest new products for any ecommerce drupal site.
Rotate contact links, share links, etc.
You could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.
It's also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.

The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.

Further enhancements
Possibly you may want to further extended this with related modules  (there are dozens of modules to further enhance views) such as Views Slideshow: Galleria. Here is a quote from that module's project page:

Integrating Galleria with Views Slideshow.
Galleria is a JavaScript image gallery framework built on top of the jQuery library. The aim is to simplify the process of creating professional image galleries for the web and mobile devices.

jCarousel
Another option is to consider the jCarousel module. Here is a quote from its project page:

... This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
Features:

Built-in Views support.
AJAX-loading of additional items as needed.
Carousel pager/navigation to jump between multiple pages.
Circular wrapping of items.
API for direct usage of jCarousel without Views.


How can I give paid access to content? I am looking to manage user access to website content using Rules and the suggested access control module i.e. ACL, TAC etc.

There 3 levels of access to manage:

Unregistered - No access to any Course Content
Registered - Access to certain Preview nodes (see Preview Module below)
Paid - Access to the content to which they have paid (as well as Preview nodes)

Unregistered

Unregistered users will have no access to any Course Content nodes
However there may be pages on the site (Cookie, Terms etc.) which anonymous will need access to to keep the site functioning during registration/payment etc.

Registered Users / Preview Module

For each Course, 1 or more Modules (taxonomy term) will be marked as a Preview Module
Preview Modules are identified by the term with a boolean check box: field_module_preview
This should allow access to Registered uses to access the nodes within this Module.

Content types:
Course – setup as a product
Content

Taxonomy:
Topic
Module

Example:

> Course
> - Module
> - - Topic
> - - - Course Content NO Access
> - Module (Preview checked)
> - - Topic
> - - - Course Content: Access
> - - - Course Content: Access
> - - Topic
> - - - Course Content: Access
> - - - Course Content: Access
> - Module
> - - Topic
> - - - Course Content NO Access

Paid Access

Payment processing will be carried out using Drupal Commerce and PayPal. The setup of this is not required. Drupal install will be supplied with Commerce and product types setup.
Once a course is paid, then access is granted to the entire Course and all its nodes

I have tried to integrate rules but no hope to make it working.

Can anyone help me to apply this scenario in my drupal 7?

Thank you in advance.

You should be able to get this to work using the Rules module, using a variation of the rule shown/explained in the answer to "How to make the permissions of a module more granular?". I.e in your case:

you can use the same Rules Event (Drupal is initializing), which to my knowledge is the only Rules Event you can use for this (for any other Rules Event you're just "too late", i.e. the content is already being displayed).
you can perform similar Rules Actions (to perform an appropriate redirect and display a message that fits your needs).
you should use one or more of these Rules Conditions (combined with "OR", not with "AND"!):

check if the current user's role is "anonymous".
related to your field field_module_preview.


add billing information in Drupal Commerce Programatically I am developing api access point for drupal commerce, from that access point user can upload his/her billing information during checkout process. Here is my code, but it can not add user full name in billing information. Any suggestion is greatly appreciated.

Thanks

  function commerce_services_bill_ship_create($data, $flatten_fields) {
    $status; $message;
    $orderId; $uid;

    $orderId =$data["orderId"];
    $uid = $data["uid"];
    $fullname = $data['fullname'];

    $order = commerce_cart_order_load($uid);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->commerce_customer_billing->commerce_customer_address->name_line = $fullname;
    $order_wrapper->commerce_customer_billing->commerce_customer_address->thoroughfare = "No.1, ABC street";

    $order_wrapper->commerce_customer_billing->commerce_customer_address->locality = "New York";
     try{
        // Save the order.
        commerce_order_save ($order);
        $status = 1;
        $message = "order update successfully.";
    }catch(Exception $ex){
        $status = 0;
        $message = "order can't update successfully.";
    }
    $reply= (array('status' => $status,'message' => $message));

    return $reply;
 }

To add billing information in checkout process first we have to create a profile object and assign it to the order. This code works for me

For adding new profile for billing information

function commerce_services_bill_ship_create($data, $flatten_fields) {
$status; $message;
$orderId; $uid;

$orderId =$data["orderId"];
$fullname = $data['fullname'];
$city = $data["city"];
$address = $data["address"];

//load order that you want to add billing information
$order = commerce_cart_order_load($uid);

// We'll assume that the current user will be the customer of our order
global $user;

$profile = commerce_customer_profile_new('billing', $user->uid);
$profile->commerce_customer_address = array(LANGUAGE_NONE => array(0 => addressfield_default_values()));

//for updating existing profile, uncomment the line below and comment commerce_customer_profile_new()
//$profile = commerce_customer_profile_load($profile_id); //

//add fullname
$profile -> commerce_customer_address['und'][0]['name_line'] = $fullname;

//add address
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;

//add city
$profile->commerce_customer_address['und'][0]['locality'] = $city;

// You sould pass the entire $profile object as parameter.
commerce_customer_profile_save($profile);

//assign profile_id to the order
$order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile->profile_id;

try{
    // Now you can save the order.
    commerce_order_save($order);
    $status = 1;
    $message = "order update successfully.";
}catch(Exception $ex){
    $status = 0;
    $message = "order can't update successfully.";
}

$reply= (array('status' => $status,'message' => $message));

return $reply;
}

Reference site - Programatically Create Order with Customer Profile
, Creating Customer Profiles Programmatically


How to alter inline entity form fields on node edit drupal I want to hide some fields of product reference on node edit. My purpose is to unset or set access to false for colors or price field of line item included in node as inline entity from in a content type. I am using hook as

$form_state){
dsm($entity_form);
unset($entity_form['field_product_colors']); // remove "colors" field from inline entity form
 }

but hook is not called at this screen when user edit a product on node edit i have shared a node edit screen where product is edited by click on edit link and then update some thing but dont want colors and price to be shown there

Actually documentation of module in readme file the hook was written and i was using that hook but only problem was the custom module name. if your custom module name is two parts like custom_websitename then this hook did not work in my case, so after one day i changed module name to single word and hook worked.. I am sharing code incase someone need to update lineitemform in node edit for drupal commerce.

function customruba_inline_entity_form_entity_form_alter(&$entity_form,   $form_state){
$entity_form['commerce_price']['#access']=false;
$entity_form['field_commerce_saleprice_on_sale']['#access']=false;
$entity_form['field_commerce_saleprice']['#access']=false;
$entity_form['status']['#access']=false;
}

this worked for me to hide some information on inline entity form


Webform Localization does not work I have downloaded the Webform Localization module from Drupal.org, but it is not working to translate form, and I want to keep a single webform across all nodes.

How can I do that?

If you create webform first and then install webform localization module , the module will see only new components in webform , so try to open each component and save it then go to Regional and language > translate interface > strings , check "webform localization" and "fields" then "Refresh strings" , then back to translate interface > translate , search for your components labels and translate them


How to translate the Home link when using Path Breadcrumb? I am  using the i18n module in my site. When using the Path Breadcrumb module, I can manage the Home link text in Path Breadcrumbs settings, via admin/structure/path-breadcrumbs/settings

But there is nothing related to this within the page "Translate interface". Therefor it allways shows in the same language for all of my site languages.

How can I also translate this Home link?

Make sure you have the Variable module installed/enabled. If you also have the
Path Breadcrumbs module enabled (as seems the case in this question), then there will be an extra tab within admin/config/regional/i18n/variable of your site (tab title = Path Breadcrumbs).

Within that tab, there are over a dozens of options available for marking them as milti lingual variables. The "Home link Title" is one of them, and probably the one you need to enable here.


Implement i18n menu's programmatically I am programmatically creating primary menu's which has the node content as links . So as soon as the node content is created, a primary menu link to that node content is created.

So while creating menu's ,I am also setting the languages of menu to which it belongs. So lets say if the node content created is in french, then a primary menu link is created with the language set to french.

The problem is despite the menu item's language is set, Still it gets displayed in all the other two languages as-well (English, German). I have installed Menu translation module as well but still its not working.

So how to implement multilingual menu's programmatically?

Tks
Vil

Ensure the i18n_menu module is enabled and the menu to which you're adding links is configured to "Translate and Localize" on the Menu edit page:

For example, the setting for the main menu would be found at the following url:

/admin/structure/menu/manage/main-menu/edit

The configuration option looks like this:


Can I create non-default EntityReferenceSelection? I have the following EntityReferenceSelection plugin:
/**
 * Provides an entity reference selection for my_entity.
 *
 * @EntityReferenceSelection(
 *   id = "extra:my_entity",
 *   label = "...",
 *   entity_types = {
 *     "my_entity"
 *   },
 *   group = "extra",
 *   weight = 1
 * )
 */
class MyEntityExtraSelection extends DefaultSelection {

  protected function getAllowedIds() {
    return [...];
  }

  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    $query->condition('id', $this->getAllowedIds(), 'IN');
    return $query;
  }

  public function validateReferenceableNewEntities(array $entities) {
    $entities = parent::validateReferenceableNewEntities($entities);
    $allowed = $this->getAllowedIds();
    return array_filter($entities, function ($entity) {
      return in_array($entity->id(), $allowed);
    });
  }

}

I'd like to call it extra:my_entity because I don't want this filtering to occur by default, every time I use it, only when I refer to it using the 'handler' => 'extra' setting explicitely.
But the core plugin manager gives these errors:
Warning: uasort() expects parameter 1 to be array, null given in Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager->getPluginId() (line 65 of core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php).
Warning: end() expects parameter 1 to be array, null given in Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager->getPluginId() (line 66 of core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php).
Warning: key() expects parameter 1 to be array, null given in Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager->getPluginId() (line 67 of core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php).

Finally, after some investigation, two required items never documented:

unlike the core EntityReferenceSelection plugins that, for some reason, get away without it, you have to provide

deriver = "Drupal\Core\Entity\Plugin\Derivative\DefaultSelectionDeriver"

in the plugin annotation.

It might be completely unnecessary in your case but you have to make sure your custom entity type has an entity_key named label. If it doesn't, core will use PhpSelector instead of your selector, forcedly.


drupal_set_message doesn't display message sometimes I'm uploading a file, to process and display a message at the end. However, the messages that drupal_set_message is set to display are displayed sometimes and don't display sometimes, even, if the processing runs successfully in the background. The reload time restriction isn't a problem as it is set to multiple minutes and the processing hardly takes 10-60 seconds on average. Is there a way to force the page to show the messages at any cost? The drupal_set_messages that I am concerned about are the last two drupal_set_messages in the code. I've even tried using drupal_set_message(t('!shell_c', array('!shell_c'=>$shell_command)), 'status'); but the issue persists where the drupal_set_message messages are shown sometimes and not shown sometimes, rather erratically.
//Before this part of the code, there is function to create Menu ($items[])
function g_p_proc_form($form, &$form_state, $values) {
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['filter'] = array (
        "#type" => "fieldset",
        "#title" => t("File Process <BR> "),
        "#collapsible" => TRUE,
    );
  // without this attribute, upload may fail on submit
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['filter']['file'] = array(
        // '#title' => t('File processing'),
        '#type'  => 'file',
        '#name' => 'files[]',
        '#description' => t('Select Submit to start processing the file'),
        '#type'  => 'file'),
        '#upload_location' => 'public://',
        '#attributes' => array('multiple' => 'multiple'),
    );
    // echo '<script type="text/javascript">Drupal.behaviors.DSU_batch_report;</script>'; //christ
    if (isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > 'size based on my requirements') {
        drupal_set_message(t(" Warning message on file size"));));
        // unset($_SERVER['CONTENT_LENGTH']);
    }

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

    );

    // drupal_set_message(t("in fn"));

    return $form;
}

function g_p_proc_form_submit($form, &$form_state) {
    header(current page)
    try{
        $number_file = count($_FILES['files']['name']);
        $f_name = array();
        for ($i=0; $i<$number_file;$i++)
        {
            $file = file_save_upload($i, array('file_validate_extensions' => array('pdf PDF')), 'public://', FILE_EXISTS_REPLACE);
            $f_name[] = $_FILES['files']['name'][$i]; //[]
        }
            }catch (Exception $error){
        echo 'Exception: ',  $error->getMessage(), "\n";
    }
    $n_f = count($f_name);
    drupal_set_message(t('Number of files to process: !n_f', array('!number_f'=>$n_f)));
    $fn_name = 'g_p';
    $fn_call = $fn_name($f_name);
function g_p($f_name=array()){
    $curr_l = getcwd();
    chdir('My file processing PHP script location ');
    $n_f = count($f_name);
    $shell_command = shell_exec("file_processing_php_script_name.php");
    //header("Location: "Current file processing module menu site"); //Commented out
    drupal_set_message($shell_command); //print_r statements from the file_processing_php_script_name.php
    chdir($curr_l);
}

It sounds like you need to maintain a stable message storage solution until the operation is complete.
The D7 core message functions drupal_set_message() & drupal_get_messages() (the core function used when retrieving messages for rendering) are pushing/popping messages to session var, $_SESSION['messages'] These messages are designed around a single page request/received operation.
If there many different async requests going on with the same session (or other modules calling drupal_get_messages() with its default options), its likely $_SESSION['messages'] is being cleared out before rendering when you need it.
Try storing your messages somewhere else (e.g. another session variable) then call drupal_set_message() with your messages once the full operation is complete. If most messages are background ops, you should use consider watchdog() for logging background ops and then use drupal_set_message() for a "operation complete" message.


How can I allow users to create private pages? I want a way to create a way to allow only specific users to see a specific page.

One page per user where one user can't see another's page.

What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather course, and to control per-user access to view a page, you must use some sort of node access control module.  There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module.

One I suggest you take a closer look at, is Flexi Access.  It let you control access to a single node (page) for an individual user.  This, I believe, fits well with your requirements.  Many other content access modules have content types and/or roles or groups as their smallest unit of resolution.

Disclosure: I am the maintainer of Flexi Access.


Cache + random + hook_form_user_register_form_alter for a captcha purpose, I'm trying to set a random number in the hook_form_user_register_form_alter

For example :

function my_module_form_user_register_form_alter(&$form, &$form_state) {
    $random_case = rand(0, 3);
    $form["random"] = array(
        "#type" => "textfield"
        , "#title" => ""
        , "#disabled" => 0
        , "#value" => $random_case
        , "#description" => null
        , "#weight" => -2
    );
}

When cache is disabled it's working as intended.

when I enable the cache the random number is always the same until I flush all caches.
I tried to flush cache programmatically, but it doesn't seem to work. What can I do ?

if I put a

die($random_case);

It's working but I think it's because drupal can't put the hook inside the cache.

Best regards.

When the forms cached, it caches the original, unprocessed $form array, and the builder functions are not called again.

you can explicitly set cache off by setting $form_state['no_cache'] = TRUE;. Note that this has potential to break Ajax forms.


How do I fix my Commerce Feeds import process post updating my modules and core? I have just upgraded to core 7.15 and updated all my modules at the same time.
When I now try and run the an import using commerce feeds I receive the error below.

    An AJAX HTTP error occurred.
    HTTP Result Code: 200 Debugging information follows.
    Path: /batch?id=892&op=do
    StatusText: OK
    ResponseText: Fatal error:
Call to undefined function commerce_product_validate_sku() in /home/mmlcofdk/public_html/sites/all/modules/commerce_feeds/plugins/FeedsCommerceProductProcessor.inc on line 216

I would really appreciate some advice on how I could go about debugging this...

I have the same problem. I think that is because I am using a old version Drupal Commerce and it is incompatible the newer version of Feeds module that i am using.

but I manage to get it work by paste in this function:

function commerce_product_validate_sku($sku) {
  // Do not allow commas in a SKU.
  if (strpos($sku, ',')) {
    return FALSE;
  }

  return TRUE;
}

into the file "commerce_prouduct.module" located in:

{mydrupal-installation}\profiles\commerce_kickstart\modules\commerce\modules\product

I found that function in:

http://drupalcontrib.org/api/drupal/contributions!commerce!modules!product!commerce_product.module/7

Hope that help!

Apollo Tang


What does the 'version' keyword mean in .libraries.yml? In theme.libraries.yml, libraries have a version key. It appears to be optional, but Drupal core libraries (core.libraries.yml) set the version key value as version. What does this keyword mean?
so :

Why we use the version keyword ?
When should I change the version keyword?

Why should I use it?

It is used as an identifier for your libraries. Just like any project/package is tagged in different versions. For eg: jQuery 3.5.1 is slightly different from 3.0.0. The difference could be anything, from API change, new features, bug fixes, etc. Thus we need a way to identify the changes that happened to our library we created. So that we can make some conscious decisions. Another example. Suppose there is a 3rd party js that is having issues with another library of a specific version. So during the install, we can check if the other library has library greater than required.

When should I change its value?

Ideally after every deployment if any change to the library has occurred.
So what Drupal does is, it happens the version number to each file in that library when attaching that library to any page. For example: if my library has a css file called custom.css and the version number is say 1.0.0. So, the way it will get attached to the page will be like /path/to/theme/css/custom.css?v=1.0.0.
This is so far ok. But ideally on prod environments there are reverse proxies which caches these files. Suppose if we make any new changes to these files and even if we clear the cache, the files will still be served from CDN, thus we also need to make sure if any change has happened on these files, it makes sense to also increase the library version number. Just as you would do with creating a new tag for a new release for any project.
If we give the version as VERSION. Then drupal sets its version = \Drupal::VERSION the current drupal core version.


Puilling Information From Referenced Entities to Display/Use In A Custom Content Type? Exposition

I have two Content Types with the following fields:

Scenes

Scene Name
Starring (Actor's names)
Streaming Link

Releases (DVD Releases)

Title
Description
Starring (All actor's names from all Scenes referenced)
Scenes (Entity references to the Scene Content Type)

My question

When displaying a Release node, how can I get Drupal to generate the list of Starring Actors by taking the names from the 'Starring' fields in the Scene nodes that have been referenced?

Thanks

Two suggestions

First, the most common solution:

Create a View
Add a "relationship" from Release to Stars
Add whatever fields you want to display, in this case, "Name", and make they "Use relationship Stars".

Second, what I would have done:

Create a suitable Panels Page for Releases
Create a mini-panel for Stars
Add the Stars reference field to the releases page with "Panels reference formatter", choose the mini-panel as the formatter.

Intro to Views.

Intro to Page manager and Panels.


How can I debug white screen when running install script? I'm doing a fresh install of drupal7 on Ubuntu following these instructions.

When I get to the point of running the install script (by pointing the browser at localhost/drupal7/install.php) it just gives a blank screen.

Most questions/help about the Drupal blank screen relate to site setup but as this is a new install, I haven't created any sites yet so am unable to figure out what to do.

Does anyone know how to debug or move past this issue?

You can edit your settings.php file and add

ini_set("display_error" , 1);