How can I split the body field to insert content between the first and the second paragraph? I have a node which shows content from the body field. I want to add a another paragraph or a block between between the first and the second paragraph, after the first </p> and before the second <p> tag.
But in my template to output the body there's only {{ content.body }}.
Drupal 7 had something like block in block. How can I do the same in Drupal 8?

I resolved my issue, using solution below
    {% set Paragraphs = node.body.value|split('</p>') %}
  {% set paragraphHalf = (Paragraphs|length / 2)|round %}

  {% if paragraphHalf %}
    {% for paragraph in Paragraphs %}
      {% if paragraphHalf == 1 or loop.index % paragraphHalf == 1 -%}

      {% endif %}
      {{ paragraph|raw }}

      {% if loop.last or loop.index % paragraphHalf == 0 -%}
      {{ insert item }}
      {% endif %}

    {% endfor %}

  {% endif %}


How to output form element values as text? On a node edit form, I want to make certain fields be non-editable by all users but the values stored in them to be visible on the form. My thought was to just print them out as text instead of in an HTML form element. What is the best way to accomplish this?

To provide some context, these values are populated via a migration and should not be edited on the site.

Changing a form field to a markup element creates problems if the form field is checked by a form validation handler or a form submission handler: #markup elements are not passed in the $form_state['values'] array, which contains the current values associated with the form fields (and which is the array used by the form handlers—both the validation and the submission handers). This method works for form fields that use #element_validate, as #element_validate is also used from the #markup form fields.
If you are sure there aren't form validation handlers that check the value of the form fields you want only to show, then you can adopt this method. As third-party modules could add form validation handlers for those fields, I would not suggest to adopt it, if not in the case the form fields are created by a custom module you created, and no other developers will alter the form fields added by your code (or alter the form created by your code).

Using #attributes to make a field read-only is not a secure method (as Berdir pointed out); to be sure the form field values are not altered, you should compare them with the value contained in the form before it shows (which means to check the values contained in the $form array).
This method has still problems with the form validation handlers (and form submission handlers) because other modules will act as those values are not read-only; only your code will act like as those values are read-only.
The other reason to not adopt this method is that is "easier" to add the #disable attribute to a form field.

Another method is to change the form field type to #hidden. If you choose this method, then you need also to render the form field value using #prefix, and #suffix.

$form['field']['#type'] = 'hidden';
$form['field']['#prefix'] = '<strong>' . t("Field title: ") . '</strong>' .
  check_plain($form['field']['#default_value']);

As side note, if those form fields don't need to be visible to users, but they must be present in the $form_state array because other modules (including the one that created the form) implement form handlers, then you can change the form field type to #value.


Can I insert the version number in the info file of a module for internal use? The documentation on the creation of custom modules says,
# Note: do not add the 'version' or 'project' properties yourself.
# They will be added automatically by the packager on drupal.org.

so I never put a version number in my module. But then I add difficulties writing database update scripts, I never managed to get an N in hook_update_N() that the update would recognize.
Also, my module really doesn't have any utility outside of my organization, since it has very specific domain requirements; therefore it is not, and never will, be released as a contributed module.
So, can I use a version number in my info file, and use it to generate the name of the update function? And if I insert it in an update of my module, will it be correctly managed?

If you host your module outside of drupal.org, including a private Git repository, or a local computer from which the module is copied on the site, you can set the version key in the .info.yml file for the module.
If the module updates are handled differently, the module could also implement hook_update_projects_alter() to tell the Update Manager not to check for that module updates, for example implementing the code shown in the documentation.
function mymodule_update_projects_alter(&$projects) {
  // Hide a site-specific module from the list.
  unset($projects['site_specific_module']);
}

As for the number N used in hook_update_N(), that number isn't related to the module version. It's just a progressive number, used from Drupal to verify which hook_update_N() implementation has been already run. hook_update_N() explains the convention for the four digits used for N.

1 or 2 digits for Drupal core compatibility (for example, 8 for compatibility with Drupal 8, 10 for compatibility with Drupal 10)
1 digit for your module's major release version (for example 1 for the 8.x-1.3 release)
2 digits for a counting number, starting from 01

To use an existing project as example, the pathauto.install file for the release 8.x-1.11 defines, as last update hook pathauto_update_8106(); the same file for the release 8.x-1.5 has pathauto_update_8107() as last update hook, which is the latest update hook also for the release 8.x-1.8.
Note that the digit for the major version release isn't sufficient to describe the version release (which would include also the minor version), but it's not sufficient also for a major version that is higher than 9.
Note also that Drupal core won't report any error whether (for example) a 8.x-2.3 release contains mymodule_update_8133() as update hook. What described is a convention for which only the Drupal compatibility digit is required.


better exposed filters and bootstrap 3. Problems with alignment I have Drupal 7 and the BEF to filter a view. My site is running the Drupal Bootstrap framework V3. The regular 'basic' theming for the exposed filters works, but I would like to use checkboxes and the JQuery slider.

I have a problem with the formatting on check-boxes and sliders.

I've googled it, but didn't find anything relevant.

Thanks in advance

https://www.drupal.org/node/2121203 gives some answers...

  Look at bootstrap/theme/process.inc at function
  _bootstrap_process_input and comment out or remove the 'select' in there.

Still looking for the "ultimate solution" myself as well.


Printing an Entity Reference Field Value in a field collection in views-view-fields.tpl.php I am overriding my view with the template views-view-fields.tpl.php, and have called it views-view-fields--front-featured-blocks.tpl.php

I wont bother putting all of my code for this block up, but the two defining lines of my code are as follows...

  <?php print $fields['field_link_to_content']->content; ?>

  <?php print $fields['field_block_title']->content; ?>

The field_block_title span prints a value, but the field_link_to_content does not.

The field_link_to_content is an Entity Reference field, which is printing the Entity ID, which I need to build a link.

Can anyone tell me why this doesnt work, but I can print every other field in the same method? The entity reference field is only allowed one value, but is there a delta value involved? How would I print a list of allowed values? I have devel installed.

I found my main answer from this question here.. Calling a field in views-view-fields--view-name.tpl.php ---- Error

My problem was excluding the display of the field. I assumed that I would want the field hidden as I wanted to show it elsewhere, but as I am overriding the views.view.fields.tpl.php anyway, I could choose to declare it or not.

As soon as I set the field to display again, I could use...

print $fields['field_link_to_content']->content;

If I had wanted to keep the field hidden, I could have used something like...

$row->field_field_my_custom_field[0]['rendered']['#markup']


url redirections not working for anonymous users I have set a redirect rule in EventSubscriber. So according to rule, when I hit example.com/my-page in browser, it should redirect to example.com/success or some external url also.

But issue is(for anonymous user):

On hitting first time this url "example.com/my-page", REDIRECT SUCCESS!! But on second time it does not redirect. It remains "example.com/my-page" only.

Now If I logged in, flush all cache, then again log out and check "example.com/my-page", it again works -- REDIRECT SUCCESS!! But again after redirecting first time when accessed the same, it stops redirecting.

This is probably because of the page cache for anonymous users. The cache is implemented as middleware and runs before any event subscriber, even if you set a  high priority.

If your site serves dynamically generated responses and redirects for every single request, then you don't need this cache and you can uninstall the module Internal Page Cache.

If you want to disable the page cache in code:

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

This will deny any page caching on the current request.


Immediately check if field content already exists in a node form I am struggling with a problem which I thought might be answered simply... Any help would be appreciated!

I have a content type called 'review'. Each review has a field called 'location'. As a user creates a new review, once they have filled in the location field, I would like a small message to appear in case that same user has already created a review for the same location.

Doing it when the user is about to save the node is not too complicated. But I actually want it to happen as soon as the relevant field is not empty.

Thanks

You can write little custom jQuery snippet using 'blur' event in order to do this. More information you may find on this page http://www.w3schools.com/jquery/event_blur.asp


Changing number of values on a field in installation profile I am creating an installation profile with multiple fields. For a 'file' field I want to change the number of values. I have two questions about this.

Is this an field setting or an instance setting?
and what is the right way of changing this setting I tried these:

'number_values' => '2',
'max_value' => '2',
'max_values' => '2',
'values' => '2',
'value' => '2',

I can't find any of this on the internet. Any help and tips would be appreciated.

It's a field setting (cardinality), so assuming you're using field_create_field() to create it...

$field = array(
  'entity_types' => array('node'),
  'cardinality' => 2,
  'translatable' => FALSE,
  'locked' => FALSE,
  // etc...
);
field_create_field($field);

For unlimited values you can use the FIELD_CARDINALITY_UNLIMITED constant.


Breadcrumb Preprocess from Module I'm currently using the preprocess_breadcrumb hook in my .theme file to customize the output of my breadcrumbs like so:

function mytheme_preprocess_breadcrumb(&$variables){
    $node = \Drupal::routeMatch()->getParameter('node');
    $current_path = \Drupal::service('path.current')->getPath();
    $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $crumbs = explode("/", $result);
    if($node){
        $variables['current_title'] = $node->getTitle();
        $variables['crumbs'] = $crumbs;
    }
}

I then use breadcrumb.html.twig to use these new variables like so

{{ 'You are here'|t }}

        {% for crumb in crumbs %}
            {% if loop.first %}

Home

        {% elseif loop.last %}

{{ current_title }}

        {% elseif crumb == 'node' %}
        {% else %}

 {{ crumb }}

        {% endif %}
        {% endfor %}

{% endif %}

However I'd like it more if all this was encapsulated in a module. In mymodule.module file I have

function mymodule_preprocess_breadcrumb(&$variables){
$node = \Drupal::routeMatch()->getParameter('node');
$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
$crumbs = explode("/", $result);
if($node){
    $variables['current_title'] = $node->getTitle();
    $variables['crumbs'] = $crumbs;
}

}

But this function never fires. Is there a way to use the preprocess_breadcrumb hook from a module?

Preprocess hooks work in themes and modules. It doesn't matter where you put it, the only difference is, that modules have higher priority.

What you have to do is to work on caching. Because of the variables you put in,  you need a cache context on url.path,

$variables['#cache']['contexts'][] = 'url.path';

That doesn't make a difference for the first run after clearing the cache, but makes sure that the hook is run for every new path.


Getting the node object in hook_form_FORM_ID_alter Follow up to this question  but I don't have enough reputation to ask clarification in a comment.

I am porting a contributed module to Drupal 8.
The sugested code on the above mentioned CR and post is not working:

$node = $form_state->getFormObject()->getEntity();

Nothing is loaded into the $node variable.

My PHPStorm IDE gives a warning for getEntity():
Method 'getEntity' not found in class Drupal\Core\Form\FormInterface less...
Referenced method is not found in subject class.

It is also not presenting this method for code completion.

In the use cause I am referencing:

use Drupal\Core\Entity;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Render\Element;

PhpStorm doesn't know as the type of form object is dynamic but it's fine.

If you want to make it happy, wrap it in a condition like:

if ($form_state->getFormObject() instanceof EntityForm) {
  ...
}

Either way, it should definitely work if you implement the correct form alter. If you don't, you should end up with a fatal error not just without a node object.

You need to share your exact code if you want a more specific answer, that's all I can tell you.


Drupal 7 Views Chart Statistics Over Time I want to create a View of node requests/views over time. The problem is grouping the Access log timestamps (minute,hour,day, etc) so that these are chartable. Does anybody know of a solution for this in Drupal 7 Views 3?

Within the Charts module, there is an interesting issue about this, i.e. Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'. The patch(es) included in this issue are expected to soon be applied.


Using kint in views-view-unformatted What is corect way to use kint in  views-view-unformatted.html.twig

I do:

{{ kint(rows) }}

but I get this error.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20794259 bytes) in /home/inatcent/public_html/core/lib/Drupal/Core/Render/Renderer.php on line 448

And for {{ kint(row) }} I get null what is ok. But I want more staff. :)

Option 1: Try to increase your php memory limit above the 250 MB.

Option 2: Don't try to debug all the rows at once.

{{ for row in rows }}
  {{ kint(row) }}
{{ endfor }}

P.S.

The reason {{ row }} was null, was because that variable does not exist in the template unless declared like in my example above.


Using custom ranking for some searches and not others in D7 I want to define a custom search ranking, and only use it on a special page, without affecting the regular search feature.

Looking at the code in node.module, I see how I could hook MODULE_ranking() in a custom module, however it won't be applied to the query unless global variable node_rank_X setting is enabled in the global config.

I could munge the global $conf for my one specific page, but this seems ugly.  Is there a more sensible way to approach this?

Search API was built to give a great deal of flexibility to searches. You can create separate search indexes to meet different criteria, weight individual fields differently per index and keep all of your configuration managed in the UI, versus trying to write custom logic into MODULE_ranking().

Download Search API, install and configure your indexes at: /admin/config/search/search_api


Modify VBO checkbox value I would like to modify the value of my VBO checkboxes but can't figure where to hook in.

<input name="objects[selection][1]" id="edit-objects-selection-1" value="1" class="form-checkbox select" type="checkbox">

becomes

<input name="objects[selection][1]" id="edit-objects-selection-1" value="1-XXX" class="form-checkbox select" type="checkbox">

I guess it should be form, so you can try the following on VBO page, if it workds.

   function  mymodule_form_alter(&$form, &$form_state,$form_id) {
      dpm($form_id);
    }


Get path alias of node on presave I was trying to get the path alias using for nodes using the following code.

\Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);

It works for nodes that are already created, but it breaks when a new node is being added. I get the following error.

  Uncaught PHP Exception Symfony\Component\Routing\Exception\InvalidParameterException: "Parameter "node" for route "entity.node.canonical" must match "\d+" ("" given) to generate a corresponding URL.

Is there an alternative way to get the path alias for nodes that have not been saved yet?

Aliases are alternative paths to the node. They require the canonical path, so that there is a path to be an alternative of. The canonical path requires the Node ID (Entity ID) as node paths are /node/[NODE ID]. The Node ID doesn't exist until the node has been saved, as it comes from the database upon save. So the path does not exist until the node has been saved, meaning there is nothing to alias.

So the answer is that no, it's impossible to create an alias before a node has been saved, as the canonical path does not and cannot exist until the node has been saved.


How to add query parameters in twig using path()? I am following the code snippet provided here

{# Link to frontpage view. #} {{ 'View all content'|t }}

{# Link to user entity/profile page. #} {{ 'View user profile'|t }}

{# Link to node page. #} {{ 'View node page'|t }}

https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates#path

As the function says path($name, $parameters, $options), I want to add a link which has query parameters as shown in below

blue?destination=blue-search&cookie[blue_referrer]=3622&cookie[blue_type]=node

I tried implementing it as follows

Find a Distributor

but it gives an error

  The website encountered an unexpected error. Please try again
  later.Twig_Error_Syntax: An
  array element must be followed by a comma. Unexpected token
  "punctuation" of value ":"
  ("punctuation" expected with value ","). in Twig_TokenStream->expect() (line 124 of /templates/node/node--product.html.twig).
  Twig_ExpressionParser->parseArrayExpression()
  (Line: 205)

Twig uses hashes where PHP uses associative arrays. So to fix your code just convert the array syntax to a hash literal:

{{
  path('blue_general.blue',
    {'node': node.id},
    {'query': {
      'destination': path('view.blue_search.page_1'),
      'cookie[blue_referrer]': node.id,
      'cookie[blue_type]':'node'
    }}
  )
}}


How can I ensure I retain access to a Drupal site after handing it over to a client? Does Drupal have a mechanism which will allow me to keep control over a site after handing it over to a client?

If things go wrong with the client relationship, I need to be sure I still have control over the website.

Yes, as the developer you can control this:

Make sure only you know the (strong) password to the admin (user 1) account.
Make sure Drupal core and modules are up-to-date to mitigate possibility of a security hole that may expose the user 1 login.
Make sure only you have access to the files/database for the site; that way your client can't change data manually that might give them access, or run PHP scripts to do the same.
If you have the PHP filter module enabled, disable it, or at the very least make sure your client can't use it.
Install User One to stop users with the "Administer Users" permission from editing user 1's password.
Make sure no other user has permission to "Administer Permissions" and "Administer Modules" so they can't grant permissions to them selves, disable User One or other critical modules.

There may be some more steps you can/should take, depending on the nature of your relationship/hosting/etc, but those should cover the basics from a Drupal perspective.

I'd strongly recommend being up-front with your client about this. Call it a 'policy' that you have, to ensure a smooth relationship, and position it that your having access to the site for maintenance/updates is actually the right move for them, not just you.


Drupal Installation modules leftovers cleanup I have some questions that more experienced Drupalers might know.

When you have been developing a Drupal site, installing, uninstalling and testing various modules for different set of functionalities, when the launch day comes how do you clean up leftovers of the modules? To be more specific.

How do you remove folders that are not needed anymore from the sites/all/modules folder?
How do you remove leftover database tables?
Is there a contrib module that can actually do that? Cleanup a Drupal Installation?

Thanks in advance.

While I personally keep and eye on module listing page and make list of modules to be uninstalled at the time of going live, usually the 'To Uninstall' list contains some UI wrapper modules like views_ui, devel, etc. But searching for any contrib module I came across unused_modules, I think it might be worth trying what this module gives out of the box.

How do you remove folders that are not needed anymore from the sites/all/modules folder?
https://www.drupal.org/project/unused_modules
How do you remove leftover database tables?

You can you schema module, which basically identifies tables and modules relation and also list down orphan tables, this can give you a list of tables which might be just left over tables.
Cleanup test data content.

delete_all module seems to allow to cleanup the test content with different variation via drush.


Questions about theming a node I am theming a specific node type in Drupal 7. I have named my file node--mynodetypename.tpl.php. Everything is fine and I can override the default node template; the issue is that I want to do very slight changes to the regular node template, basically the way the DIVs are structured. I get into trouble trying to replicate the original layout.
I have installed the Content Templates module, and I am getting the variable names from there. I am not using it because it has some bugs in the current version.

How can I add the comments block to the end of my content type? I just want the ordinary comments engine placed in there, but it disappeared with my new layout. Contemplate does not provide the variable to make all that comments block appear.
Is there a correct way to publish the URL of an image? Contemplate provides me with this $node->field_image['pt-br'][0]['filename'] for the raw image file, but then I have to manually fulfill all the folder structure; it also gives me this $node->field_image['pt-br'][0]['uri']. It presents the folder structure above the image file, more or less like public://images/folder1/folder2/filename.JPG.
Is there some kind of function I should call that would build the entire image URL for me?
I have created a piped list of countries as a select list. In my layout, I would like to show the name of the country, but the variable generated in contemplate $node->field_country['pt-br'][0]['value'] only holds the country code; I would like to get the name of the country.
How can I do that?

Take a look at the default node.tpl.php. You'll notice that they render the content with render($content).

I've never used Contemplate, but if you install the devel module you can then use the dpm() function to take a look at the variables in detail. Try dpm($content), and you see all the content that you can render, or even use the hide function to remove content. For example, you can use hide($content['links]) prior to render($content) and the links will not be rendered; you can display comments with render($content['comments']);. Don't forget to print the value returned by render(), as render() returns the HTML markup used to render the element passed as argument to the function.

You can easily render the image field with render($content['your_image_field']).
If you are using the Countries module, then you can control what it is displayed in the content types display on admin/structure/types/manage/your-content-type/display, and simply render it like you do with the rest of your content.


Render picture module image in a custom module I am trying to render a responsive picture module image from within a module. I cant find any functions that I can pass the picture mapping into.
If I render the whole node from within the module it works fine but if I just render the image it does not work.
Any thoughts would be great.

Here is my solution to build the render array of the drupal 7 picture module v2

//Load picture renderable array

$picture_name = 'mapping_name'
$fallback_image_style = 'large';

$image = $node->field_image[LANGUAGE_NONE][0];

$picture_mappings = picture_mapping_load($picture_name);

$breakpoint_styles = picture_get_mapping_breakpoints($picture_mappings, $fallback_image_style);

$picture = array(
        '#theme' => 'picture',
        '#width' => isset($image['width']) ? $image['width'] : NULL,
        '#height' => isset($image['height']) ? $image['height'] : NULL,
        '#style_name' => $fallback_image_style,
        '#breakpoints' => $breakpoint_styles,
        '#uri' => $image['uri'],
        '#alt' => isset($image['alt']) ? $image['alt'] : '',
        '#attributes' => isset($image['attributes']) ? $image['attributes'] : NULL,
        '#timestamp' => $image['timestamp'],
      );

print render($picture);


Taxonomy view problems I have a taxonomy list (sector), linked with differtent content, for example:

Company 1 has taxonomy Security & Computers.
Company 2 has taxonomy Security
Company 3 has taxonomy Computers

I created a view, but, in my view I get the following result:

Security
Company 2

SecurityComputers
Company 1

Computers
Company 3

Is it possible to get:

Security
Company 1
Company 2

Computers
Company 1
Company 3

So, that he show 2 times the company who is linked with different taxonomy?...

You should group your view by Taxonomy and for the taxonomy field in the view you should uncheck "Display all values in the same row".

These are the steps:

Add a taxonomy field to your view and uncheck "Display all values in the same row" and exclude this field from display.

Use the taxonomy field to group your view (Format settings of the view)

Of course add title field or other field to your view to have your content displayed (e. g. Company 1, 2, 3).


View and CCK select list i have created a content type in which i have a field with a select list. I create views for each option i have on the select list and am not sure how to go about it.

Example - Select list options - car, bicycle, motorcycle

View displaying all cars
view displaying all bicycles
view displaying all motorcycles

i Have tried using taxonomy but i keep getting ajax errors hence why i created a cck select list.

Thank you in advance.

In a page view, add all of the fields you wish to display. Then add a filter in the Filter Criteria area that includes this field, then set the Operator to once specific selection (e.g. cars). Clone each page and override this filter for each page to filter for the other selections. (You could also just create on page view and expose the filter for users to change it on the fly.)


How do I paginate results with db_query? How do I paginate results with db_query in Drupal 7? I didn't find any example using db_query.

db_select() is the way to go using a so called query extender. Here is a simple example:

$query = db_select('node', 'n')
  ->condition('type', 'article')
  ->extend('PagerDefault')
  ->limit(10);

Then theme_pager() can be used for outputting a pager.

Find more details on this drupal.org working example


Is linking to autocomplete results possible? When users search a member profile using Views autocomplete exposed filter text field, is it possible to link the result values? Suppose we are searching some 'XY' user. The results appear as autocomplete drop-down. When we click on them, we are redirected to the member's description page.

Is linking to autocomplete results possible?

Yes it is possible.
You can try Search Autocomplete moodule.

Module page says:

 This module allows you to add autocomplete functionality to virtually any fields of a Drupal site. During the input, the field will be expanded and offer a list of suggestions before you start the search.
    By default, the module integrates with search forms from the Drupal core Search and Search Block.

Uses either static data, external or internal URL callback or an embeded view style to easily create your suggestions set.

For more information go through the module documentation.


Show items not linked by a view relationship I have two content types: Item and Order.

There is a link from Order -> Item through field_items.

I have a view showing content of type Item and any related order data in a table. I have set up a non-required relationship to Content using field_items to reference the Items.

I have a filter on the view to ensure that the content type on this relationship = Order. This is because I have another content type which is not shown on this view that uses field_items.

The view functions largely as required. However, it only shows Items that are linked to an order via field_items whereas I would also like it to show items for which this link doesn't yet exist.

I have tried adding a second condition for content type on the relationship is EMPTY and putting the two filters into a filter group with the OR operator. However, when I do this, nothing shows up in the view.

How do I get the view to show all Items (linked or not) with linked Order data where this exists?

This looks like the answer:

https://www.drupal.org/project/drupal/issues/2744777

There is a known bug in Drupal 8 whereby filter groups in views are not saved. The two filters (content type is empty and content type) Order are being AND-ed rather than OR-ed so therefore nothing is displayed as content type cannot both be empty and = Order.


How can I create a custom variable to use it in my layout template page? For my new project, I'm using the brand new Omega4 theme. It comes with a lot of cool and nice features build in, so no complain about that!

But when I try to use a custom variable in my theme-layout.tpl.php with the hook_preprocess_html(), nothing is passed...

function theme_preprocess_html(&$variables) {
  $variables['my_variable'] = 'My New Variable';
}

When I try to access my new variable in my theme-layout.tpl.php page with <?php print render($page['my_variable']); ?>, nothing is appearing.

Although, if I dpm my $variables in both my template and my html.preprocess.inc file, the dpm in my template is printed first... So it looks like the template is printed first and then the preprocess hook is called.

How can I create a custom variable to use it in my layout template page?

Your approach is right but this has less to do with omega than with the order in which Drupal is preprocessing your hook. The html template hook is too late in the process, this is just for rendering the html wrapper and already assumes the existing variables. Instead, following the 1st handbook link above, use the base preprocess hook to establish your variables, ex:

function theme_preprocess(&$variables) {
  $variables['my_variable'] = 'My New Variable';
}


Display Google Map after entering address? Trying to find an easy way to do the following:

1) Visitor enters their address in a form field
2) Google map display's their address on the page

Does not seem to be an easy way to accomplish this in Drupal 7?

I think you are looking for geofield gmap module, it have the option same like your requirement. See the below screenshot and also easy to configure.

Geofield Gmap allow to use a google map v3 map to input a location.

A quick text input + geocode allow you to specify an address.

You can also drag and drop the marker to narrow the position.

Geofield Gmap require geofield.

Geofield is a module for storing geographic data in Drupal 7. It supports all geo-types (points, lines, polygons, multitypes etc.)


How Do I get specific fields value in Twig? Background:

I have a Block view and content coming from content_block with number of fields.

So I want to access those fields value in custom template
Is this possible?
thanks

In a block twig you can access a field value like this:

{{ content['#block_content'].field_myfield.value }}

This is the database value of the field.

Most times you want to render a field:

{{ content.field_myfield }}

This will display the field as it is configured in the view mode.


Multiple owners for commerce order [or] Allow non-owner to pay for an commerce order Scenario:

Drupal site with "Member" and "Spouse" roles.
For any given married couple, Member and Spouse each have their own user accounts.
entity reference field from spouse defines the relationship between the 2 users
an order exists, belonging to Member user (order->uid)

Desired functionality:

Regardless of the uid value for order, allow either Member or Spouse to proceed through checkout and payment for the order.

I realize this is not possible through vanilla Drupal Commerce.  I'm looking for any ideas that will help me figure out how to implement this via existing Drupal techniques, or a custom module.

Specific questions:

Has anyone achieved this successfully?
Are the any specific ways (Drupal techniques) that could help solve this?
What specific hooks or overrides should I be looking at?

Bonus points for elegant workarounds or shortcuts like a simple hook_access override, or a clever way to just-in-time reassign the order uid.

You may want to look at https://www.drupal.org/project/masquerade module for some ideas to see how it does the switching since it allows:

  "...(anyone with enough permissions) to switch users and surf the
  site as that user (no password required). That person can switch back
  to their own user account at any time."

You can then write a custom module.


Save values after add more ajax in form api - field name issue I've created a form using Form API and AJAX for an add more button, but I think I have problems assigning names to the new ajax fields in the loops, cause when I try to insert my data into my database I get an error:

  Undefined index

What am I doing wrong? Here's a section of my code:

<?php
function main_form_form($form, &$form_state) {

  $form['group_tabs'] = array(
      '#type'     => 'horizontal_tabs',
      '#attached' => array('library' => array(array('field_group', 'horizontal-tabs'))), // Converts fieldsets into tabs
      );

  $form['main_film_tab'] = array(
      '#type'  => 'fieldset',
      '#title' => t('Film General Info'),
      '#description' => t('Use this tab to enter basic info about the film.'),
      '#group' => 'group_tabs',
      );

  $form_state['storage']['main_film_tab']['add_title'] = isset($form_state['storage']['main_film_tab']['add_title']) ? $form_state['storage']['main_film_tab']['add_title'] : 0;

  $form['main_film_tab']['film_title']= array(
      '#type' => 'textfield',
      '#title' => t('Film Title'),
      '#size' => 60,
      '#maxlength' => 120,
      '#required' => TRUE,
      '#group' => 'main_film_tab',
      '#description' => t('Enter Film Title.'),
      '#attributes' => array(
        'title' => t("Title of Film"),
        )
      );

  $form['main_film_tab']['add_title'] = array(
      '#type' => 'container',
      '#tree' => TRUE,
      '#prefix' => '
',
      '#suffix' => '
',
      );

  if ($form_state['storage']['main_film_tab']['add_title']) {
    for ($i = 1; $i <= $form_state['storage']['main_film_tab']['add_title']; $i++) {
      if ($i <= 2) {
        $form['main_film_tab']['add_title'][$i] = array(
            '#type' => 'fieldset',
            '#tree' => TRUE,
            );

        $form['main_film_tab']['add_title'][$i]['main_film_tab']['film_title_'.$i] = array(
            '#type' => 'textfield',
            '#title' => t('Film Title '.$i),
            '#size' => 60,
            '#maxlength' => 120,
            '#required' => FALSE,
            '#group' => 'main_film_tab',
            '#description' => t('Enter Film Title.'),
            '#attributes' => array(
              'title' => t("Title of Film"),
              )
            );
      }
      else {
        return FALSE;
      }
    }
  }

  $form['main_film_tab']['button_add_title'] = array(
      '#type' => 'button',
      '#value' => t('Add another title.'),
      '#href' => '',
      '#ajax' => array(
        'callback' => 'custom_registration_ajax_button_add_title',
        'wrapper' => 'add_title',
        ),
      );

  $form['main_film_tab']['button_add_title']['#executes_submit_callback'] = FALSE;
  $form['main_film_tab']['button_add_title']['#limit_validation_errors'] = array();

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Film Info'),
      );

  $form_state['storage']['main_film_tab']['add_title']++;

  return $form;
}

function custom_registration_ajax_button_add_title($form, $form_state) {
  return $form['main_film_tab']['add_title'];
}

function main_form_form_submit($form, &$form_state) {
  $film_id = db_insert('film_main')
    ->fields(array(
          'film_title' => $form_state['values']['film_title'],
          'film_title_1' => $form_state['values']['film_title_1'],
          'film_title_2' => $form_state['values']['film_title_2'],
          ))
    ->execute();
}

I was having problems with the fieldset, since it was set to #tree. The submit handler should look like this:

function main_form_form_submit($form, &$form_state) {
  $film_id = db_insert('film_main')
  ->fields(array(
     'film_title' => $form_state['values']['film_title'],
     'film_title_1' => $form_state['values']['add_title'][1]['main_film_tab']['film_title_1'],
     'film_title_2' => $form_state['values']['add_title'][2]['main_film_tab']['film_title_2'],
     ))
 ->execute();


Hide node and file paths in view when printing page I have a views page that lists nodes that contain uploaded PDF and bibtex files (see here). Everything looks fine when you view the page, but when you go to print it in the browser, the node path (from the linked title) and the path to the uploaded files are displayed.  The client would like to be able to print the page without  those paths being shown.  Is there a way to suppress these paths when printing from the browser? I suggested having a link to another print friendly page, but he just wants to be able to print from the browser.

Sounds like a CSS issue, so before this question gets flagged, hopefully this will help you out.

The most efficient way, assuming it is a CSS issue, is to add a stylesheet to your theme whose media type is print (see below for example).

Assuming the part you want to hide is an element (div, span, etc) whose class is mycustomclass, inside that stylesheet you could add something like this:

.mycustomclass {
  display: none;
  visibility: hidden;
}

And here's the example mentioned above:

<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/all/themes/mytheme/print.css" media="print" />

HTH...

:)


Collapse Text Module and Bullets I have my collapsing working, but I'd like each collapsing title to have a bullet. When I try, my bullets are on a line by themselves, one line higher than the title.  I thought I could accomplish this through CSS but can't figure out how.

Thanks so much!

CSS

I'm going to assume you are using the default markup that the Collapse Text module generates, which is fieldsets. I'm being intentionally verbose in the CSS rules below so you can see the html elements along with the classes I mean to target, just in case your markup is different. You will probably not need so much specificity.

To insert bullets before each title, you can use the following CSS in your theme:

fieldset.collapse-text-fieldset legend span a.fieldset-title {
    display: list-item;
    list-style-position: inside;
}

html.js fieldset.collapse-text-fieldset legend span.fieldset-legend {
  background: none; /* Removes the arrows */
  padding-left: 0; /* Depends on your theme */
}

Outcome

Explanation

Collapse Text wraps each collapsible chunk of text in a fieldset and adds a few wrapper classes like collapse-text-fieldset. I suggest specifying one of the wrapper classes before targeting anything inside the collapsible fieldsets to avoid selecting all of the fieldsets on the page or on the site depending on where in the theme you're adding the CSS.

Your theme may have different indentation or padding applied to fieldset elements. In my test case there was 15px of padding-left on all fieldset legends as part of the base styles of my theme, and I wanted to remove that in order to avoid unnecessary space.


How can I display node fields contextually in a block with terms from two separate vocabularies based on node ID? I've got a content type that has a file field and as part of custom content type that we use to display document links. As part of that content type I have taxonomy 1 "site section" that I'm using to categorize the documents from that field so that they are displayed in specific places on the site. That part is easy.

However, the client just requested an additional level of filtering because they want more fine-grain control over what documents are displayed on what page/node. So far, the best I can figure out is that this level of filtering should be based on a new taxonomy 2 "site sub-section" that I've created that will correspond to specific nodes in the site where the documents need to be displayed.

I'm trying to figure out how I can set my contextual filter so that it will display the resulting file field document results based both on taxonomy 1, and new taxonomy 2, based on the node ID, but I can't figure out the logic to make this happen.

I'm open to other options regarding contextual filters but the node ID is the only one I can think of that would give the specificity necessary to control how and where they're displayed. But, I also cannot figure out to to declare that "when the node ID is [some node id], display nodes with taxonomy terms y and z, and only those nodes."

Is there a way to do this within Views or should I just look to create a custom PHP piece to do this?

My original goal here was to do this dynamically via contextual filters so I wouldn't need to create a bunch of individual blocks to control various displays. However, I never found a suitable solution for doing this dynamically via the contextual filters, so I ended up resorting to using different blocks with the different filters applied for each one appropriately. It makes a little more of a mess when it comes to managing blocks, but that's not that big a deal.


How do I change the javascript loading order I am using mixitup.js for my custom module. But it gives error when firing because it needs to load the jQuery before loading the mixitup.js. But my jQuery files are in my site folder which are loading in the end of the page. Is there way to load my mixitup.js in the end of the page. mixitup.js should be in my custom module too.

To add a js library to the header, define your library in my_module.libraries.yml with the header: true property.

my_library:
  header: true
  etc ...

Any dependencies defined for your library will always be loaded before your library whether loading your js in the header or footer.

See Asset loading order section here.


Behaviour of using drupal_add_js When using the drupal_add_js function, should I see the script I am loading appear in the list of scripts being loading in the header of the generated html page? I thought I should, but I don't - so perhaps my understanding of this function is wrong. Can someone clarify what is suppose to happen.

Just as note I have verified that the path to the script is correct so I know that isn't the issue.

Thanks.

With drupal_add_js() you can set the scope to either header or footer, specify the group the script is loaded into, and give the script a weight relative to that group. Scripts are loaded by scope > group > weight, where a lower weight will be loaded before a higher weight.

If you have aggregation turned on in /admin/config/development/performance, the script will be combined with others with the same scope & group, and ordered by weight.


How to set up Media module with image editor? I have installed Media module (7.x-2.0-beta2), but I can't find the module or setting for editing images that is in the video Drupal 7: Media Upload with Image Editing.

I want to set up the Media module for editing images as per this video.

Image editor in the media module

Take a look at the article "Crop, rotate, and scale embedded images".

You have to install Media crop module. Some details about this module (from its project page):

  Adds cropping, rotating and scaling to the media module's image embed
  function. Only available for images local to the server (not for
  remote images), and only when adding media via CKeditor.


Disable payment via custom module is there anyway, we can disable payment of specific payment option via custom module? I Have done some research that payment in drupal commerce is setup via rules, so is there an option we can create custom module and hit the current payment rules and disable it?

and is there a way via custom module, we can get the list of available or activated payment?

some references would be great.

thank you!

Option 1: Hook Form Alter

Rules are event-based conditional actions. For "showing" or "hiding" payments, that event it almost always going to be simply showing the form on checkout. So, technically, you could just use hook_form_alter() and locate the checkout pane that has the payment details and modify from there.

A video where I walk you through how to do hook_form_alter: https://youtu.be/xYMd6WDqxKY?t=1m3s (admittedly, this is for a different use case, but I do show you how to locate the form_id and customize the form_alter for whatever situation you're in).

Option 2: Custom Rules Condition

Another option would be to create a rule condition that you can add to your payment gateways. I think this would be more in spirit with how Drupal Commerce works.

Over here, I have shown you how to create a custom Rules action and condition:
Different vat rate per commerce shipping service

There is also a clear example here:
How do I add a new condition in Rules 2?

How to do option 2

As I said above, this is how Drupal Commerce is supposed to work. If you create a custom rule condition (perhaps there's a business server that returns a REST true/false for an A/B comparison) then that condition is exposed in the user interface and keeps the logic in code where it can be maintained separate from being implemented.

Create the custom rule condition in your custom module with your custom logic
Add that condition to your payment method: /admin/commerce/config/payment-methods
Know that every time that payment method might appear (both in checkout and on the order editing payment screen) that rule condition will be run


Can you disable Rules Components? Is there a way to disable a Rules Component? And if so, -how-?

Using Commerce, I've set up various Sales Taxes. If I understand, the Rule for Sales Tax triggers all 'Components' to be evaluated which are of type Sales Tax and then executes any/all that match the condition.

But in our case, we -know- ahead of time, that some of those Components will never be executed, so I was hoping for a way to prevent them from being evaluated and thus speed execution.

I'd prefer to keep some Components 'disabled' rather than delete them in case we need them in the future or for importing old orders.

You can't disable Components.

Components are configurations, so they already have an 'active' field available.
Actions would be more difficult to disable.

You may read read from here Components: enable / disable


Draggableviews with 2 separate views I have 2 views. One is used to sort content of type slider using draggableviews. The other one displays an image field of the same slider content type. How can I use the weigh (sort order) of the first view in the second one?

In other words, I want to have one view that lets me sort my slider content, and another one that displays the slider content in the order defined in the first view. Any help would be appreciated. Thank you!

You can 'connect' both views through the (hidden) node ID:

add the field Content: Nid to the fields list of your first view and check Exclude from display on the next screen.
also add the field Content: Nid to the fields list of your first view and check Exclude from display on the next screen.
add Draggableviews: weight to the sorting criteria of both views.
in your second views sorting settings choose your first view under Display sort as to connect both.


Do I have to move contributed modules to "sites/all/modules" for upgrading? In Drupal 6, I have placed my contributed modules inside the modules directory in the Drupal root directory (not in sites/all/modules). I need to upgrade my site to Drupal 7.

Do I have to move the contributed modules inside sites/all/modules before upgrading to Drupal 7?

You don't have to, but it is highly recommended. It greatly ease identification of the files to keep while upgrading (and following the upgrade documentation).


Displaying entity form on node page I'm a bit new to Drupal, but I'm on a project, where the most handy stuff is drupal. I only used it for 6 months, then I used mvc-s and stuff. Now I'm back to it.

The project is kinda simple. There is a site admin, who creates events and a registration form for that event (almost every registration form is different).

I want to display that entity form on the event page. I downloaded entityform blocks and it works, but I was just wondering if there is a module out there that creates a field type with the entityform types and the user can easily chose the entityform to display on the event page, when creating a new event.

If there is no such a module, then can it be solved by writing a custom field type? Thanks in advance!

Entity Reference lets you do this.

Add an entity reference field.
Target Type: Entityform Type.
If you want to limit the options for a user, you can create an entity reference view for entityform types and select it in the options.
Go to your content type's "Manage Display" and select "Rendered Entity" for the field.
Or for Panels, add a Context>Relationship>Entityform Type from Node.
Add it to the page under Page Content>Rendered Entityform Type.


Get the views filter's value I'm building a views that has a PHP field with  SQL queries.
I wondering if I can get the date filter value to use it in my select statement?

Take a look at hook_views_query_alter(). You can grab exposed filter values by inspecting $_REQUEST and grabbing the appropriate value from that array. I usually implement hook_views_query_alter and just wrap the query in a dpm() call (from the Devel module) so I can browse the array.

If using AJAX in your views, you'll need to refresh the page after you filter your view before Devel can print the array in your messages.


Using FormState::setError() in Form::submitForm() I am writing a form in Drupal 8 that provides user values to a web service, which will either act on them or send back an error.

How can I display that error message to the user?

Here's the situation in code:

class FooForm extends BarForm implements FormInterface {

  protected $fooClient;

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

    $result = $this->fooClient->post($form_state->getValue('bar'));

    if ($result->hasProblems()) {
      // This doesn't seem correct: Posting to a web service is not idempotent.
      $form_state->setErrorByName('bar', $this->t('Problems.'));
    }
  }

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

    $result = $this->fooClient->post($form_state->getValue('bar'));

    if ($result->hasProblems()) {
      // This throws a LogicException.
      $form_state->setErrorByName('bar', $this->t('Problems.'));
    }
  }
}

Drupal treats 'validate' and 'submit' as two separate steps, but the web service doesn't. The only way to determine if the values are fully 'valid' is to get the web service to look at them, which is an operation that potentially has side effects.

validateForm() and other form validation handlers are not supposed to contain business logic, since they may get called multiple times during the life of the form, particularly if AJAX is involved.

However, all errors are meant to be resolved before submitForm() and any other submission handlers are called. FormState::setError() enforces this by throwing a LogicException if you try to create any. Also, submitForm() clears away the user's values, and the next page builds the form from scratch.

I've seen this similar question for Drupal 7. Back then, it was possible (if discouraged and ugly) to use form_set_error() in the submit handler or the form builder. As far as I can tell, that flat-out doesn't work in Drupal 8.

How am I supposed to interact with RESTful web services? Is there a way to pass errors up from a form submit handler? Or is there a way to ensure a validation handler runs once, only once, and only if all other validation passes? Or is there some way to do this with multi-step forms?

The Drupal form system, isn't really built for what you are trying to do. I see two ways of going about this:

Webservice validation

If the webservice can do a validation of the data or such a method can be added, you can use the form system as is, and use ::validateForm to validate via webservice.
Rebuild form

What you can do, instead of doing a "validation" is to delete your ::validateForm method entirely and just send the data to the webservice in the ::submitForm. If the operation fails, you can rebuild the form and display a message to the user. You can make it appear as a validation error even though it technically isn't. Drupal does something like this as well. Fx in NodeForm::save

public function save(array $form, FormStateInterface $form_state) {
  ...
  $node->save();
  ...
  if ($node->id()) {
    ...
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
    $form_state->setRebuild();
  }
}

So basically, you can use $form_state->setRebuild() and drupal_set_message to make something that mimics validation in the submit handler. You can also save data in the store ($form_state->setStorate($data)) which you can use the form method to display error message or something else to the user.


Why render funcion hide img tags? I have a simple text that contains  tags but when I try to render the field, the img tags disappear!

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

Why?

What type of field are you using ? If it is a body_format using a format (i.e.: Filtered HTML, Full HTML) verify the filter settings. Probably Limit allowed HTML tags is enabled and the  tag is not part of the allowed tags.

To verify / change settings, it is under admin/config/content/formats and click on configure link of your used format.


Why cannot edit views because "The requested page could not be found." I am having a sudden error on a drupal site I inherited in that I cannot edit views anymore, any of them. One moment I am able to open a view for editing by clicking the edit link on the all views list and the next moment the edit link results in

  The requested page could not be found.

for all views.

The only change I made was to change the display on a field from do not display to display for a specific view. I then updated the view and saved it. At first the save did not work, but then I clicked again and it saved. The field I wanted displayed but now I cannot reach the edit screen for any of the views.

The log only references the 404 error, but nothing as to why, my apache log is equally unhelpful in determining why this has become the case suddenly.

The rest of the site, so far as I can tell, is running as usual and I can still list the views and see the actual views when going to their paths.

Update (problem solved but question remains): I drush cc all (cleared the cache) and the view edit pages are reachable again.
Though for future reference, what might be the reason that this happened? I feel like this isn't the first time I've found Drupal acting unpredictable and that clear the cache sets it straight.

The update to your original question suggests that the problem wasn't with Views itself.

When you do a drush cc all, it essentially calls drupal_flush_all_caches(), which

clears the JS cached files
clears the CSS cached files
rebuild2 the list of themes
rebuilds the theme registry
rebuilds the menus
rebuilds the list of content types
deletes all temporary items from the cache bins, and all items that had TTLs set which have expired

What I suspect, is that something happened to the menu tables and the cached entries were not fully rebuilt (I have seen this before).  Typically, it happens when you do a cache clear from the Performance page, and the process barfs, normally from running out of memory or timeouts because of load (I have seen the later on some servers).

When you did this from the command line, the menu tables got fully rebuilt that time, and your pages are available.

You should keep an eye on the amount of memory your site is using for page requests from a stale cache, and compare with the PHP memory_limit on your site.  If the two are close, you may have periodic overages which will cause sporadic problems.  Also make sure your Apache and MySQL are well tuned, as poor tuning can cause process stacking during cache clears, which can avalanche into a mess.


Lowercase in facets search api I have an issue with Facets on search API (Solr Integration).

Facets items are all in lowercase, and thats not how the content type save them, and I've made a query to solr server directly and the index items there have uppercase letters

can someone help me ?

Thx

You could use hook_facetapi_filters() to define a new filter for your facets.

/**
 * Implements hook_facetapi_filter().
 */
function MODULE_facetapi_filters() {
  return array(
    'uppercase_items' => array(
      'handler' => array(
        'label' => t('Uppercase items'),
        'class' => 'FacetapiFilterUppercaseItems',
      ),
    ),
  );
}

and then extend the FacetapiFilter class like this:

class FacetapiFilterUppercaseItems extends FacetapiFilter {

  /**
   * Filters facet items.
   */
  public function execute(array $build) {
    // Do your magic.
    foreach ($build as $key => $value) {
      $build[$key]['#markup'] = ucfirst($value['#markup']);
    }
    return $build;
  }

  /**
   * Adds hook documentation.
   */
  function settingsForm(&$form, &$form_state) {
    $form['uppercase_items'] = array(
      '#title' => t('Uppercase filters'),
      '#type' => 'checkbox',
      '#default_value' => TRUE,
    );
  }
}

I haven't actually tried this out but this is pretty much what Facet API Bonus does, which is also a great example for creating your own filters.


Domain Access module: Adding nodes programmatically to subdomains I am using Drupal 6 and Domain Access-6.x-2.11.
I need to programmatically add nodes to subdomains defined in Domain Access configuration. I've been looking the source code of domain.module but can't figure out how to use the api of the module to add a node to certain subdomains.

Any suggestions?

Since I didnt find a way to do this with api I solved this by editing the table where domain access keeps the info about which node belongs to which domain.


Attaching a field of a node type in another form I have content type 'story' which have an upload field. I have workflow modules installed.

I want the upload field to be presented within the workfloaw form. So within form alter function I did:

field_attach_form('node', $node, $form['append'], $form_state);

then unset all other fields of the story node and appended validation and submit handlers:

$form['#validate'][] = 'node_form_validate';
$form['#submit'][] = 'node_form_submit';

on submission I get this error:

"EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7409 of /var/www/site/includes/common.inc)."

I tried by specifying 'bundle' and 'entity_type':

$form['#bundle'] = 'story';
$form['#entity_type'] = 'node';

and

$form['append']['#bundle'] = 'story';
$form['append']['#entity_type'] = 'node';

but did not help. What can I do?

Thanks.

"EntityMalformedException: Missing bundle property on entity of type node."
means that Drupal does not recognize your entity as a valid one. In the entity info listing, there is a mapping from "bundle" to "type", for nodes.

Either your $node doesn't have a ->type, or Drupal no longer has the type registered. The type could have been removed, either from the UI, or by disabling a feature, and possibly in more interesting ways as well.


How can I NOT show the Request new password tab within the /user (login) page for one particular user Drupal 7 /user url goes to a page that has 2 tabs Login and Request new password which is what I want for all of our users except for one.  How can I NOT show the Request new password tab within the /user (login) page for one particular user ($user->name)?

If you just wish to hide the tab, you can do that by using the Tab Tamer module. However, the user would still be able to access the form through the URL http://<yoursite>/user/password.

If you wish to disable (along with hiding) the password tab, you can implement the hook_menu_alter().

function MODULE_menu_alter(&$items) {
  //condition to check the user
  global $user;
  if($user->id == '<USER_ID_OF_THE_USER>') { //can use $user->name as well
    $items['user/password']['access callback'] = FALSE;
  }
}


How can I modify the arguments passed to a core hook? Due to a recent update of Drupal core, I'm getting the following error:

  Notice: Undefined index: taxonomy_term in
  taxonomy_field_formatter_view() (line 1601 of taxonomy.module)

Now, this is caused because the core taxonomy hook taxonomy_field_formatter_view() has an argument called $items that expects an array of values that have two elements: tid, a numeric value, and taxonomy_term which is the taxonomy term object.

In the case of my code, each array in $items is missing the taxonomy_term element.

Now a simple fix would be to hack core and simply set $item['taxonomy_term'] = taxonomy_term_load($item['tid']) if it doesn't already exist. But of course, hacking core is a no-no so I'm trying to find a way to catch the $items argument for taxonomy_field_formatter_view() before it is passed to this hook.

What's the approach here? Would defining hook_field_formatter_view() in a custom module and fixing the $items argument work? Presumably not because the core hook is going to fall over first, so I'll need to modify it before it's passed into these hooks?

Implement hook_module_implements_alter and replace taxonomy_field_formatter_view() to your function.


Custom page template for a node type? I am creating a custom theme, and I need different page layouts depending on the node types. I can't use the node--xxxxx.tpl.php template, because I need control on the page layout outside the content of the particular page.

How can I do this?

There's a module for that: the Context module is what you need.
You can do it with page-[type] via preprocess functions.


How to add first and last classes to local task items? I'd like to add some classes to local task items, now there is only "active" class available which is pretty not flexible, I'd like to have "first" on first item and "last" on last item.

Tried theme_menu_local_tasks() and theme_menu_local_task(), neither of them work. And the post about "Add first and last classes to secondary local tasks" is probably for Drupal 6 so it's not working either.

You can use jQuery :first and :last selectors, example:

$('ul li:first').addClass(‘first’);
$('ul li:last’).addClass(‘last’);

Or you can use CSS :first-child and :last-child selectors, example:

li:first-child { add your css here }
li:last-child { add your css here }

The CSS way will give better performance.


render form in page--node--add--contenttype.tpl.php In Drupal 6, there was a method to theme the edit form for nodes of a custom type:

 /**
* Implements hook_theme().
*/
function hook_theme($existing, $type, $theme, $path) {
    return array(
   'node-type_node_form' => array(
   'variables' => array(
   'form' => NULL,
     ),
   'template' => 'node_type-node-form',
   ),
 );
}

Drupal 7 handles this method with the following template files: page--node--add--contenttype.tpl.php, or, page--node--edit--contenttype.tpl.php.

I didn't find any documentation about how I should render form items in these templates. $form is null.

Which variable should I use to render the edit form for my content type?

Can you try this code in page--node--add--yourcontenttype.tpl.php

module_load_include('inc', 'node', 'node.pages');

$form = node_add('your node type');

print drupal_render($form);

Refer Change aspect of node add form (not only via css)


What is an alternative to hook_node_view()? When a node is rendered in a panel pane, hook_node_view() is not invoked. (I use Panels 7.x-3.4.) Is there any alternative to change rendered node content in any other hook?

I have tried  with hook_ctools_render_alter(), but the HTML output of the node is presented as one large string. I need to change node content in one particular field, so I need to access a $node variable as an array, as it happens with hook_node_view(). I need to execute custom PHP for changing the output of one of the fields.

If you are just editing one field you can use template_preprocess_field(), hook_field_display_alter(), or hook_field_display_ENTITY_TYPE_alter(). Those should also fire in other contexts if you use that field outside the panel pane in the future (which may be a good or bad side-effect depending on your context).


Users Export module hook I'm using Users Export that provides a hook with no extra information.
I need somehow to explore the $info parameters in order to this extra fields

my code:

function display_my_users_loft_data_grids_info_alter(&$info) {
    var_dump($info);
}

But in that case the var_dump doesn't work.

Does someone know any example or documentation or help me to debug that?

Get the Devel module installed and use the dpm() function, e.g.

function display_my_users_loft_data_grids_info_alter(&$info) {
    dpm($info);
}

Then perform whatever action it would take to invoke that hook, and you'll see the $info variable exported to the messages area for easy browsing.


How can I register an already uploaded unmanaged file as managed file? I am stuck in a point that should be easy but I couldn't figure it out.

To make a long story short; I uploaded manually some images to the public directory and now I want to register them as managed files but I am stuck for some time where I couldn't figure out how to do it.

I tried using system_retrieve_file but it seems to accept only URLs not local paths public:// as it uses cURL to get the file

Also, I tried using file_save_data with no luck as well for the same mentioned points.

Any ideas?

I ended up creating a new managed file, pretty easy as the following:

$user = \Drupal::currentUser()->id();
    $image = File::create([
    'uri' => $image_local_path,
    'uid' => $user,
    'status' => FILE_STATUS_PERMANENT,
  ]);
  $image->save();


menu block or view that shows only siblings and parents It seems like this function was removed in drupal 8 so I am trying to find a solution that doesn't involve created a large amount of blocks or hard coding something. (Best would be a block or a view)

I have menu structure like this:

Parent 1
- Child 1.1
-- Grandchild 1.1.1
-- Grandchild 1.1.2
- Child 1.2
-- Grandchild 1.2.1
-- Grandchild 1.2.2
Parent 2
- Child 2.2
-- Grandchild 2.2.1
-- Grandchild 2.2.2

When I am on Grandchild 1.1.1 I want to see only the entire tree of Parent 1 (that means parent 1 plus all of its child and grandchild items), nothing from Parent 2 and below.

It seems this question has an ongoing patch at https://www.drupal.org/node/2811337 (which i found just after offering the bounty! :)


Limit number of event registrations per month I'm creating a membership-based site in D7, using Date, Calendar, and Entity Registration (which was very easy to setup). Only authenticated users may register for an event.

I'm trying to limit the number of events an authenticated user may register for during a certain time period (probably by month or by quarter), and I'm stuck. I created a field called 'Registration Count' for user accounts. And I created a rule that increments the counter when the user registers for an event.

But I'm trying to figure out:

How do I prevent a registration based on the user's current registration count? I got as far as creating a rule that is triggered prior to a registration and checked his current registration count. And I can display a warning, but the registration still goes through. Isn't there an action I can assign that would halt the registration?
How can I reset the registration counter field for all user accounts back to zero at a certain interval? I can't find access to user fields on that broad level.

Adding more details:

I have a node type called "Event". My registrations are entities. This is out-of-the-box functionality for the Entity Registration module, and it was very simple to get it up and running.

Each user has a field called field-registration-count. When a user registers for an event, I have a rule set up as follows:

Event: After saving a new registration
Action: Set value site:current-user:field-registration-count, add offset 1. This increments the user's registration count by 1.

I have another rule:

Event: Before saving a registration
Condition: site:current-user:field-registration-count > 2
Actions: Page redirect, and then Show a Message on Site

On the third registration, the page redirect happens as expected, and the message is displayed, but the registration is still saved. Based on the provided event named "Before Registration", I think I'm tapping in a the right time; I just can't find an action to cancel the registration itself

Note: When a user actually registers, it doesn't create a node. The Entity Registration module creates an entity type instead, and each registration is an entity.

Action to halt registration

Use "Page redirect", with a value for "URL" that could be either one of these:

some special node that you want to display to inform the user that the maximum number of events was reached.
the same URL that the user uses to add the event, combined with "Show a message on the site" whereas the message content provides appropriate information to the user that the maximum number of events was reached.

If that doesn't help/work, then you may want to try a variation of my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle? (that question was about "Node is 'going' to be viewed, while yours is about something like "entity is 'going' to be created").

Reset registration counter

Similar to the "Registration Count" field that you added, add another field like "Count start date". And each time a user tries to create a new event, just use that "Count start date" to compare it with the "current date": if then the time span between those 2 dates is longer then that "certain interval", then reset the "Registration Count" to zero.


hook_feeds_processor_targets_alter - how to set a value not in the feeds source? I need to import a csv that has only two fields (date and name) to a content type that has 3 fields:

date
name
file

The file field should be set as the name of the file being imported.

My code until now is this:

function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['my_feed'] = array(
    'name' => t('field_filename'),
    'description' => t('This field has the csv file name.'),
    'callback' => 'mymodule_import_filename',
  );
}

function MYMODULE_import_filename($source, $entity, $target, $value, $mapping) {
    $my_filename ='file.csv';
    $entity->{'field_'.$target}[$entity->language][]['target_id'] = $my_filename;
}

Where am I doing a mistake? Is this the way to import a value outside the file being imported?

Thanks.

I managed to get the answer to this question.

In MYMODULE_import_filename() we can get the data we want to import, in my case is just a simple text: 'file.csv'.

The simple way to do it is like this:

function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['my_feed'] = array(
    'name' => t('field_filename'),
    'description' => t('This field has the csv file name.'),
    'callback' => 'mymodule_import_filename',
    'real_target' => 'field_filename',
  );
}

function MYMODULE_import_filename($source, $entity, $target, $value, $mapping) {
    $my_filename ='file.csv';
    $wrapper = entity_metadata_wrapper('node', $entity);
    $wrapper->field_filename->set($my_filename);
}


Custom Drush command and Settigns::get(), Config::get() how can I access site configuration when in Drush command?

Global variable $config === null and when I use Config::get('key'), I get

  Error: Using $this when not in object context in Drupal\Core\Config\Config::get() (line 85 of /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Config/Config.php)`

What is the recommended approach? I can't find it anywhere... thank you!

Edit

I actually intended to access Settings, not Config - that's where the confusion came from. Settings::get() works just fine. To get data from config, just follow the accepted answer.

Get is not a static method, so it should not be called statically (using ::). Use Drupal's service container and get the config service using \Drupal::service('config'), then get your config from that.


Different user registration small question

I've created a content type 'Player' with the necessary fields. With the 'Inline Entity Form' module i've added this tot the default user registration form.

Now when a user register, he immediately creates a node for the content type 'Player'. And when he edit his user profile, he also edit the node.

Now I want to have the option, that a user can choose to register as a player or a coach. When a coach register, he should fill in other fields, and so create a node for the content type 'Coach' .

With which modules can I realize this?

You can achieve this using Profile 2 and Profile2 Registration Path

As the project page of Profile2 Registration Path mentions

  Profile2 Registration Path enables you to set a unique registration
  path for each Profile2 profile type. Users who register via that
  unique path will be presented with fields from the chosen profile
  type(s).


Cant create View with Many to Many Relationship I have a situation with three content types. (Simplified)

A Person is referenced in many Transactions, and a Transaction also has a reference to a Company. I.e. Person -< Transactions >- Company

Here the Transaction holds the entity reference to a Person, and a reference to a Company. I need to create a view that given a value from the Company content type, returns all the Person entities.

In SQL I would do something like this, to give me Persons who have had Transactions with a specific company:

  SELECT P.*
    FROM Person P
    JOIN Transaction T on T.PersonId = P.Id
    JOIN Company C on C.Id = T.CompanyId
    WHERE C.Name = 'Drupal Co.'

It's quite simple:
Create a view which shows content of type Person (or users, if for Person you mean users).

Now let's say that Transaction has an Entity Reference field named field_person and another one named field_company.

In the view's Advanced section click on Add relationship, search for field_student and check "A bridge to the Content entity that is referencing Content via field_person" if Person as a node type or "A bridge to the Content entity that is referencing User via field_person" if Person is a user. In the configuration window that pop ups check "Require this relationship" and save. You have just configured the first join.

Add another relationship. How that you have configured the first one, you can search for field_company and check "A bridge to the Content entity that is referenced via field_company". In the configuration window click on "Require this relationship" and check that the Relationship combobox has the first relationship selected. Now you have configured also the second join.

Finally create a Contextual filter. Search for "Content: Nid" and check it. In the configuration window, the Relationship combobox must have the second relationship selected. Choose what to do "When the filter value is NOT available" (this depends on what you want to do).

Done!

EDIT: I noticed just now that you search Company by name, not by NID. Just change the field in the contextual filter!


Is there any need to check the block name when my module just define a block? I am reading "Drupal 7 Module Development", and I followed the book's steps to create a block in my module.

/**
   * Implements hook_block_info().
   */
  function first_block_hook_info() {
    $block = array();

    $block['list_modules'] = array(
      'info' => t('A listing of all the enable modules'),
      'cache' => DRUPAL_NO_CACHE
    );

    return $block;
  }
  /**
  * Implements hook_block_view()
  */
  function first_block_view($block_name ='') {
    if ($block_name == 'list_modules') {
      $list = module_list();

      $theme_args = array('items' => $list, 'type' => 'ol');
      $content = theme('item_list', $theme_args);

      $block = array(
        'subject' => t('Enable modules'),
        'content' => $content
      );

      return $block;
    }
  }

first_block_view($block_name = '') is using if ($block_name == 'list_modules') to check which block should be rendered, but I think Drupal will only send  list_modules' to my module.

Is there any need to check the block name in hook_block_view()?

While your module defines only a single block, technically no, it's not necessary.

But, as soon as you want to add another block, you'll need to distinguish between that and the existing one, so you'll need to check the block delta.

It's a good practice to get into, even if it's not strictly necessary to test the delta in the block view function.


How to abort a cron run? I would like to have the ability to prevent cron from running based on a variable set in the database. I have created a hook_cron implementation in a module with an extremely low weight so it will presumably run before all other module's cron hooks. Within that function I then check the variable and call exit() to abort PHP's execution. This seems to work but is there a more elegant way to prevent cron from continuing? Calling exit() seems a bit harsh and I am concerned about unintended consequences. Example code below.

function ex1_cron() {
  if (variable_get('ex1_var', 1) === 1) {
    watchdog('ex1', 'Cron is being aborted.', array(), WATCHDOG_WARNING, NULL);
    exit();
  }
}

Calling exit() yes is a little bit too harsh and it does bring some consequences with it:

Typically when drupal_cron_run() finishes running all the cron jobs created with hook_cron() it logs into the watchdog the message "Cron run completed". Aborting your cron cycle mid-execution leaves you with no traces of how or when your cron finished.
When the cron cycle begins, Drupal creates a cron lock by using variable_set('cron_semaphore', time());, which prevents further cron cycles from running until you release the sempahore (manually) or until 3600 seconds pass since the last time you aborted the cron.

When your abort condition is met, you should at least do the following:

// Call cleanup function.
drupal_cron_cleanup();

// Release cron semaphore
variable_del('cron_semaphore');

watchdog('name_of_yourmodule', 'Aborted because XYZ.', array(), WATCHDOG_ERROR);

Also like @wiifm mentioned in his answer, a lot of critical functions defined by core and contrib depend on cron running to keep your site working. Abort cron and your site suddenly stops running smoothly. I would really avoid doing this.


Displaying all the entity reference entities in a view I have a "press release" node type which uses entityreference to link to any number of file_entity images, another field for file_entity videos and another to file_entity audio files.

There is a need for a block to display the first six images from the most recent press release, with some text from the press release.

So I built a view that finds the most recent press release and then displays the first six image entities. Or it should have but it doesn't, it always reports zero images (or zero videos, or zero audio files) regardless of how many there are.

So I ripped into Views to find the problem and discovered that entityreference does not provide a field handler, as a result Views assumes it's referring to a node and not an image and it all goes pear-shaped.

All entityreference does is provide a relationship handler, which is fine as far as it goes but you can only display one entry from the list of references - the first one.

Am I really going to go completely non-intuitive and have the images as the main table, and then sort by and group by parent press release node?

Any better ideas? (Short of writing a proper Views field handler?)

I think you will need to create a view of image entities, rather than nodes. The use a reverse relationship with the node that references it as a filter.


How to show a specific amount of multivalue fields depending on a value of the parent node? I need to show a specific amount of multivalued fields on a comment depending on the value of the node (field_optionsamount) that the comment is attached to. There are modules that allow to set the number of fields shown (e.g. https://www.drupal.org/project/multivalue_extras) but the limit is the same for all fields and does not depend on the node.

The code below removes the add more fields button and provides the amount of fields that need to be shown. I don't know how to show x fields though.

function customisations_form_comment_form_alter(&$form,&$form_state,$form_id) {
     $parentNode = $form['nid']['#value'];
     $node_data = node_load($parentNode);
     $amountOptions = $node_data->field_optionsamount['und'][0]['value'];
     drupal_set_message("Amount: ". $amountOptions);
     unset($form['field_toinvest']['und']['add_more']); //hides the add more button
}

Don't know what the proper way is to handle answers where the solution comes from another posting. So I only make the reference here: https://drupal.stackexchange.com/a/140861/24957

The code below works perfectly and only shows $amountOptions fields.

if (!isset($form_state['build_info']['args'][0]->field_toinvest[LANGUAGE_NONE][0]['value']) && !isset($form_state['default_fields'])) {
for ($i = 0; $i < $amountOptions; $i++) {
// First field is already in form.
  if ($i > 0) {
    $form['field_toinvest'][LANGUAGE_NONE][$i] = $form['field_toinvest'][LANGUAGE_NONE][0];
  }

  // Set form values
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#default_value'] = 0;
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#value'] = 0;

  // Set row weight
 $form['field_toinvest'][LANGUAGE_NONE][$i]['_weight'] = array(
  '#type' => 'weight',
  '#title' => t('Weight for row ' . ($i + 1)),
  '#title_display' => 'invisible',
  '#delta' => $i,
  '#default_value' => $i,
  '#weight' => 100,
 );
}
$form_state['default_fields'] = 1;
$form_state['field']['field_toinvest'][LANGUAGE_NONE]['items_count'] = amountOptions - 1;
}


"This version is not compatible with Drupal 8.x and should be replaced." The below theme files, which are the only files I have in my theme folder called 'Lychee', throw the error (in the 'Uninstalled themes' section of /admin/appearance):

  This version is not compatible with Drupal 8.x and should be replaced.

How should I resolve this? I followed this guidance: https://www.drupal.org/node/2349827

lychee.info.yml

name: Lychee
description: 'Mobile first theme.'
type: theme
core: 8.x
libraries:
  - lychee/global-styling
regions:
  - navbar: 'Navigation bar'
  - parallax: Parallax
  - content: Content

lychee.libraries.yml

global-styling:
  version: 1.x
  css:
    theme:
      assets/css/styles.css: {}

Your regions section is slightly off. It should be:

regions:
  navbar: 'Navigation bar'
  parallax: Parallax
  content: Content

Note the removal of the - in front of each region.


show content in a modal / popup window I'm using views in my drupal site and I want to show a popup window containing custom information (the information from the content type I guess) when I click on a view item.

Something really similar to this: http://conference.99u.com/#speakers

Is there an easy way to do this in Drupal? Which is the best module for that?

Thanks you in advance!

sounds like colorbox_node might be the module you want.

  Gives the user the ability to display ANY page inside a colorbox modal
  without the header and footer. Those pages include:

  Node Pages
  User Pages
  Views Pages
  Webforms (requires Webform Ajax Module)
  Integration with Views
  Integration with Context
  Integration with Panels


how to get content type field name as drop down for filter in view In Drupal 7.10, I have created new content type with 15 fields and file upload for collecting input from end user(named inputdata). I need to create a search page with content field of "inputdata" (content type) . In views I select the "inputdata" using exposed filter 15 field is difficult, its not fair. So I need these 15 fields as drop down (instead of equal to , contains, greater than ...in exposed filter).
So How do I get the names of fields as drop down for search ? Which modules I need to configure ?

I can only give you an example of querying the users table and displaying the people in the users table as an option but this might help:

  function example_page_builder() {

  $form = array();

 //getting the list of users
  $query = "select * from users where name!='';";

  $result = db_query($query);
  foreach ($result as $user) {
    $users[$user->uid] = $user->name;
  }

  $form['example_field_set']['users'] = array(
    '#type' => 'select',
    '#weight' => -6,
    '#title' => t('Select User:'),
    '#options' => $users,
  );

  return $form;
}


Why are my AJAX forms submitted twice? I've been looking up and down for hours now trying to figure out what I am doing wrong.

Every time I submit a form via AJAX, the submit function gets invoked twice. In other words, the form gets submitted twice. Here is an example I have been working with in my attempt to boil everything down to the basics in hope of finding the root of this very annoying issue (the example assumes AJAX requests, and is not really geared towards graceful degradation).

This is not an issue with multiple AJAX requests being sent from the browser. The browser only sends one single request when i click on the form's 'submit' button.

/**
 * Page callback for 'welcome'. This path has been registered
 * as a plain MENU_CALLBACK.
 */
function us_welcome() {

  // This is where the user arrives at first when navigating to
  // 'welcome'. The user is simply presented with a link which
  // will load the registration for via AJAX and show that form
  // on the very same page.

  $html[] = l(t('Register'), 'welcome/register/nojs', array(
    'attributes' => array(
      'class' => array(
        'use-ajax'
      ),
    ),
  ));

  $html[] = '

';

  return implode($html);

}

/**
 * Page callback for 'welcome/register'. This path has been registered
 * as a plain MENU_CALLBACK.
 */
function us_register($mode = 'nojs') {

  // This callback is responsible for the path 'welcome/register'
  // and is the one which the link invokes. If invokation happens
  // from the link, then $mode is 'ajax'. Otherwise, it is 'nojs'.

  // Get form.
  $form = drupal_get_form('us_register_form');

  if ($mode != 'ajax') {
    return $form;
  }

  // Generate commands array.
  $commands = array(
    ajax_command_replace('#form-register-wrapper', drupal_render($form)),
  );

  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);

}

function us_register_form($form, &$form_state) {

  // A plain old form builder function. Nothing magical
  // going on here.

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['#action'] = '/welcome/register/nojs';

  $form['messages'] = array(
    '#markup' => '

',
  );

  $form['basic'] = array(
    '#type' => 'fieldset',
    '#title' => t('Basic Details'),
  );

  $form['basic']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Your Name'),
  );

  $form['basic']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Your E-mail'),
    '#required' => TRUE,
  );

  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'us_register_form_submit',
      'wrapper' => 'form-register-wrapper',
      'effect' => 'fade',
    )
  );

  return $form;

}

function us_register_form_submit($form, &$form_state) {

  // This is the form submit function. The weird thing is that it gets
  // called twice every time the form is submitted via AJAX.

  // This block of code will only apply to AJAX requests. Normal requests will
  // return from the validation function(s) if validation error(s) should occur,
  // and by the time normal requests get to this point everything have been
  // validated. AJAX requests, on the other hand, goes through the validation
  // function(s) but will still reach this point even though validation error(s)
  // occur. Thus, we need to check for errors and return error messages in case
  // of validation errors. In case of errors, return the form again.
  $errors = form_get_errors();
  if (!empty($errors)) {
    return $form;
  }

  // @todo : carry out registration here.

  $content = array();
  $content[] = t('Thank you for registering!');

  // Process form submission.
  $commands = array(
    ajax_command_replace('#form-register-wrapper', implode($content)),
  );
  $page = array('#type' => 'ajax', '#commands' => $commands);
  return $page;
}

The problem you are noticing is caused from the fact that  us_register_form_submit() for Drupal is the form submission handler for the form returned from us_register_form() and, at the same time, you set us_register_form_submit() as AJAX callback.
That function will be called twice, when AJAX is enabled: first as AJAX callback; then, as form submission handler.

Just change the code as this. (See the /* changed this */ comment.)

  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'us_register_ajax_callback' /* changed this */,
      'wrapper' => 'form-register-wrapper',
      'effect' => 'fade',
    )
  );

AJAX callbacks are not for validating a form, and they will never get called to validate a form, except when you set as AJAX callback a function already used as form validation handler. The purpose of an AJAX callback is reacting when a JavaScript event happens for a form field, and updating the form without returning to the browser a full page.


Remove duplicate records from views feed display for node with multiple grouped terms from one vocabulary I have an RSS feed display in a view, and one of the fields in the view is a multi-value taxonomy reference field. The feed settings have a "Grouping field" setting, and I've chosen that field (and I also have DISTINCT selected in the query settings), but I still get duplicate records.

When I run the query in MYSQL, I can see that it returns one record per term, so I'm guessing the grouping like that is handled in the display layer that an RSS view doesn't have (even though it does have a grouping setting).

That being said, what is a good place to filter out duplicate results? I saw the Views Distinct module, but it doesn't have a D8 release. In looking at the views hooks, it looks like hook_views_pre_render would be the best place, because at that point the query is run and the $view object has the results.

If anyone has experience with this or a better way, I'm open to suggestions.

Thanks.

Here's what I came up with that does the job:

/**
 * Implements hook_views_query_pre_render().
 */
function video_export_views_pre_render(Drupal\views\ViewExecutable $view) {
  $unique_nids = $new_results = array();

  // Loop through results and filter out duplicate results.
  foreach($view->result as $index => $result) {
    if(!in_array($result->nid, $unique_nids)) {
      $unique_nids[] = $result->nid;
    }
    else {
      $new_results[] = $result;
    }
  }
  // Replace $view->result with new array. Apparently views requires sequentially keyed
  // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
  // unset the duplicates.
  $view->result = $new_results;
}


Commerce Donation page I want to create a button on each node to a donation page. The button needs to send the title of the node to that page, I have managed to do this.

I have a product type donation. I modify the form price with line item and setup a form where you can select different donations values.

The problem is that I need to find a way to include that title in the donation form so It can be passed to cart.

I have tried commerce add to cart function to alter that, but it doesn't work.

Made a Product Type: Donation
After that I created Products of: 2 USD, 10 USD etc.
Created a donation page of form: /donation/*
When I reference the donation page from the node page the links look like this: /donation/%nid
On the donation page I create a custom form and there I modify the submit function.


PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'semaphore' doesn't exist I am having problems migrating my site to a production server. It's build in Drupal 7. I used the backup and migrate plugin to export the DB. The development server is Windows with Wamp installed and the production server is CentOS with Cpanel.

These are the errors I am getting:

  Error The website encountered an unexpected error. Please try again
  later. Error message PDOException: SQLSTATE[42S02]: Base table or view
  not found: 1146 Table       'fosagams_co_za.semaphore' doesn't exist:
  SELECT expire, value FROM   {semaphore} WHERE name = :name; Array (
  [:name] => variable_init ) in    lock_may_be_available() (line 167 of
  /home/balabalab/public_html/includes/lock.inc). Uncaught exception
  thrown in shutdown function.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table      'fosagams_co_za.semaphore' doesn't exist:
  DELETE FROM  {semaphore} WHERE (value = :db_condition_placeholder_0) ;
  Array (      [:db_condition_placeholder_0] =>
  191980980751f69eddeb26b7.24464293 ) in  lock_release_all() (line 269
  of /home/balabalab/public_html/includes/lock.inc).

I did however verify that the semaphore table exists. I am out of ideas, any help would be appreciated.

Thanks in advance.

I also got the same problem.
Then i realizez that when migrating, i copy and paste from old server. And when i opend the database on my new server and choose a table in it, it was emty giving me error: "table does not exist". So check out if it is importing the content of the data firt before continuing with your search.


How to use LESS (CSS) in a Zen sub-theme? I'm trying to use LESS in a Zen sub-theme, but while the CSS files are correctly included (even with a ".less" extension), the LESS rules themselves don't seem to be recognized and processed.

Here's my setup :

Zen theme installed, and sub-theme created (and activated)
LESS module installed and enabled (along with Libraries)
the lessphp library has also been installed, following the instructions on the LESS module page.

In my sub-theme folder, I basically have the following files :

mytheme.info, which includes the css/styles.css below.
css/styles.css: (provided with the Zen Starter Kit) only contains a bunch of import rules; among them I added @import "mytheme.less"; which will be the main CSS (LESS) file for my theme.
css/mytheme.less, in the same folder as the styles.css. I used this file to test simple LESS rules.

When I use a normal CSS rule in the mytheme file, it's recognized and displayed normally in the site (e.g. body {color: red;}. However, even basic LESS rules seem to be simply ignored. Example of code that doesn't work:

@color: red;
body {
    color: @color;
}

I'm not familiar with CSS preprocessors, so I don't know if I'm missing anything. Or is the Zen theme somehow incompatible with the LESS module?

So, any help is appreciated. Thanks in advance.

I can't comment directly about using LESS with Zen, but I have used it with Omega 3.

With this, you have to specify the proper filenames in the theme.info file.  The stylesheets need to be named like "styles.css.less", and specified like:

stylesheets[all][] = styles.css.less

in the .info file.  Includes with variables and mixins get named like "mixins.less".

Assuming files are named this way, the module will do its thing, and compile the sheets and rewrite the paths to reflect the compiled versions.

That said, we stopped using LESS a while ago, and have moved on to Sass/Compass.