Ultimate Cron. Invoke a cron from a cron. Set a cron enabled status to TRUE till its queue gets empty. Then set it to FALSE I am using Ultimate Cron for running individual cron runs and I see Ultimate Cron provide hook_cronapi() to create own cron task runs and provide enabled key as either TRUE or FALSE.

My objective is create two cron task one cron will run at specified time say 01:00pm and will update the enabled statues of second cron to TRUE so that it will run until it achieved certain condition  during each 1 min interval of this second cron task and after this condition is met, will be shut down the second cron task status by setting disabled status to FALSE so that it stop processing uselessly.

So, how do I set that enabled status to TRUE/FALSE during its run time.

Answering my own question.

In your .info file first define ultimate_cron as dependencies

dependencies[] = ultimate_cron

Next, in your .module use hook_cronapi() and define two cron attributes.

/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi() {
  $items = array();
  // This launches at specified time once a day.
  $items['custom_cron_1'] = array(
    'title' => t('This will run once every day'),
    'scheduler' => array(
      'name' => 'crontab',
      'crontab' => array(
        'rules' => array('* 2 * * *'),
    ),
  );
  // Run only when invoked and until & unless condition is met so we are not left for tomorrow
  $items['custom_cron_2'] = array(
    'title' => t('Run when invoked'),
    'enabled' => FALSE,
    'scheduler' => array(
     'name' => 'crontab',
     'crontab' => array(
       'rules' => array('*/1 * * * *'),
     ),
  );
  return $items;
}

Next step is to define the cron job callback and here in first callback we will schedule to run second cron job.

function custom_cron_1() {
  $job = _ultimate_cron_job_load('custom_cron_2');
  // Enable the job.
  $job->enable();
}

Next we will define callback for second cron and continue this cron process each minute until condition is met.

function custom_cron_2($job) {
  // Check for condition.
  if(...) {
    $job->disable();
  }
  else {
    // Continue the process
  }
}


Hide Webform Message "You are viewing this form as..." How can I hide the message at the top of a webform which says
You are viewing this form as [user name]. Please click here if that's not you.

Doh! I didn't realise this was a configuration option in another module - Webform CiviCRM.


Same file_temporary_path for localhost and production server? Each time I move one of my Drupal website from localhost to production server or vice-versa, I have to edit my settings.php to update the path of the temporary file directory:

# $conf['file_temporary_path'] = '/home5/dawnings/public_html/fw2/tempdir';
$conf['file_temporary_path'] = 'c:/Temp/Drupal/tempdir';

Is there a way to specify a unique relative path to this temporary file directory once for all and which would work both for localhost and production server? The objective is to avoid having to update my settings.php anymore.

There is more than 1 way to accomplish something like this. I am not aware of a simple "1 line universal fix" unless you try a relative path, but that assumes some consistancy between your servers which clearly by your directory paths you dont have.

Option 1:

At the bottom of you settings.php put something like:

$local_settings_conf = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings_conf)) { include $local_settings_conf; }

I do this programmatically in BASH with like:

#!/bin/bash

# I actually install drupal via the command line with a custom install
# profile and append on the tidbit to settings.php programmatically like
# so ...

cd $drupal_www_dir
drush site-install MY_INSTALL_PROFILE \
  --locale=en \
  --db-url="mysql://dev_user:dev@localhost:3306/demo_drupal" \
  --account-name=admin \
  --account-pass='admin' \
  --acount-mail=foo@test.com \
  --site-name=demo --verbose -y

#
# Now that drupal is built we modify the settings.php file with additional db
# and other custom configuration values by appending a child seetings file.
#
# This is in concept similar to an Apache vhost directive file.
#
echo "altering settings.php to be aware of our 3rd party remote databases."
sudo chmod -Rv a+rw "${drupal_www_dir}/sites/default"
read -r -d '' PHPCODE <<'EOF'
/*
 * For our project we provide our own localized configuration schemes.
 */
$local_settings_conf = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings_conf)) { include $local_settings_conf; }

EOF
echo "${PHPCODE}" >> "${WWW}/sites/default/settings.php"

Then for each server you keep a version of this file. Or in this file make an If-Else PHP block that stores the correct $conf value based on whether this configuration file is $local vs $dev or $prod. So basically you can move all your custom settings.php stuff that arent 100% stock drupal into a special appended configuration file ... this way the stock drupal settings.php stays as it is and all your custom stuff can go into its own file as-needed.

Option 2:

Use something like the Environment module and in PHP set the value for the file_temporay_path with variable_set as that is what is being called by file_directory_temp().

Those are the two options I know of that aren't brain surgery ...

EDIT 09/26/2014 by author

You can also use Drush on each server to run: drush vset file_temporary_path "to/some/path"
If you're comfortable with virtualhost settings you can also always create a aliased directory in your webserver configuration (pushing the problem up 1 level in the production stack (out of PHP))


How can I loop through checked entity reference values with a taxonomy condition? I'm using Drupal 7 and Commerce. We have several product displays: Caramel, Chocolate, Cinnamon, Cheddar, etc. Each of these product displays has 5 SKUs (5 products) for the 5 different sizes we offer. Each product display also gets tagged as either "premium" or "standard."

I'm trying to then build a "sampler" where they choose up to three of those flavors. To do this, I'm using an entity reference field so that that list always has the current flavors. i.e. If they had Hazelnut, the sampler gets updated with Hazelnut.

If they choose a premium flavor, it should add $5 to the total price per premium flavor, but if there are no premium flavors, then it should stay the same price.

I have a rule set up that is halfway there. Problem is, if there is even just one premium flavor, it charges $5 per item checked, regardless of whether they're premium or standard.

I can't figure out how to only apply the upcharge per premium flavor. Any help is greatly appreciated. Willing to help fund this some if needed.

The first (crucial) part of your rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

So add a loop related to the flavors that got selected. After you do, you should iterate over each item in that list (= each flavor).

And for each iteration you should then perform an appropriate verification if it is a premium flavor (in which case you want to add $5). But, within Rules Actions, you cannot just add another Rules Condition (as you may have noticed) ... Except if you use the Conditional Rules module (which is exactly the purpose of this module ...).

Done

PS: are those funds still available?


Problem with the schema structure produced by Schema module I have a drupal 7.34 installation in my local computer. I also installed schema 7.x-1.2 module. Now

Below is my code:

function myid_schema(){
    $schema = array();
    $schema['myid_templates'] = array(
        'description' => 'TODO: please describe this table!',
        'fields' => array(
            'template_id' => array(
                'description' => 'TODO: please describe this field!',
                'type' => 'serial',
                'not null' => TRUE,
            ),
           'template_name' => array(
               'description' => 'TODO: please describe this field!',
               'type' => 'varchar',
               'not null' => FALSE,
           ),
           'portrait' => array(
               'description' => 'TODO: please describe this field!',
               'type' => 'boolean',
               'not null' => TRUE,
           ),
           'template_width' => array(
               'description' => 'TODO: please describe this field!',
               'type' => 'numeric',
               'not null' => TRUE,
               'default' => 0,
               'precision' => 0,
               'scale' => 0,
           ),
           'template_height' => array(
               'description' => 'TODO: please describe this field!',
               'type' => 'numeric',
               'not null' => TRUE,
               'default' => 0,
               'precision' => 0,
               'scale' => 0,
           ),
       ),
       'primary key' => array('template_id'),
   );
   return $schema;
}

/**
* Implementation of hook_install().
* Perform initial setup tasks.
*/
function myid_install(){
    drupal_install_schema('myid_templates');
}

After installing my module, it throws an error:

Notice: Undefined index: boolean:normal in DatabaseSchema_pgsql->processField() (line 229 of C:\xampp\htdocs\drupal-7.34\includes\database\pgsql\schema.inc).

PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "NOT" LINE 4: portrait NOT NULL, ^: CREATE TABLE {myid_templates} ( template_id serial, template_name varchar NULL, portrait NOT NULL, template_width numeric(0, 0) NOT NULL default 0, template_height numeric(0, 0) NOT NULL default 0, PRIMARY KEY (template_id) ); Array ( ) in db_create_table() (line 2720 of C:\xampp\htdocs\drupal-7.34\includes\database\database.inc)

Why does it throws an error when my code is copied from the schema structure produced by the schema module? How will I fix it? By the way I'm using postgres.

Drupal doesn't have a boolean type for DB schema, and there's no automatic fallback for a type it doesn't know about, so you end up with the invalid portrait NOT NULL instead of portrait boolean NOT NULL in the create statement.

To fix, just add a pgsql_type to the column. DatabaseSchema_pgsql::processField() knows what to do with it.

'portrait' => array(
  'description' => 'TODO: please describe this field!',
  'type' => 'int', // Keep it portable
  'pgsql_type' => 'boolean',
  'not null' => TRUE,
),


Is it possible to use a user display form in a page? I've seen that it's possible to create different user display form here :

/admin/config/people/accounts/form-display/my_infos_form

How can I call it in a particular page for instance : /my/infos ?

As we have a lot of fields, we would like to separate the user edit page into multiple form page.

Unlike view modes there is no UI in core to apply different form modes other than the user register form. You can try one of these modules:

https://www.drupal.org/project/form_mode_control

https://www.drupal.org/project/form_mode_manager


how to resolve undefined property error This is my code:

function my_module_node_presave($node){
  if ($node->type == 'add_stock') {
    $stock_value = $node->field_stock_value['und'][0]['value'];
    drupal_set_message('stock_value :'.$stock_value);

    $sku = $node->field_sku['und'][0]['value'];
    drupal_set_message('sku :'. $sku);

    $key = $node->field_reference['und'][0]['nid'];
    drupal_set_message('key :'. $key);

    $key1 = node_load($key);
    //$pnode =  $key1->field_product_stock['und'][0]['value'];
    //drupal_set_message('key1 :'.$key1);
    //if (module_exists('uc_stock') && function_exists('uc_stock_adjust')) {

      uc_stock_set($node->$sku, $stock_value);
      uc_stock_adjust($node->$sku, $stock_value);

    //}
  }
}

The error I get is the following one:

  Notice: Undefined property: stdClass::$tshirt-11 in my_module_node_presave() (line 40 of
  D:\xampp\htdocs\photo\photogallary\sites\all\modules\my_module\my_module.module).

  Notice: Undefined property: stdClass::$tshirt-11 in my_module_node_presave() (line 41 of
  D:\xampp\htdocs\photo\photogallary\sites\all\modules\my_module\my_module.module).

When you write $node->$sku, PHP takes the value of $sku and uses it as name of a property.
In your case, $sku contains 'tshirt-11', and $node->$sku is equivalent to $node->tshirt-11. Since $node->tshirt-11 is not defined, you get the error you see.

The code you should write is the following one.

  uc_stock_set($sku, $stock_value);
  uc_stock_adjust($sku, $stock_value);

As side note, the value of a field is accessed using field_get_items(). The code you use to set $sku should be rewritten as the following.

$items = field_get_items('node', $node, 'field_sku');
$sku = $items[0];


Give permission to translate a specific language I want to give an editor the permission to translate only (a) specific language(s).
By default a user can translate content to all available languages.

Any ideas?

There is an awesome module for it... Translation Management

  You can specify that a user can only translate from English to Spanish
  and another user can translate from English to French and you can also
  have a translation administrator to maintain translation jobs.. And it
  provides a beautiful interface for it.. There is a Guide for it
  too..


Table Drag problem with Jquery Update to jquery 1.4 and highers I want to use some jquery plugins that need jquery 1.7.x
But as you know jquery update in drupal 6.x only support jquery 1.3.x and lower.

if we copy jquery 1.7 to jquery update folder, it cause problems in table drag function.

Is there any way to repair table drag bugs with jquery high versions?

The problem is that newer jQuery .after function returns the content to be added if you invoke it on an empty list. This breaks the tabledrag.js makeDraggable function.

The following patch that function fixed it for me:

   // Insert the handle after indentations (if any).
-  if ($('td:first .indentation:last', item).after(handle).size()) {
+  var td = $('td:first .indentation:last', item);
+  if (td.size() > 0) {
+    td.after(handle);
     // Update the total width of indentation in this entire table.


How do I give a user limited access to theme settings? I am interested in giving the site administrator some limited access over the appearance. Currently I can give them access to administer themes or not to, and nothing more granular than that. I would like, for instance to limit the themes they can enable and disable to a small number, and perhaps also limit what, within the settings they can change.

You could do that with hook_menu_alter to change the access callback on your theme settings page.

e.g,

/**
 * Implements hook_menu_alter
 */
function mymodule_menu_alter(&$items){
  $items['admin/appearance/settings/my_theme']['access callback'] = 'user_access';
  $items['admin/appearance/settings/my_theme']['access arguments'] = array('administer nodes');
}

You can also add your own access callback and return TRUE or FALSE depending on more custom user access rights access there.

See system_menu for the core 'admin/appearance/settings/' . $theme->name menu definition


How to get the list of field-types? I'm porting a module from Drupal 7 to Drupal 8. In this module's configuration settings I need to get the list of the currently existing field-types.

In Drupal 7, this was achieved using the field_info_field_types() function.

In Drupal 8 (8.0.0-rc3), I get an error "function does not exist", despite the information stated by a Drupal API Reference Help page, clearly out of date.

Then investigating I found a DrupalContrib page, where the function is declared deprecated, and proposing to now use Drupal::service('plugin.manager.entity.field.field_type')->getDefinitions().

But using it fires another error "Unknown service plugin.manager.entity.field.field_type", fortunately associated to the suggestion "Do you mean plugin.manager.field.field_type?"

So I tried using Drupal::service('plugin.manager.field.field_type')->getDefinitions() and wow: I got the expected array of field-types.

But each array member (one field-type) is now an object (instead of a child array), and the data I'm looking for is nested within protected properties, so I can't access them.

At this stage, I'm stuck. I considered it might exist some class I could expand to navigate through these data, but with no luck: I notably couldn't even figure out which is the component in Drupal 8 where field-types definitions is centralized.

The first level is an array. The keys are the plugin id's. You can list them:

$defs = Drupal::service('plugin.manager.field.field_type')->getDefinitions();
foreach ( $defs as $key => $value ) {
   echo $key, "\n";
}

This is the result:

comment
datetime
file
image
link
list_string
list_float
list_integer
path
text_with_summary
text
text_long
email
boolean
created
changed
timestamp
string_long
language
decimal
uri
float
password
string
integer
entity_reference
uuid
map
taxonomy_term_reference

You can pick one and dump the plugin definition.

var_dump($defs['comment']);

If you are interested in a special object, you can digg deeper with the help of api.drupal.org. But it will be easier, if you search for the plugin in the core directory.

To access an object, locate it in the var_dump and use a method:

$defs['comment']['description']->render();

In this case it is the object TranslatableMarkup, which has the method render to access the translated string.


Using Zurb Foundation without installing the required dependencies: npm, gulp, bower, etc I just created a sub theme for zurb foundation 6 on drupal 8, and reading the docs it tells me to do a npm install and a npm bower

When doing a npm install I get the following errors:

I fixed that by figuring out how to update npm and node and that solved that issue. Now I have to install bower and do a bower install.

My question is: Do I have to install all these things in order to setup foundation to work? I prefer not to use SASS as I work in a team of devs and sometimes the backend dev goes in to edit the css files without knowing that they have to first turn on a sass compiler before doing that.

Alternatively, you could simply use the ZURB Foundation theme

  Do you like grid systems? How about rapid prototyping? Do you believe
  in mobile first? Then this theme is for you! Foundation is made by
  ZURB. This theme implements the Foundation framework for Drupal.


Dynamic Menu with Views Background: This is not the first question asked around here. I thought I found a solution but nothing worked in the end.

I have 2 content type: Parent and Child

Child possess 2 Entity Reference(ER) fields, Section and Parent(ER)

Section is linked to a Parent node, Parent(ER) is linked to another Child node, allowing for 3 level of Hierarchy, level 1 being a Parent node, level 2 being a Child node with a Section, level 3 being a Child node with a Section and a Parent(ER). I have created a Child node name NONE and use it as default for Parent(ER) to easily distinguish between level 2 (with no Parent(ER)) and level 3 (with a Parent(ER)) nodes.

I'm currently trying to build the menu for Child pages using multiple views providing data. Currently, I have the Parent(ER) section of said menu down, as it's pretty easy to build. The problem comes when I try to create the Siblings. Here is the requirement for this view:

I need to list all level 2 Child nodes, so the ones with a Section but no Parent(ER) (already dealt with using a conditional filter on Parent(ER) and checking for all pages with the NONE nid.)
I need to remove the currently displayed Child node as it's already present elsewhere
I need to print ONLY Child with the same Section as the current node

I can't find the contextual filter/relationship combination to achieve my goal.

How can I achieve this?

Your levels are a bit confusing, I'm guessing it's to do with your project structure and doesn't provide relevant information about the reference hierarchy, so I'll just rely on the information you provided about which entity references which.

list all Child nodes with a ref to Section but no Parent(ER)

Even though you already solved this the solution that first comes to my mind is to list all Child pages where the ER field to Section isn't empty, and the ER field towards Parent(ER) is empty. No need for special NONE nodes.

You can do this by adding a Filter for each of those ER Fields and setting the Operator to Is empty (NULL) and Is not empty (NOT NULL) respectively.

Remove the current node from the list

Add a Contextual filter ID from the Content Category and configure it with these options:
    When the filter value is NOT available
    Provide default value
    Content ID from URL
    More
    Exlude

List siblings relating to same node through ER

To list siblings you first need one Relationship to get to the parent of the ER relationship (in your case Section), then another Relationship in reverse direction that is using the first one to find all other children of the parent. Then configure a Contextual filter to use the second Relationship, that is the one that is identifying siblings.

Add a Relationship Content referenced from field_section (or however it's called in your particular case), you can require it, this introduces the Section into the Views.
Add another Relationship Content using field_section, set it to use the Relationship from the previous step, you can require it. This is the reverse direction, pointing to all children that are pointing to this parent (Section).
Add a Contextual Filter ID from Content Category and set it to use the second relationship (field_section) and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Child
If this is a Block Display place it on Child nodes and it will show other children that relate to the same Section.

To check the Contextual filter with Views Preview, enter the NID of the Child node you want to simulate, and enter it for each Contextual filter.

If you have both the contextual filter that identifies siblings and the one that excludes the current node from the list (and the Child NID is 24) enter 24/24.

If you want to see all the results, unaffected by Contextual filters enter all/all.


What's the class or id of the autocomplete suggestions pane? I'm doing a form with a fairly standard autocomplete_path textfield, like:

$form['the_field'] = array(
    '#title' => t('A title'),
    '#type' => 'textfield',
    '#autocomplete_path' => "path/to/autocomplete",
    '#description' => "Some description."
);

It's working fine, but I want to do some styling of the suggestions that show up in response to the user's type-in.  I'm trying to track down the id or class of this pane so I can add some css or whatever, but I can't find it -- the various browser inspectors keep closing when I try to look at the pane.  Does anybody know what this is?  Thanks!

The element's id attribute is autocomplete.


How do I modify the CSS in webform? I made a booking form using Webform. How do I modify the CSS?
Where do I find the CSS file of the webform?

The CSS files in Drupal look nothing like in Vanilla CSS. I'm bit lost there.
I would just like to reduce the width of my rows or change how the date-picker looks like. Or to display my rows in two columns.

I don't want to touch the PHP files too much either, hence why I found the answers about this topic on this forum not satisfying.

You'll find the .css files in your theme directory, usually sites/all/themes/THEME_NAME/css.

To see easily in which line of which css file is the rule you'd like to change, you can go to admin/config/development/performance and un-tick Aggregate and compress css files checkbox.

Then with Firebug or similar development tool you'll be able to explore the css.

Check also if there's a sass or less folder in the same directory. In that case, you would have to edit the relevant scss/less files instead of the css ones, and make sure your editor is well configured to compile them to css.

You can explore scss files with the help of FireCompass addd-on and less ones with FireLESS.

EDIT

As underlined by Beebee comment, if the css you'd like to override are into a module css file, such as webform's css, don't edit that file, but override it in your own theme's css file.


DB API: How to add the result of an embedded query and a retrieved value More fun with the DB API:  I'm tracking the number of views of instances of a particular node type: I have a table that collects entries of the viewed node's nid and the timestamp of the view (which makes sense for a variety of reasons in the situation).  These nodes, being regular nodes, can also have comments.

I want to retrieve a set of nodes that is ordered by the sum of the number of views and the number of comments on that node.  (Don't ask why... :)  The following code almost works:

$the_tasks = db_select('node', 'n')->range(0, 5);

    $the_tasks->condition('n.type', 'whatever');

    $the_tasks->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');

    $count_task_views = "(select count(*) as count from {vr_task_view_log} where tid = n.nid)";
    $the_tasks->addExpression($count_task_views, 'count_task_views');

    $sum_of_views_and_comments = "(count_task_views + ncs.comment_count)";
    $the_tasks->addExpression($sum_of_views_and_comments, 'sum_of_views_and_comments');

    $the_tasks->fields('n', array('nid', 'title'));
    $the_tasks->fields('ncs', array('comment_count'));

    $the_tasks->orderBy('sum_of_views_and_comments', 'desc');

$the_tasks = $the_tasks->execute();
$the_tasks = $the_tasks->fetchAll();

Like I said, it almost works: sum_of_views_and_comments is coming out as just the number of views -- the number of comments (which are getting successfully retrieved and returned as part of the query) aren't getting added in.  I've also tried omitting the "ncs." qualifier from the addition statement, but that has no effect.  Any advice on how to make it work?

This was indeed a database question; a fix for the "unknown column" problem can be found at https://stackoverflow.com/questions/14879342/can-i-do-math-on-the-result-of-an-embedded-query-in-the-parent-query (short answer: the computing of count_task_views needs to be done in a lower-level SELECT).  Back to Drupal: I have my query working as pure SQL handled through db_query; I should probably figure out how to do it via the API, but that's going to wait for awhile...


Programmatically Render a Webform I'm attempting to render a webform inside a block plugin. I'm able to successfully retrieve the webform using the following code

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('my_webform');

However I'd like to render this form. I've attempted using

return $webform;

But I receive the error

  Recoverable fatal error: Argument 1 passed to
  Drupal\Core\Render\Element::isEmpty() must be of the type array,
  object given

I'm assuming this is because $webform isn't formatted as a proper render array, but I'm not sure how to do this. I've been searching for clues inside the code of the original webform module, but I haven't been able to find anything.

How would I programmatically render a webform? And/or is there a way to find in the code of a module or entity the way to render that entity?

I managed to find a method for the webform entity class called getSubmissionForm. I found it in the webform module code in src/Entity/Webform.php

I invoked it like so

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('my_webform');
$webform = $webform->getSubmissionForm();

return $webform;

Which returned the specified webform rendered.


How to make a region available to a non-page tpl file? I'm working with a custom theme (which I did not develop.) We're wanting to add a block to a specific node type, which has a template called node-session.tpl.php. This template prints out all kinds of internal html and php, but is framed by the page.tpl.php file. The node-session.tpl.php contains the code that's printed by the $content variable in page.tpl.php.

I have a new block (created by the AddThis module) that needs to be positioned on the page such that it's nested inside a div created in the node-session.tpl.php. Unfortunately placing the region inside that file doesn't work, and in fact just testing for the variable $add_this itself returns false. According to all the documentation I can find, region variables are available to page template files only. Is there a way I can make the variable available to the node-session.tpl.php file so that I can position the block correctly?

Sure, you can use a node_preprocess() hook to create the variable much like this:

function mytheme_preprocess_node(&$variables) {

   // whatever else you are doing goes here

   $block = module_invoke('AddThis', 'block', 'view', 0);
   $variables['mynewblock']=$block['content'];

}

which would call the AddThis module to invoke it's block hook and return block with delta 0.

Lots more detail can be found here:  http://www.pixelclever.com/how-insert-a-block-a-tpl-or-content-programmatically-with-drupal


How to make getTree works? I want to expose a vocabulary to an external server using services module. I have followed this question How to create test_endpoint, and checked every checkbox, and enabled the `REST Server Module.

The only endpoint that I interest is getTree. But I don't know how to compose the URL. I can't find any document describing the detail (please tell me if you know).

Which HTTP method should I use? GET or POST? I think it should be a GET, but I got nothing
how to specify the vid? /taxonomy_vocabulary/[vid]/getTree ? /taxonomy_vocabulary/getTree/[vid] ? or /taxonomy_vocabulary/getTree?vid=[vid]? any other params?

I have try some URL,

GET  [endpoint]/taxonomy_vocabulary/getTree will response [false] (what is this mean?)

POST [endpoint]/taxonomy_vocabulary/getTree will response 401 Unauthorized, but whatever I disable or enable the Session Authorization, I got the same response.

you must add {"vid":"1234"} in the body of HTTP POST request and add Content-Type in the header request with "application/json"


Loading a library only for the front page I want to load JavaScript only on the home page of my site. I found this preprocess function but I don't know how to customize it for the home page:

function mytheme_preprocess_maintenance_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
}

I was originally including the library I needed in every page of my site, but I only need it on the home page, so I need to figure this out.

Originally I had it in the .info.yml file like so:

libraries:
 - 'themename/library'

Any help is appreciated.

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
        $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
    }
}


Drupal statistics does not count visits when I see the node from a custom panel I have a web site where each node has three diferents designs (i do it through panels and arguments) and i use the statistics module, that way i can see how many visits has the node.

But the statistics module jus count the visits when they visit the main design. I can explain with a example:

website .com/node/01 <---when a user visit this url, a visit is counted
website .com/node/01/mobile <----- here is not counted the visit
website .com/node/01/lightbox <----here is not counted the visit

This was built for panels and arguments... so, is there anyway to put a php code in two panels that visitors don't have to start to count?

Best,

It's because panels doesn't invoke node_view(). Please try following code:

function MODULE_ctools_render_alter(&$info, &$page, &$context) {
  if ($context['handler']->task == 'node_view') {
    $key = $context['handler']->conf['context'];
    $node = $context['contexts'][$key]->data;
    statistics_node_view($node, 'full')
  }
}


Display node content with frontend theme in admin route I need to display content with the frontend theme in an admin page to get a preview.
I get the content and built it with the ->getViewBuilder('node') but the template used is coming from the admin theme and the created template in the frontend theme node--newsletter.html.twig is not taken into account.

Is there a way to see the node view mode with the frontend theme instead of the admin theme ?
Thank you.

If this is a custom route (defined in a routing.yml file with a custom controller) you are able to do this by defining the route in the routing yaml with
options:
    _admin_route: FALSE

Which will cause the route to be treated as a "frontend" route. However it sounds like this is likely not the case here.
If you simply want to have previewing of standard content, the core preview function (the button next to "Save") is the standard mechanism to do this.


Video Filter module warning I have installed the video filter module on my site. I added the following to my video source field.

[video:https://www.youtube.com/watch?v=686A5yPMWrs]

When I view the node, I get the following warning:

  Warning: Illegal string offset 'id' in Drupal\video_filter\Plugin\Filter\VideoFilter->process() (line 91 of modules/video_filter/src/Plugin/Filter/VideoFilter.php).

Is this something to pursue and fix? Is it safe to just disable the warnings when I push the site live?

The Video Filter module is still in alpha so it's very likely this is a bug. You should consult the issue queue to see if it exists, and create a bug report if it doesn't exist.

As for the ignore and deploy/pursue and fix question, it depends on how fault tolerant you are. Certainly the project maintainers (and community) would appreciate the bug fix. Deploying early release code is risky, but if the functionality is little used and has no chance of catastrophic results (e.g. complex DB manipulation that could result in corruption.) then deploy/ignore can be a fine strategy (regardless, you should always have warnings turned off on production).


qTip2 and Drupal 6 troubleshooting I am currently trying to implement a tooltip using the jQuery extension, qTip2. I have installed both of the files included in the extension (jquery.qtip.min.js and jquery.qtip.js in my /theme/js/ location, and their appropriate CSS sheets in /theme/css) and declared them in my theme's .info.

At the moment, I'm trying to write a function that displays the tooltip "Hello World" whenever someone hovers over an element of with the attribute #T6roll. I have the following as a script in my /sites/js/ location:

Drupal.behaviors.magds = function (context) {
  // Sounds, if using class "sound", these "#T1roll, #T2roll, #T3roll, #T4roll" can be removed, ul.dropdown li a,
  $('ul.links li a, .sound, #T1roll, #T2roll, #T3roll, #T4roll').mouseover(function(){$.fn.soundPlay({url:Drupal.settings.magds.themeAbsolute+'flash/mouseover.wav',playerId:'embed_player',command:'play'});$("#sound").html("mouseover.wav");}).mouseout(function(){$.fn.soundPlay({playerId:'embed_player',command:'stop'});});

  // IE helpers
  if ($.browser.msie && ($.browser.version < 8)) {
    $('#main-menu li').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
  };
};

/*
 * implements jquery.qTip.js
 */

 (function($){
    $(document).ready(function() {
        $('a#T6roll).qtip({
            content: 'Hello World!',
            position: { target: 'mouse'}
        });
    });
 })(jQuery);

However, the site does not seem to be executing this. Is there any ideas as to what might be the cause of this? At first, I thought that it might be the qtip syntax, but I kept it as simple as can be to debug and it's not functioning.

After doing some research, it turns out that there is active development being done in the jQuery_Update module. Specifically, you may reference this post .

The issue with the jQuery_Update module is that it would only update your Drupal 6 jQuery install to v. 1.3.0. With the patch that is applied in the aforementioned post, you are able to update all the way to jQuery 1.7.

An alternative to this solution would have been to load jQuery from another location and use the noConflict() function. Drupal has some excellent documentation regarding this.


Custom module is not showing up for regular user This is what Drupal returns if URL defined from the module is accessed:

  Access denied
  You are not authorized to access this page.

THe permissions are all checked for authorized, and anonymous users.

The implementation of hook_menu() is the following.

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

  // This determines the path used to show the form and also makes a menu entry
  // This first path is for the entry form
  $items['qarena'] = array(
    'title' => t('QArena'),
    'page callback' => 'qarena_display_page',
    // drupal_get_form, registers the given form in drupal.
    'access arguments' => array('ask question'),
  );

  return $items;
}

user_access(), the access handler used by default from Drupal when no other access handler has been set, returns TRUE (the user has access to the menu) only when the permission string is one defined from a module, and the user has that permission.

If "ask question" is not a permission defined from any module with hook_permission() (Drupal 7 or higher), or hook_perm() (Drupal 6 or lower), then you will get an access denied error.

Once you are sure a module (including the one you are developing) defines the permission you want to use, be sure the same permission is assigned to any of the roles the currently logged-in user has. For example, if the user has the role of editor, then the permission you are using needs to be assigned to the editor role, or to the authenticated user role.


Runtime Exception - no weight or dimension field after importing Drupal 8 - Commerce 2 has its import from Ubercart now in the Commerce Migrate module.  Field text data was left behind, and it is its own issue - see below
At admin/commerce/config/product-variation-types for what did import was the product types and products themselves, and if I try to edit the imported "Product", Product_kit" or "uc_recurring" variation to make it shippable with dimensions a Runtime Exception error is thrown that no "dimension" or "weight" field exists.

RuntimeException: The field "dimensions" does not exist on bundle "product" of entity type "commerce_product_variation". in Drupal\commerce\ConfigurableFieldManager->hasData() (line 119 of modules/commerce/src/ConfigurableFieldManager.php).
Drupal\commerce\EntityTraitManager->canUninstallTrait(Object, 'commerce_product_variation', 'product') (Line: 77)  . . . . more (for Product)

and

RuntimeException: The field "weight" does not exist on bundle "product_kit" of entity type "commerce_product_variation". in Drupal\commerce\ConfigurableFieldManager->hasData() (line 119 of modules/commerce/src/ConfigurableFieldManager.php).
Drupal\commerce\EntityTraitManager->canUninstallTrait(Object, 'commerce_product_variation', 'product_kit') (Line: 77)  . . . . more (for Product_kit)

For "uc_recurring" it throws the first one listed.
I did try adding the fields at /admin/commerce/config/product-variation-types/product_kit/edit/fields it took them for "products" but stated duplicates could not be used for the others, so I stopped.
However, with Devel / product generate it does not work. The default variation works fine, but these are tied to the imported products and I personally don't know what to edit to add the missing values to get the form to work and the only way to try now anything else is to start over with a new database and import again via upgrade using Commerce Migrate - which never worked right in the first place - because it left the text data field behind and is a bug it appears in in itself.
See https://www.drupal.org/project/commerce_migrate/issues/3044987.
Reference https://docs.drupalcommerce.org/commerce2/user-guide/shipping/enable-shipping-products
Does anyone know if there is a way to manually add these fields to these entities or otherwise fix this ??

A patch and code insert posted at comment 14 and 15 at
https://www.drupal.org/project/commerce_migrate/issues/3044987 partially solved this but for the text data field import still did not work to bring in the text


Disable editing of a node after it has been published Scenario:

A user can create a node (content type "story"). All story nodes that are created are unpublished by default.

I have a boolean field called "publish my story". Once this has been checked and saved the node is published using rules.

Question:

Is it possible to revoke a users ability to edit published nodes by using rules as I do not want them to change the story afterwards.

Yes, you can define dynamic rules in a custom module. See hook_node_access

Here's a sample implementation:

/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {
  if (
    // The $node argument can be either a $node object or a machine name of
    // node's content type. It is called multiple times during a page load
    // so it is enough if you perform the check once you get the object.
    is_object($node) && $node->type == 'story' &&
    // Operation on which you want to act: "create", "delete", "update", "view".
    $op == 'update'
  ) {
    // Check if the node is published.
    if ($node->field_published[LANGUAGE_NONE][0]['value'] == 1) {
      return NODE_ACCESS_DENY;
    }
  }
}


How can I programmatically flag a user? I am creating a new user programmatically in drupal7. At the time of user creation is there any way to flag the user automatically.
I am using flags module.
I tried in the hook_user_presave
function MODULE_NAME_user_presave(&$edit, $account, $category) {
$flag = flag_get_flag('name_of_the_flag');
$flag->flag('flag', $account->uid);
}

Have you checked that $account->uid exists? I'm not sure that a new user would have a UID inside of hook_user_presave(). You may want try setting the flag in hook_user_insert() instead. Also worth making sure that users are allowed to be flagged by your flag type.


looping over images in an image field I have an image field which lets the user input as many images as they want. (set allow number of values to unlimited in field settings) I'm creating a twig template where i want to loop over these images and apply specific style if it's the first image or set a different style if its any other image.

I know I can use {{ file_url(node.field_home_hero.entity.fileuri) }} to get the url of the image in an image field. I'm trying to get this for every image in my field now though which is proving to be a challenge.

I'm curently iterating over the field in twig as so:

{% for image in content.field_field_name %}
  {% if loop.first %}

  {% else %}

  {% endif %}
{% endfor %}

But doing the above does not load up the images for me. I know for sure I'm messing up with the access somewhere but not able to figure out what i'm doing wrong. If someone could point me to the right direction that would be great!

If you want to access the file uri in the node you have to iterate over the field in the node:

{% for image in node.field_image %}
  {% if loop.first %}

  {% else %}

  {% endif %}
{% endfor %}


How to get list of installed/enabled modules ready for repopulating new site with drush module installation? When doing drush pm-list I get a whole list of modules but too much info also, like this:

Mail               Privatemsg filter (privatemsg_filter)          7.x-1.4
Mail               Privatemsg Limits (privatemsg_limits)          7.x-1.4
Mail               Privatemsg roles (privatemsg_roles)            7.x-1.4`

I have to edit in notepad++ and run macros...

I want the module list, but ONLY drush module names X_Y

Is there a way to get a clean list like:

module_a
module_b
module_c

ONLY

And then can use it as:

drush en module_a module_b module_c

drush pm-list --status="enabled" --pipe

  --status="enabled" Filter by extension status. Choices: enabled, disabled and/or 'not installed'. You can use multiple comma separated values. (i.e. --status="disabled,not installed").
  --pipe Equivalent to --format=list.
  --format="list" Select output format. Available: table, csv, json, list, var_export, yaml. Default is table.


Is it possible to append Media's file browser to a certain node type? I have a certain node type with a canvas on it, allowing users to draw on the node. Basic functionality such as lines are working, but I'd like to allow people to upload images to it as well. Since the rest of the site is using the Media module (V2 dev), allowing users to browse the library and their personal uploads... I was hoping to be able to use it here as well.

The same question was posted as a support request in Media issue queue as well but so far there is no reponse: https://www.drupal.org/node/2423415

What I am looking for is a way to embed the media browser on the node and catch the path of the returned file so the JavaScript and the canvas can read it.

So far I've managed to add the media widget to the node with:

function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'mytype') {
    $form = drupal_get_form('mymodule_media_form');

    // append a new field to the content
    $node->content['imageupload'] = array(
      '#markup' => drupal_render($form), // and render the form there
      '#weight' => 10,
    );
  }
}

function mymodule_media_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media-widget',
    '#title' => t('Image'),
    '#description' => t('Upload a file'),
  );
  return $form;
}

It shows the Media file upload button, but the dialog does not popup (due to missing JavaScripts I suppose). Is there a better way to load this field with all required JS etc? I do suppose I need to at least use hook_form() assuming I can't display a form field outside form context.

It appeared I had been using the wrong form element. My custom form was created as below:

function mymodule_file_upload_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media',
    '#title' => t('Choose an image'),
    '#description' => t('Choose an image'),
    '#tree' => TRUE,
    '#input' => TRUE,
    '#media_options' => array(
      'global' => array(
        'file_extensions' => 'gif jpg jpeg png',
        'file_directory' => 'conferences',
        'types' => array(
          'image',
        ),
        'schemes' => array(
          'private' => 'private',
        ),
        'enabledPlugins' => array(
          'upload',
          'media_default--media_browser_my_files',
        ),
      ),
    ),
  );

  return $form;
}

And then with some javascript I manged to get the fid of the file

$("form").on("change", "input.upload", function() {
  var val = $(this).val();
  $.ajax({
    url: Drupal.settings.basePath + 'draw/file/' + val,
    success: function(data) {
      src = data
    }
  });
});

That path was registered in hook_menu() to return the path of the private file as per:

function mymodule_menu() {
  $items['draw/file/%file'] = array(
    'page callback' => 'mymodule_page_file',
    'page arguments' => array(2),
    'access arguments' => 'view own private files',
  );
  return $items;
}

function mymodule_page_file($file) {
  global $user;
  if($user->uid == $file->uid) {
    echo file_create_url($file->uri); // Use echo to prevent theme to appear.
  }
}


Sorting orders by name rather than by order number On my orders page you can search orders by order number only - how do I change this so I can also sort by name, date, ect. When we have customers come in that do not know their order number, we cannot search for their name! The name column on our orders table also does not sort correctly, you can sort by most recent or oldest date, but you cannot sort names alphabetically. Not sure how to change this. Thanks!

Assuming you are using views to build your table, take a look at the table settings. In there you can set default sort, and there is a checkbox to make columns sortable.


Testing upgrade to PHP 7 I have upgraded to PHP 7.1 on my local dev environment and my Drupal 7.59 site with CiviCRM 5.1.2 seems to be working just fine. I can't find any issues. I am wondering if there is a way in the CLI to check the compatibility of all enabled contrib modules or if I need to look each one up and/or just test extensively to see if anything isn't working.

At this point assuming your site doesnt make use of extra modules, you can likely assume 7.x php works fine. I have found in numerous sites in the last few months that moving to php7 went fine and most php 7 were squashed in popular D7 modules in the last year or two.

If you have alot of custom modules you could try running a php 7 linter from github to check modules for php7 related issues, rather than trying to live-test drupal itself.

Something such as this github repo:
https://github.com/wimg/PHPCompatibility


Get currently logged in user I am facing an almost similar problem whereby if I do:

$userCurrent = \Drupal::currentUser();
$name = $userCurrent->getUsername();

I get the site account name instead of the logged in user. Which is the right way to get the logged in username or roles for that matter. I even tried:

$user = Drupal\user\Entity\User::load($userCurrent->id());

But all this does not seem to work.

Any suggestions?

Try this

<?php
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// get field data from that user
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;

$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;
?>

Or

$uid = \Drupal::currentUser()->id();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getUsername();

You will get more details about User::getUsername.


Accessing html.tpl.php variables from outside The Drupal 7 has it's default html.tpl.php looking similar to this:

<!DOCTYPE html>

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

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

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

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

How can I access those variables ($styles, $scripts, etc.) from outside the html.tpl.php? (suppose from page.tpl.php)

Thank you in advance!

Direct answer to your question - you can populate the variables you need by emulating the same functions that the processing function for html.tpl.php uses to render the page:

http://api.drupal.org/api/drupal/includes%21theme.inc/function/template_process_html/7

function template_process_html(&$variables) {
  // Render page_top and page_bottom into top level variables.
  $variables['page_top'] = drupal_render($variables['page']['page_top']);
  $variables['page_bottom'] = drupal_render($variables['page']['page_bottom']);
  // Place the rendered HTML for the page body into a top level variable.
  $variables['page']              = $variables['page']['#children'];
  $variables['page_bottom'] .= drupal_get_js('footer');

  $variables['head']    = drupal_get_html_head();
  $variables['css']     = drupal_add_css();
  $variables['styles']  = drupal_get_css();
  $variables['scripts'] = drupal_get_js();
}

So to access the styles variable, you would just need to call the same function the template engine is using:

$mystyles = drupal_get_css();

However - just to check, these values are already on your page because the html.tpl file is a wrapper for page.tpl.php. Sure you want to print it twice?


Authenticated users can not see own Ubercart order detail Using Drupal 7, Ubercart 7.x-3.10.

A user purchases product, gets a user id and logs in. He clicks on Orders tab in My Order History and sees the last order. But, when he clicks on the order number or View order icon, he gets HTTP 500 error (not access denied) instead of seeing order detail.

As admin, I can click on same link and see order detail.

In permissions, Authenticated user has checked:

View own orders
View own invoices

They can see uc_orders_user view /user/606/orders but get page not found error when they click on link to view individual order /user/606/orders/15. Oddly enough, Print order user/606/orders/15/print does work.

Rebuilt permissions, same error.

In order settings, admin/store/settings/orders, I use the Customer On-site invoice template, but I don't see any options to allow users to view orders/invoices (as referred to in this answer to similar question: User cannot view their Orders in Ubercart)

Any suggestions?

I found the offending code. It was the code for a block to display a link to "My Orders" if the user had any orders. I removed this code from the block, and the order detail now displays for authenticated user.

The offending code:

global $user;

$uid = $user->uid;

// print 'This is my user id ' . $uid;

        $count = 0;
        $args = array($uid);
        $view = views_get_view('uc_orders_user');
        $view->preview('page', $args);
        $count = sizeof($view->result);

// drupal_set_message($count);

  if ($count > 0) {
    return TRUE;
  } else {
    return FALSE;
  }

Do not know why this code causes the error, but it does.  If I find a way to tweak it to work, I'll post it here.


Externally Requesting Browser Test Created URL for Relaxed Replication I am trying to write a browser test for for a workspace replication via relaxed web services using the multiversion, replication and relaxed modules. For this purpose I set up an external Drupal installation as a content repository to clone from.

The content repository is installed locally and is reachable as I have tested it with an other Drupal instance as a replication target.

My problem is that the Drupal instance created by the browser test always gives me a 404 error once I try to reach it like follows:

\Doctrine\CouchDB\CouchDBClient::create([
      'url' => 'http://replication_user:password@browsertest.url/relaxed/live',
      'port' => 80,
 ])->getDatabaseInfo('live');

The local url and WorkspacePointers are set up correctly and the rest resources are also active. I even have a custom Drupal profile which activates all needed services and writes all configs for this functionality to work and it is being used by dozens of sites, but using relaxed replication in a test (even with the working profile) seems impossible…

I found the answer. To target the current test instance in a request one needs to set the http  client user agent header to drupal_generate_test_ua(drupal_valid_test_ua()).


Print five star ratings and reviews I am using Fivestar rating in custom print. See image:

I'm trying to print a fivestar as follows:

$your_average = $variables['result']['node']->field_rating['und'][0]['average'];
$your_maximum = "100";
print theme('fivestar_static', $your_average, $your_maximum);

But, I'm getting the following error:

  Fatal error: Unsupported operand types in /var/www/html/book1/includes/theme.inc on line 1088

Any suggestions?

Looking at the definition of fivestar_static theme-function in fivestar.module file under fivestar_theme(), you need to provide the theme function with an array including the following keys: rating, stars, tag. A working example should look like:

$fivestar_variables = array('rating' => $your_average, 'stars' => $your_maximum);
print theme('fivestar_static', $fivestar_variables);


Views "post" filter (complex query) I have a View (let's call it A) that gets the 4 more recent nodes of type News. The News node has a boolean field called IsImportantNews. Since I render the most recent important News (IsImportanNews = true) in another View (B), I'd like to filter out from View A the most recent important News that I already shown in View B.

Eg:

News1 -> date: 02 Mar 2013, IsImportant = false
News2 -> date: 01 Mar 2013, IsImportant = false
News3 -> date: 25 Feb 2013, IsImportant = true
News4 -> date: 21 Feb 2013, IsImportant = false
News5 -> date: 19 Feb 2013, IsImportant = true
News6 -> date: 11 Feb 2013, IsImportant = true

I'd like to show the News3 in the View B (and I can do that easily).
I'd like to show News1/2/4/5 in the View A, somewhat filtering out the News3.

Is there a way to do that? I thought about taking the 5 more recent News and than apply some php code to filter out the unwanted News but I can't seem to find a place to put that code without writing a new module. Is there another way to do that?

hook_views_pre_render() would enable you to filter out results after the query has already been run. Keep in mind that the results that are filtered out are still part of the query, with all the performance ramifications of that. Putting that in a custom module would be how I would do that.

If you don't want a view that's just a filtered version of the IsImportant == TRUE view, you could clone the first view and create a similar one whose only difference is that it returns four more results than the IsImportant == TRUE view. You could then add whatever filtering logic you want, and then limit the display to a certain number of items before rendering.

You may also want to take a look at the Peek Summary module, since it gives some further granularity to number of results returned beyond what Views alone offers.


After enabling repeat date on node, calendar won't show repeated dates I made a calendar view that displays all my events. When I created the view the content type Events wasn't enabled for repeating dates.

But now I do want repeating dates, so I enabled the repeat date modules en settings in the content type.

So when I input repeated dates it shows correctly in my node buildmodes but it doesn't show the repeats in my calendar only the first one. Can I still change the calendar to display repeated dates?

Thanks in advance

UPDATE

There's an issue in the date module
The last solution is for drupal 6 I think because I can't find Global Settings of 'Number of values as 1' in Drupal 7
http://drupal.org/node/1391464

solution

I had to delete my field_event_date and recreated to be repeating
I only lost my dates instead of my full nodes.

After deleting and recreating the date field on your content type (as in the Original post), re-add it to the list of fields in the Views context filter (Date: date(node)).


Use a search bar (exposed filter) to search for different node fields I am trying to make an advanced search with exposed filters and views in drupal.

I am trying to achieve the following:

On the left textfield, the user would input whatever he wants to search, and the views will only search by the field selected in the list at the right (field_A in the picture example). (In short, the column by which to search would be the one selected in field to the right)

NOTE: field_A, field_B, etc, would be all from the SAME node type.

I can make it work easily if I only have 1 field to search by (this field is set by interface when you configure the autocomplete functionality in drupal).

What I want is to be able to dynamically supply the field to search by, because said field will depend on what the user chooses from the combo box at the right (as explained in the note, this combo box will have different choiches field_A, field_B, field_C....etc).

Would it be better to create a custom module instead of using Views with exposed filters?

Thanks.

Views with exposed filters, and then a bit of custom js should do the job fine.

Basically loop over the fields that are there and use them to build a select so users can choose which field to search. The existing fields names relate to the query string key that we need to use.

Something like this should suffice:

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

      // Build the HTML for the new field we are adding.
      var newField = '
';
      newField += '<input type="text" class="form-text" maxlength="128" size="30" value="" name="combined-search-text" id="combined-search-text">';
      newField += '<select id="combined-search-field">';

      // Loop over the existing widgets to add options to our new select.
      $('.views-exposed-widgets .views-exposed-widget').each(function(){

        var title = $(this).find('label').text().trim();
        var value = $(this).find('input').attr('name');

        if(title && value) {
          newField += '<option value="'+value+'">'+title+'</option>';
          // This this widget
          $(this).hide();
        }

      });

      newField += '</select>
';

      // Add our new field.
      $('.views-exposed-widgets').prepend(newField);

      // Create a submit function for the views search form.
      $('.view-filters form').submit(function(e){

        // Stop the form doing it's default action.
        e.preventDefault();

        // Build the new URL.
        var baseURL = window.location.protocol + '//' + window.location.host + window.location.pathname;
        var field = $('#combined-search-field').val();
        var text = $('#combined-search-text').val();

        // Off we go...
        window.location = baseURL + '?' + field + '=' + text;

      });

    }
  };

})(jQuery);

Further work that needs to be done:

Check if there is already a search argument in the query string and set the default value of the custom search field and select.


Issues with the entity field output Suppose, we have an entity "song", that has a required field, called "authors":

In the list of songs in the admin panel I want to output the list of all the authors in the search block:

//search form
$form['search'] = array(
  '#type' => 'fieldset',
  '#title' => t('Basic Search'),
  '#collapsible' => TRUE,
  '#collapsed' => !empty($search_term) ? FALSE : TRUE,
);

//song name
$form['search']['search_text'] = array(
  '#type' => 'textfield',
  '#title' => t('Search Term'),
  '#default_value' => !empty($search_term) ? $search_term : '',
);

//authors
field_attach_form('song', null, $form['search'], $form_state, NULL, array(
                      'field_name' => 'field_authors',
                      ));

//submit button
$form['search']['search_submit'] = array(
  '#type' => 'submit',
  '#value' => t('Search'),
);

In the output I get this:

How can I make the checkboxes group non-required for the search form?
Why is the order of the fields broken? I added authors before the submit button, but in the output it's below the button.

If I may, you're not doing this in the most optimal way.

The best solution would be to implement hook_views_data(), and describe your custom entity's base table to Views. Then you can use Views to build your page through the UI, and all of your entity's properties and fields will be available to output as fields, filter by (exposed or not), and sort by.

You get all of the flexibility you're used to with Views for nodes, and it's easy to write custom field/filter/sort handlers for your custom properties if they need a bit more functionality than the default.

To answer your original questions (in case you don't want to go down the Views path):

Remove the required attribute after the call to field_attach_form(), e.g. unset($form['field_foo'][LANGUAGE_NONE]['value']['#required']);
The order isn't broken, it's exactly what you've asked for. If you want the fields to appear before the search, but field_attach_form() before the definition of $form['search'].


Permission Drupal folders I create a  website  on Linux/Apache and I want move it to Windows/IIS 6  here , my panel is Plesk.
I can't upload files and images and my Images that customize with Imagechach module not shown!
I guess folder permission not trust.
where I can find a list of Drupal folder permission?I don't know how to set permission in Plesk,Please help me ..!? :(

Most directories and files in a stock Drupal environment just need read/execute for the IIS user - this allows IIS/PHP to read and execute the .php, .inc, and other files. For your "files" directory - typically in sites/default/files - IIS will also need write permissions, so it can write uploaded files and create new files (for instance, ImageCache derivatives).

As for how to do this in Plesk, it will vary, but here's a guide that should get you pointed in the right direction (depending on your host, some of the user/group names may differ, but should be close):

http://knowledge.3essentials.com/web-hosting/article/478/Setting-file-folder-permissions-from-Plesk-control-panel-for-Windows.html


Create a Ubercart Drupal site to sell memberships? I want to create a website to sell licenses (not software licenses).
Basically, these licenses are sold in the form of packages for, say, package of 1 license or package of 2 licenses.
If a user comes to the site and buys a package with n number of licenses then n number of Drupal users will be created.

The created users can have different role types to allow different content to be accessible for different users.

Is it possible to achieve that with some Drupal 7 modules?

I did some research and found that it is possible to sell roles/subscriptions using the Ubercart module but I don't know how to create users that way -- with different roles after buying license package(s).

I was also trying to do this fairly recently.  Found a nice tutorial on Site Membership and Ubercart from Torontowebsitedeveloper.

https://www.youtube.com/watch?v=vbeqlNjBvwQ


How to set #value to the form item from HTML data-*? In product.tpl.php I have a code like this:

<div class="paint-order" data-pid="<?php print $node->field_product_ref['und'][0]['product_id']; ?>">

With JQuery I can get this product_id with this code:

var paint_id = new Number($('.paint-order').data('pid'));

I create ctools popup form, and want to fill #value of form element

$form = array();
$form['form_wrapper']['buy_art_buy_one_click_product_id'] = array(
  '#type' => 'value',
  '#value' => (string) htmlspecialchars(insert ['product_id'] here),
);

What I must to use instead of 'insert ['product_id'] here' to get value of data (or other) HTML-attribute?

I solved this task with Drupal.behaviors in js-file

like that:

Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
        var paint_id = new Number($('.paint-order').data('pid'));
        $(context).find("[name='mymodule_product_id']").val(paint_id);

    }
}


How to fix active-class problem in minicalendar with calendar / exposed filters I have a calendar view for events. The events are categorized by taxonomy terms. I use the minicalendar for the selection of days and filter the result list with an exposed list of the categories.
This is all working fine.
But user interface lacks a bit of coherence. There's no indication of which day is picked on the minicalendar (which only has a class for "today").
This snippet helped me getting an "active" class for the datebox, so users can see, which date they have chosen:
<?php
function YOURTHEME_preprocess_calendar_datebox(&$vars) {
  $url = $vars['url']; // The (absolute) URL of the item.
  $current = url(request_path(), array('absolute' => TRUE)); // The absolute URL of the page being viewed.
  if ($url == $current) {
    $classes = explode(' ', $vars['class']); // Extract the current classes as a list.
    $classes[] = 'active'; // Add 'active' to the class list.
    $vars['class'] = implode(' ', $classes); // Concatenate and attach the updated class list.
  }
}
?>

But here's the problem: when i select a taxonomy term, the url changes from:
/myview/2014-11-27

to
/myview?field_category_tid_selective=8 (e.g)

and my active class is gone.
How can i achieve that the class stays, even when a filter is active on the results?
Any help appreciated!
Thx

Try next, that work without using urls, using second argument:

function YOURTHEME_preprocess_calendar_datebox(&$vars) {
  $arg = arg();

  // If no second argument provided - that's mean today.
  // Please check how argument date supplied for next day: 2014-12-01 or 2014-12-1 and change date() to appropriate.
  $url_date = empty($arg[1]) ? date('Y-m-d') : $arg[1];

  if ($vars['date'] == $url_date) {
    $classes = explode(' ', $vars['class']); // Extract the current classes as a list.
    $classes[] = 'active'; // Add 'active' to the class list.
    $vars['class'] = implode(' ', $classes); // Concatenate and attach the updated class list.
  }
}


Views: Highlight today's post based on previously referenced node I have a weekly recipe list view, I manually create the list at the first day of the week.

for instance I assign Node 1 for Reference field labeled with Monday, Node 2 for Tuesday and so on using reference field in my Weekly content-type.

Next I made a page views of Weekly nodes and show the last node which contains that 7 referenced nodes previously mentioned.

What I want to do is to somehow determine today's date and change display mode of today's node along with Views Sort, like that if today is Sunday, the node referenced in Sunday field becomes highlighted and shows on top of the list.

Is there anyway to manage this using views, display suite or any other way?

From what I understand your page view only displays a single (the last one) weekly node that in turn displays the fields with references. If this assumption is correct, what you can do (and what I would do in this case) is to create a node--weekly.tpl.php file in your theme folder based on node.tpl.php. Here you will be able to get the current day of the week in PHP. Based on that, use render() to display the reference fields in the order you wish, while adding the required html and css classes to make the current day highlighted.

More information about theming individual content types can be found here: https://www.drupal.org/node/17565

I don't know what's your experience with theming, but if you need help with the actual template, let me know.

[later edit]
You can of course use a separate display suite template if you don't wish to override the general template of the weekly node. It's the same principle, but instead of having a node--weekly.tpl.php, you will have something like this: https://www.drupal.org/node/1098068 I think that the custom display suite layout involves a bit more work, but I may be wrong. Depending on your particular use case and how do you plan to display the "weekly" nodes across your website (e.g. if you will always have the same template or use multiple ways of displaying it), then you can choose one approach over the other. Both of them can help you accomplish what you need.


The send function does not work in a custom form I have a module that creates a form in a block with a template.
But when I press the submit button, it does not execute the submitForm function.
Instead if in the template only {{form}} if you do.

To clarify, in the template the fields are customized and I call them: {{form.date}}, {{form.submit}}

/**
 * {@inheritdoc}
 */
public function getFormId() {
    return 'custom_form';
}

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

    $form['name'] = [
        '#type' => 'textfield',
        '#size' => 60,
        '#placeholder' => 'Votre nom',
        '#maxlength' => 128,
        '#required' => TRUE,
    ];

    $form['tel'] = [
        '#type' => 'number',
        '#default_value' => "",
        '#placeholder' => 'Votre numéro',
        '#size' => 20,
        '#maxlength' => 20,
    ];

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Réserver'),
        '#button_type' => 'primary',
    );

    return $form;
}

 /**
 * {@inheritdoc}
 */
 public function submitForm(array &$form, FormStateInterface $form_state) {

foreach ($form_state->getValues() as $key => $value) {
  drupal_set_message($key . ': ' . $value);
}
 }

You have to write the submit handler for the form to save data.

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Insert queries.

    $query = \Drupal::database()->insert('mymodule_table');
    $query->fields([
      'name' => $form_state->getValue('name'),
      'tel' => $form_state->getValue('tel'),
    ]);
    $query->execute();

  }


Create view of child terms below parent term and how many nodes are tagged with those child terms I have a content type called 'schools' and I have a vocabulary called "destinations" that contains:

-USA
-- New York
-- Miami
-UK
--London
--Manchester

I have 2 school nodes that are tagged with "New York" and "Miami", respectively. So:

School 1: Terms tagged with from "Destinations" vocabulary: "USA",  "Miami"
School 2: Terms tagged with from "Destinations" vocabulary: "USA",  "Miami"
School 3: Terms tagged with from "Destinations" vocabulary: "USA",  "New York"

I want to show a view on the top country level page. So on the USA page I want to show:

City: New York
No of Schools: 1
Name of School: School 3

City: Miami
No of Schools: 2
Name of School: School 1, School 2

I know how to create a view to show me the city name using a contextual filter: Taxonomy term: Parent term. But is there a way I can get the other two things to show: count of schools and name of schools? In the same view..

The problem with your question is that you want to use both Aggregated and Grouped data in the same Row.

Additionally you want to show more than one School in the same Views row, while the Title isn't a multi-value field, you're not linking Schools from Terms but Terms from Schools.

You can use an additional module to achieve that: Views Field View, although it may be performance heavy.

You can easily create a View that would display either one or the other case:

  City: New York No of Schools: 1
  City: Miami No of Schools: 2

To achieve that see my answer here: Create a Term Queue on views only instead of adding a Sorting criteria you add Content: Title under Fields and set it to Count Distinct under Aggregation settings.

Or this case:

  City: New York Name of School: School 3
  City: Miami Name of School: School 1, School 2

To achieve that follow that same procedure only don't use Aggregation and under Format select the City field as a Grouping field. You can achieve many different layouts with clever Format settings and overrides.

To combine these two views use the Views Field View module to insert the second View into the First one and use the City field as an argument that you pass to the second View.

So the first View would have a Contextual filter for the Country (the first level of Taxonomy), and the second View would have a City Contextual (second level) or something along those line, depending on your particular configuration.

You should first aim to build those Views separately and make the Contextual filters work, then use the Views Field View to combine them.

Another way to go about solving this is mentioned in the Answer I linked to: Use Views Summary to display Terms with node count, then when you click on the term it takes you to actual Views results page showing nodes for that term. This is a two-step process but it may be acceptable to your visitors and it's easy to set up.


Why does aggregator report "There is new syndicated content" but still 0 items for this feed? We've had a working feed aggregator running for quite some time now (over 12 months) from a YouTube feed link (http://gdata.youtube.com/feeds/base/users/[username]/uploads). We just recently noticed that there are no items displaying in this feed's block. Upon visiting the feed configuration page (admin/config/services/aggregator/edit/feed/[feed-id]), I can see that there are 0 items in the feed. Running the feed manually reports "There is new syndicated content from YouTube.", but there are no items created. The dblog shows an entry from the feed aggregator with the same message, but no error messages.

Has anyone experienced this or have any ideas on where to troubleshoot? Without any actual errors I'm unsure if this is a bug, works-as-designed, or potentially something wrong with YouTube's feed. I've validated the feed on a couple of websites and there are no (apparent) issues with it.

I have just been experimenting with the aggregator and come across the same issue. The only workaround that I have been able to find in order to pull content from the RSS feed in issue has been to use the Feeds module. If you are still having this issue then this is a possible solution.

EDIT: Just found a far simpler solution for the problem. By default the aggregator deletes items older than 3 months and 3 weeks from the feed. If the youtube feed you are subscribing to has not had new content added in that time then you may get the situation you describe. If that is not the case then go with the first option I suggested. Otherwise you can change how long Drupal keeps the feed items in the Aggregator settings tab.


Printing the last 6 characters of a field into a confirmation email I have a booking system set up using Rooms.

The customer enters their phone number on checkout, which is a 5 number area code, followed by 6 other numbers. E.g. 01234 567 890.

The rooms at the hotel have a secure pin pad entry which is set to the last 6 digits of their phone number for their arrival.

As far as I can see there are two ways of doing this.

Replace the phone nunber field with two fields, one for area code and one for the 6 digits, then send the 6 digits to the customer in a confirmation email. The only downside to this will be the existing customer phone numbers in the database will not fit the new fields, and also the validation of phone numbers used in the "Phone Number" module will not work for a split field.
Create a way to only print the last 6 digits of the data in the phone number field. This seems like the best option, as it doesn't involve me having to edit the data for current bookings.

Can anyone explain to me how I might achieve option 2? Printing the last 6 digits in views etc would be easy enough, but I need to print the last 6 digits into an email template, and then send that email with rules.
I have a token for [commerce-order:commerce-customer-billing:field-phone-number] that I can put into the confirmation email. Is there a way to trim the output of a token?

You could probably use the rules module with the "Execute custom PHP Code" option to execute a small php substr function.

You might need to enable the php filter module for this.


PHP code to display block based on list (text) field Drupal 7. I'm trying to display a block using the "Pages on which this PHP code returns TRUE" feature. The field is a single value list (text) named field_display_block so all I want to do is determine if field_display_block is set to "1".

I'm sure there are a couple of ways to do this. Any help on this would be greatly appreciated.

Thanks

Les Z

With the following script you can check the value and return true. I've added my comments before each line.

// First check if the current page is a node
if ($node = menu_get_object()) {
 // Then, check if it is your content type
 if ($node->type == 'your_content_type') {
   // Get the value of your field
   $display_block = field_get_items('node', $node, 'field_display_block');
   // If the field's value is equal to 1, then return true
   if ($display_block[0]['value'] == '1') {
     return TRUE;
   }
  }
}


How can I create a GET form with the Form API? I have been struggling with the Drupal 8 Form API all afternoon. It seems that the API is not meant to create GET forms, while the comments state otherwise. I am trying to build sort of a filter-form that should pass it's parameters to the URL so that it can be bookmarked, etc.

My first problem is that the FormBuilder->getForm($myForm) method creates a FormState object that defaults to method POST. Even when I set my form's method to 'GET', the FormState object will check the request method before the form is even being created and since the requestmethod is GET and the FormState's method is POST it will not process anything at all.

So instead I tried to create my own FormState object (which I obviously set to GET) and call buildForm instead (that way bypassing the getForm logic):

$form = new MyForm();
$form_state = new FormState();
$form_state->setMethod('get');
$form = \Drupal::formBuilder()->buildForm($form, $form_state);

This seems to work better. However, as soon as I give my form a submit-button it then gets in some sort of redirect loop, which I haven't been able to pinpoint yet.
I don't have such problems when using POST.

It's really weird that the API doesn't seem to be able to handle GET forms.

Also:
Would I get this to work, the comments in the Form API code state that GET forms do not use a form-ID, however the FormInterface does require a getFormId method.

Could someone please clarify what I am doing wrong, or point out some documentation about this?

A proper example

I decided to simplify my testscenario a lot, in order to make sure that I wasn't doing anything weird. So now my testscenario is as follows:

I created a simple module with a hook_preprocess_node. There I render my form and add it to the template:

<?php

use Drupal\my_module\Form\TestForm;

function my_module_preprocess_node(&$variables) {
    $form = new TestForm();
    $variables['test_form'] = \Drupal::formBuilder()->getForm($form);
}

My form is as simple as I could make it:

<?php

namespace Drupal\my_module\Form;

use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class TestForm extends FormBase {

  /**
   * @inheritDoc
   */
  public function getFormId()
  {
    return 'test_form';
  }

  /**
   * @inheritDoc
   */
  public function buildForm(array $form, FormStateInterface $form_state)
  {
    $form_state->setMethod('GET');

    $form['test_input'] = [
      '#type' => 'textfield',
    ];

    $form['actions'] = array(
      '#type' => 'actions',
    );

    $form['actions']['submit'] = [
      '#name' => 'test-submit',
      '#id' => Html::getUniqueId('edit-submit-test-form'),
      '#type' => 'submit',
      '#value' => 'Submit it',
    ];

    return $form;
  }

  /**
   * @inheritDoc
   */
  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    // TODO: Implement validateForm() method.
  }

  /**
   * @inheritDoc
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    // TODO: Implement submitForm() method.
  }

}

Now my node template renders a simple form containing an input field and a submit button.
When I submit the form it submits using a GET-request and I see the fields appear as GET-parameters.
However the Drupal formbuilder does not pick up the form as being submitted. It does not call the validate nor submit methods.

The form contains both $form_state->setMethod('GET'); and $form['#method'] = 'GET'; as suggested in the comments.

I have looked at Views's exposed filters to copy the behaviour I want.
Views however manipulates the behaviour in several places. I created my own FormBuilder instead (which wraps around the core's FormBuilder) in order to get the behaviour I want.

<?php

namespace Drupal\my_module\Service;

use Drupal\Core\Form\FormBuilder as CoreFormBuilder;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\my_module\Form\AbstractForm;

class FormBuilder {

  /**
   * @var CoreFormBuilder
   */
  private $formBuilder;

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

  /**
   * @param $form AbstractForm
   * @param $method string GET|POST
   */
  public function getForm(AbstractForm $form) {
    if ($form->getMethod() !== 'GET' && $form->getMethod() !== 'POST') {
      throw new \Exception('Method must be either GET or POST');
    }

    /**
     * Other than core's FormBuilder, we provide a way to set the form's method to GET
     * Note that the getMethod()-method is not a default FormInterface method.
     * It is part of our own AbstractForm which implements both Drupal\Core\Form\FormInterface,
     * plus our own needed interfaces.
     */
    $form_state = new FormState();
    $form_state->setMethod($form->getMethod());

    /**
     * Because we remove the form ID's from the GET request,
     * we must set the form to always process.
     * And as a result of that, we must also disable the redirect,
     * or the submit process will become an endless loop.
     */
    if ($form->getMethod() === 'GET') {
      $form_state
        ->setAlwaysProcess()
        ->disableRedirect();
    }

    // Default behaviour copied from core's FormBuilder
    $args = func_get_args();
    // Remove $form_arg from the arguments.
    unset($args[0], $args[1]);
    $form_state->addBuildInfo('args', array_values($args));
    $build_form = $this->formBuilder->buildForm($form, $form_state);

    // Make sure that the form identifiers do not end up in a GET request
    if ($form->getMethod() === 'GET') {
      $build_form['form_build_id']['#access'] = FALSE;
      $build_form['form_token']['#access'] = FALSE;
      $build_form['form_id']['#access'] = FALSE;
    }

    return $build_form;
  }

}

By using this FormBuilder, it will:

remove form_id, form_build_id and form_token from the rendered GET-form, so that these won't be send to the GET request when the form is being submitted;
and because those identifiers are not there, the form_state will be set to setAlwaysProcess(), so that the form will be processed.


Best way to enter(insert) the content in drupal, so a non techie can edit the content I am some what new to drupal tho familiar with CMS tho drupal way is to put into views tho i dont see how best a non techie can edit such content what am i missing  thank you

Do you have a WYSIWYG editor installed for your end-users?

You can use CKEditor, or a number of other editors, and install as a module. Here is a walkthrough for installing CKEditor: CKEditor Quick Start,
 Or you can install the WYSIWYG module and choose from a handful of WYSIWYG editors to use on your site. By doing so, you would give your content editors a way to create content similarly to how we enter our answers and code examples here on StackExchange and your users will not need to know any html or code to get the job done.


block view is not displaying This problem starts with the subtheme. I am using drupal 7 with a subtheme based on omega 3.1.

For some reason node title and admin tabs are displaying only on the home page and two basic pages, while they do not appear on the rest of the website(articles, basic pages, custom type content).

I tried goggling and trying out different solutions but none of them were successful.

So I thought I could create a view block that would display only a node title. in the view I used contextual filters 'content: Nid', display 1 item, fields 'content: title'. By default auto preview does not display anything, when you insert a node number or a page name it displays it's title which means that the view works fine(as example when I enter '1' it displays 'About me' title).

After that I insert the block on a page by going blocks > configure for the block view > selecting the region in the sub theme I am using and in Show block on specific pages selecting 'Only the listed pages' and typing '1' as an example.

When I click save block and going to about me page I still do not see the title then check by inspect the page there is no html for the block view found.

To check weather the problem is not in the omega, I switch to bartik and select to display the block for bartik theme too, but still cannot see it on the page. The answer is probably something really simple.

Sounds to me like you have the 'Only listed pages' setting wrong.
I tend to use pathauto, so always have nice 'friendly' URL's, but I suspect you want "node/1" rather than simply "1" in the "only listed pages" field of the block config.

WRT your initial issue - are you using Delta? Regions may not be enabled for all delta's of the subtheme which could cause the initial problem.


managed_file #progress_indicator never finishes I've been beating myself up on this issue all week. This is my first time using file uploads in custom modules so I'm using managed_file.

Here's a snippet of it that's being used:

  $form['family_fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Family photo'),
    '#description' => t('Upload a family photo, allowed extensions: jpg, jpeg, png, gif'),
    '#upload_location' => 'public://families/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('png gif jpg jpeg'),
    ),
  );

The file upload works fine but the 'throbbing' ajax indicator never finishes and the customer is not happy. Looking around on SO I see that I must:

pecl install uploadprogress

And I have locally. Drupal in /admin/reports/status reports:

Upload progress Enabled (PECL uploadprogress)

No change, even after restarting apache 2.4 on ubuntu. The bad thing is that this project needs to go to Dreamhost shared hosting so I cannot install using PECL. They do point to where I can add "extension = uploadprogrevs" to my .phprc and I have. They have restarted but Drupal on DH does not see it. (FIXED: see edit) Regardless, I have to get some notification to the user that the file upload was successful.

Looking at file_managed_file_submit it describes the function doing a $form_state['rebuild'] at the end, which is ideal. But I don't get that. I don't want to hack a core function so asking around we tried a hook_file_presave($file):

function calendar_admin_file_presave($file) {
  drupal_set_message('File uploaded');
}

But no message at any point, esp. when user clicks "Upload".
We have tried hook_file_insert and it doesn't seem to work.

We have tried adding #process to the form array:

'#process'=>array('file_managed_file_process','_custom_file_process'),

with this functions:

function _custom_file_process(&$element,&$form_state){
if ($form_state['values']['family_fid']['fid']){
  module_invoke_all('file_presave', $file);
}

with no different result.

To further troubleshoot this drupal 7 app I set up a custom content type with a file field. It exhibits this same behavior locally. However, another Drupal 7 app on the same local server, same php 5.4.33 works as expected.

Even if I could get it to work on this app locally, I still will have an issue with Dreamhost shared server. So if I can get a notification to be done when a file is uploaded, I'd be OK. However it seems that Drupal in this app #uploadprogress is not working.

What else can I try to at least get a drupal_set_message inserted? thx, sam

One part of this is to get the PHP extension uploadprogress installed on Dreamhost and that is successful. Either we figure out why the drupal "callback" functions aren't working, or we can determine what could be causing this drupal 7 app to break this AJAX update when other Drupal apps on the same server don't have this issue?

Since you seem to be having trouble with javascript, you might check your install to see if you have the jquery_update module and check to see if it needs to be updated?


POST from external source I have external site that needs to POST my drupal site (it basically shares data). I need to take the POST data parse it and create a node from it. Is this possible? I have created a PHP file take_post.php this file receives the POST request, parses it creates a node object and then sends it to http://api/v1/node this works fine, though it seems a little long winded?

My problem is that if a post is deleted from the external system a DELETE request is send via HTTP, however the external system has no idea of what the node ID is, and at the point of delete niether do. Is there a way to delete a node without knowing it's NID, maybe via a custom field value?

The UUID field is what you are looking for. It stands for Universal Unique ID.

  The UUID is guaranteed to be unique and can be used to identify an entity across multiple systems.

-- from Entity::uuid


show content type fields from user on another content type I need to be able to show fields from one content type on another.

Example:

Article: basic title/body fields
Author Bio: User information (website, twitter and FB info, email, etc... fields)

Trying to create a block that will look at the NID, pull the node author and show the bio at the bottom of the node.

I tried using UID and NID as the contextual filter and author as the relationship. I also filtered to show only published and content type "author bio"

But when I try and use the auto preview, I get my labels with no data.

So I went into the individual fields, but there is no drop down to force a relationship to the node author like in entity references.

I am missing something, but I can't seem to find it. Any help would be appreciated.

Thank you.

I wonder if it may be better to just add all personal info fields to the User entity itself instead of creating a whole new Content Type (go to Configuration > People > Account settings and add fields such as website, twitter, etc to the user entity). Then simply create a view of articles and create a relationship to the user entity by choosing Content: Author. Then simply add user fields to your list of fields in the view. Am I missing something in your question? (it's not very clear). Let me know and I can edit this answer.

Edit after your comment: Since you are interested in providing these info fields to specific users, I would then explore the profile2 module, which allows you to add additional fields for certain users. You can create different profile types with different fields, and allow certain roles to have access to specific profiles. In your View you can create a relationship to Content: Author first, and then one to the profile, then add those profile2 fields to your list of fields in the view.

Otherwise, if you still want to do this with a Author bio content type, I would suggest that you add an Entity Reference field to the User, and then you can use that as a bridge to your Article. Let me know if you want more details on this.


How to set a "must be greater than a value" condition in Rules I need to check with the Rules module whether a field is greater than some value. To be more precise, if the size in cm of a product (the field size is created through the Commerce Physical module) is > than 5000.

How can I do this?  I tried to add a 'Data comparison' but i only get "equals" or "is one of" when i select the comparison operator. I would have expected an "is greater than".

Check what kind of field you have.  If you have an Integer field, "is greater than" and "is less than" will be available for Data comparison.  Perhaps you mistakenly set it to text?  If so, you may need to delete the field and create it again.


Dynamically indented text display I'm happy to say that I've succeeded in importing an Access database into MySQL and getting a table from it to show up in Views. Progress! Thank you for all the help I’ve been getting here to overcome the hurdles along the way.

So now, the first webpage I'm working on has a rather unusual HTML table on it that’s a bit of a hack and I wonder if Views is capable of making it or if I need to find a different way.

You could call what I’m trying to do a “dynamically indented text display.”

On the current website, the javascript that builds the main part of the HTML table looks like this:

'
' + (nLevel == 0 ? '' : ' 	') +
     '' +
          (sHeading  == '' ? '' : sHeading + ' ') +
          (sParty    == '' ? '' : '' + sParty + ': ') +
          (sURL      == '' ? '' : '' + sLinkText + '') +
          (sNotes    == '' ? '' : sNotes) +
          '	' +
     '
'

In the data table, every row has (a) a value of nLevel between 0 and 12, inclusive, and (b) either a value of sHeading or a value of one or more of the other text variables. Therefore, every row of the HTML table has either a heading or a text block, and whichever it is is indented by an amount controlled by nLevel.

Two elements of simple logical processing stand out there:

     The numeric variable, nLevel, determines the level of indentation by a pair of  tags in which the sum of the “ColSpan” parameters is 13. So there are 13 levels of indentation (from 0 to 12) across the page. (On the current page, the width of the indentations is set by 12 repetitions of “&nbsp;	” in the first row of the table.)
     A link is constructed from the variables sURL and sLinkText.

I see that Views allows for the calculation of a math expression in the construction of a table, but I don’t see anything that allows for this kind of programming there. So I’m thinking a Views table won’t work, unless there’s something I don’t know.

It’s possible that an HTML list could work if Views allows for nesting of lists, which would control the indentation. When nLevel increases from one row to the next, it always increases by one, so this gives the same behavior as “
” (plus a bullet, which I could live with). But still, I would have to be guiding Views programmatically in its placement of “
” and “
” tags, and I don’t see how I would do that.

Maybe now you can see why I was originally thinking of just translating the code from javascript to PhP and putting that directly on the page. The code is pretty simple, so that would be easy. (The part that I still don’t know how to do is how to connect to the database with a query to get the values of the variables above.) But when I posted my question about whether this was a good idea, I got some strongly worded advice that it’s usually a very bad idea to put PhP code directly on the page.

So what is the right way to get Drupal to do the kind of dynamically indented text display described above?

Thanks for your help.

depending on you exact set up (which you may be able to modify to suit), you could look into Views Tree module:

  This module provides a tree-based style plugin for Views. It is
  equivalent to the tree-based style template from Views 1.

  It is based off of the list style. Although it generates a nested
  view, there is still only a single query run for the view making it
  quite performant.


Conditional PHP works in Node Template but not in Views Custom Fields This code in my node template checks a CCK field and prints some text dependent on the value:

<?php if ($node->field_stock[0]['view'] == 'No' ) : ?>

Out of Stock

<?php endif; ?>

How can I do something similar with Views Custom Field's PHP filed type?
Thanks

If 'm not mistaken you are trying to move this logic out of your tpl.php template file by using views custom field.

You first need to get the name of the accessible fields with this code.

<?php print var_export($data, TRUE); ?>

Then you should be able input in the custom field something similar to this.

<?php if ($data->field_stock == 'No' ) : ?>

Out of Stock

<?php endif; ?>

There is more info here http://drupal.org/node/467190.