Entity form additional arguments I have normal Drupal8 Content entity, and I'd like to set up some additional arguments for the entity form builder.

Ie I have entity form path like so: /tilaus/uusi/{tilaus_type} and I'd like to add additional parameter, like so: /tilaus/uusi/{tilaus_type}/{some_additional_argument}. Preferably in a way that would have both of those urls working and I could handle the missing argument in buildForm method.

I've been searching for a while now, but can't find anything about adding stuff to entity form paths. Normal forms are fine and I know how to handle those. It seems that I just can't figure out the entity routing.

So: How to add additional arguments to entity form url and builder?

Cheers,

Janne

An entity add form is built with a new entity. And when you create this entity you can use parameters for this. See this example from the block module.

The new route with the additional parameter:

block.routing.yml

block.admin_add:
  path: '/admin/structure/block/add/{plugin_id}/{theme}'
  defaults:
    _controller: '\Drupal\block\Controller\BlockAddController::blockAddConfigureForm'
    theme: null
    _title: 'Configure block'
  requirements:
    _permission: 'administer blocks'

This adds the parameter theme.

And the controller for this route:

BlockAddController.php

 public function blockAddConfigureForm($plugin_id, $theme) {
    // Create a block entity with prepopulated values.
    $entity = $this->entityManager()->getStorage('block')->create([
      'plugin' => $plugin_id,
      'theme' => $theme,
    ]);

    return $this->entityFormBuilder()->getForm($entity);
  }

Here the additional parameter theme is used when creating the entity.

Using both routes at the same time is no problem, the standard entity route configured in the entity annotations will still be in place.

Another way to use parameters in entity forms is in the third parameter $form_state_additions:

$form_state_additions['langcode'] = $langcode;
$form = \Drupal::service('entity.form_builder')->getForm($entity, 'default', $form_state_additions);

This example is from the source of the entity formbuilder:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityFormBuilderInterface.php/8.2.x


Code comments in template file show on page Im using page--front.tpl.php to override my front page. Ive commented out the content with the code below, however this '-->' is shown on the page.

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

How can I stop this. Thanks

Try

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


Print view header using the "Twig Tweak" module I would like to print out the header for a view, but not the rest of the content using the Twig Tweak module. I've tried variations on {{ drupal_view('VIEW_NAME', 'PAGE_NAME', 'view_header') }}, but that prints out the entire view.

I have create simple extension for that:

add the following to MYMODULE.services.yml

    services:
      MYMODULE.twig.render_view_header:
        class: Drupal\MYMODULE\Twig\HeaderView
        tags:
          - { name: twig.extension }

Create HeaderView class inside MYMODULE/src/Twig.
Copy the code from HeaderView.php
Clear cache.
In your twig call the extension like:

{{ render_view_header('VIEW_NAME', 'PAGE_NAME') }}


How to choose a CSS grid system for new theme? I am going to make a new responsive theme based on an existing base theme for drupal 6. The theme need to be minimal but flexible. As there are many CSS grid systems to choose from, I've read that 960.gs has fallen out of fashion as it is too small for current monitors. So I'm wondering whether there are any important differences between fluid and non-fluid ones, and currently what are the best options available and why?

Ok, there is no single best answer.  It really depends on your needs.

960.gs may be out of fashion, but you can use the Variable Grid System to make just about any grid you need (both fixed and fluid).

In my opinion, the difference between fixed with and fluid grid has more to do with the theme you want (and your art director).  Not all designs will work with fluid grids, especially ones that require pixel perfection.

That said, there are techniques that you can use to have a fixed grid, but have it adaptable for different screens.  Basically, you design a few grids with the link above, and then use CSS3 Media Queries to load the grid you want based on screen size.  This is precisely what the Omega Theme does.  I have good results with this approach (though with the Drupal 7 version), and highly recommend it rather than tacking on the grid to another base theme.  I used Zen 960 a few years ago, and ended up fighting some of the automatic grid reassignments that it did.

If you go with Omega, just note that the grid-24 that it includes is slightly different than the one from 960.gs.  This means that you can't use the 960.gs templates with Omega's grid-24.  You can hook_css_alter in the sheets from 960.gs without any side effects (Drupal 7), or use other shenanigans for Drupal 6 to change the sheets you need.

If you really do need to retrofit an existing Drupal 6 theme (and can't use Omega), then I think I would sledgehammer in the multiple-grid approach that Omega uses directly into page.tpl.php.


Fetch data from database I want to fetch student result from database, by asking user to enter roll number and name. I have created a webform to take inputs but I don't know how to fetch the records from the database and display it in tabular form. Kindly tell how to fetch the record and display it.

One thing I tried is create a form in basic page content type using HTML and do the required using PHP, but I cannot figure out how to do if the form is created using Webforms.

The requirement you have asked can be easily achieved without making custom queries or use of webform module

Consider this:
If the students enrolled are supposed to login into your site, then with no doubt use user entity and wherever you want to list the students in tabular form or simple list use views module as suggested before.

If the students are not supposed to login to the system they go well with node entities,for that simply create a content type as students with field on it as you require like roll number etc.. again to list them simply use views module it will do the query for your plus will allow you to show the results in tabular way.


Responsive inline images? Recently implemented Omega/ST Alphorn and was hoping for a real responsive/adaptive result. Overall it works as expected, apart from the inline images in articles. (IMCE/WYSIWYG)

Done some searching, done some reading and found that inline images apparently are still a big challenge. It´s either js, cs, php or a combination of those.

Leaves me with two questions:

Is there a way to get a true responsive site without first learning php, css, js and then potentially mess up a perfectly working layout?
Is it really that hard to make inline images behave well in a responsive grid? I mean...  images in websites are not exactly a new phenomena, right?

Cheers

Oh, one more thing... Maybe someone with +300 reputation can create a tag `inline_images´ ... the fact that it does not even exist, worries me a bit.

You could use Media (7.x-2.x branch) and some modules for managing responsive images (I use Picture).

You should enable this modules and:

add the "media" button for Wysiwyg (I've tried both Tinymce and Ckeditor)
configure media to use the "Picture" module for a custom display mode for files

So, when you add a media to a textarea you can choose the display mode for the file.
For documentation about Picture please read this.

Obviously you could use also other modules, but the logic is the same: associates a responsive style for a display mode for images.


how to remove all slashes from all path aliases After I import data to my site, the url aliases  have / at the end, when I visit that Url alias I faced with page not found, I tried to edit one of  them manually and when I removed the slash from end I could see that node correctly, my question is how can I remove all slashes / from all aliases ?

one solution is using Views Bulk Operation, create a view  and with using  run arbitrary Php option in VBO try to remove all / from aliases,

something like ( I didn't test this )

  $entity->path['alias'] = rtrim($entity->path['alias'] ,'/');

and another and faster solution is using MYSQL TRIM in order to  update in database
go to phpadmin my admin ( or mysql command line ) and  run below command

 UPDATE `url_alias` SET `alias`= TRIM(TRAILING '/' FROM `alias` )


How to debug merge query? I have a simple merge query, with one key and three fields, something like:

$query = db_merge('product')
->key(array(
  'id' => $id_product,
))
->fields(array(
  'name'   => $form_state['values']['name'],
  'symbol' => $form_state['values']['symbol'],
  'weight' => $form_state['values']['weight'],
));

Usually it works all right, but some combinations of data passed to it and data already in database cause me headache. I'm sure I would be able to know what's wrong and why, if only I could grab actual SQL query that goes to my database.

Usually I would do:

  kpr((string)$query);

It works well for insert for example, because insert has __toString() well implemented. Sadly, implementation of MergeQuery::__toString is somewhat nonexistent:

public function __toString() {
}

It isn't even a proper implementation of this magic method, as it should always return string, but OK, I can assume it was on purpose. Anyway, this changes nothing: I can't simply cast it to see it.

What other options do I have, to see queries generated by db_merge() / MergeQuery for database interaction debugging?

A MergeQuery just runs a SELECT and INSERT internally - there isn't a single query string available, so the __toString() method doesn't make sense (which is probably why it's short-circuited).

SelectQuery and InsertQuery both implement __toString() fully, so your best bet for debugging would be to temporarily add some code to MergeQuery::execute() to dump the $select and/or $insert query before they're run, so you can inspect the query string.


Responsive jcarousel doesn't resize images Im using the jcarousel module and its responsive setting:

http://smartpeopletalkfast.co.uk/carousel/

Below you can see screenshots of how it works. When I resize the browser and the final image doenst fit it is then hidden.

This is working however the original jQuery plug in also resizes the remaining images so they take up the full available width:

http://sorgalla.com/jcarousel/examples/responsive/

How can I get my Drupal site to behave the same way? The only solution I can think of is pretty hacky. I could run javascript on page load and window resize which measured the images and the container, and then resized the images to take up the full width.

I think JCarousel still uses 0.2.x version of the JCarousel library and the example you're refering uses version 0.3.3 of the library which brings wider responsive support. Since 0.2.x and 0.3.x are not compatible as one can read here https://github.com/jsor/jcarousel, I think it will be difficult to achieve the features of the 0.3.x library in the drupal module. Look at the roadmap on https://www.drupal.org/project/jcarousel


Where to place the admin screens for a module When developing a module with an admin-area, what are the guidelines for menu-placement?

There is admin/settings/*, admin/structure, admin/content and so forth.

From what I can see, most modules follow arbitrary guidelines and often clearly content-related pages end up in admin/settings/foobar, or pages that have little to do with the architecture of the site end up under structure.

What are rules-of-thumb? What are the guidelines?

For example, I have a module that renders a tag-cloud, and I have some settings that allow manipulating how this module renders its pages. Settings such as "what vocabularies to include" and "amount of tags to render".

From a user POV, I would expect the first setting under admin/structure yet the other one under admin/config/user-interface. But I'd rather keep them together; since I believe a user (1) installs and then (2) immediately configures this type of module, once.

There is a handbook page that covers where you should place these menu items.

See Information architecture

I won't copy and paste the info here as it is too long. You also don't provide any info on what your module is about, so I can't even paste a excerpt that pertains directly to your issue.

The handbook page should be considered the canonical source for this info.

EDIT:

While these are guidelines, I don't think that they are very cut and dry. I would personally place the menu where the other two major tag cloud modules (Cumulus and TagCloud) place theirs: admin/config/content and keep them both in the same spot (one as a child item of the other)


How to specify the version for drush site-install I am running drush site-install and I want to install d6 but d7 is default, how to I specify the Drupal version?

Usually I use drush dl drupal then cd into the drupal directory and then drush si [other parameters].

That means, when you download drupal core you need to specify the version at that time -- not during site installation (which is just running the files).

You can do that by appending the version onto your dl argument, for example:
drush dl drupal-6 or drush dl drupal-6.x


Where is Twig service defined? In twig_render_template(), I see this drupal_container()->get('twig')->loadTemplate($template_file)->render($variables). But I can not see where the twig service is defined.

The class that registers the Twig service is CoreServiceProvider which, in CoreServiceProvider::register() (the method that every service provider needs to implement), uses the following code.

  // The 'request' scope and service enable services to depend on the Request
  // object and get reconstructed when the request object changes (e.g.,
  // during a subrequest).
  $container->addScope(new Scope('request'));
  $this->registerTwig($container);
  $this->registerModuleHandler($container);

The class used for the Twig service is not the Twig_Environment class that Symfony implements, but a subclass of it (TwigEnvironment) implemented by Drupal.

The other registered service is twig.loader.filesystem, which uses the Symfony's Twig_Loader_Filesystem class.


How can I link css/js from main bootstrap theme to subtheme? I'm kinda a newbie to web development and web coding languages. I recently installed Drupal 7.54 on localhost (xampp), then loaded it with Bootstrap 3.13 theme but when I come to creating a subtheme, It does not resemble the main theme though I've followed instructions here: https://www.gaslampmedia.com/tutorial-drupal-bootstrap-3-4-subtheme-with-less/

My subtheme looks like this:

Can anyone configure this? thanks

The fact that you've got the Drupal Bootstrap site logo means the theme was correctly enabled. However, this is a symptom of the browser not finding your CSS file.

And you don't actually use the Bootstrap CSS that comes with the parent theme. You actually have to import Bootstrap into your SASS/LESS. That's why you need to download Bootstrap to your subtheme (Step 4).

If you're using the SASS/LESS starterkit, you will actually need to compile your CSS (that's steps 4 and 5 of the Overview). Once you've got it compiling, you need to tell your subtheme the path of the compiled CSS by adding it to the info file (step 3 of the Overview).

stylesheets[all][] = path/to/compiled/styles.css


Core forum form dropdown empty In a D6 site, when a user goes to node/add/forum, they find that the dropdown "Forums" just shows "Please choose" but there is nothing in that menu.

There is nothing in the PHP error log or in the watchdog.

I am sure the user has correct privileges - after all, the form does show. It's just that the dropdown that otherwise (for admin) shows all the different forums on the site, is empty, and the form cannot be submitted without it.

I've seen pretty much all the web searching for a solution, without success. Hope there's somebody in this new slick interface who will show me the right answer or direction.

Right, so I tried all sorts of illogical things, one of which was deactivating and uninstalling Forum Access module (http://drupal.org/project/forum_access).

I did not have to - because the form was accessible - but I did anyway, out of desperation.

Then I enabled it again. Set all permissions again.

And things work!

BUT this is not a proper solution. Something in Forum Access was screwed up badly and ideally this issue should've been solved at its root, not by a workaround like mine.


Drupal 8 custom type content, getting values for a field of type Taxonomy (hence, Entity Reference), which can have multiple values in the field I have a custom content type (we'll call it 'book')... and it has a field  (We'll call the field 'category') which is of type Taxonomy Term and which can hold say ten items.

I can load the content programmatically:

$nids = \Drupal::entityQuery('node')->condition('type','custom content type machine name')->execute();

        $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

I can then scroll through the items of node using something like

  foreach ($node as $node_item){
      echo $node_item->title
   }

However, how would I output the content of the reference entity 'category' ... say if category has 3 items assigned to it, it would be something like this:

  foreach ($node as $node_item){
      echo $node_item->title,
      echo $node_item->category[0]->target_id,
      echo $node_item->category[1]->target_id,
      echo $node_item->category[2]->target_id,
   }

But, this does not work...

There is the suggestion that $node_item->category has to be loaded as an entity reference but using $node->cateogry->referenceEntities () does not load anything.

Any ideas?  Thanks in advance.

I think $node_item->category->referencedEntities() is what you want to use.

You have misspelled the method in your question.

 if ($node_item->category->isEmpty() === FALSE) {
    $vars = [];
    // Get referenced entities and add each to array of terms.
    foreach ($node_item->category->referencedEntities() as $term) {
      $vars[] = [
        'name' => $term->label(),
        'phone' => $term->field_phone_number->value,
        'email' => $term->field_email_address->value,
      ];
    }
  }


After I overrode a block template for a primary links, block-edit-link doesn't show anymore...? I just created block-menu-primary-links.tpl.php file in the root of my theme, in order to strip off some default structures I have for other blocks, but now that I did that, block-edit-link which was displaying itself by default on hover, doesn't appear anymore. It's not that I want it to back, but I just wonder why did it go away and how can I control it?

UPDATE:

Here is what I have in my block-menu-primary-links.tpl.php:

<div id="block-menu-primary-links">
    <?php echo $block->content; ?>
</div>

When I inspect html structure after it is rendered I see that contextual links are in there, but hidden and obviously block has lost something that made the logic tick.

Ok, tracked down the reason - every block requires to have a className of block:

<div id="block-menu-primary-links" class="block">
    <?php echo $block->content; ?>
</div>

Once I added this, contextual links regained the functionality. Still not sure where it comes from though, or if it's the only thing sufficient in all cases.


drupal 7: How do I add individual css elements to an existing module css drupal 7: How do I add individual css elements to an existing module css so that if later on when this module css is updated when the module is updated my individual css are not deleted?

You don't. You are supposed add your individual CSS files in your custom themes (possibly sub-themes of existing ones) or in your custom module.

In both cases, do it using stylesheets[all][] = your.css clausule in module's .info file or theme's .info file.


Can I add pagination to individual blog posts in my twig file? I have a views page which has all the blog articles, and you can click on a link to bring you to a single blog page.
On that single blog page I want to be able to add buttons for Previous and Next post. Something like
Previous Article
 Next Article

Is this possible?

That is the exact feature of the Book module.
Book module overview
You can configure which types are allowed to be added as book pages. There is a Block you can place on Book pages to show Book navigation and Previous/Next links (it obeys the Book pages order).

Regular Views don't have a feature to center the Pager around a pagination placement.
A custom solution can be created to add that, but there are also modules you can check out that may help:

Pager
Pagerer


Changing SQL JOIN type via PHP in Views How do I change the JOIN type in a SQL query that Views creates?

For example, in this code

<?php
function eb_mine_views_query_alter(&$view, &$query) {
  if ($view->name == 'statuser') {
    dsm($query, 'before');
    $query->where[0]['type'] = 'OR';
    dsm($query, 'after');
  }
}
?>

Will change

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM
{node} node
INNER JOIN {taxonomy_index} taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = :views_join_condition_0
INNER JOIN {taxonomy_index} taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = :views_join_condition_1
WHERE ((( (taxonomy_index_value_0.tid = :db_condition_placeholder_2) )**AND**( (taxonomy_index_value_1.tid = :db_condition_placeholder_3) )))
ORDER BY node_created DESC

to

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM node node
OUTER JOIN taxonomy_index taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '9'
OUTER JOIN taxonomy_index taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '6'
WHERE ((( (taxonomy_index_value_0.tid = '9') )OR( (taxonomy_index_value_1.tid = '6') )))
ORDER BY node_created DESC LIMIT 5 OFFSET 0;

As you can see the query changed from AND to OR through the use of OUTER JOINs.

Now I want to change the same code like this:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM node node
LEFT OUTER JOIN taxonomy_index taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '9'
LEFT OUTER JOIN taxonomy_index taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '6'
WHERE ((( (taxonomy_index_value_0.tid = '9') )OR( (taxonomy_index_value_1.tid = '6') )))
ORDER BY node_created DESC LIMIT 5 OFFSET 0;

rather than using OUTER JOIN I want to use LEFT OUTER JOIN.

So how do I do this in my hook?

You can use query alter will help you out

function custom_views_query_alter(&$view, &$query) {
    if($view->name == "tag_cloud"){
        print_r($query);// before modifying the query.
        $query->table_queue['taxonomy_index']['join']->type = "LEFT OUTER JOIN";
        //sample field change where  ever you want
        print_r($query);// after modifying the query .
    }
}

hope this helps


Display Text using flags on user profile? I'm running a D7 site and want to use a flag to display message/text on user profiles.

I'm currently using 'Form' to capture message when user flags himself/herself but cannot find a way to display that message/text on user profile.

Is there any way to capture that message using 'Form' within flags and than display that message on user profile flag till unflagged.

I achieved 'Out of office' flag functionality using rules module.

Placed an out-of-office flag on user profile and set visibility rules (panels)   to show flag only if its user's own profile
Within flags used flagging form to capture user out-of-office message
Added an extra field 'out-of-office' within user's profile.
Created a rule on flagging-event to populate 'Out-office-field' with text from flagging form.
Created a rule to delete the text from 'out-of-office' field on unflagging.


How to add an 'operations' link to a custom route? I'm implementing a custom entity with bundles in Drupal 8.

In the list of bundle entities page (i.e. equivalent to Node's Content Types listing page), I would like to provide an extra option to the list of operations, which currently include Edit, Manage Fields, Manage Display, Delete, to let the user create an entity of that bundle. So if this were on Nodes, then it would be like adding an "Add Content" link for each content type in the content listing page, which would take you to /node/add/{node_type}.

Relevant code I have so far:

Added an 'add-entity' option in the links section of the config entity's annotations:

* @ConfigEntityType(
*   id = "bloom_stem_type",
*   label = @Translation("BloomStemType"),
*   bundle_of = "bloom_stem",
*   ...
*   links = {
*     "edit-form" = "entity.bloom_stem_type.edit_form",
*     "delete-form" = "entity.bloom_stem_type.delete_form",
*     "collection" = "entity.bloom_stem_type.collection",
*     "add-entity" = "entity.bloom_stem.add_form"
*   }
* )
*/

Note that this points to a route in another entity, the actual entity that this is a bundle for.

That route is defined in (routing.yml):

entity.bloom_stem.add_form:
  path: '/admin/bloom_stem/{bloom_stem_type}/add'
  defaults:
    _title: 'Add BloomStem'
    _controller: '\Drupal\bloom\Controller\BloomStemController::addForm'
  requirements:
    _entity_create_access: 'bloom_stem'

Then I've implemented getDefaultOperations on a custom list builder class:

class BloomStemTypeListBuilder extends ConfigEntityListBuilder {
  ...
  /**
   * Gets this list's default operations.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity the operations are for.
   *
   * @return array
   *   The array structure is identical to the return value of
   *   self::getOperations().
   */
  public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);

    $operations['add'] = array(
      'title' => $this->t('Add'),
      'weight' => 10,
      'url' => $entity->urlInfo('add-entity'),
    );

    return $operations;
  }

However, when I visit the entity bundles list page, there's an exception thrown about being unable to create a route/path. On step-through debugging this seems to be because Entity::urlInfo() does not appear to use the route set in the annotation, thanks to this line that constructs its own route:

$route_name = "entity.{$this->entityTypeId}." . str_replace(array('-', 'drupal:'), array('_', ''), $rel);

The only documentation I could find on the links part of the annotation just
says:

  links
  Entity URL definitions, referencing to routes from MODULE.routing.yml.
  'canonical' is the default route for the entity. edit-form and delete-form
  can also be set. These are mostly used for Field UI. Arbitrary keys can set
  here. For example, User sets cancel-form, while Node uses delete-form.

Which I took to mean ("referencing to routes from MODULE.routing.yml") that if I
referenced a route, that route would be used.

Aside: Other things I've tried include creating the URL more directly (clearly not the
right way of doing things):

$url = \Drupal::getContainer()->get('url_generator')
  ->generateFromRoute('entity.bloom_stem.add_form', ['bloom_stem_type'=>$entity->id()]);

That generates a valid path, but a string value is not what getOperations
is expected to spit out under its url key output.

Can anyone fill me in on how this is supposed to work/where I've gone wrong?
Thanks.

What drupal core version are you using?

Link templates have been changed to links instead of route names a few months ago. See Node and other example entity types.

Another requirement is that link template names and route names need to match.

However, your primary problem is that link templates about the entity or at least entity type that you have, and that's not the case for your example.

Using link templates for operations is convenient when possible but in no way required. It can be any Url object. So your last attempt is actually close, you're just not using the right API yet (and yes, there are definitely way too many ways to generate links/URL's).

Try this:

\Drupal\Core\Url::fromRoute('entity.bloom_stem.add_form', ['bloom_stem_type' => $entity->id()])

Then use that for 'url'.


How to create a fieldset in a node form, that expands with ajax I have a (view of a ) tasks list on a page, and also a form block where users can add a new tasks.
I want to increase page load time by hiding some fields in the tasks form block, which can expand using ajax by clicking on "task details" link (the fieldset label)

Is this is possible without programming?

You might need to add this module.  https://www.drupal.org/project/field_group
Add those fields on the form to a field group, and set the group to start out "Collapsed".


Content Access exclusive permissions per node I'm playing around with content_access module, and I have a question. For my use-case, I need particular nodes to limit editing by role. This means that the content type will allow role_x to edit by default, but a particular node of that content type will not.

The way it's behaving is inclusive from the top down? If the role has permission on the content type, then they have permission on all nodes of that content type. It's only editable on the individual nodes if they DON'T have that particular permission.

Can someone tell me for sure if that's the proper behavior, or if there's a way around it? And yes, I DO have "Enable per content node access control settings" checked for the content type.

you can use Content Access Module.

A quick view :

  "This module allows you to manage permissions for content types by
  role and author. It allows you to specifiy custom view, edit and
  delete permissions for each content type. Optionally you can enable
  per content access settings, so you can customize the access for each
  content node."

I hope it works for you


Cannot redeclare MyClass - but it's only declared once I'm trying to port an image effect from D7 to D8.

I've got Drupal to list the plugin, but when I try to use it I get a WSOD with "Fatal error:  Cannot redeclare class Drupal\image\Plugin\ImageEffect\EffectMagic".

I've checked and there is no other declaration of this class anywhere.

My file is in mymod/src/Plugin/ImageEffect/EffectMagic.php
and it looks like this (nb. content of functions is removed)

/**
 * @file
 * Contains \Drupal\image\Plugin\ImageEffect\EffectMagic.
 */

namespace Drupal\image\Plugin\ImageEffect;

use Drupal\Core\Image\ImageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\ConfigurableImageEffectBase;

/**
 * Scales and crops an image resource.
 *
 * @ImageEffect(
 *   id = "image_effect_magic",
 *   label = @Translation("Effect Magic"),
 *   description = @Translation("Use ImageMagic command line to process images.")
 * )
 */
class EffectMagic extends ConfigurableImageEffectBase {
  public function buildConfigurationForm(array $form, FormStateInterface $form_state)
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state)
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state)
  public function applyEffect(ImageInterface $image)
  public function transformDimensions(array &$dimensions, $uri)
  public function getSummary()
  public function defaultConfiguration()
}

When you are creating a custom module, you have to make sure your module registers its own namespace. In the current situation your module is attempting to use the namespace of the image module namespace Drupal\image\Plugin\ImageEffect;. Where you should actually be using a namespace of your own module namespace Drupal\mymod\Plugin\ImageEffect;

Then if you require functions of the image module, you can (as you have done already) load the other classes and functions with use. Like use Drupal\image\ConfigurableImageEffectBase;.


Module to view node in a grid layout with the ability to quickly change the reference I'm looking for a module which allows me to have a grid layout presenting nodes in a certain view mode (like teaser or even a module own one).
In the end it should look something like this:

(The picture shows some node references. I didn't prepend all titles, but all blocks should be rendered the same way, except the first one, which should be rendered bigger)

Now I could do this with either views or panels, but I want to add as many blocks as I want and the first one should be rendered differently as the rest. Note that there are pictures in the node which should also be shown in different size.

I already tried it with Mini Panels, but the problem with Mini Panels is, that I can only append one node - and it is a little tricky for end users who should be able to change the node reference quickly.

Is there a good module which comes with such a solution?

You don't really need a module - just some css.
If you are using the views module to create your html then something like this should suffice:

.view-content .views-row {
    display: inline-block;
    margin: 0 20px 10px 0;
    vertical-align: top;
    width: 207px;
    font-size: 0.8em;
}
.view-content .views-row img {
    width: 170px;
}
.view-content .views-row-1 {
    font-size: 1em;
    width: 439px;
}
.view-content .views-row-1 img {
    width: 350px;
}

Here is an example in jsfiddle: http://jsfiddle.net/42LHW/3/


Display Ubercart Attributes and Add To Cart button in separate locations on product node page? I need to display my product page as such:

[-----------ATTRIBUTES-----------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]

[------ADD TO CART BUTTON-----]

How can I split the attributes and add to cart button in that way? Is there a way to do so in a tpl file? I'd prefer to avoid absolute positioning.

Create a new product template for your product node type.


What's the proper way to refer to all the code in `core/lib/Drupal`, or the code in `core/lib/Drupal/Core' or `core/lib/Drupal/Core/Foo`? When we say 'core' we mean the whole of Drupal core that you get from the Drupal project page.

On D7, core code that wasn't in modules tended to be called 'the includes' IIRC.

But on D8 they're not include files any more. They in core/lib/Drupal and we have:

core/lib/Drupal
core/lib/Drupal/Core
core/lib/Drupal/Components
core/lib/Drupal/Core/Foo
core/lib/Drupal/Components/Foo

What's the correct way to refer to these?

What you describe is correct, when you install Drupal, everything in the 'core' directory is considered the core set of Drupal files, or the bare minimum installation package.

The files in 'core/lib' is essentially all of the source code for the running system.  Personally, this is what "core" means to me.  The files (for the most part1) outside of that are the scaffold (or support files).

The files in 'core/lib/Drupal/Core' are called "Core", pronounced with a big C.  The files in 'core/lib/Drupal/Component' are called "Component", pronounced with a big C.  Confusing, yes?

"Component" are the set of files that Drupal uses, but don't actually rely on anything else in "Core".  For example, DateTimePlus and Time are two Components, that don't need anything in 'core/lib/Drupal/Core'.

"Core" are the set of files that Drupal uses, but are interdependent on each other, and also require "Component".  For example, DrupalDateTime relies on DateTimePlus (in Component) and the Language subsystem (in Core).

1Ignoring tests for this discussion.


Is there anyway to get the $form_state inside a hook_block_configure? Is there any way to get the $form_state inside a hook_block_configure()? I'm trying to do that to make #ajax work on hook_block_configure().

You don't have this information, but you can access to it with hook_form_alter. But to access to this form (that call block_configure) you have two form_id block_admin_configure and block_add_block_form.


What will be my function name in template.php for particular .tpl.php I have template.php and node--product.tpl.php files. What should be my function name in template.php to pass variable from template.php to .tpl.php

Here is template.php code

function mytheme_process_product(&$variables){  **//What should be my function name here**
$variables['temp_var']="This is demo Temporary Variable for Perticular Product .Tpl.php";
}

node--product.tpl.php

<?php print $temp_var; ?>

And my .tpl.php file name is node--product.tpl.php where product is my content type name.

Please reply.

You need to use theme_preprocess_node function in template to add variables..

/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */

function YOURTHEME_preprocess_node(&$variables, $hook) {

  // define $node object, so it's be easier to use it
  $node = $variables['node'];

  // add variables to node--nameofnodetype.tpl.php file
  if ($node->type == 'product'){

      // $variables: an array with variables
      // you need to add one, so just define it
      $variables['my_variable'] = 'whatever';

  }
}

In your node--product.tpl.php file:

// check if your new variable exist
print $my_variable;


Drupal 7: How to create dynamic link based upon url I simply want a menu item which scans the url, grabs the second argument, and plugs it into the second wildcard location of the new menu item it's creating.

So if the URL is: http://drupal.org/contenttype1/johndoe (johndoe = 2nd argument)

the menu item displayed will be: http://drupal.org/contenttype2/johndoe (johndoe = wildcard location)

So far, based upon a few forum, I've sketched out the following code, which is clearly incomplete, and it is doing nothing right now.

Basically, I just want this menu item to link to an existing page mysite.com/[coach name]/page. I'm using clean URLs by the way.

        <?php
    function coachmenu_menu() {
      $items = array();

      $items['%/page'] = array(
        'title' => 'Coach Page',
        'page callback' => 'coachpagelink',
        'page arguments' => array('0'),
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
        'menu_name'=>"menu-coach-menu",
      );
        return $items;
    }

    function coachpagelink($wildcard) {
        return $wildcard;
    }

Any ideas on what I can do?

Your code is fine except for a detail. The correct menu definition is the following one.

$items['%/page'] = array(
  'title' => 'Coach Page',
  'page callback' => 'coachpagelink',
  'page arguments' => array(0),  // Use an integer, not a string.
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name'=>"menu-coach-menu",
);

If you use a string in the page arguments, the page callback is not receiving part of the URL, but that string. In your case, the page callback is always receiving '0' as argument, even when the page callback is invoked for example.com/jhondoe/page.


How do I add  tags to the output of a view list? The output of a view I am using contains the following code.

    ....

    ...

    ....

    ....

I want to add
....
 around the following snippet.to group two fields

      ...

      ....

the loop

 <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <<?php print $field->inline_html;?> class="views-field-<?php print $field->class; ?>">
    <?php if ($field->label): ?>
      <label class="views-label-<?php print $field->class; ?>">
        <?php print $field->label; ?>:

    <?php endif; ?>
      <?php
      // $field->element_type is either SPAN or DIV depending upon whether or not
      // the field is a 'block' element type or 'inline' element type.
      ?>
      <<?php print $field->element_type; ?> class="field-content"><?php print $field->content; ?></<?php print $field->element_type; ?>>
  </<?php print $field->inline_html;?>>
<?php endforeach; ?>

how to add the div tags to the loop?

In the View edit screen, click Advanced. At the very bottom of that, you'll find a bit called: Theme: Information. Click the Information link and a new window will pop up, showing you theme overrides for the view. Each category changes different parts of the view.

All of the file names listed on each type will show the available filenames which could be used to override this view, in order of least specific to most specific. So if you pick the first one, it will probably override all of your views, while if you pick the last one, it will only override that view in a certain display.

Once you've picked what you're going to override, click the link and copy all of the code shown there to the clipboard. Then go to your theme directory and make a file with the filename you picked from before and paste in the code you copied. Now just add the
 tags you want wherever you like.

You'll need to click the "Rescan template files" button for Drupal to pick up your new theme override file. Views shows you which one it will use for the view by putting the one it will use in bold.

Edit: When writing this, I was going through the steps for Drupal 7, but I believe the steps are very similar for Drupal 6.

Next Edit: From the code you have pasted, it looks like the most appropriate place to put the new div tags would be (see the asterisks):

**
**
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <<?php print $field->inline_html;?> class="views-field-<?php print $field->class; ?>">
  <?php if ($field->label): ?>
    <label class="views-label-<?php print $field->class; ?>">
      <?php print $field->label; ?>:

  <?php endif; ?>
  <?php
    // $field->element_type is either SPAN or DIV depending upon whether or not
    // the field is a 'block' element type or 'inline' element type.
  ?>

    <<?php print $field->element_type; ?> class="field-content"><?php print $field->content; ?></<?php print $field->element_type; ?>>
    </<?php print $field->inline_html;?>>
<?php endforeach; ?>
**
**

I normally experiment a bit with this, so it's a bit difficult to tell you the exact spot offhand, but hopefully the above will be close...


Programically update node when visited by 'editor' role My goal is to have promote-node-when-visited-by-editor feature. This is code from MYMODULE using hook_node_view:

function MYMODULE_node_view($node, $view_mode, $langcode) {
    // 'promote-node-when-visited-by-editor' (roles[6]) feature
    if ($node->type == 'blog') {
        if (empty($node->promote)) {
            if ($view_mode == 'full') {
                global $user;
                if (isset($user->roles[6])) {
                    $node_data = node_load($node->nid);
                    $node_data->promote = '1';
                    node_save($node_data);
                }
            }
        }
    }
}

When all IFs are met, I get this error in execution part with hook_node_view:

Recoverable fatal error: Argument 1 passed to drupal_attributes()
must be of the type array, null given, called in /includes/common.inc
on line 2534 and defined in drupal_attributes() (line 2426
of /includes/common.inc).

What's the right hook when I want programically update node when (after, right before...) visited by editor role. For example rules have content is viewed event.

I have replaced these 3 lines

            $node_data = node_load($node->nid);
            $node_data->promote = '1';
            node_save($node_data);

with

            db_update('node')
                    ->fields(array(
                        'promote' => '1',
                    ))
                    ->condition('nid', $node->nid)
                    ->execute();
            db_update('node_revision')
                    ->fields(array(
                        'promote' => '1',
                    ))
                    ->condition('nid', $node->nid)
                    ->execute();
            db_query('DELETE FROM cache_entity_node WHERE cache_entity_node.cid = :nid', array ( ':nid' => $node->nid));

and it seems working :)


Redirect Using Rules Based on Account Role Further to this previous question, https://drupal.stackexchange.com/questions/1790/redirect-users-after-login-depending-on-the-users-roles I am trying to accomplish a similar redirect on a D7 whereby once a user with a specific role type has logged in, they are redirected to a homebox (using the Homebox module) page of 1 of 2 types (1 Teacher; 2 Student) and the homeboxes nodes are named accordingly: 1) teacherhomebox, 2) studenthomebox using URL aliases. I have been following Johan Falks tutorial http://vimeo.com/28804544 (many times now!) and thought I understood what appears to be a simple task, but after testing either of the said roles, my redirects do not show the relevant (after login) user homebox as the primary page and simply stays on my custom Panel 'landingpage' I have setup as the primary welcome site homepage. Of course they do log in and it shows their account link on the header (which I'll remove later) I'm not sure what or why the redirects are not working, maybe I've not put the correct account select in the Rules UI but FYI and for testing purposes (using a student role) the setup is as such:

Event:
User has logged in

Condition:
User has role(s) (parameter: Role= student, match=ANY)

Actions:
Element: Page Redirect (parameter: URL: studenthomebox)

I have in the URL redirect Value, put "studenthomebox"

I would also like to add that I am trying to create a 'homebox' dashboard as per drupal.org and would be happy to acheive the same along with using the Rules module (with homebox) and would prefer to stay using Rules given the option.

Any help is very much appreciated as I'm after many hours, rather confused now.

Check that you are not using any other contrib modules like Login Toboggan which may be setting a redirect after log in.

Failing that, turn on Rules Debugging by going to admin/config/workflow/rules/settings and ticking the 'Log debug information to the system log' checkbox.

Log out and log back into your site as a student user. Then go to admin/reports/dblog and check the debugging messages set by Rules.

You will then be able to see which of your conditions is failing.


How to allow a route to a user as long as he has the good role? Maybe this is a noob question but here goes:

I have a menu a menu that contains four links. However, I need one of the items to be accessible only if the current user has "beneficiary" as role.

Since the user's 'roles' is an array containing all kind of roles, how can I set my route in a way that as long as the user has the correct role ?

IE, let's say that a random user has the following:

$user['roles'] = ['authenticated', 'beneficiary', 'elected'];

and would pass, but another random user having the following:

$user['roles'] = ['authenticated', 'elected'];

wouldn't.

I'm pretty sure there is a way but I can't find explicitely what I'm looking for in Drupal's documentation

Thank you in advance

I've never personally tried this, but it looks like in your routing.yml file, you can specify a _role permission under requirements:

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

my_module.your_route:
  path: '/your_menu_path'
  defaults:
    _controller: '\path\to\your\controller'
    _title: 'Menu title'
  requirements:
    _role: 'beneficiary'


Druapl 7 Update displayed price of product when quantity changes I'm new to drupal. What I want is the price to be updated for an ubercart product when I change the quantity the same way it happens with the attributes on the product page.

So far I have a custom module to edit the type of the edit quantity form when I add a product in my cart. I turned it to a select box and tried to append the class ajax-processed but nothing happens.

Well after some tail chasing I managed to do it. It probably is a bad solution since I had to modify uc_product_module itself. Here's what I did:

1) Created a custom module that adds two buttons in hook_form_alter- and + that will modify the quantity:

    $form['decrease'] = array(
        '#name' => 'decrease',
        '#id' => 'decrease-product-qty',
        '#type' => 'button',
        '#value' => t('-'),
        '#prefix' => '<div class="form-item form-item-qty-btn form-type-uc-quantity form-group">',
        '#ajax' => array(
            'wrapper' => 'wrapper',
            'callback' => 'decreaseProductQuantity_form_ajax_callback'
        )
    );

/**
 * AJAX callback function for addToCartFormEditQuantity_form().
 */
function decreaseProductQuantity_form_ajax_callback($form, $form_state)
{
    $nid = $form_state['values']['nid'];
    $node = node_load($nid);

//Get current quantity
$quantity = (int)$form['qty']['#value'];
// Adjust
if ($quantity > 1) {
    $quantity--;
}

$form_state['storage']['quantity'] = $quantity;

// Calculate updated price to be displayed
$displayPrice = uc_currency_format($node->price*$quantity);
// Price textfield id and class
$fieldId = "#total-price-uc-product-" . $nid;
$fieldClass = '.uc-price';

// Update field via command
$commands = array();
$commands[] = ajax_command_invoke('#edit-qty', 'val', array($quantity));
$commands[] = ajax_command_html($fieldClass, $displayPrice);

// Send the command to the page.
$page = array(
    '#type' => 'ajax',
    '#commands' => $commands,
);
return $page;
}

2) Saved quantity in $form_state['storage']['quantity'] = $quantity; as seen above. In order to keep the value form being erased add use $form['after_build']:

//Inside hook_form_alter
$form['#after_build'][] = 'addToCartFormEditQuantity_after_build';

function addToCartFormEditQuantity_after_build(&$element, &$form_state)
{
    $form_state['storage']['quantity'] = (int)$element['qty']['#value'];
    return $element;
}

3) Final step modified ubercart/uc_product/uc_product.module function uc_product_view_ajax_commands:

 * @return
 *   An array of Ajax commands.
 */
function uc_product_view_ajax_commands($form_state, $keys) {
  $commands = array();
  if (variable_get('uc_product_update_node_view', FALSE) && !empty($form_state['storage']['variant'])) {
    $node_div = '.uc-product-' . $form_state['storage']['variant']->nid;
    $build = node_view($form_state['storage']['variant']);
    foreach ($keys as $key) {
      if (isset($build[$key])) {
         //Modify display price to take qantity into consideration
        if ($key === "display_price") {
          $quantity = (int)$form_state['storage']['quantity'];
          $totalPrice = (float)$build[$key]['#value'];
          $totalPrice *= $quantity;

          $build[$key]['#value'] = $totalPrice;
        }
        $id = $node_div . '.' . str_replace('_', '-', $key);
        $commands[] = ajax_command_replace($id, drupal_render($build[$key]));
      }
    }
  }
  return $commands;
}


How do I consume JSON data via a hook_menu callback? I'm trying to set up Tropo's WebAPI with a Drupal site, and I thought I'd just create a hook_menu() callback for example.com/tropo, then use the hook_menu callback I just created to consume the API call from Tropo (which contains a simple JSON array of data), then respond.

I can do the response part pretty easily... build the data, drupal_json_output() and exit (that just returns the JSON basically).

The part I'm having trouble with is getting the data that is sent to the /tropo menu callback... I can't access any data by using either of the following:

$json = file_get_contents("php://input"); // returns NULL

(below uses the inputstream module:)

$json = file_get_contents("drupal://input"); // also returns NULL

I checked what some other modules do, and it looks like they use hook_init to grab the JSON. Is this the preferred method? I'd love to be able to do it in hook_menu and use my own path and such...

Alternatively, would I be better off writing my own PHP script and running outside of Drupal, just doing a bootstrap for the database if I need to?

Well, it turns out I was getting the data, but I forgot to decode it...

In my hook_menu callback:

$received = file_get_contents("drupal://input"); // Use inputstream module.
$received = json_decode($received, TRUE);

Then I can play around as much as I'd like with the $received value.

Additionally, the inputstream module is invaluable in letting me get to the input stream more than once (if you try using php://input more than once, the second time, and those following, will return NULL).

As an additional note, I just noticed today a new module that might be an even simpler way of handling this: Content as JSON


console.log() renders elements as "D.fn.D.init" I have a strongly ingrained habit of using console.log() to pinpoint where an element is on the page. Usually if you had a page like this

hello Drupal.stackxchange.com This is my first question!

goodbye

and then you ran a jQuery function like this

console.log($('div'));

your console would spit out this

[▶
…
, ▶
goodbye
]

which works just as good as the element inspector. Hovering your mouse over one of these will make the actual element on the page be highlighted in yellow with a helpful tooltip. It's one of my favorite ways to work with markup, however the jQuery that comes with Drupal makes it impossible by spitting out the following alternative.

[▶D.fn.D.init, ▶D.fn.D.init]

which does NOT work with the highlighting feature because it's not the actual element being passed to the console, nor is it very descriptive visually.

Why?

After a bit of digging around I managed to reproduce this on a couple of dev sites and I think I've narrowed down the problem.

The issue seems to be with the number of elements being passed to console.log.

This is what the output looks like with 100 <div> tags on the page:

And this is what it looks like with 101 <div> tags on the page:

So it seems either jQuery or console.log is imposing some sort of limit on rendering the output. I don't have time to look into it but my hunch would be that console.log is responsible for that.


How do I add a description to the node title form field? This might sound stupid, but I can't find a way to do it. I need to add a description to the node title, just like I add a description to other fields. How can I do it?

In a hook_form_alter() or hook_form_FORM_ID_alter(), add a description attribute to the node form element array:

 //Add a title field description
  $form['title']['#description'] = t('Enter your awesome title field details.');


Override user/%user page callback for a role I have done this by altering the 'page callback' for the path and then checking for the user role in the callback function. I am not sure if this is the best way to go about it.

function mymodule_hook_alter(&$items) {
  // change callback for user view page to our dashboard function
  $items['user/%user']['page callback'] = '_client_dashboard';
}

/**
 * Callback function for menu item user/%
 */
function _client_dashboard($account) {
  global $user;
  // since we override user.module page callback for user/%user
  // perform default function for users without client role
  if(!in_array('client', $user->roles)) {
    // return the function used by user.module passing in account
    return user_view_page($account);
  }
  return t('Dashboard');
}

I know you cannot have logic in hook_menu_alter since it's only called when caches cleared and stored in routing table.

The approach that you took is fine. It's one of the ways that you can control which page you have to show depending on (this case) the role.

Tip: take in consideration if "client" is going to be always the role allowed to see that page. If that could change in the future (add more roles or change to other), try to make it configurable.


How to remove wrapper when rendering page region? $sidebar_second = render($page['sidebar_second']); print $sidebar_second;

generate by default

How can i remove these wrappers ?

Add a copy, or edit the existing copy, of the core (or your theme/sub-theme's) region.tpl.php file, to your active theme. You can change the wrapping markup to whatever you like in there.

Clear the cache, and you're done.


AJAX - How to dynamically add options to select? In my drupal module, I want to dynamically add values to my select list. I also write them to the database. After it is added to the select and written to the db, I sort the options of the list alphabetically.

No problem at all, but whenever I add a value that will be the last one in the list (say zebra), and I select it right away, I get an "illegal choice detected" error. Why is this and how do I fix it?

Code when creating my form:

   $form['acategory_text'] = array(
      '#type' => 'textfield',
      '#title' => t('Nieuwe categorie'),
      '#size' => 25,
      '#maxlength' => 31,
      '#attributes' => array(
        'class' => array('textfield'),
      ),
    );

$form['acategory_button'] = array(
  '#type' => 'button',
  '#value' => t('+'),
  '#ajax' => array(
    'callback' => 'new_acategory_callback',
    'wrapper' => 'orderapp',
    'method' => 'replace',
  ),
  '#attributes' => array(
    'class' => array('button'),
  ),
);

$form['store_appcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => 'Order.app categorieën',
  '#multiple' => TRUE,
  '#options' => get_values('ac_id','appcategory',appcategories_load_multiple(FALSE, array('sid'=>$id))),
  '#prefix' => '
',
  '#suffix' => '
',
  '#size' => 7,
  '#ajax' => array(
    'callback' => 'get_mapped_categories_callback',
    'wrapper' => 'orderapp',
    'method' => 'replace',
  ),
);

Callback method:

function new_acategory_callback($form, &$form_state) {
  $newappcat = $form_state['values']['acategory_text'];

  $id = $form_state['values']['id'];
  $entity = entity_create('appcategories', array('sid' => $form_state['values']['id'], 'appcategory' => $newappcat));
  entity_save('entity_test', $entity);

  $form['store_appcategories']['#options'][] = $newappcat;

  usort($form['store_appcategories']['#options'],create_function('$a,$b','return strcasecmp($a,$b);'));

  $form_state['rebuild'] = TRUE;
  return $form;
}

You need to build up the correct options directly in your form builder function, not in the ajax callback.

You can for example do so by converting your button to a submit type, add a specific #submit callback function, and then add something to $form_state and trigger a $form rebuild. In your form builder function you can then look into $form_state and build up the $options accordingly.

Logic always needs to be in the form builder/submit callbacks, the only thing that the ajax callback needs to care about is which part(s) of the form need(s) to be returned. The easiest way to correctly implement ajax in most cases is to build the form without ajax (which will just work with the method described above) and then add #ajax on top of it, once it works without.

You also don't need to set $form_state['rebuild'] in your ajax callback that only has an effect in the submit callback.


How to allow user registration and allow them to upload videos? I am creating a video sharing website like youtube, dailymotion etc. So I need to allow registered users to upload videos when they come to their profile on my website.

I have already setup a media content type with images and video options.

How can I allow users to create it?

If you have to upload a Youtube video in your website, there is the Youtube field module which enables you to upload videos from Youtube by putting the link in the field.

If you want to upload a video from any site use the Media module for this.

  The YouTube field module provides a simple field that allows you to add a youtube video to a content type, user, or any entity.

  Display types include:

  YouTube videos of various sizes.
  YouTube thumbnails with image styles.

  This module is a lightweight alternative to Media or Embedded Media Field, if you're looking for a way to add video fields from more than one provider, you may want to consider looking into either of those two modules.

  The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.

  Media is a drop-in replacement for the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Any files uploaded before Media was enabled will automatically take advantage of the many of the features it comes with.


How can I obscure what I am using to run my site? Is there anything I can do to prevent somebody from knowing my site is using Drupal by looking at the source code of the front page? I am referring to people who scan sites using software that detects the software used to run the website to be able to attack it using any known weak point.

If it is not possible to completely hide the fact that the site is using Drupal, is it at least possible to confuse them (e.g., by aliasing the node pages with URLs like http://example.com/servlets/<node-id>.jsp)?

You can't hide it completely. Most of what's needed to do it, would require hacking core. The biggest tell, is the Drupal JavaScript variable which is readable from the front page, or any page for that matter.

If you want to improve your sites security by hiding that it's a Drupal site, your effort is better spent on code reviews than it is on trying to hide the fact that the site is made with Drupal.


8 - How can I detect when an entity is being autocreated? I have an entity_reference field that autocreates entities (i.e., the 'Create referenced entities if they don't already exist' option is enabled in the field's configuration). I'm looking for a way to set some values on those autocreated entities before they are saved (e.g., author, revision message, ...).

What I've tried so far:

hook_node_presave(), but there is no indication on the $entity object that it's being 'autocreated' through an entity reference field.
I can see that the new entities are being autocreated in \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::preSave, but it's not clear to me if/how I can override that method without implementing my own entity_reference field type.

Any suggestion for how to set values on an entity when it is being autocreated?

You need a custom EntityReferenceSelection handler plugin. An example would be how the node module sets the autocreated entity to published:

Drupal\node\Plugin\EntityReferenceSelection\NodeSelection:

  public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
    $node = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);

    // In order to create a referenceable node, it needs to published.
    /** @var \Drupal\node\NodeInterface $node */
    $node->setPublished(TRUE);

    return $node;

You find more information in the plugin annotation class https://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/Annotation/EntityReferenceSelection.php


Users can rate product after their order status changed to completed I want to give permission to user to rate a product when their order status set to completed. For that I've tried using rules but in action i was not able to set permission for particular user whose order completed.

I'm using five star drupal module which is using voting api. Need help to implement this feature.

What I am suggesting is to create a new node type "review" and referenced this to product with references module. Create one view to display reviews or rating on product page. Create one permission or need to hook for permission to access already purchase of same product.


what is the difference between Drupal.formatPlural() and Drupal.t()? what is the difference between :
Drupal.t(string, arguments, options ) and Drupal.formatPlural()
Drupal.t() is used in the javascript part to translate the string and it can accept a set of arguments that will translate the string placeholders ex:
var translatedString = Drupal.t('a string about @subject that needs to be translated', {'@subject': 'Javascript in Drupal'});

what about Drupal.formatPlural()

Actually after some playing aroud with the code I HAVE FOUND THE ANSWER :
formatPlural($count, $singular, $plural, array $args = array(), array $options = array());

code
the formPlural function enable us to translate a string in plural or singular format according to the first argument $count , a $singualr string will display if $count = 0 or 1 otherwise if $count > 1 the $plural string will be displayed , and in plural string we can get the $count value using @count , for example in the code bellow  :

the first formPlural function will return $singular  string since
$count = 1
the second formPlural function will return $plural
string since $count > 1

var typeVar = 'list';
var singular = Drupal.formatPlural(1, 'I have 1 item', 'I have many @type items', {'@type': typeVar});
$('#translate_singular_item').html(  singular   );

var plural = Drupal.formatPlural(3, 'I have 1 item', 'I have @count @type items', {'@type': typeVar});
$('#translate_plural_item').html(  plural  );

output

Back-office Translation
now we can translate both singular and plural string :


Displaying Images in Search Results I have a Resource content type that has an image field (field type and widget are both 'image'); the standard image type.  The title of this field is 'Icon' and the machine name is 'field_icon'. I created my teaser so that the title, date, image, and description fields show and customized my search-result.tpl.php and template.php files so they are displaying the teaser/snippet. That works fine.

However, now I'd like to be able to format the returned results a bit more. I see how I can put HTML directly in the .tpl file, fine. But I want to customize the image field so it appears to the LEFT (float or align left) of the other returned teaser elements.

My problem is I can't figure out how to get the variable that represents the image so I can manipulate it in my .tpl file. I tried the following, but it just returns the number to indicate there IS an image or not:

$result['node']->'field-icon';

Can someone please tell me how to get the proper variable or link to the icon itself so I can manipulate it in my .tpl file?

Thank you.

Note, here's my current search-result.tpl.php code:

<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_suffix); ?>

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

Perhaps something like this will help:

/**
 * Implements hook_preprocess_search_result()
 */
function MYTHEME_preprocess_search_result(&$variables) {
    $node = $variables['result']['node'];
    if (is_object($node) && $node->nid) { // if the result is a node we can load the teaser
        $variables['teaser'] = node_view($node, 'teaser');
    }
}

That will provide the variable $teaser to your search template. In search-result.tpl.php you can then access your field data:

    <?php print render($teaser['field_icon']); ?>

<a href="<?php print $url; ?>"><?php print $title; ?>

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


Creating SearchAPI searches without using Views I am using SearchAPI on a website with 20,000 entities indexed. Searching through them with SearchAPI is pretty simple. Its fast. I want to keep it as fast as possible with very low overhead, without using Views.

I've created the appropriate code needed to create a form, blocks, and a page callback via a custom module. What I would like to do is have someone use a custom search form, hit submit, and be sent to the search results page callback.

What is the best way to store and read from form values in a page callback? Is there any way to have values persist outside of $_SESSION? Or is that the best method? If I wrote a method in my search class that inspected $_POST and did proper validation on it, would it be better to use that to keep executing a search based on that?

I already have paging methods worked out in the code, but kind of scratched my head on how to execute a form, then when using a pager, keep those values for querying the next set. I think I am close, but wanted some input if there is a way I am not seeing.

Realized I never added a follow up. Search API Page does not solve all the cases, and this is possible in Drupal 8 as well.

A query string was added on form submission, redirecting to my url + query string args. These prefill form values (sanitized of course) and modify the initial Search API query. Extra work was done to store some data in session, so that the query could be repeated on detail pages for sidebar results (prev/next navigation in the same result set).

Using the normal Drupal pager worked fine as well.

As part of this work, a module was born: https://www.drupal.org/project/search_api_view_modes

Here is an example of doing it in Drupal 8: https://gist.github.com/kevinquillen/cad07541347385744b161a26690ab75d

Taking this route allows you to create and provide a very tailored, controlled experience.


Payments and user balances/virtual coins I would like to implement some premium options within my website.  But most modules I have looked at, focus on providing payment-interactions (buying items, adding node etc.).

In contrast, I am looking for keeping a seperate account per user and their purchases.  My expected workflow would be that the user establishes a certain balance eg. 100 USD and then uses this balance to purchase many small items/subscriptions/etc. The payments should be handled via automated payment gateways (Paypal or some credit card processor) or through manual payments added by admin.

Can you suggest any modules - ideally for D6, but feel free to post D7 solutions too - that would faciliate managing a user-based account in Drupal?

Btw, I am aware that the complete solution is not availible out of the box and that custom modules will be necessary.  I am also open to suggestions relying on external services or alternative ideas like the userpoints module.

Yes, Userpoints should work for this, with one major exception: It doesn't support decimal values. There are patches available for both D6 and D7 but you're pretty much on your own when using them.

There is integration with Ubercart available for D6 and Commerce for D7 (http://drupal.org/project/commerce_userpoints) which allows you to buy points with money. There are also modules available in the Userpoints Contrib project for requiring points to create nodes, which you can combine with Userpoints Nodes and Comments to remove points when a node is created, resulting in the ability to sell creation of nodes. And, there is Userpoints Node access, http://drupal.org/project/Userpoints_nodeaccess, which allows to buy access to nodes (only the D7 version works).

In general, the D6 versions of the modules aren't well maintained, especially the modules in Userpoints Contrib are very unstable (while those ported to D7 should work pretty fine).

Disclaimer: I am the Userpoints D7 maintainer and might be biased.


When do I use views_get_view_result()? I have basic listing in a View. I can give styles, or unformatted text, provide a link, etc. However, I would need the listing to be a list of linked items, with the destination URL changing depending on context: language, type of user, etc. So I just retrieve the listing with a view, and in the template, I use views_get_view_result to print the fields I need and warp them with the necessary parameters (the dynamic URL, etc.). Is that a good approach or could this be achieve through the config of the View or with aid of another module (Context, Context Views, whatever...). Thanks!

Trying to give a reply to the question title:

you use views_get_view_result() when you need the result of a view inside your custom code. It works fine inside module or theme files.

For instance: you need  to get a list of users inside your custom module. Instead of querying the database with db_query, yuo can build a
Users View named a_list_of_users and get results with

    $res = views_get_view_result($name = "a_list_of_users", $display_id = "default");

Any additional parameters will be passed as arguments.

I love this function!


Adding js and css from a module but only to node view, not node edit I'm adding js and css from a custom module and it works except for the fact that it also adds to the node edit page which I don't want.

I have this in my custom module:

function MYMODULE_preprocess_page(&$vars) {

// Global node.
$node = menu_get_object();
 if (!empty($node) && $node->type == 'my_node_type') {

// do stuff here like add_js, add_css

  }
}

... this works except that it also adds js and css files to the node edit page which I do not want. I've been playing around with this now for a while and any searches I've done have come up blank so I'm out of ideas for now. I suspect I need an extra argument to only add this to a node view and not node edit.

A quick, dirty way would be to check the current path for 'edit':

$node = menu_get_object();
if (!empty($node) && $node->type == 'my_node_type' && arg(2) != 'edit') {
  // ...
}


How to allow access to create terms in a specific vocabulary? If you remove "Administer vocabularies and terms" from a role in Drupal 8.4, but you want to give access to a role for a specific Vocabulary, there is no out-of-the-box way to do this for "create" access for terms in specific vocabularies.

For example, for a Vocabulary called "Author".

You are given the option to "Delete terms from Author" and "Edit terms in Author", but no option to "Create terms in Author".

How would you add this option a role in Drupal 8 after you have removed the "Administer vocabularies and terms" permission?

You can create a custom permission: "Create new authors" in mymodule.permissions.yml:

create new authors:
  title: 'Create New Authors'
  description: 'Create New Author Taxonomy Terms'
  restrict access: true

Assign the new permission to the roles you want.

Then using hook__access_entity_create_access():

function mymodule__access_entity_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle) {
  if ($entity_bundle == 'author' && $account->hasPermission('create new authors')) {
    return AccessResult::allowed();
  }
  // No opinion.
  return AccessResult::neutral();
}

This will give explicit access to roles with your custom permission, and in other cases it will defer to the default drupal permissions.


JS/CSS aggregation not creating css folder I am creating a Drupal 8 website with a custom theme.
When css and js aggregation checkboxes are checked, js directory is created in sites/default/files/, however css folder does not get created.

Also all js and css is not working.

When I ran this command in terminal ls -l sites/default/ I get the following line for files folder

drwxrwxrwx  7 admin  staff    224 May 10 10:30 files

Would there be any reason the site does not create css folder in sites/default/files?

Thanks in advance.

I believe this issue is due to incorrect permission. Can you check the permission on the folders. It will also be helpful if you print the related error/warning/notice logs with the question.

Thanks


taxonomy auto-path views path issue I have used the taxonomy menu and auto path to create a url alias something like below. The reason is so that the taxonomy menu has the right path.

/my-alias/[term:name]

I then enabled the taxonomy view and modified the view page so that it is like url below.This view grabs the taxonomy term and then filters that term and displays the fields in the view this works fine when I test it in the view itself

/my-alias/%

My question is how do I get drupal 7 to look at the view url first and not send it to the taxonomy alias?

I think your problem lies in the fact that you are using the same URL for both a view and a node - this is a really bad idea in most circumstances.

If you always want the view to show - what does it matter if the taxonomy itself is at /category/tag/[term:name]?

You might find Page Manager useful for what you're trying to do, there's a fantastic free tutorial and familiarisation set of videos that have helped me immensely of late.


Searchand Replace text in Drupal Nodes I client has recently been acquired by a new Group and has requested that I do a search and replace for their name e.g. "Foo Group" and replace this with "New Group". There will be multiple instances of this e.g. "Foo Housing Trust Group" and "Foo Housing Trust".

I can see in a previous post How to fix millions of alt text that are missing on body content that I can use the Search and Replace Scanner module but would this be the best way to do this rather than a DB Query?

Thank you for any help you can provide. Pete.

A possible alternative to achieve what you're trying to do, is to use a combination of these (commonly used) modules: Rules, Views and VBO.

With these modules in place, you could implement (for each of the fields that your question is related to) a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

Create a Rules Component with a Rules Condition to checks if the field contains the string you're interested in (probably using a "text comparison" with a "regular expression" to find all variations).
Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

Repeat the above for each field (simply by adapting your Rules Component for each of these fields).

PS: I'm assuming this question is above D7 ...

Done ...


Can a custom module be used to assign permissions associated with a different module? Drupal 7. I'm using a contrib module that has one user permission associated with it.  Enabling the module assigns that permission to only the "Administratror" role. I'd like to find a way of using a custom module to also assign the permission to a custom role I've created.

So far, I have within my custom module a function that runs when the contrib module is enabled.

function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module' => TRUE,
      ));
    }
  }
}

But it results in an error like this (output from Drush):

  WD php: PDOException: SQLSTATE[23000]: Integrity constraint violation:
  19 role_permission.module may not be NULL: INSERT INTO
  {role_permission} (rid, permission,  [error] module) VALUES (?, ?, ?);
  Array (
      [0] => 5
      [1] => 1
      [2] => )  in user_role_grant_permissions() (line 3076 of /var/www/d7/modules/user/user.module). PDOException: SQLSTATE[23000]:
  Integrity constraint violation: 19 role_permission.module may not be
  NULL: INSERT INTO {role_permission} (rid, permission, module) VALUES
  (?, ?, ?); Array (
      [0] => 5
      [1] => 1
      [2] => )  in user_role_grant_permissions() (line 3076 of /var/www/d7/modules/user/user.module). Drush command terminated
  abnormally due to an unrecoverable error.
  [error]

Looking at the table structure that third value [2] that's blank is supposed to be the name of the contrib module associated with the permission.

I think the problem is something along the lines of either the permission doesn't exist yet at that point in the execution, or maybe it's a security safeguard that prevents custom code from assigning permissions associated with separate modules. Either way I'd appreciate someone pointing me in the right direction with this.

There are hooks* to revoke or change permissions so there is no need to set TRUE or FALSE in your snippet.

Try this:

function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module',
      ));
    }
  }
}

In this call, you are setting the array's value to the permission name -- Not the key.

*: user_role_change_permissions() and user_role_revoke_permissions()


How to achieve clean HTML markup? If you visit official website of Dries Buytaert https://dri.es/ and look into the source you will see very clean and minimal markup with no unnecessary tags and classes, eg:

When I create a simple custom block it has lots of junk under each field,  eg:

How to strip and delete all the junk and leave or add only classes and wrappers you need?

I did look up Fences, but it's latest version is in alpha since 2016 (and not sure if it does that) and cannot figure out how to strip at least classes with Display Suite extras module, it seem that it doesn't do anything, went though all settings.

Did Dries use any of known public modules or is it all custom code?

A lot of those classes are added by the classy base theme templates. You'll be able to get rid of them with a theme based on stable instead.


How can I modify a user's last access date using Rules? Goal

I want to make a Rule that automatically changes the user account last-access date to "now" for certain users.

Use case

I have a view that displays users by last access date, but I need some users to consistently appear near the top of the search results.  Previously, I simply assigned all the users that I needed at the top to a specific role, and then sorted the view so that that role came first, but the problem with such an approach is that the same users always appear at the top in the same order.  I want the order to look a bit random, so I want to update the access date with a rule that automatically re-schedules itself every x hours.

Problem

I can write a rule that re-schedules itself.  However, to update the "last access" date, when I use the Set a data value action, I receive the following message:

  The selected data property doesn't support writing.

How can I get around this and refresh the last access date in Rules?  I can write a custom rules action if necessary, but I don't know what to put in the action to reset the access date.

Two options:

Just as you said, a custom rules action:

function MY_MODULE_rules_action_info() {
  return array(
    'MYMODULE_action_update_last_access' => array(
      'label' => t('Update last accessed timestamp'),
      'group' => t('Custom'),
      'access callback' => 'rules_user_integration_access',
      'parameter' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('User'),
          'description' => t('User account whose last accessed timestamp will be updated.'),
        ),
      ),
    ),
  );
}

function MYMODULE_action_update_last_access($account) {
  // There might be another way to update the last accessed date, but you can
  // also do it directly in the database.
  //
  // NOTE: the code below will update the last access to current timestamp.
  // You could also do something like this, to get a random value in the last
  // 24 hours:
  //    $timestamp = rand(REQUEST_TIME - 24 * 60 * 60, REQUEST_TIME);
  $timestamp = REQUEST_TIME;
  // Update the data in database.
  db_update('users')
    ->fields(array('access' => $timestamp))
    ->condition('uid', $account->uid)
    ->execute();
}

Use hook_cron() implementation in a custom module. This can be cleaner if you don't need to configure this more than once.

function MYMODULE_cron() {
  // Decide how often you want to do this, e.g. daily, weekly, etc.
  // Below is an example for daily trigger.
  $last_updated = variable_get('MYMODULE_var_last_time_access_updated', NULL);
  if (!$last_updated || $last_updated != format_date(REQUEST_TIME, 'custom', 'z')) {
    // Define user IDs which need to be updated.
    $accounts_to_update = array(1, 2, 3);
    // Update them.
    foreach ($accounts_to_update as $account_to_update) {
      // See #1 above; I'll use a random timestamp in last 12 hours this time.
      $timestamp = rand(REQUEST_TIME - 12 * 60 * 60, REQUEST_TIME);
      // Execute the query.
      db_update('users')
        ->fields(array('access' => $timestamp))
        ->condition('uid', $account_to_update)
        ->execute();
    }
  }
}


Extending Entityreference Field Class to contain additional input fields I am currently trying to build a custom field consisting of an EntityReference Input Field (Autocomplete Widget) and two textfields to add additional information in Drupal 8beta11.

I used the code from the example module and the EntityReference field type. I copied it into my custom module. Everything worked.

But then I remembered the 'new' OOP approach of Drupal 8. Why copy, when I can extend? Extending the EntityReferenceItem Class worked without any problems. The table was correctly created.

Then I tried to extend the autocomplete widget class EntityReferenceAutocompleteWidget to show my additional two textfields. Here it somehow doesn't work. The Error I get:

Fatal error: Call to undefined method Drupal\Core\Field\FieldItemList::referencedEntities() in ...\core\lib\Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget.php on line 95

I know it means more or less, that somehow the $items, which are put into the parent::formElement method doesn't have the function referencedEntities implemented. But how can I fix this?

I tried to look into other modules and even found Drupal\Core\Field\Plugin\Field\FieldWidget\AutocompleteTagsWidget to extend the EntityReferenceAutocompleteWidget, but I don't find the difference.

This is my CompoundReferenceWidget. I am grateful for any advice or hint to get it working. Or to get the information, that it can't be done the way I tried it.

/**
 * @file
 * Contains \Drupal\compound_reference\Plugin\field\widget\CompoundReferenceWidget.
 */

namespace Drupal\compound_reference\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
/**
 * Plugin implementation of the 'compound_reference_widget' widget.
 *
 * @FieldWidget(
 *   id = "compound_reference_widget",
 *   module = "compound_reference",
 *   label = @Translation("Modeling a reference with additional fields."),
 *   field_types = {
 *     "compound_reference"
 *   }
 * )
 */
class CompoundReferenceWidget extends EntityReferenceAutocompleteWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['description'] = array(
    //$element += array(
      '#type' => 'textfield',
      '#title' => t('Description of the reference.'),
      '#default_value' => isset($items[$delta]->description) ? $items[$delta]->description : NULL,
      //'#min' => 1,
      //'#required' => TRUE,
    );
    $element['start'] = array(
      '#type' => 'textfield',
      '#title' => t('Start Date'),
      '#default_value' => isset($items[$delta]->start) ? $items[$delta]->start : NULL,
      '#description' => t('Start'),
    );

    return $element;
  }
}

The error is on the field item list class.

What you are missing is the list_class definition in the annotation of your field type, for anything that's an entity reference, you need to explicitly specify it, since annotations aren't inherited. See EntityReferenceItem:

*   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",


How do I allow only username for password reset form? By default the password reset module allows 'Username OR E-mail'. I am using a module which allows multiple user accounts with a same email address (but usernames are unique and auto-generated), so the unique user account identifier for logging in is username, I need this to be the same in case of password reset form.

Using the following module solves the issue as it has an option to make the reset form 'username only'.
https://www.drupal.org/project/sharedemail_pass_reset/


Disallow purchase if coupon code is not entered? I have a product that is part of a Groupon-like promotion. The customer purchases a promo code at the Groupon-like website and those coupon codes are entered into my Ubercart system as 100%-off discounts. I want to only allow this particular product to be purchased when one of those specific codes has been entered into the cart. In other words, the credit card entry panel would not appear until they have entered a valid code for that product's promotion.

Is that possible? If so, how might I accomplish that? Rules/Conditional Actions?

Thanks!

There is no easy way to do this sadly, your best bet would be to try and play around with hook_form_validate or hook_form_submit on the ubercart form submit and see if you can find the field values in one of the submitted panes.

If that doesn't work then your best bet would be to try and code your own "pre review order" coupon box, that hooks into the cart view page. So what I am thinking is

Users goes to /cart
Has the listing of the items in the cart
Has the "coupon stuff" at the buttom, but part of the "Checkout" form (use
form_alter for example)
And use the hook_form_validate hook to verify it has data, and the coupon is good, then proceed


How to alter an existing breadcrumb link programmatically? I am trying to alter the 'Home' Breadcrumb link using
hook_system_breadcrumb_alter()
The default Breadcrumb class allows you to add New links using the
addLinks
method.
However it does not allow one to edit the links. Is there a way to edit an existing link directly?

Turns outs you can't edit the existing breadcrumbs. However you can fetch them using the getter function, modify them and then call the Breadcrumb builder class.
<?php
/**
 * Implements hook_system_breadcrumb_alter().
 */
function MODULE_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // Add new link
  $breadcrumb->addLink($link);
  // Saving the original links and caching
  $original_links = $breadcrumb->getLinks();
  $cacheability = CacheableMetadata::createFromObject($breadcrumb);
  // Remove the old value of the array.
  array_shift($original_links);
  $home_link = array_pop($original_links);
  array_unshift($original_links, $home_link);
  // Finally generating the new link.
  $breadcrumb = new Breadcrumb();
  $breadcrumb->setLinks($original_links);
  $breadcrumb->addCacheableDependency($cacheability);
}


Trigger delete cache of url I've two api url

/api/v1/get-list
/api/v1/post-item

In API url /api/v1/get-list I was set cache like this:

$build = [
  '#cache' => [
    'contexts' => ['url','url.query_args'],
    'max-age' => 3600,
  ],
];

$res = new ResourceResponse($response, 200);
$cache_metadata = CacheableMetadata::createFromRenderArray($build);
$res->addCacheableDependency($cache_metadata);

Response will be cache in one hour with url /api/v1/get-list?_format=josn. When I use api /api/v1/post-item response of /api/v1/get-list will changed value. But response was cached in one hour. So how to trigger delete cache of url when use orther url. I find some code

\Drupal::service('page_cache_kill_switch')->trigger();

but just for current request.

Add a cache tag to the response of /api/v1/get-list:

$build = [
  '#cache' => [
    'contexts' => ['url','url.query_args'],
    'max-age' => 3600,
    'tags' => ['api-v1-list'],
  ],
];

and then invalidate this tag in /api/v1/post-item:

\Drupal\Core\Cache\Cache::invalidateTags(['api-v1-list']);


Search based on user profiles in Drupal 7 I want to develop user matching feature on website. A user will search by giving some search criteria (like we give search criteria in dating / real estate website to filter out search results), and system after, filtering out, will return the users matching that search criteria.

How can it be accomplish in Drupal 7 ? Is there any module or combination to modules to achieve that goal ? Thanks in advance.

Searching with Drupal core is not very performative because you are doing search queries in a mysql database.

Apache Solr is much more performative and includes a much greater feature set for searching Drupal content: http://drupal.org/project/apachesolr

If you want to limit search results just to users you can use the solr module above plus Facet API http://drupal.org/project/facetapi and only expose the facets for the content authors. You can also create a view using Solr Views that will return the author in the search results.


Submit handler: Prevent other handlers from running in certain circumstances only I'm creating a custom module which adds a submit handler to a form.  The idea is that it checks whether a hidden "honeytrap" field has been filled in.

If the field has been filled in, a success message is shown, but the form content is not e-mailed.  If the field has not been filled in, the form is submitted as normal.

I don't want to use a form validator here (so this answer on DSE is unfortunately no use).  I want the spam robot to think that the form has been submitted, so that it doesn't try again and learn about my special field.

At present, I have the following code:

function par_report_repair_form_webform_client_form_26_alter(&$form, &$form_state, $form_id)
{
    array_unshift($form['#submit'], 'honeytrap_submit_handler');
}

function honeytrap_submit_handler($form, $form_state)
{
    // what goes here?
}

I'm not clear what to put in my submit handler.  I'd like the following behaviour:

If the honeytrap field has been filled in, display a "success" message but don't allow any additional handlers to run
If the honeytrap field hasn't been filled in, continue as normal.

Any suggestions?  I've tried simply setting $form['#submit'] to be an empty array, but that didn't help.

By the time your submit handler is running you cannot change the other submit handlers that are running.

What you could do is make sure your form alter runs last (change the weight of your drupal module in your install file to a highier number to make it run later).
That way you can be a bit more sure that no one else is adding submit handlers after your form alter.

Then in your form alter do something like this:

// Add the original submit handlers to the form state for us to use later.
$form_state['original_submit_handlers'] = $form['#submit'];
// Replace the original submit handlers with out own.
$form['#submit'] = array('honeytrap_submit_handler');

Then in your submit handler:

if (honey_trap_fails) {
  // Do whatever, but don't call the original submit handlers.
}
else {
  // Do whatever, and then:
  // Call the original submit handler because it was a successful submission.
  // Replacing yours as it has already been called.
  $form['#submit'] = $form_state['original_submit_handlers'];
  form_execute_handlers('submit', $form, $form_state);
}

There is something important to take into account here:
If there are submit handlers on the button that was clicked then they will take precedence over submit functions attached to the form.
See form_execute_handlers() for a bit of further insight on how to handle button submit handlers.


How do I export/import all the relations created by Relation module? There are standard procedures to export/import relation types, but not for the relations themselves. At least, I couldn't find any. Am I missing something obvious?

Export/Import of entities is something that is not standardized and there are many methods of approaching the problem. This is also something Drupal 8 is attempting to solve.

Currently you want to look at Deploy and UUID Features are your best bet. Neither have stable D7 releases, but I played around with deploy and using the views plugin I was able to export entities.

The primary issues with content (entities vs configuration) is that content many times needs to be merged from one server to another so it ends up being a fairly complicated proposition.


View access based on roles I have 1 view /admin/people, and its 2 display, both are of type page.

I want display = page will be shown to admin role while display = LMA is for xyz role.

After setting roles for 2 different pages with same access url /admin/people, I logged as admin role and xyz role. Display for admin role is working fine, but for xyz role, it says access denied.

Whats the correct way to have views display for different roles.

This didn't work for me either. I worked around this one by creating a panel page and using two different variants, placing each view block in the appropriate page and restricting the access based on user roles.


Field Relation Between Content Types and Some Questions I have two content types (Movies and Actors), both with picture and name fields.

In Movies I have a field collection with two fields: name and character. This name field is a node reference to Actors content type. I created a view block for the Movies nodes which lists the cast (a list of Actors nodes).

What I want is the actor's pictures. The picture is automatically added to the Movies nodes; I would want the same for my block.

(1) The only way of not writing a custom script I can think of would be to use the Display Suite module. Out of the blue I would try the following.

Create a new display mode (besides content and teaser) for the actor content type. Call it something like "just image" or "photo only". It should be set to only display the image field.
Create a new display mode for the movie content type, maybe called "actors". It should only display the field collection and the name (reference field) should use the previously created display mode "just image".
Create a (views) block that shows the original node (Contextual Filter: Nid, default parameter in URL). Display type of that view should be Node and use the "actors" display mode.

What I would expect is to get a block that shows the actors' photos along with their characters' names.

(2) An easier way (if you are able to program Drupal modules) would be to write custom scripts. Also, this would allow you to fine-tune your output. I would create a custom module which creates the block you want by using the _block hooks to define the available blocks and their contents.

(3) Another way of accomplishing what you want would be to restructure your website's architecture. This might not be suitable for you if you already have a lot of entries. Instead of field collections you would then use an additional content type (character). Character would then have relationships with both movies and actors.