How do I check the entered quantity before the checkout phase in Drupal Commerce? How to check product quantity before checkout ?

I want to avoid the order if a required quantity is not reached.

Nota : I use Commerce Physical Product module.

You can use rules to change the quantity in a line item... so you could force the quantity up and output a system message. I don't know of a way to prevent them from checking out using rules.

So: Condition: Data Comparison: Line item: Product: SKU  equals XX
Condition: Data Comparison: Line Item: Quantity less than X
Action: System message explaining why we're increasing quantity
Action: Data Set Value: Set quantity to X+3

Update: this strategy might work for you.


Multiple relationships in Views Contextual Filters I use Views in every project, and its not that often that I run into a use case like this any more.

In the set up below, I have a Content type with two field collection fields (day guest and evening guest). I want to display the results of both field collection fields on the node, in the same view.

Both field collections share an "E-mail" field, and when a user enters their e-mail field, I want them to see their results, whether they have been added as a day guest, or an evening guest.

Here's the setup...

When I remove one of the two Contextual filters, the results show for the remaining field, and vice versa. But when both Contextual filters are added, I get no results.

Is there a way to do an AND or OR for Contextual filters?

Or in the Contextual filter options, a way to add multiple relationships like below?

While I know this is not possible in the default behaviour, it is a good example of what i'm trying to achieve, perhaps someone knows a decent workaround to the issue?

Use this module:  https://www.drupal.org/project/views_contextual_filters_or
it gives you posibility to achive your needs


Select address functionality during checkout for Drupal Commerce 2.x I am using Drupal Commerce 2.x for my e-commerce website. I have installed the Address module which provides functionality for storing, validating and displaying international postal addresses. I've added the field for the address in the user registration form through which I can accept multiple addresses from the user.
As per the default checkout flow, the user has to mention his address manually while entering shipping details. So, is there any mechanism where the user can select the address previously set by him? Or I have to rely on customisation to achieve this functionality?

There is a patch in progress to add this feature.

To apply the patch to the most recent version of Commerce (2.1 as of this writing), based on this comment, you can add this to your composer.json:

"drupal/commerce": {
      "reverse profileSelect change to allow PR 760": "https://www.drupal.org/files/issues/2844920-reverse-profileSelect-temp-fix.patch",
      "reuse profiles": "https://patch-diff.githubusercontent.com/raw/drupalcommerce/commerce/pull/760.diff",
      "reuse profiles enhanced": "https://github.com/fliegen/commerce/commit/57c11175d279fe55db9454b4274608195211aeb8.diff",
      "checkbox same as billing": "https://www.drupal.org/files/issues/checkbox-same-as-billing-2852207-69.patch",
  }
  "drupal/commerce_shipping": {
      "profile select enhancement": "https://github.com/fliegen/commerce_shipping/commit/797b5ef351851d60b2cb6c1a55837501c2a036a5.diff",
      "profile in shipping method widget fix": "https://www.drupal.org/files/issues/profile-reuse-enhanced-2908683-1.patch",
      "auto-recalculate shipping": "https://www.drupal.org/files/issues/commerce_shipping-autorecalculate-2849756-35.patch"
  }

You don't need to add the checkbox same as billing and commerce_shipping part if you are not collecting a shipping address.


How can I implement user timezone & user's last login in this format? Im trying to create a block and I'm  having trouble. I'm trying to get the user's last login & the user's timezone. How can I implement those functions in these hooks. All I know is the fact that I need to use the functions of hook_info & hook_view.

function hook_block_info() {

  $blocks[‘syndicate’] = array(
    ‘info’ => t(‘Syndicate’),
    ‘cache’ => DRUPAL_NO_CACHE,
  );

  $blocks[‘recent’] = array(
    ‘info’ => t(‘Recent content’),
  );

  return $blocks;
}

function hook_block_view_alter(&$data, $block) {

  if (is_array($data[‘content’]) && asset($data[‘content’][‘#contextual_links’])) {
    unset($data[‘content’][‘#contextual_links’]);
  }

  if (is_array($data[‘content’]) && $block->module == ‘some module’) {
    $data[‘contentr’][‘#theme_wrappers’][] = ‘mymodule_special_block’;
  }
}

You can use the global $user object to get user details, or load user details from a uid like this: $user = user_load($uid); From the $user->login property you can get last login timestamp.

Thanks


Failed SELECT value from Date field (single value) I've installed date module. the field data stored in field_data_field_date_start_rent. The field dont have multiple values

I want to select field_date_start_rent_value.

So, I'm testing SELECT it and UPDATE to other date field. It not works.

Below is the SELECT, but I'm using text field to UPDATE to see if it works:

$nid = $node->nid;
$startrent = db_query("SELECT field_date_start_rent_value FROM {field_data_field_date_start_rent} WHERE entity_id = $nid")->fetchField();
$endrentf = db_query("UPDATE {field_data_field_cubagan} SET field_cubagan_value = $startrent WHERE entity_id = $nid");
return $endrentf;

If using the same SELECT query on integer field, it works without problem. I think it must have something different in the SELECT query for date field.

It would be a lot easier to use a different set of API calls to do this, you can avoid having to manipulate the database directly:

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

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

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

// Save the node
node_save($node);

Just as an aside: you're not making the best use of the DB API at the moment, you should be using placeholders and provide arguments to db_query() rather than interpolating them directly into the query string. The equivalent of your SELECT statement written the recommended way would be:

$args = array(':nid' => $node->nid);
$sql = 'SELECT field_date_start_rent_value FROM {field_data_field_date_start_rent} WHERE entity_id = :nid';
$startrent = db_query($sql, $args)->fetchField();


Display only one book in Views I have several books with several pages on them.
I want to create a view to display page from a specific book. I'm pretty sure View can dop it but I don't find the way to.

Do you have any idea ?

You can add a filter on nid or title. If you want to, you can add a contextual filter (top right) and let the filter work with the url.


Why are the regions being highlighted when I mouse over on them? On each region hover over the region is highlighted with a background colour of light blue and the border changes to red.
I cant work out whats causing this (i'm a newbie).
Im using a base theme of ninesixty and only have a few additional modules installed.
Its not a browser addon as I see the same thing in firefox and chrome.

Please help!

This is a debugging feature that this theme uses. Disable this line (or similar) in ninesixty.info by adding a semicolon before it.

stylesheets[all][] = styles/framework/debug.css

Then clear caches for example on this page: admin/config/development/performance


hamburger menu moved after update We use we-mega-menu. After performing an update the mobile (hamburger) menu changed its alignment to the left as well as some other things I was able to fix the other things but I can't seem to figure out how to align the menu to the right within the container. Any ideas?

Looks like that styling is being driven by the flex display on div.region-we-mega-menu.
Creating a style that overrides justify-content: flex-start; to justify-content: flex-end; should do the trick.


Replace the date of a filtering criterion with "Views PHP"? I created a "like" flag on the nodes.

I created a comment view.

I want my view to show only comments posted since the flag date.

The solution will be to create a filter criteria with the filter "Comment: Publication date" (Is greater than or equal to) and replace the value with the date of the flag.

The problem is that there are no tokens for the filter criteria.

How to do this with "Views PHP" ?

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

Don't.

Views PHP or any other method of stored PHP is a bad idea (What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?). It's also extremely slow, because it usually involves loading all data and then doing all the processing in PHP.

Instead, build a module and define a views filter plugin there, then you can build the query there how you like it. How exactly to do that is IMHO too complex to answer in a single question, you should find plenty of examples and tutorials on how how to create views filter plugins (there are dozens of plugins in core alone), look for something similar to your use case and start from there.


login form generated by drupal_get_form('user_login_block') does not log in I have a custom module part of which builds a block with the login form

function my_module_block_view($delta = '') {
  switch ($delta) {
    case 'awsImage_public_info_forms':
      $user_login = drupal_get_form('user_login_block');
      $out = drupal_render($user_login);
      $block['content'] = $out;
      break;
    }
  return $block;
}

Form shows up on the page I have set the block to, BUT it will not log in. I can add and incorrect username / password and I'll get a drupal status error about the incorrect username, but when the login details are correct, it will not log in - the page will reload with "?destination=node/1137" - node/1137 is the node I am using the block on. Admin pages just show access denied.

I can log in via /user and there are no watchdog messages.

You shouldn't need to render the form, and this may be causing your problems. The output of drupal_get_form() is a render array, so you can use that directly. Try changing this:

$user_login = drupal_get_form('user_login_block');
$out = drupal_render($user_login);
$block['content'] = $out;

To this:

$block['content'] = drupal_get_form('user_login_block');

Also, are you doing anything else to the block with preprocessing or processing? Is the system rendering the block normally, or are you rendering the block in some different manner, with a template or something?


How to validate email on webform if the field type is textfield and you have data by mistake, on a webform, in the field e-mail we selected fieldtype = textfield instead of email type, no problem to change it if you do not have data, but if you have data, when you delete the field all your data is gone.
o
So the email field is NOT validate to enter just email addresses. How to validate this field without export and migrate the data?

After a couple days asking google for the solution, I did this.
1. Install the module  https://drupal.org/project/webform_validation
this will add another tab on your webform.
2. select "Regular expression, case-insensitive"
3. add the next regex (regular expresion)   ^[_a-z0-9-]+(.[_a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,3})$
4. select your email field to validate and add some text to the error message.
that's it...
from now on all your email will be validate,  but the old data must be fixed by hand...
the good thing, is you do not need to migrate your data just for  fix it..

hopefully this will be helpful to someone...
 best


How to send a newsletter to all email addresses attached to a content type? I have a content type (customers) having an email field (field_email). I need to create a newsletter using those emails that every certain period increase.

I try to use the module Newsletter but I must to re-enter all emails again and new email every time a new customer is registered.
Is there a way to import all emails from my content type, to list the newsletter module?

Unfortunately, it doesn't look like Newsletter supports that.

On the other hand, the Simplenews module has decent Rules support which may make managing your subscribers easier. As far as I know a user account isn't required to subscribe.

Off the top of my head, here is an example of a rule that might automatically add an email address to a subscription list when a new 'Customer' node is created:

IF
  (condition) 'After saving new content' (node is created)
AND
  (condition) 'Entity is of type' (node is 'Customer' type)
AND
  (condition) 'Entity has field' (node has 'email' field)
THEN
  (action)  'Set a data value' (get value of email field)
THEN
  (action)  'Subscribe an e-mail address to a newsletter'

(The full implementation is beyond the scope of this answer but there are plenty of other posts dealing with Rules.)

As for importing email addresses, in both of the 7.x branches there is a "mass subscribe" option at People > Subscriptions.


For "parent" node, how do I show list of child nodes related by child field of type "Entity Reference"? CONTEXT:  Let's say I have a one-to-many relationship between parent "companies" and child "contacts".  Each is its own content type.  The contacts content type has a field of type Entity Reference that can be used to associate a child Contact node to a parent Company.

QUESTION:  How, when I am on the display of an individual Company node, can I see a list of related contacts right beneath the Company node fields?

Essentially this functionality would be like a "related list" in Salesforce.

Surely there is a module or modules that enable this without having to resort to code?

I've seen the Views Field View module.  It looks promising.  The Panels module looks promising but apparently it is not just for use on its own; it just enables other modules.

Thanks in part to @Niall Murphy's response, I was able to find a Drupal Community Doc that got me further along, though I had to do some translation from Drupal-7 terminology to Drupal-8 terminology before I reached a solution/answer. I've updated the Doc accordingly so you can read it for the solution/answer details.

Note: No additional modules were needed. I was able to do everything with freshly-installed out-of-the-box Drupal 8.0.2 functionality.


Uber cart external payment system Now I working on project who need support some external payment systems (not PayPall or Google Chackout). I try search some tutorial/documentation about creation Ubercart payment system, but nothing found. So which way to look or where to start to solve this problem?

Basically, you need to create a custom module and let ubercart know about your gateway using hook_uc_payment_gateway(), then use hook_uc_payment_method() to define a payment method.
Then, you continue with defining a form that is used on checkout and finish it with creating redirect to your external payment system.

You can start with this - http://nmc-codes.blogspot.sk/2012/07/how-to-create-custom-ubercart-payment.html, it should give you a good start.


How do I pass field variables for a database insert helper function I am trying to set up a database insert helper function for a group of modules for a program I m using to learn Drupal.

I can't figure out how to use my returned array in my db_insert query, can anyone assist please.

I assumed I could use a for loop as below but that's not working for me, I really appreciate any help you can offer

function my_db_insert($table, $fields) {

// Build up a string based on my returned array via a for loop
$insert_fields="";
foreach ($fields as $key=>$value) {
    $insert_fields = $insert_fields . $key . "=>" . $value . ",";
      //drupal_set_message($key . "=>" . $value . ",");
   }

  // Insert into the database.
$id = db_insert($table)
->fields(array(
  //This is where I need put the result of my array so it will add to the database
  $insert_fields
))
->execute();

return $id;

drupal_set_message(t("Record Added!"));

}

This was answered on the drupal.org forum by @Jaypan:

$id = db_insert($table)
  ->fields($fields)
  ->execute();


How to add 'odd' or 'even' class in each row of a Views Table output? I'd like to take advantage of Drupal's default CSS for even/odd rows in a table.
I use Views to list the content of a custom entity with 'Table' format.
I don't know where to put this setting...

Thanks in advance

P.-S. I use Drupal 8 (8.1.2)

This can be related to Drupal, since you want to add classes to table rows, here is how you do it:

Copy the core/themes/classy/themplates/views/views-view-table.html.twig to your theme's template folder, and change the following lines (line 95):

  <tbody>
    {% for row in rows %}
      {% set parity = cycle(['odd', 'even'], loop.index0) %}
      <tr {{ row.attributes.addClass(parity) }}>


How can I set up a Drupal rules action to play a specific sound? I would like set a sound alert as a Drupal rules action- for Drupal to play a specific sound file eg in audiofield. How can I do that?

I would redirect to the node with the audiofield and set it to autoplay. This way you can have only one audio field per node of course.


How to get addressfield geocoded on import with Feeds? I am using Drupal 7.10 with the Feeds module 7.x-2.0-alpha4. The data I'm importing has address data that will be imported into my content type's address field, and the content type is also using the field implemented in the Geofield module, which holds coordinates and it is set to be populated from the address field when a node is saved.

However, when I import the data into nodes, the nodes are not geocoded; if I then edit the node, and save it, the node will be geocoded, and my map will display.

How can I get the Feeds module to trigger geocoding upon data import?

I just found an issue about this: Feeds + Addressfield Integration.

UPDATE

Found the issue about "Creating Your First Map Using OpenLayers, Geocoder, and Feeds" which references a patch. I tried this patch and re-imported my nodes. However they still were not geocoded.

The way that your Geocoded data will populate after save indicates that there is some hook in the geocoding module that triggers after a save. Perhaps the initial save in feeds bypasses this.

I suggest you find in the Geocode module the point at which this save is triggered, but as a work around for you which should work, trigger another save once feeds has saved your node.

Create a custom module with a hook_feeds_after_save, then call $entity->save() on it again to issue a re-save and that should force your Geocoded values to populate.


How to solve the error while uploading image to nodes? I have a content type and it has an image field. I'm using the File Field Paths module for the image field.

I uploaded images for some nodes via Drupal interface but then deleted them via FTP.

Then I'm trying to re-upload images to these nodes via Drupal but it gives this error and couldn't find anything to solve the problem.

How can I solve this problem via Drupal or via PHPMyAdmin etc.?

Try the Upload QC module. Some details about it (from its project page):

This module offers checks and validations for the process of uploading files. It extends the Drupal 7 core and helps avoid errors during file upload. You can now say good bye to PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 2: INSERT INTO {file_managed}.
WHO SHOULD USE
This module is for you if:

you run into errors like this one PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 2: INSERT INTO {file_managed} OR PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ... for key 'uri': INSERT INTO {file_managed}.

you would like to add additional file upload validations that check for (a) file name length, (b) file name containing certain words/characters, (c) file name not containing certain words/characters.

Drupal and/or PHP upload size limit is not working for you and you would like to set it yourself in your admin section.

Looks like item "1." is pretty close to your issue, no?


Theme stylesheets not loaded I am learning Drupal 8 and have installed Drupal 8.1.2 version on XAMP.
No theme files are included when page is loaded (viewed source).

When trying to solve this, I changed theme from default bartik to stark. Still no theme files are loaded.
And now I am trying to switch it back to bartik, but I am unable to.

"Bartik is now the default theme." is displayed but Stark 8.1.2 (default theme) is default theme.

See screenshot below:

I recommend you use Aquia Dev Desktop, easier to use than Xamp, one click install.

https://dev.acquia.com/sites/default/files/downloads/dev-desktop/AcquiaDevDesktop-2-2016-09-05.exe

Just use that, and it will all work 100% the first time.

Something else you might need to do with Xamp is adjust timeouts ect...with Aquia dev desktop the settings are usually already adapted to Drupal requirements.


How to prevent node delete for a specific node? I want to prevent a specific node from being deleted by anyone except admin. For this specific bundle there are two roles that have full access to the node: admin and manager. A manager can delete any nodes of this content type, but I want one specific node to be locked.

I tried hook_node_delete and it does not work as the delete hook for the specific content type (node) has already run by then.

I tried the Content Access module and setting of permissions per node, but then when I go to the specific node's edit page the 'delete this content' for the role manager is enabled and greyed out.

I also do not want to just remove the action from the edit form as the node can be deleted in a view bulk operation. Hence I need a catch all solution.

I don't think there's a catch all solution.

On second though, you maybe can create a new content type, say node2, and set the permissions for that content type to admin only.

and if you will ever need more than one admin-only node, you'll have no problems at all.

however i have no experience whatsoever there :p

in hook_menu_alter change the 'access callback' for the "node/%nid/delete", since you need it only for a particular node ( say nid=120)

$items['node/120/delete'] = $items['node/%nid/delete'];
$items['node/120/delete']['access callback'] = 'custom_function';
unset($items['node/120/delete']['access arguments']);

this will prevent that node to be deleted directly.

then you need to remove the delete button from that node form edit (however i don't know the form name).

this should be enough and prevent the deletion "nicely", but you can use hook_delete like pointed out in the other answer to catch everything and everything else that can't be prevented like that.


How to embed plugin configuration form elements into another form? I have a form that lists entities and each of the entities has a checkbox.
The form also contains a list of actions(Action plugin) that can be performed on selected entities as a select list.

I would like to be able to configure actions that extend the \Drupal\Core\Action\ConfigurableActionBase class, which means they are configurable, right in my form since some actions can have very different settings and creating action entity for each variation of those setting is just impossible. I would create a new action entity from those settings, without saving it, and use it to perform the action(although I could do it just with the plugin, but that's not important right now).

I am able to retrieve the form elements for those configurable actions and display them in my form. The issue I have is that incorporating those elements into form is tricky on its own, but validating and submitting them is on another level since I cannot just encapsulate those form elements under some specific form array/key because the validation and submit handler for those plugins will not work with that.

The \Drupal\Core\Plugin\PluginFormInterface::buildConfigurationForm() is not a proper D8 form but it just holds the form elements so it's not like I am trying to embed a form within another form, but it is stillquite impossible as I am seeing it right now.

So how can I do this? Or can you recommend a different approach?

This is the initial design: http://pastebin.com/b8SCFvUQ

I have solved this by making sure my forn had a unique element names to avoid collision with the Action's configuration. I have added a 'x_' prefix to names of all my elements. Since my form did not use #tree globally I have put the Action's configuration under a 'configruation' key and in form validation and submit callbacks I have provided this array as $form['configuration'] to the validation and submit handlers of the Action plugin instead of the whole $form array. So far it works withotu any issues.


How to programmaticaly serve a 404 in template.php I have the previous logic to feed a View in MY_TEMPLATE_preprocess_page.
When the URL, where I have some paremeters passed in a user friendly way, does not exist (the parameters are not correct), I am serving a "Product not found message". However, I think it is more correct, for SEO purposes, to serve a 404-Not Found page, with the correct HTTP Headers. I am trying to achive this with drupal_not_found but the page takes a minute to load and finally shows a blank screen.

Where should I put the logic and the drupal_not_found call? Must I move it to my custom module, in MY_MODULE_init() or something? I need to access $node->nid.

Example:

Correct : http://www.example.com/products/shoes

Wrong (404) : http://www.example.com/products/dsfsdfswerweipwr

My personal advice is to return the "No results found" message from Views instead of issue a 404. Why? Because if you ever wind up adding products or changing the name of a product, what used to be a 404 is not anymore. I feel like from an SEO perspective you would have an uphill battle. Anyway.

One way to do this would be from a custom module. Do not do it in template.php.

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(&$view) {
   if ($view->name == 'myview' && some_other_conditions) {
     if (empty($view->result)) {
       drupal_add_http_header('Status', '404 Not Found');
       drupal_not_found();
       drupal_exit();
     }
  }
}

Bonus, Drupal 8:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(ViewExecutable $view) {
   if ($view->id() == 'myview' && some_other_conditions) {
     if (empty($view->result)) {
       throw new NotFoundHttpException();
     }
  }
}

Is the view generating the page at products/%? Why do you need to know the $node->nid?


Why can't I find any pages after migrating a site? I need to migrate a drupal site from one host to another. I didn't create the original. I tried using "Backup & Migrate", and I also tried to export the sql database in phpmyadmin from old site, import into new site, and move the file manually with ftp. My new host is GoDaddy. I can change that if GoDaddy causes issues!

Here is the problem, The theme used in the old site appears as an option, I can choose it, and the site works, but no content is there at all. All the modules show up in the new environment, still no content. I go to search for content, still no content. I can't find any pages anywhere!!!

Any help?

So, the usual way to do this is like this.

dump all caches and back up the database
clean drupal install on your new server
move the db to your new server
configure proper db user on new server
copy the sites folder to the new server
make sure settings.php is correct for new server config
run update.php

It's not clear from your description exactly what's happened, but I would try it again. From what you describe, it doesn't sound like you followed all the steps for a normal site migration, so you need to make sure all the stuff drupal needs is there. I've also had some issues with folder permissions when moving stuff to Godaddy, so you can look at that too.


How to filter views rows whose nid is less than nid provided by url? Drupal 7. In a node/edit form panel I have added a view that returns nodes.
I whish to filter thoses nodes and keep only the nodes whose nid is less than the nid of the node beeing edited.

the url of the node/edit form   is : /node/11541/edit?step=11538

the nid of the node being edited is : 11541

I wish the view to return only the nodes whose nid < 11541

I use Views PHP

You can implement the hook_views_query_alter() to alter your query and change the = operator by the < operator.

function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW_NAME') {
    /* Using the following line dmp($query)
     * (you need the devel module to use dpm) you will be able to search
     * where is condition to alter, you will see that in the
     * $query->where[0]['conditions'][0]['field'] you will have:
     * node.nid = :node_nid
     * so your solution will be replace the
     * = operator by the < operator
     * at this moment you can't do this from the Views UI
     */
    dpm($query);

    $query->where[0]['conditions'][0]['field'] = str_replace('=', '<', $query->where[0]['conditions'][0]['field']);
  }
}

I test the code and in my environment it works as I want it to.

Here is my view for if you want test the code (in this case the view name is articulos):

$view = new view();
$view->name = 'articulos';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'articulos';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'articulos';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'articulos/%';
$translatables['articulos'] = array(
  t('Master'),
  t('articulos'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('All'),
  t('Page'),
);


Commerce discounts by day-of-week and by age I am creating a store where users can pay for attending events at a fixed rate of £7 for each event; that's the easy part.

The hard parts are as follows:

Every Tuesday all events are half price (£3.50)
Students are admitted any day of the week half price
Senior citizens are given a £1 discount every day of the week

I am investigating the Rules module as the most feasible solution, but I am not sure it will deal with all the scenarios above.

I would appreciate any advice to help me reach a working solution.

You can use rules for first requirement. You will need to add PRODUCT PRICING rule & check the day in condition. Just multiply the base price by .5 & you can apply what you wanted..
Anther things are user role based, so if a user has role of student in condition then do the same in another PRODUCT PRICING rule.

Add one more rule for senior citizen, check their user type & apply the new price.

These will work for sure..


D7 CCK default values and PHP input what happened the ability to add PHP to the default value of a CCK field? Also, is it possible to set a CCK field to 'greyed out' or disabled by default? I don't need users editing this ref # field but I need admins to search it.

Drupal 7 is a lot different than Drupal 6 in many ways. What used to be called CCK, now called "fields in core" or "fields" is also different. Not all of the features that was in CCK is available in Drupal 7 fields, some are, but contrib modules is needed.

Regarding using PHP default values, I don't know of a module that does this. It's possible with hook_form_alter in a custom module, but this might not be what you are looking for.

I don't know of any way to gray out fields when editing an entity, other than again using hook_form_alter. The field permissions module might be able to help you, to deny users the ability to edit the field. It would then disappear entirely, but that could be a possible solution.


How can one add inline JavaScript in the validation function for the Form API? I found that there is a way to add javascript files in the form validation function as stated in "drupal_add_js not work in form validation failed".

However, I would like to know how to add javascript using the drupal_add_js function with the inline option. I would just like to execute some javascript code while I am in the validation function of the Drupal Form API.

See the docs @https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

  drupal_add_js() example:

drupal_add_js(
  'jQuery(document).ready(function () { alert("Hello!"); });',
  array(
    'type' => 'inline',
    'scope' => 'footer',
    'group' => JS_THEME,
    'weight' => 5,
  )
);

  #attached example:

$element['#attached']['js'][] = array(
  'type' => 'inline',
  'data' => 'jQuery(document).ready(function () { alert("Hello!"); });',
  'scope' => 'footer',
  'group' => JS_THEME,
  'weight' => 5,
);

Just replace $element by $form.

Original source: https://web.archive.org/web/20160502205421/http://www.failover.co/snippets/drupal-7-attaching-css-and-javascript-forms-or-form-elements


How do I add managed images to the Media Module browser stored locally through a remote URL? This question has been asked lots of other places and I was quite determined to make it happen. The use case is copy and paste a URL for an image on the web into the Media Module file browser. The Remote Stream Wrapper module does something similar except the images are not stored on the local server. Instead the metadata about the image is stored in the database while Image Cache stores images locally. I really wanted to import images I have access to onto my server.

First, a form is built. Then the elements in the form array are expanded during drupal_process_form(). The default value of each element is set during this stage. The file.module has a callback hook added during the set element value stage which other form elements do not have, '#file_value_callbacks`.

I simply added a textfield element to the upload form for the media browser and registered a callback. If there is an URL in the textfield, drupal_http_request() is used to pull the data / image and save it passing the file ID as the value of the upload widget element to finish processing the image.

It seems to work as expected. There are some gaping security holes which need to be cleaned up. Nonetheless, this implementation will greatly increase the efficiency of workflow for my next project.

Here is my solution:

/**
 * Implements hook_form_FORM_ID_alter()
 */

function helper_form_file_entity_add_upload_alter (&$form, &$form_state, $form_id) {
  // Keep the textfield clear if there is a file ID
  // We only have to upload the image once then who cares?
  if (!empty($form['upload'])){
    $form['upload']['#file_value_callbacks'][] = 'helper_file_value_callback';
    $form['url'] = array(
      '#type' => 'textfield',
      '#title' => 'Enter image URL',
    );
  }
}

function helper_file_value_callback (&$element, &$input, &$form_state) {
  global $user;

  // Make sure that there is a $url
  if (empty($input['fid']) && valid_url($url = $form_state['input']['url'])) {

    $upload_name = implode('_', $element['#parents']);
    $destination = $element['#upload_location'];
    $parsed_url = parse_url($url);
    $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);

    // Make sure that there is a directory.
    if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
      watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.',
          array('%directory' => $destination, '!name' => $element['#field_name']));
      form_set_error($upload_name, t('The file could not be uploaded.'));
      return FALSE;
    }

    // Download file and make sure that return code is 200 or else abort!
    $result = drupal_http_request($url);
    if ($result->code != 200) {
      drupal_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.',
          array('@errorcode' => $result->code, '@remote' => $url)), 'error');
      return FALSE;
    }

    // Construct the $file object
    // file_save() adds the timestamp and filesize on save
    // file_unmanaged_save_data posts message on error
    if ($uri = file_unmanaged_save_data($result->data, $path, FILE_EXISTS_RENAME)){
      // Create a file object
      $file = new stdClass();
      $file->fid = NULL;
      $file->uri = $uri;
      $file->filename = trim(drupal_basename($parsed_url['path']));
      $file->filemime = file_get_mimetype($file->uri);
      $file->uid = $user->uid;
      $file->status = 0;

      if (file_save($file)){
        $input['fid'] = $file->fid;
      }
    }

  }
}


Dynamic loading using Tabs module and CCK Fieldgroup tabs I am currently using the Tabs and CCK Fieldgroup Tabs modules to display views in a tabbed format on nodes of a custom type. However, pages take a long time to load because the content in every tab is loaded at once. I want to dynamically load each tab only when it is clicked. How can I accomplish this? For example, look at the first node on this page

That example page uses Quick Tabs module.

  I want to dynamically load each tab
  only when it is clicked. How can I
  accomplish this?

Quick Tabs gives the option to dynamically load content with ajax. Here is demonstration linked to by the Quick Tabs project page. To get that solution please read the Quick Tabs documentation.

Yes, the example you give uses the Quick Tabs module. It says so in the markup. class="clear-block quicktabs_tabs quicktabs-style-excel ui-tabs-nav tabs primary"


ArgumentCountError: Too few arguments to function Drupal\hal\Normalizer\ContentEntityNormalizer::__construct(), 3 passed and exactly 5 expected I've replaced the deprecated functions with non-deprecated functions using drupal-check and PHPStorm. The site builds on Drupal 8.9.13. I update composer.json to 9.1.5 and run composer update. drush status output is the following.
    Drupal version   : 9.1.5
    Site URI         : http://default
    DB driver        : mysql
    DB hostname      : 127.0.0.1
    DB port          :
    DB username      : ----
    DB name          : ----
    Database         : Connected
    Drupal bootstrap : Successful
    Default theme    : - - - -
    Admin theme      : seven
    PHP binary       : /usr/local/Cellar/php@7.3/7.3.27_1/bin/php
    PHP config       : /usr/local/etc/php/7.3/php.ini
    PHP OS           : Darwin
    Drush script     : /usr/local/bin/drush
    Drush version    : 10.4.0
    Drush temp       : /tmp
    Drush configs    : ----
    Install profile  : standard
    Drupal root      : ----
    Site path        : sites/default
    Files, Public    : sites/default/files
    Files, Private   : sites/default/files/private
    Files, Temp      : /tmp

When I run drush cr, it fails.

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Drupal\hal\Normalizer\ContentEntityNormalizer::__construct(), 3 passed in /web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 257 and exactly 5 expected in /web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php:57
Stack trace:
#0 /web/core/lib/Drupal/Component/DependencyInjection/Container.php(257): Drupal\hal\Normalizer\ContentEntityNormalizer->__construct(Object(Drupal\hal\LinkManager\LinkManager), Object(Drupal\Core\Entity\EntityTypeManager), Object(Drupal\Core\Extension\ModuleHandler))
#1 /web/core/lib/Drupal/Component/DependencyInjection/Container.php(447): Drupal\Component\DependencyInjection\Container->createService(Array, 'private__...')
#2 /web/core/lib/Drupal/Component/DependencyInjection/Container.php(460): Drupal\Component\DependencyInjection\Container->resolve in /web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php on line 57
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Drupal\hal\Normalizer\ContentEntityNormalizer::__construct(), 3 passed in /web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 257 and exactly 5 expected in /web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php:57
Stack trace:
#0 /web/core/lib/Drupal/Component/DependencyInjection/Container.php(257): Drupal\hal\Normalizer\ContentEntityNormalizer->__construct(Object(Drupal\hal\LinkManager\LinkManager), Object(Drupal\Core\Entity\EntityTypeManager), Object(Drupal\Core\Extension\ModuleHandler))
#1 /web/core/lib/Drupal/Component/DependencyInjection/Container.php(447): Drupal\Component\DependencyInjection\Container->createService(Array, 'private__...')
#2 /web/core/lib/Drupal/Component/DependencyInjection/Container.php(460): Drupal\Component\DependencyInjection\Container->resolve in /web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php on line 57

Then I run drush updb (which is doomed). locale_update_9101 runs, but the Hal module post-update returns this error.

ArgumentCountError: Too few arguments to function Drupal\hal\Normalizer\ContentEntityNormalizer::__construct(), 3 passed and exactly 5 expected in Drupal\hal\Normalizer\ContentEntityNormalizer->__construct() (line 57 of /web/core/modules/hal/src/Normalizer/ContentEntityNormalizer.php)
#0 [internal function]: Drupal\hal\Normalizer\ContentEntityNormalizer->__construct(Object(Drupal\hal\LinkManager\LinkManager), Object(Drupal\Core\Entity\EntityTypeManager), Object(Drupal\Core\Extension\ModuleHandler))

The front page in the browser shows the same.
The container is not created. How do I debug this?

#0 in the stack trace contains Drupal\hal\LinkManager\LinkManager. That was ultimately the clue that the missing services were in our custom rest module. Whereas three services in our custom module was okay in Drupal 8. In Drupal 9, all five need to be included.
So yes, upgrading a Drupal 8 site to Drupal 9 works as advertised. It is, of course, still a lot of work. :-)


How do I group by and display only first row of each group? I want to apply aggregation on my view so that only first row of each group should be displayed after group by aggregation.
I have a view with two fields Subject and Due_Date and sorted values like,
Subject     Due_Date
A               2016-03-24
A               2014-06-28
A               2012-10-15

B               2013-11-21
B               2011-10-18
B               2010-03-04

C               2013-07-13
C               2012-12-09

After group by aggregation I want it to have like this,
Subject     Due_Date
A               2016-03-24
B               2013-11-21
C               2013-07-13

It should only have the first row of each group.

I have tried Views aggregator plus, but it is just hiding the values and not eliminating them. With that I couldn't get my filters working the way I need.
Is there any solution for this to work?

If you are using D7 - View Merge Rows module can provide the functionality that you need.

In your scenario, select field subject as Grouping field Nr.1.

Access Merge setting in Advanced section of your View.

For the Subject field - select the setting "Use values of this field as a filter".

For the Due_Date field - select the setting "Use the first value of this field".

If your View contains more than two fields, you will need to select the settings for Merge rows to accommodate processing of added fields.


Insert JavaScripts into head of only one page I want to an SVGMap product that requires that I insert the following javascript into head but I only want to use this on one page of my website in a block. If I insert it into the html.tpl.php page, it will load for every page. Is this a drain on resources or is there a better way to do it for just the block that I need it?

Thanks

<link href="/mapsvg/css/mapsvg.css" rel="stylesheet">
<script src="/mapsvg/js/jquery.js"></script>
<script src="/mapsvg/js/jquery.mousewheel.min.js"></script>
<script src="/mapsvg/js/mapsvg.min.js"></script>

Drupal provides theme suggestion for html.tpl.php

you can put html.tpl.php in templates folder inside you theme directory

html--node--id.tpl.php

id will be your page id
e.g. ID = 123, then file name will be html--node--123.tpl.php

Hope this will help.

===================================================================

For particular block you can use hook_block_view_MODULE_DELTA_alter

@see https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view_MODULE_DELTA_alter/7.x

like,

function module_name_hook_view_MODULE_DELTA_alter(&$data, $block) {
  drupal_add_js();
}


Adding content of products based on subtype I have type (eg. women in clothes) and sub type (eg. jeans in women category). Now i need to add product but the product properties are decided by type(women) and sub type(jeans) and product is itself custom content type. I know in eCommerce website, this is basic situation but my project(drupal 7) is not eCommerce. I need to create this manually.

I have created the category and sub category as custom content type and mapped subcategory to category using entity reference. Now i have created new content type "product feature" and mapped to subcategory using entity reference. Now i need to add those product feature as field to the product when admin add the product. I need help in that.

Lets start by saying that content types are not meant to be used for grouping. Drupal content (nodes) come with permission checking and invoke a lot of hooks upon loading. That is not bad per sé (and in fact required for most content), but is overkill for grouping. Your parent child structure would involve 3 node loads where you want to display one.

If you need grouping, you need taxonomy. This offers almost the same functionality as content types with regards to fields and url aliases, but is much lighter in use. To start you could recreate your reference structure using taxonomy terms.

However, as I already explained in the comments, why not use nested taxonomy? You could place all your categories in one taxonomy vocabulary, allowing you to see, edit and rearrange all terms from one page. It would make your system much more maintainable. Also the fact that you state that you need second level terms to show up after selecting the first is possible. Have a look at Hierarchical Select, Simple hierarchical select and Client-side hierarchical select. These offer exact that functionality.

Your last requirement (if there is more please edit them into the question):

  I need to list category and sub category separately

Depending on how you want to achieve this, is can be done. With views it is very easy. Add a filter to the view, select the parent term, then select that it should be empty. It should give you a list of top level taxonomy terms.


Get block programmatically It is possible get parent entity block by entity block_content? I don't know the block's machine name but I have a uuid of block_content

Use BlockContent::getInstances

$blocks = $block_content->getInstances();

or the code of this method directly:

$blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties([
  'plugin' => 'block_content:' . $uuid,
]);


I'm getting a 404 on a user/reset/%/%/% path I'm getting a 404 on a user/reset/%/%/% path. The cached router item looks good but the page is still not found.

Array
(
[title] => Reset password
[page callback] => drupal_get_form
[page arguments] => Array
    (
        [0] => user_pass_reset
        [1] => 2
        [2] => 3
        [3] => 4
    )

[access callback] => 1
[type] => 0
[file] => user.pages.inc
[module] => user
[_load_functions] => Array
    (
        [2] =>
        [3] =>
        [4] =>
    )

[to_arg_functions] =>
[weight] => 0
[_number_parts] => 5
[_parts] => Array
    (
        [0] => user
        [1] => reset
        [2] => %
        [3] => %
        [4] => %
    )

[_fit] => 24
[_visible] =>
[_tab] =>
[tab_parent] =>
[tab_root] => user/reset/%/%/%
[menu_name] => user-menu
[delivery callback] =>
[theme callback] =>
[theme arguments] => Array
    (
    )

[load_functions] => a:3:{i:2;N;i:3;N;i:4;N;}
[access arguments] => Array
    (
    )

[title arguments] => Array
    (
    )

[title callback] => t
[description] =>
[position] =>
[context] => 0
[path] => user/reset/%/%/%
[file path] =>
[include file] => modules/user/user.pages.inc
)

I've used drush fn-hook menu_alter to see if anything is changing this path but I would figure that end up in the cached router entry above. Any help with this would be much appreciated.

This was being caused by a third party custom module, funny enough not in hook_menu_alter.


'Show block on specific pages' wraps url in paragraph tags I have a Drupal 6 site and I want to add a block to a page. This block is generated from a custom module, from the hook_block function.

Under the blocks admin section, under Page specific visibility settings header, there is the setting for Show block on specific pages. I've entered my url under Pages and selected Show on only the listed pages.

When I click save, Drupal wraps my path in <p> tags. I don't have anything in my module that would be overriding the default drupal behavior. Why is this happening and how can I get it to stop?

We have CK Editor enabled on our site. In order to fix this, I had to go under CK Editor and change the profile for my role. Under Visibility Settings, there was a place to specify paths of textareas not to affect. I put in the path and I'm good to go!


How can I add a class to a title of a view? I'd like to add a class to the title (H1) of a view, so that a specific style could be applied. This is Drupal 6 with a Zen subtheme.

Thanks

If you're using Views 3, you should be able to click on Style Settings on the field, Customize field HTML.  From there, you can set H1 as the HTML element or click on "Create a CSS class" to add a class.


Overriding third-party module code I am using Composer to download third-party modules to my Drupal 8 repository.

I have a requirement that involves all of the functionality that module gives but there are unfortunately 2 lines of code that I need to remove in a PHP file in the module_name/src/Helper folder.

The lines I've commented out are to stop the request to open a jQuery UI dialog box.

I'm curious as to what you guys think. It is a requirement from the client that I have this functionality in place.

Here is the code snippet taken from the Ajax Add To Cart Module:

namespace Drupal\ajax_add_to_cart\Helper;

use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\ajax_add_to_cart\Ajax\ReloadCommand;
use Drupal\block\Entity\Block;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Class AjaxCartHelper.
 *
 * @package Drupal\modules\ajax_add_to_cart
 */
class AjaxCartHelper {

  /**
   * Ajax add to cart response.
   *
   * @param string $form_id
   *   Form id.
   * @param object $response
   *   Response object to store information.
   *
   * @return object
   *   Return response object.
   */
  public function ajaxAddToCartAjaxResponse($form_id, $response) {
    // Adding modal window.
    $options = [
      'width' => 250,
      'height' => 300,
    ];
    $settings = [
      $form_id => [
        'title' => t('Successful Added'),
        'message' => t('Cart Updated Successfully'),
      ],
    ];
    $title = $settings[$form_id]['title'];
    $message = $_SESSION['messages']['status'][0]->__toString();
    if (!empty($this->cartBlock)) {
      // ****LINE TO REMOVE****
      $response->addCommand(new OpenModalDialogCommand($title, $message, $options));
      // **********************
    }
    else {
      $customblock = $this->container->get('plugin.manager.block')->createInstance('commerce_cart', []);
      $render = $customblock->build();
      // ****LINE TO REMOVE****
      $response->addCommand(new OpenModalDialogCommand($title, $render, $options));
      // **********************
    }
    $response->addCommand(new ReplaceCommand('.block-commerce-cart', $this->cartBlock));
    $response->addCommand(new ReloadCommand());
    unset($_SESSION['messages']);
    return $response;
      }
}

I've added the comment - / ****LINE TO REMOVE**** to the lines that need to be removed

My ideas are:

Duplicate the whole module so that it's custom and use that as the solution (even though module updates won't affect the custom module and i'll have to update it each time)
Comment the two lines out and then update the third-party module

Is there any other methods I'm missing? I've seen the libraries override but thats for the purposes of theming purposes- JS and CSS, I just wondered if theres anything out there in the drupal community fro overriding the PHP that modules provide?

It must be a common requirement by Drupal Devs.

I think the best method would be to use the cweagan patch manager package with composer and a local patch file.  This would allow the module to be updated normally with composer and the patch applied. If the code changes too much for the patch, it will fail and you can update the patch.

Just require cweagans/composer-patches and then modify your composer.json to include the patch.

Also, this is a good way to add patches from Drupal.org or github issues.  If your fix is something that should be generally available, sumbit an issue with the patch.  Then set up your composer patch section to use the URL to the patch in the issue.  For d.o. patches, this makes it easy to find the issue related to the patch since it issue number is in the url.


Corrupted mysql cache_rules table - dropped the table and now I cannot create it anymore!? Stuck I'm not sure how this happens, but the cache_rules table is corrupted and it prevents me from doing a drush cache clear all. I dropped the table successfully, but now I can't create it. Throws this error:

ERROR 1005 (HY000): Can't create table 'cache_rules' (errno: -1)

Luckily i have my db backed up and don't have to lose too much data. Now I tried to drop my entire database and that's not working neither. It does in fact drop all the tables, but it prevents the database from getting dropped entirely.

I tried dropping the database multiple ways. via command line and phpmyadmin. none of that worked.

What did work was going into the database files directory and deleting it manually. These mysql database tables are just regular files you can delete. Mine were located here: /var/lib/mysql/

here's what i did:

After that I was able to recreate the table via mysql command line. just copy and paste this to recreate the table with the schema:

CREATE TABLE `cache_rules` (`cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.', `data` longblob COMMENT 'A collection of data to cache.', `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.', `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.', `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).', PRIMARY KEY (`cid`), KEY `expire` (`expire`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';


Do I need to build a custom page to list nodes by content type? Environment

Mac OSX 10.8.2
MAMP
Drupal 7 (just downloaded the stable today)

Objective
Create a menu item in the main menu to list recent and all nodes of a specific content type.
Question
It appears that I'm going to need to build a custom page, and leverage an API, to simply list nodes by content type. I just know I'm missing something. Can somebody point me in the right direction on how to do this?
I ran this Google searche, drupal 7 list nodes of content type, to come to the conclusion that I'm going to need to build some kind of custom code.

No need to build a custom page.  What you want to do is very simple to do with the Views module.

Just build a View to list nodes, and under Filter criteria, add a filter that only displays nodes of whatever content type you want to single out.


How to remove the "Save" button from checkout cart summary form? On the first checkout page (checkout/xx/checkout), there is a view which displays line items for the order.  The view appears to be named "Shopping cart summary (Commerce Order)"

When I add the standard Delete button to the view (for deleting line items), it causes a Save button to appear below the line items.

How do I remove that Save button?

Update:

I tried a form-specific hook_form_alter(), but didn't find the Save button in the $form array. It appears to be a form embedded in another form.  Reading answer from @Yogesh made me realize that maybe I had the wrong $form_id and can debug with a general hook_form_alter() and look for a nested call for the embedded form.

One way of doing this is implementing hook_form_alter and hiding save button. Check example below:

function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID') {
    // Set access to FALSE will prevent rendering form element on form.
    // Check the hierarchy of 'Save' button, before using #access.
    $form['actions']['save']['#access'] = FALSE;
  }
}


Display user's profile in a lightbox When a user clicks on the "My Account" link I would like the user's profile to show up in a lightbox much like the admin menu overlay works.

I am using Drupal 7.

I am not sure how to do this. My first attempt was to render $user_profile and put it in a lightbox:

<div id="lightbox_this_div">
   <?php print render($user_profile); ?>
</div>

but $user_profile is not available in page.tpl.php

Any thoughts?

EDIT: To be clear I just want to lightbox the content of the user's profile along with the tabs and be able to style the page. So I am not looking to lightbox the entire /user page with the site headers in an iframe style.

you need to "rel" tag in link.

My Account

If you want show a specific region then use this.

 *" rel="lightmodal[|width:700px;height:300px;]">Click to see only the content inside #content-inner

Detailed tutorial can be found here


Different forms per user role I need to hide the description field from regular users when entering data, but the field should be visible to administrator users, which also can edit it. I used the Display Suite module to hide that field by using different view modes, but I could not figure it out how to hide the field on forms. Any guidance would be appreciated!

Display Suite is not what you need, field_permissions is, check out the screen.

DS is mostly used to change the global look and the availability of some fields and labels (like Teaser, Product, Fullpage ...)


Can I run 2 active polls on my site? We have a regular poll on our homepage, which I set up by selecting 'most recent poll'.

However, I want to add a different poll on a seperate page on my website. Can I do this? I can't find polls as a block or node function other than 'most recent poll'

Help?

Define an auxiliary content type (say MyPoll).

I added a Node reference CCK field to standard Poll and a CCK Node Referrers (backreference) field to MyPoll. You can then easily create one (or even more!) polls as "children" of your MyPoll node, and attach their teaser content (the voting widget) to the MyPoll node.

As MyPoll is a "standard" content type, you can do whatever you want with it in views... including the display of the referred poll widgets. It's not straightforward...

I was inspired by http://www.lullabot.com/articles/photo-galleries-views-attach. Look at it this way: "galleries" are "mypolls", and "images" are "polls".


"b.handleError is not a function" on image remove/upload I was not able to upload/remove CCK field images from the UI; when I looked at the console in Firebug, it said, "b.handleError is not a function." When I look for this error on Internet, I keep getting redirected to http://drupal.org/node/1064890, but this has a patch for Drupal 7.

Has anyone faced something similar?
More importantly, was this fixed?

I am using Drupal 6, and the following modules:

jQuery UI 1.7.3
jQuery Update 1.5.2

You can update the jquery.form.js as found in this comment:

https://drupal.org/comment/7520175#comment-7520175

I tried on my system which also makes use of a newer version of jQuery and it works like a charm.


Limit Webform Submission to one per quarter per user I need to limit one webform submission per quarter. For each quarter, the user can only make one submission. I want to use one webform. Here are some examples of the date period and the due date. How can I achieve the desired outcome with Webforms?

Q1 (Oct. 1, 2019 – Dec. 30, 2019): due by Jan. 15, 2020
Q2 (Jan. 1, 2020 – Mar. 30, 2020): due by Apr. 15, 2020
Q3 (Apr. 1, 2020 – Jun. 30, 2020): due by Jul. 15, 2020

ok so here is how to do that.. you need to create a module and set Drupal cron to run once a day on your hosting provider
then you need your webform to have email unique then do this ....

/**
 * Implements hook_cron().
 */
function YOURMODULE_cron() {
  $current_month = date('m');
  // Get first month of quarter
  $new_month = (3 * floor(($current_month - 1 ) / 3)) + 1;
  $new_month = substr('0' . $new_month, -2);
  $first_quarter_day_date = date('Y') . '-' . $new_month . '-01';
  $today = date('Y-m-d');
  // So this is the first day of the quarter.
  if ($first_quarter_day_date == $today) {
    // Use cache to make sure this runs once.
    $cid = 'clear_out_webform_date';
    $cached = \Drupal::cache()->get($cid);
    $run = TRUE;
    if (!empty($cached)) {
      if (!empty($cached->data['date'])) {
        if ($cached->data['date'] == $today) {
          $run = FALSE;
        }
      }
    }

    if ($run == TRUE) {
      // change this to your webform id
      $webform_id = 'contact';

      // Export all submissions to file.
      $webform = \Drupal\webform\Entity\Webform::load($webform_id);
      $submission_exporter = \Drupal::service('webform_submission.exporter');
      $export_options = $submission_exporter->getDefaultExportOptions();
      $export_options['delimiter'] = ';';
      $export_options['multiple_delimiter'] = ',';
      $submission_exporter->setWebform($webform);
      $submission_exporter->setExporter($export_options);
      $submission_exporter->generate();
      $file_path = $submission_exporter->getExportFilePath();
      // rename the file to something good.
      $filename = $today.'-export.csv';
      $uri = 'public://' . $filename;
      $fileContent = file_get_contents($file_path);
      $destination = $uri;
      // Save the file to be a file entity.
      $file = file_save_data(
        $fileContent,
        $destination,
        FILE_EXISTS_RENAME
      );
      if (is_object($file)) {
        // Probably email your self a reminder here.
        // ^^ file is now an entity so you can do something like.
        // load a know entity and append the file to a document field.
        // or just download it as in the public file dir.

        // Delete previous quarter submissions.
        $query = \Drupal::entityQuery('webform_submission')
          ->condition('webform_id', $webform_id);
        $result = $query->execute();
        if (!empty($result)) {
          $webform_submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
          $submissions = $webform_submission_storage->loadMultiple($result);
          foreach ($submissions as $submission) {
            $submission->delete();
          }
        }
      }
      // set the cache to today so it wont run again.
      \Drupal::cache()->set($cid, ['date' => $today]);
    }
  }
}

have fun and good luck.


How to pass value from form to url parameter in my sidebar i have block with a form where users add name of restaurant and when they cick Submit they are supposed to be redirected to a page where my webform is.

I need url like this /add-your-restaurant?key=value-from-text-field but im not sure how to pass that value in url with my form.

I have already %get[key] as default value for my Name field in webform.

This is my html form:

<form name="addres" id="addres" method="post" action="">
<span>
<input type="text" name="addresfield" class="resfield" value="Enter your Restaurant name"/>
</span>
<input type="button" class="btn"/>
</form>

This is solution and working form as desired.

<form name="addres" id="addres" method="get" action="add-your-restaurant">
 <input type="text" name="addresfield" class="resfield"
 name="key" value="Enter your Restaurant name"/>
<input type="submit" class="btn"/>
</form>


Draggable views module doesn't sort content I wanna sort my view with Draggable Views Module , but my view display content not field.
is there any solution to sort my views ?

Only solution that worked for me was the following:

go to your content type/vocabulary
add a weight field (label: weight | machine name: weight | field type: integer
edit your sorting view and add sort criteria for your newly added weight field
edit your draggable views field and change "Handler" from Native to FieldAPI
under Field select your weight field
go to your content view and add the new weight field as you sort criteria

This is the only thing that worked for me. If it doesn't work immediately, just reorder a few items on your draggable view so that the ordering values are reset.

Hope this works for you too.


Where is the "Add fields" button on content types when using the Minimal installation profile? I just installed Drupal 8.1.x and used the Minimal installation profile.

I added a new content type, but how do I add additional fields? I don't see a button anywhere.

The minimal profile lives up to its name - the vast majority of modules aren't installed when using it.

This include the core Field UI module, which provides the UI you're missing. Just enable that module and you should see a "Manage fields" link as the default option in the table from your screenshot.


Search form block not showing in IE7 and IE8 Search shows fine in chrome but not in IE8- looking at the code the DIV block-search-form simply isn't there. This occurs in different themes and also if I change where search should be displayed.

I'm on a fresh install of 7.12 with commerce kickstart, internationalization and other pretty standard modules.

Any ideas?

Judging from your commments it's a permission issue. To solve it select People -> Permissions from the admin menu (or use the path admin/people/permissions) then look for Search and give 'Use search' (and possibly 'Use advanced search') permissions to the roles you want.


How does one change the machine name of a Feature? I have created a feature with a typo in the machine name. I've tried just search/replacing instances of the misspelling with the proper spelling in all files within the feature's directory, but when I do that it disappears from the list of available features entirely. (Yes, I drush cc all'd.)

How can I change the machine-readable name of this feature?

Using Drupal 6, btw.

Use this procedure to rename a Feature module:

drush pm-disable old_feature_name
drush pm-uninstall old_feature_name
rename the Feature module folder
rename the .info file
rename the .module file
rename any hook prefixes
drush pm-enable new_feature_name


How to create a Class that I can reuse in multiple modules? I would like to create a class that has a set of methods that I want to reuse across the site in either mytheme.theme or secondmodule.module files.

How would I create this class and class methods so that they can be used in multiple areas? Would I have to create a custom module for this?

Here is what I was trying so far, but need assistance on next step.

<?php
namespace Drupal\CustomClass;

class MyClass {
  public static function processEntity($var1, $var2) {
    /* process the parameters */
    return value;
  }
}

If I wanted to use this in a mytheme.theme file I was thinking to do this

<?php

use Drupal\CustomClass\MyClass;

function _some_function() {
  /* processing logic here which results in $var1, $var2 */
  $results = MyClass::processEntity($var1, $var2);
}

Your use case is where Drupal 8 services come into play. When you'd like to create classes/methods that can be used across Drupal by other modules and your theme, create a custom module that provides this class as a service. You can then get an instance of this service class by either using the static service getter \Drupal::service() within *.module or *.theme files, or dependency injection in other classes/services.


Why views retrieves results one by one I'm actually trying get the count of total rows retrieved by view. When I added count($row) in Global:PHP of views field it returned 1. That also ten times, Means query executed 10 times to retrieve 10 row of data. When I printed the query with dpq($view->build_info['query']); it returned same query 10 times. How can I avoid multiple execution of same query.

You can list the number of results instead with a snippet of php code in the header:

<?php
  $view = views_get_current_view();
  print $view->total_rows;
?>

Learned this trick from: https://stackoverflow.com/a/2989197


how to create signup form with MailChimp module I want to follow the tutorial at https://drupalize.me/videos/create-your-first-mailing-list-and-sign-form?p=2235 but I'm stumbling as soon as we get to create sign up forms in the MailChimp module configuration. I don't see a "SIGNUP FORMS" tab but instead I get 5 red error messages on top that say Failed to load MailChimp PHP library. Please refer to the installation requirements. and if I look under /admin/reports/status, I see The MailChimp MCAPI library could not be found. under the MailChimp module. How can I get these resolved?

I get it. You’ve just signed up for Mailchimp and set up your first list. You want to put a signup form on your Drupal 8 (probably works in D7 as well) website so visitors can start signing up for your newsletter or announcements. Here's how you place a signup block. I know this is a late answer, but hopefully it will help someone. To get through this process you have to clear cache a lot. Here's what worked for me.

Install and enable the mailchimp module and the Mailchimp_signup module. Set up the API key with your mailchimp API clear cache (on the command line you can type ‘drush cr’ or you can do it in the admin menu | config page | performance link | clear all caches button).

Go to admin/config/services/mailchimp/signup and add a signup form. Give it a name and remember the name since that’s what you’ll search for when you’re ready to place the block. Check the ‘Block’ checkbox. Choose at least one list that you’ve set up on Mailchimp’s website or on the Lists tab. Save the form.

Refresh cache ‘drush cr’ again.

Go to the Structure | Block layout tab. Choose a region where you would like the signup tab and choose ‘Place block’. Search for the name you used when naming your signup form. Choose it and ‘Save block’.

Now go to your site and observe your work. Your form will appear in the area you specified.


Commerce: Setting Custom Form Default Values I would like to set custom default values for both the Customer Shipping and Billing forms. I built a custom page/pane that occurs at the beginning of the Commerce Checkout process. This page/pane has 5 fields that pull basic user information before depositing the user at the 'express' checkout form (part 2 in the multi-step form -- or better known as the typical Shipping/Billing forms). My objective is to be able to use the data saved in $form_state['order']->data; in order to pass it into the default_values in certain textfields within the Shipping/Billing forms.

Using hook_form_alter does nothing to modify the Shipping/Billing in either $form_state or $form. There doesn't appear to be a declaration of default_value within the forms. Even if I do declare a value/values, it does not show up on the page. Any ideas?

The trick is to use

function hook_field_widget_addressfield_standard_form_alter(&$element, &$form_state, &$context) { }


"Disabled" regions re-enable after navigating away and back from module page I have a form module that I would like to have on its own page, with no header, footer, etc.. I thought I was successful with adding hook_menu() and a page callback to render the form's block, then added hook_page_alter() to cycle through all available regions and unset them:

function mymodule_menu () {
  $menuitems['myform-page'] = [
    'title' => 'Survey Form',
    'page callback' => 'mymodule_form_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  ];
  return $menuitems;
}

function mymodule_form_page (&$page) {
  dpm($GLOBALS['_GET']['q']);
  $current_path = $GLOBALS['_GET']['q'];
  if ($current_path === 'myform-page') {
    $module = 'mymodule';
    $delta = 'mymodule_block';
    $block = block_load($module, $delta);
    $form_page = _block_get_renderable_array(_block_render_blocks(array($block)));
    return $form_page;
  }
}

function mymodule_page_alter (&$page) {
  $current_path = $GLOBALS['_GET']['q'];
  if ($current_path === 'myform-page') {
    $regions = ['top','header','footer_1','footer_2'];
    foreach($regions as $region) {
      foreach($page as $key => $value) {
        if ($region === $key) {
          unset($page[$key]);
        }
      }
    }
  }
}

After all of that, I clear cache and visit the "myform-page", er, page. All the undesired regions are gone (though their HTML wrapper DIVs are still rendered, but I'm okay with hiding those with CSS). I leave that page, going to the front page, for example, then manually type in the address for "myform-page" in the browser and hit enter. The header and footer regions are back!

The "mymodule_page_alter" function only runs once and never again until I clear cache again. The "mymodule" block loads, looks, and functions exactly how I want it to, except for the regions returning when I navigate back to the page. I've reproduced this in a virtual OS environment, so I'm afraid I done goofed. I just don't know where. I've tried using hook_theme() to load a simple page template per info found here:
PHP Output in module
...with varying results, ultimately with the undesired regions still showing up. Would anyone know why the page alter hook stops working after executing once? I'd appreciate everyone who can point me in the right direction.

I believe I resolved my issue. Both the page callback function and mymodule_page_alter function were in a mymodule.pages.inc file that is linked to in the mymodule_menu function. Drupal doesn't like the hook being in the .inc file, so I moved it to the .module file, cleared cache, and reloaded the page. The form's page seems to be loading the content I want to see and nothing else, even after navigating away from the page and coming back to it later.

Lesson learned -- I'll just keep all API hooks in the module file unless taught to do otherwise. Or, unless hooks being outside of the .module file isn't possible anyway.


Get node path via javascript I am attempting to add history states to view items that are loaded using the infitine scroll module. On my first attempt, I am adding the following code to the infinite scroll.js file in the load section. I have partial success in using Drupal.settings.basePath variable, however, I would like to get the node that gets loaded as opposed to the baseurl. Is there a call in javascript for this? Here is my sample so far:

var baseUrl = Drupal.settings.basePath;
history.pushState('', '', baseUrl);

You can add the node ID manually to Drupal settings with drupal_add_js(), for example from a preprocess function.

// PHP
$setting = array('setting_1' => 'value_1', 'setting_2' => 'value_2');
drupal_add_js($setting, 'setting');

// JavaScript
var nodeId = Drupal.settings.setting_1;


How is block different from mini panel? I am a newbie in Drupal.

Can anybody explain how is block different from mini panel.

Mini panels allows you to use layouts, so you can have rows and columns within a mini panel block. Making life way easier when it comes to applying css.

In addition, it allows you to attach other things, such as views, other blocks, etc..
In contrast, if you use a regular block, you can only do one thing at a time with them.

So if you have lots of blocks, it can be messy if you want to change the block position. While if all the blocks are inside a mini panel, you can move them all at once.

Don't think of it as mini panel vs block. Think of it as mini panel being a block management system.


#states with effects (fade, slide) I'm using the form api #states feature to show and hide fields based on the value of other inputs.

This is working great however I would like to have the option to fade or slide the inputs as they are shown and hidden.

I realise the conditional fields module offers this functionality however I found it too buggy to use.

This live example from the examples module shows the Additional Information section sliding up and down when the checkbox value is changed.

The code used to achieve this:

$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);

This made me think using 'expanded' instead of 'visible' would make the element slide and not just appear however this is not working for me.

I am editing a node form using hook_form_alter so my working code (but with no effect) looks like this:

$form['field_full_name'][LANGUAGE_NONE][0]['value']['#states'] = array(
    'visible' => array(
        ':input[name="field_person_type[und]"]'=> array(
            array('value' => 'Contractor'),
            array('value' => 'ICM'),
            array('value' => 'Member of public'),
        ),
    ),
);

Replacing visible with expanded or collapsed has no effect so I guess these properties only apply to fieldsets, not elements. A full list of possible states can be found here.

So, is is possible to fade or slide form elements using #states?

Please try this. may be it will help you.

**Your Code:**
$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);

Instead of that you can try it in another way which is mentioned below in hook_form_alter() function.

Example:

$form['more_info'] = array(
                          '#type' => 'fieldset',
                          '#title' => t('Additional Information'),
                          '#collapsible' => TRUE,
                          '#collapsed' => TRUE,
                     );

**$form['more_info']['und']['#states']**= array(
                                'expanded' => array(
                                 ':input[**name="expand_more_info[und]**"]' => array('checked' => TRUE),
                                ),
                             );

Note: you can use 'visible' instead of 'expanded'.
you can try this in your custom module or template.php


What are the nfs values seen in the Strongarm seciton of features When preparing a feature I see that there are a number of values beginning nfs_ in the Strongarm section.

What are these nfs_ values and do I need them in my feature?

Gonna go out on a limb and guess that they come from the Node and Comments Form Module, which uses nfs as a prefix for variables.

Failing that, have a look through your contributed modules and see what you have that can be shortened to NFS - that's probably the culprit.


How to save POST variables securely using entity api I am creating a module that connects Drupal Commerce to Shipworks (a shipping management system). They communicate with each other using HTTP POSTs via a single endpoint URL on Drupal. One aspect I am trying to understand is how to handle the POST variables returned from Shipworks in a secure manner.

For example, when a shipment is created in Shipworks the corresponding order id ($_REQUEST['order']) and tracking number ($_REQUEST['tracking']) are posted to Drupal at the endpoint. How do I save the tracking number in a secure manner using the entity api? Can I use the following code?

if (is_int($_REQUEST['order'])) {
  $order_id = $_REQUEST['order'];
}
else {
  _outputError(40, "Not a valid order id.");
}

$order = commerce_order_load($order_id);

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$tracking = $_REQUEST['tracking'];

$tracking_number = str_replace(' ', '', strtoupper($tracking));

$order_wrapper->field_tracking_numbers->set($tracking_number);
$order_wrapper->save();

It really depends on how ShipWorks works. If it lets you specify a URL when it downloads the order data, you could use a secret key appended to the URL that you can use to authenticate a request as Ayeshk mentions. If it allows the merchant to specify a URL in a configuration form, at least you can set the secret key once and have the merchant copy it, kind of like how Drupal appends a secret key to the cron URL.

I also have a project upcoming that requires ShipWorks. Are you sharing the code publicly anywhere?


How to create simple dynamic Views in Drupal 7 I have a Drupal 7 photo gallery that I would like to auto simulate a View to be created once new photo gallery content has been saved/published for it. For instance, I have a content type called "Gallery" with your basic fields: Title, Taxonomy and Image(w/ unlimited values).  I want to be able to have a dynamic View fire off and create the new gallery once  gallery content has been saved. So this way I don't have to login to create the view manually every time...it would instead pull the necessary unique values for new gallery View from the content:  Taxonomy, URL Alias and Title. I'm thinking this is possible to do in some way with Token, Rules, View rules, or VBO.  Perhaps even a hook may be necessary? -Thx

Ok, after some long researching, I found the solution over here --> [l]Context Filter with Path Alias in URL

Patrick and Stage many thanks, but your explanation indeed you don't have to add a bunch of modules or anything over complicated.  Here's what i did:

To recap in detail: I added a "Block View". This is important as it WILL NOT WORK in a Page View. I'm not too entirely sure why, but you'll get no results on your pages ...just only on the View preview will it show correctly. Perhaps it's due to the way the url's are created in Views .vs PathAuto. So a Block view here is the way to go.

My contextual filter is as follows:

WHEN THE FILTER VALUE IS NOT AVAILABLE
Choose: 'Provide default value' Type: 'Raw value from URL' Path component:'2'
Check: 'Use path alias'

WHEN THE FILTER VALUE IS AVAILABLE OR DEFAULT IS PROVIDED
Check: 'Override Title'. Add the value of '%1'
Check: 'Specify validation criteria' Validator: 'PHP Code'
Add the value of:
'$handler->argument = str_replace("-"," ",$argument); return true;'
then save

*Plus make sure to add the %1 to the Title  of the View as well.
 Save flush cache and your dynamic gallery will work by unique title!

Minor issues still:
- Need to find a way to remove special characters out of the title field when constructing the URL Validator. e.g. If a user uses "&" in their title name, then it can't create the url correctly. So I need a PHP string condition to handle special characters for instance: 'If !@#$%^&*():"; then just remove the character'


View for latest articles - but able to override at page level I have a requirement to create a view which will return the latest 4 articles added to the site to be displayed in a block on multiple pages.

This in itself is easily done - however the client has requested the ability to override the articles shown in this block on certain pages. Again this would be easy if all 4 latest articles were to be swapped for these 4 statically selected articles - but the request is to allow any number between 1-4 static choices to be made when creating content.

If a user chooses just one article manually - the other 3 in the "related" block should be the latest 3 articles from the site.
Similary if 2 were manually selected, 2 latest articles should follow them. And so on.

I think I may be overcomplicating this - but having played with Views all morning trying to achieve this I'm struggling - can anyone give me some pointers?

This is possible with attached displays. You would create a view with 2 displays: manual and reverse chronological.

Manual would use a relationship with node's field (entityreference field) that allows to pick releated nodes.

Automated will always select 4 recent articles.

Attach manual to an automated to appear at the top.

You gonna end up with 4 to 8 articles.

To remove extra nodes from results, implement hook_views_post_execute()


Drupal on IIS 7: URL Rewrite vs. ISAPI Rewrite modules I'm preparing to install Drupal 6 on an Win2k8 server. I'm still on the fence about using IIS 7 exclusively as the web server, or installing Apache and avoiding IIS 7 altogether. I work on a campus with a lot of different networks & system which mostly run on Windows servers, so I fear that not utilizing IIS 7 in some form may come back to bite me later on.

Anyway-one of the main issues I've seen from folks who've installed Drupal w/o Apache is in configuring clean URLs & URL rewriting. I'd like to ask if it is any easier setting up URL rewriting with the MS URL Rewrite vs. an ISAPI Rewrite module? Is there a major difference between the two modules other than that the full-feature ISAPI modules seem to cost money?

Thank you.

Jason

This should help you out: Clean URLs with IIS

  The best method is Microsoft's URL Rewrite Module for IIS7, available
  via the Web Platform Installer on Windows Server 2008 and Vista.
  Download and documentation are also available on Microsoft's IIS.Net
  site. You can also use third party rewrite modules (see list above).


Form API: Hiding form option on node forces node to be unpublished I'm using Drupal 7

I'm creating a node through a node add form. The settings are such that it should by default be published. I'm trying to hide some of the options from the user, but when I

hide($form['options']);

for some reason the node does is no longer published by default. I've tried tracing out the value of that portion of the form

drupal_set_message('Options'.'<pre>'.   print_r($form['options'], TRUE) .'</pre>');

and I get the same values when the field is visible as when it is hidden. Seems like perhaps something is fishy?

When you hide the form['options'] array you essentially set it to 0.  Which means the published field will always be 0 (unpublished).  Try hiding the fields with CSS or JS if you need it to be conditional.


How to disable field on register form but keep show in edit profile? I need to know how to disable field on register form but keep show in edit profile? because now if I can only enable in both section, edit profile / register.

I need only show username + email field on register, but custom a lot of custom field on edit profile. thanks

Drupal 7

In D7 you can edit each user field under Configuration > People > Account Settings > Manage Fields and untick the option Display on user registration form.

Drupal 8

In D8 after you add your fields under Configuration > People > Account Settings > Manage Fields go to  Configuration > People > Account Settings > Manage form display, scroll down and uncollapse Custom display settings, tick the Register option and Save.

Now you will see two sub-tabs on that page: Default and Register. Visit the Register sub-tab and rearrange the fields to disable the ones you don't want. This will apply to the Registration form only.

The Default settings will apply to the User Edit form, so you'll want to keep the field enabled there.


how to remove module-created links from menus? I've ended up with two basic pages in the navigation menu and there seems no way to get them off.

The pages are just plain ol' pages; the pages are not created by a module. I am using the Drupal 7 core Book Module. One of the pages in question is a book; the other is a child page of the book. The book has other child pages which are not listed in the navigation menu. The Book navigation menu works fine.

admin/structure/menu/manage/navigation has no "Delete" Links by the pages.
editing the page, there is no "add page to menu" specified. I've even tried turning that on, creating a menu item, then turning it off again. The pages still list in Navigation.
I've tried drush cc all

I have the option to disable these pages, but clearly that's just wrong. Can anyone help?

Ok, just in case anyone else finds this useful: I got in this pickle because I installed a module (nodehierarchy) which generated menu items. Menu items created by modules are not deletable in the normal admin UI. When I removed the module it did not clean up after itself, leaving orphaned entries that drupal thought belong to a module that doesn't exist.

I don't know why drush cc menu didn't clean them out, perhaps a policy of not deleting data just in case.

To fix: start a mysql client on your drupal db and inspect the contents of menu_links, find the rows and delete. e.g.

mysql> delete from menu_links where module='nodehierarchy';

Then clear caches and fixed.


How to get video length of a youtube video in drupal7 I created a node in drupal7 which contains a youtube link. I installed youtube module in my site. with the help of this module i just created a field for inputting url to youtube video.
every thing worked fine. It is showing me the thumbnail,video etc.
But the problem is how to get the length of the youtube video ?

I am using views to generate a json web service the output is

{
            "title":"social networking",
            "field_eventcat":"Performing Arts",
            "field_eventdaytime":"06\/06\/2012 - 05:00",
            "field_eventvideos":"http:\/\/sample sites\/sites\/default\/files\/styles\/thumbnail\/public\/youtube\/6a_KF7TYKVc.png",
            "nid":"34"
         }

I want to get the video lenght with this object. pls help

You can follow the function youtube_get_remote_image on how to make a call to youtube api and retrieve video length.

Youtube public api provides this info without any authentication, for instance - http://gdata.youtube.com/feeds/api/videos/dc4UltkRJsw contains video length in the tag: yt:duration. I have not tested the below function, but should work.

function youtube_get_video_length($id = NULL) {
  $path = 'http://gdata.youtube.com/feeds/api/videos/' . $id;
  $query = array(
   'v' => '2',
   'alt' => 'jsonc'
 );
  $url = url($path, array('query' => $query));
  $result = drupal_http_request($url);
  $data = json_decode($result->data);
  $video_length = $data->data->duration;
  return $video_length;
 }

Also I dont suggest that you write this in youtube.inc of youtube module, write in your custom module or template.php of custom theme.

Hope that helps.


Anonymous access to paid downloads using unique link Is anyone aware of a solution using Drupal Commerce (or alternatives) whereby I can have a product which can go through the following sequence:

anonymous user places in cart
anonymous user goes to checkout
payment is completed
a unique token/string is assigned to the email address provided in purchase
a url from which an anonymous user can download the purchased file is created and emailed to the address provided as well as displayed on checkout completion screen
after a defined period of time the link would expire
non-expired links could then be retrieved via a form by supplying email address to resend them

I can achieve most of the above with commerce_file but it seems that it requires logging in to the user account to access paid for downloads.

Seems like this would be a use case that would not be completely unique so hoping someone has an idea of how best to achieve this without having to roll my own solution.

Thanks in advance

Rich

Drupal commerce has a permission to complete the checkout process, that might be your issue there, check the permissions page (admin/people/permissions) and grant anonymous users the "access checkout" permission


Entity Reference, references dont display I have an article content type, and this article can be assigned to a topic content type. I have created a bunch of articles and topics, and this worked before. But for some reason, all of the sudden no more topics show up when editing an article content-type.

I was in the progress of adding a 'featured' story field with entity reference to the topic. This might have confused the database? Anyway, can I roll back without redo-ing everything and get this two sided relationship working?

** edit **

It seems that the old references still exist in the database as well, but dont show up as options in the article content-type add/edit forms.

Okay, found it. I had changed the language for my user session on the frontend.  Content wasn't yet populated in that langauge, therefore it didn't display.


Should my code use the Drupal class? When reading the documentation for the Drupal class, I notice the following sentence:

  This class exists only to support legacy code that cannot be dependency injected. If your code needs it, consider refactoring it to be object oriented, if possible. When this is not possible, for instance in the case of hook implementations, and your code is more than a few non-reusable lines, it is recommended to instantiate an object implementing the actual logic.

The example code that uses a service in a hook implementation, is the following one.

 // The preferred way: dependency injected code.
  function hook_do_stuff() {
    // Or, even better, rely on the service container to avoid hard coding a
    // specific interface implementation, so that the actual logic can be
    // swapped. This might not always make sense, but in general it is a good
    // practice.
    Drupal::service('stuff.doing')->doStuff();
  }

  interface StuffDoingInterface {
    public function doStuff();
  }

  class StuffDoingClass implements StuffDoingInterface {
    protected $lockBackend;

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

    public function doStuff() {
      $lock = $this->lockBackend->acquire('stuff_lock');
      // ...
    }
  }

The code is still using the Drupal class.

Should my code use the Drupal class? Are there any methods of that class I should avoid using in Drupal 8 code written from scratch?

By the definition of that class, anything that is not an object with injected dependencies is legacy code. That's a rather bold statement. ;)

In hooks, it is usually fine to use static methods on the Drupal class. Making that a service like suggested there is only useful if it's non-trivial code that someone might want to implement differently or/and you want to write unit tests for it.

If you're writing a service, plugins, form classes or controller classes, you should inject the dependencies.

So it's not really a question about which methods you should be using or not; it depends on where you would call it.