Twig D8 Field Format Is it possible via Twig to output a field's value, that uses the fields formatter. I would like to display a file field two different ways in the same twig file. The first will be a link to the file with a label to the left. The second will be the SOLR Extract text from the file, with a label on the left.

Here are the formatters I am talking about.

As shown in the second image, there are multiple options for how to display the field. Is there a way in Twig to do something like the following.

{{ content.field_name.FORMATTER_NAME_HERE }} or
{{ content.field_name[0].value | FORMATTER_NAME_HERE }}

I would like to use the URL to file and Text extracted from attachment formatters.

There's no out of the box way to display a field in twig with two different formatters.  But it can be done with a hook in a custom module.

You can repurpose a field in hook_entity_view or hook_ENTITY_TYPE_view().

Here's an example:

function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article' && $view_mode == 'teaser') {
    $settings = [
      'type' => 'pdf_special_formatter',
      'settings' => $build['field_pdf']['#items']->getSettings(),
    ];
    $build['pdf_alternate_display'] = $build['field_pdf']['#items']->view($settings);

  }
}

Note that the settings may need to be altered before sending to another field formatter.  You'll have to look at that field formatter for the required settings.


How can I change page title in search results page? When user search Drupal 7 site, output page's title becomes:
"Search | example.com"

But i want to make page title as:
"Search: keyword1 keyword2 .. | example.com"

I installed "Page Title" module but i couldn't change it by it.
Is there a module to convert page title regarding to this?

Thank you very much

Install and enablde Page manager and Panels.
Go to admin/structure/pages, on the line "search-node", click enable, then edit.
Add new variant -> Create variant -> Choose any suitable layout -> Continue twice.
On the final page in the Wizard, expand "Substitutions". You should see two keywords in there, copy "%keywords:raw" to the empty "Title" field above
Below the keywords, click a cog in any suitable region, in the popup click Widgets, and select "Search form".
Repeat step 6 for "Search results".
Click "Create variant", followed by "Update and save".

Take variations for choosen layout into account, and your configuration should now look something like this


Drupal Deployment to Dev & Prod and Git Code Repository Setup I have a dev and a prod server with 4 other developers. What is the most efficient way of setting up a development code push environment without the need to have to get too involved in the process? I know the term these days is called CI (continuous integration). But the thing is that it can involve many moving parts during deployment I've read some setups have automated testing in the process. I don't believe I would need that as that's an extra system to manage.

My sites are just mainly information sites and its mainly used internally which is less than 1000 hits a day.

What is the simplest way some people approach this issue?

CI (continous integration) can contain many moving parts during deployment and code pushes. But instead of using all of it, which isn't necessary for every site, I've come up with the following setup:

2 environments: Dev and Prod domains
Code revisions gets stored in the git servers
2 git branches: dev and master, the master branch is the prod server code.
Each developer will have their own local servers for testing and coding on their laptops.
Each developer checks out the dev branch.
Master (prod) branch should only be touched when dev is tested. Then, merge dev into master.
Once a push to the Dev branch is detected, script on server will auto 'git pull' to get new changes.
Once a merge with dev + master, script on server will auto 'git pull' to get new changes into prod.
Drupal files content will be managed by the "Stage File Proxy" module without the need to download all files.
Database will be synced by downloading a copy from the dev server with "drush sql-dump"


How do I move a site from a server to another one? I am trying to move a Drupal 8 site, but I get the following error:

The website encountered an unexpected error. Please try again later.
InvalidArgumentException: Class "\Drupal\system\Controller\Http4xxController" does not exist. in Drupal\Core\DependencyInjection\ClassResolver->getInstanceFromDefinition() (line 29 of core/lib/Drupal/Core/DependencyInjection/ClassResolver.php).

How do I properly move a Drupal 8 site from a server to another one?
What I did was importing the database, moving the files, and changing the database connection settings.

In a nutshell, moving a Drupal website from one host to another is just a matter of moving the files and the database, and then connecting the two.

However, there are several things you need to consider:

Server environment should be as close as possible to each other. This way you will avoid any errors that are a result of having different software/configuration on production and development servers. Compare PHP version, MySQL version, Apache modules, and setup of all of these components.
File permissions need to be set up properly. I've seen problems caused by this dozens of times. In short, the Apache user needs to have enough permissions to access and work with your Drupal website. Otherwise, it won't be able to write and even read files in some cases. Read more about how to secure correct file permissions here.
If you do this manually via FTP, make sure that all files are transferred. It often happens that one of the files wasn't uploaded completely. This usually results in broken Drupal site and random errors. Other ways to migrate a D8 website are Drush, Git or simply zipping the whole directory and using wget on the other server to transfer it directly from server to server.
You will need to clear all caches. Preferrably you won't have CSS/JS aggregation and page caching turned on when you migrate the database. You can do this through SQL/phpMyAdmin. See this answer for more information.
Update trusted hosts in /sites/default/settings.php file.
Once you can access your website, update the temporary directory path at /admin/config/media/file-system, as well as any other settings (e.g. of contrib modules) that store server paths/domain name.

See also docs on migrating a D7 site. Most items are still applicable for D8.

If you follow the guidelines above, you will avoid most issues. If you still have problems after migration, post here the exact log messages you're receiving.

Regarding the error you already posted: I'd make sure that all files are there, and that your cache is cleared before doing anything else.

Hope this helps.


Is there a simple way to notify users about new posts on the site? I want my users to be able to "subscribe" to new content that is posted on my site.

I've looked at the Notifications and Subscriptions modules and they are just massive! I've also looked at Simplenews (which which has a very attractive name), but it seems targeted towards distribution of a custom newsletter and not sending out general notifications about new content posted on the site.

Is there simple a way to set up a rule (by means of the Rules module) to accomplish this?

You may consider the Notify module, which is a lightweight framework for sending out periodic notifications about new site content to users and admins.

From the project page:

  The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.


New Content type is not listing in Add Content in Drupal 7 When create custom content type through UI or programmatically in Drupal 7, there is no link is listed in the Content > Add content.

I was creating the content types without any trouble, but now it is created(succes message is showing) when I check them in the node_type table but not lising in the admin/structure/types.

But no content type is listing(not any links showing) in the Content > Add content, or Structure > Content type administration menu.

Here is the code that allows users to access node pages:

/*
 * Allow users to view the contents
 */
function mymodule_node_access_records($node){
    $grants = array();
    $grants[] = array(
        'realm' => 'example_realm',
        'gid' => 123,
        'grant_view' => 1,

  'grant_update' => 0,
    'grant_delete' => 0,
    'priority' => 0,
);
return $grants;
}

/**
 * Implements hook_node_grants().
 */
function mymodule_node_grants($account, $op){
    $grants = array();
    if ($op == 'view') {
        $grants['example_realm'] = array(
            123,
        );
    }
    return $grants;
}

Then I rebuild permissions using Content Access module.

Check the permission for node creation of that type in admin/people/permissions
Clear all caches and retry and it should be OK


Cannot insert images in body of a basic page I am using CKEditor and WYSIWYG. After updating Drupal core to 8.5.6, I cannot upload an image using the CKEditor's 'image' button anymore saying "Image Field is required."

I have checked CKEditor's plugin settings. Image upload's enabled there.

I have not found a solution yet. Any help will be appreciated.

PS: If I add an image using html "img" tag then it shows up properly, it's only the button that is not working properly.

I found a solution. Suggested by Tech-Tonic:

https://www.drupal.org/forum/support/post-installation/2018-08-24/ckeditor-image-button-cannot-insert-images-in-body-of-a#comment-12854570

  Does your content type have other file fields on it?
  If so, try temporarily disabling all file/image fields for the content type in "Manage form display" and save. Then enable them again and save. Worked for me, in Drupal 8.6.3.

As mentioned above, I also had an image/file field in the content type. Under 'Manage form display', I disabled the image field and saved. I then went back to 'Manage form display', moved it back to where it originally was and saved again.

After this the error no longer appears. This worked on the production, staging and development copies of the same site.


Count the number of Flagged users I'm running a D7 site and need some help with a view.

I've a 'Follow' Flag on every user profile which users can use to follow each other.

I'm trying to build a view where I want to see the list of users who have followed less than 5 other users.

Is this possible?

Well, actually it's not too late to implement if you do the following:

1) Add a following count (integer) field as a user field.

2) Go to /user/1/edit and put any number other than 1, inside of this field. (this is just a temporary place holder).

3) With PHPMyAdmin or a DB viewer program, export the following count field as a CSV file.

4) The 1 is where the USER ID goes, and the other random number is the actual following count.

So with views, create a view that shows the user ID and the following flag count number.

Then you open the exported .csv file on Excel and paste these data in the proper columns.

5) Import back into your Drupal DB and clear flush cache.

*Note: Instead of doing steps 3, 4 and 5, you could just do this with Views Bulk Operations + Rules.

6) Using the Rules module, create a rule that +1's the user following count field, when a user flags the follow flag and -1's it when they unfollow.

7) In views, in your List of Users View, for Filter, simply add the following count field and put less than 5.

8) Use the Field Permissions module to hide the following count field, that way when they edit their profile, the user cannot insert/modify the number.


How to include a caption (a cck field) in lightbox? I'm working on a theme i bought and since i'm just learning php i'm having a hard time including a field as a description text in the lightbox once the thumbnail is clicked.

Here's the code (that's in the tpl.php file) that outputs the thumbnails (from a view)

<?php
if (isset($fields['field_image']->content) and strpos($fields['field_image']->content, '<img')) {
 print str_replace('<a ', 'content); ...
?>

Here's the html version of the lightbox script :

<img ...

How can in include the caption tag ?

Thanks !!

Both the caption and the description will be displayed on the image preview.


Where are fivestar data stored? On a D7 site using fivestar , I'd like to extract data from the module but there is not such table or node in the database and looking at the source code, I could not figure out in which table/fields the fivestart data are related/stored.

So appreciate your help about this.

Fivestar module defines a field.
Add a field to a content type. If fx you add a field named "test" of type fivestar reting to a content type then you can find the table with the name "field_data_field_test".


How to set up Apache solr search for Book Specific search I have two books in my website (Drupal 7) and i am using Solr search.

I want to implement book specific search so that, if user is searching for Book1 content then it should show results from Book1 and not from Book2 and also let me know how to provide option of Book1 and Book2 near search bar so that we can filter the results.

I didnt find any module for this in drupal.Please provide me suggestions.

If you are familiar with views this can be done with the following steps.

We have a contributed module for apache solr views, by installing this module you can change the views module to apache solr views i.e you can route the queries from database queries to apache solr.

Working example :

Step 1:

Download and install the apache solr views module.

Once the module is installed the following steps is equivalent to creating a normal view with an exposed filters.

Step 2:

Create a new view I have named book search (I have created a normal menu  for the book search and added in the views path configuration i.e : " Path: /apachesolrfilters ", you can create a stand alone page or add it to any existing blocks), add fields and filters,

Fields : I have added content title, body & content type
Filters: I have added  Content: Published (Yes), Content: Type (exposed) & Content: Title (exposed)

Configure the filter content type to show only the book types book1 & book2.

Save the view and clear the cache.

Screen shot:


How to get the real sql query of a view? One of drupal view displays reviews based on a selected event. It should display 3 reviews but instead it displays only 2. It doesn't happen for all the events and only for certain events instead of 3 it displays 2 items. As the data is all correct and I have validated the same. I wanted to see the query that is being used. The query that is displayed in the view is not helping me either. If I copy paste the same and run the sql, it throws a lot of error.
How can I debug and see what is the query that got executed for that particular view?
The view has relationsships and also it uses contextual filters.
Thanks

The query displayed in the administration UI contains database prefixing brackets. You can remove those brackets to have valid SQL that can be executed by any SQL client.


How to render / preprocess list of entity reference nodes? I hove a content type that editors can 'attach' related nodes to.

When I 'theme' / 'style' nodes of this content type through view mode everything is basically fine: the related nodes are rendered as teasers and I can style them as I like.

Now I need to wrap the list of related nodes in an extra class e.g. 'related-nodes' according to the output of another field. For example the editor chooses 'round corners' from a list field, then the css class "rounded" should be added to the wrapper of the list of related nodes should.

I am aware I can remove the entity reference field from the display settings and preprocess it through template.php. But then how do I preprocess the list in template.php? So far I just don't know how to actually access / handle it.

In devel tab I do get the array of related items. I could of course loop through that array and re-build node by node thruogh node_load – but since I only want to wrap that loop re-rendering each node feels wrong.  Any suggestions?

As per @Clive comment, Fences module may be able to help with that.

A quite straightforward option would be to implement hook_node_view() in a custom module and add a #prefix and #suffix to the field element (prefix of <div class="foo">, suffix of </div>)


Drupal6 sidebar code? I got this d7 sidebar code from a theme and I am trying to make it work for d6..  Can someone help

Info file contains:
regions[sidebar_a] = 'Sidebar A'
regions[sidebar_b] = 'Sidebar B'

This is the code:

                  <?php
                      if(isset($variables) && isset($variables['sidebars'])):

                        if(isset($variables['sidebars']['left'])):
                          foreach($variables['sidebars']['left'] as $value):
                            if (!empty($page['sidebar_'.$value])): ?>
                            <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar left tb-height-balance tb-region tb-scope tb-sidebar tb-left">
                              <?php print render($page['sidebar_'.$value]); ?>

                        <?php endif; endforeach; endif; ?>

                      <?php
                        if(isset($variables['sidebars']['right'])):
                          foreach($variables['sidebars']['right'] as $value):
                            if (!empty($page['sidebar_'.$value])): ?>
                            <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar right tb-height-balance tb-region tb-scope tb-sidebar tb-right">
                              <?php print render($page['sidebar_'.$value]); ?>

                        <?php endif; endforeach; endif; ?>

                      <?php
                        if(isset($variables['sidebars']['hidden'])):
                          foreach($variables['sidebars']['hidden'] as $value):
                            if (!empty($page['sidebar_'.$value])): ?>
                            <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar right tb-height-balance tb-region tb-scope tb-sidebar tb-right tb-hidden">
                              <?php print render($page['sidebar_'.$value]); ?>

                    <?php endif; endforeach; endif; endif; ?>

Functionality aside, I think the basic structure for D6 would be:

<?php
if(isset($sidebars['left'])):
  foreach($sidebars['left'] as $value):
    if (!empty(${'sidebar_'.$value})): ?>
    <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar left tb-height-balance tb-region tb-scope tb-sidebar tb-left">
      <?php print ${'sidebar_'.$value}; ?>
    </div>
    <?php
    endif;
  endforeach;
endif; ?>


How to display page loading time in drupal 7 for each page I want to display page loading time in every page in the footer. I can do this through some custom php script but want to know that is there any drupal way to achieve this

The Devel module will show queries and their execution time in the footer which will get you an idea of how long the page is loading.


I can't save changes of settings of an Omega subtheme. Problem just happens in remote server I can't save changes of settings of an Omega subtheme in admin/appearance/settings/omega_subtheme_2

I get no error message. The changes are not saved at all.

This problem just happens in remote server. In my local server works just fine.

I guess it could be a folder or file permission problem. I already set the permission of site/all/themes/omega subtheme 2 folder and all its content to 777. But the problem persist.

this thread may answer your question: http://drupal.org/node/1388196

for some it is a suPHP request.max_vars and  post.max_vars issue


Commerce discount rule Have this scenario, a user must get 10% discount on only these products (product 1 & 2 is defined in rules), if at least 5 items of each is in cart.

Cart:

5 pcs    product 1         500
5 pcs    product 2          50
1 pcs    product 3         100

with the discount, the total will be 595, since the user will get 10% on 500+50 and not product 3

If the scenario is

5 pcs    product 1         500
4 pcs    product 2          50
1 pcs    product 3         100

the user will not get any discount.

It will help if you add the rule that you have added. Also if you think it's a complex rule to be applied, you can apply the discount in the checkout page rather than before that without using the rules itself. In other places just display the 1pcs price with the discount applied.


How do I override a module template (.tpl.php) from my custom subtheme? I've seen how to override module templates from other modules and theme templates from subthemes, but how do I override module from subtheme? The file is under the profiles folder.

Edit:

I'm using Open Atrium. I want to override this file:

  /var/www/openatrium/profiles/openatrium/modules/apps/oa_home/oa-home-default.tpl.php

From my subthem wich is located at:

  /var/www/openatrium/sites/all/themes/my_radix/

The subtheme is working fine, but I need to override some .tpl.php files that are not part of the parent theme. How can I do that? Where do I copy them? How do I tell Drupal to use the new files?

Copy file from your module folder: /var/www/openatrium/profiles/openatrium/modules/apps/oa_home/oa-home-default.tpl.php
and paste this to your subtheme in following path : /var/www/openatrium/sites/all/themes/my_radix/templates/oa-home-default.tpl.php

open this file and write something like this somewhere under php tags

 drupal_set_message('in new file');

go to admin/config/development/performance/ and clear all cache. Now when you visit to the page where the template is getting rendered, you'll see the message.


Why is langcode in configuration files ignored during installation? I have noticed that if I install Drupal in language other than English any config that will be imported during installation will be assigned to that language no matter what language is set in the config itself (the langcode value).

This results in a strange fact that my English config is showing up as XY language and if I enable English I can translate this config only into English, which does not make sense.

So how is Drupal 8 supposed to be installed properly when it comes to i18n?

Currently I am installing in English, and in last step of installation process I add my desired language and set it as default. But that seems like odd thing to be required in order for Drupal to work "properly".

It has to work like this. The alternative would be that a single-language non-English site would need to use the configuration translation to translate its configuration.

For the en langcode configuration, the installer will attempt to override it with the provided locale translations, from localize.drupal.org or local, and store the original English configurations separately, as far as I know. So, if you install in a language where you have translations, it should use them; if you don't, you have to change your configuration to the desired language.


Create content within the site instead of the Drupal modal popup? I have a content-type "client-request" and I would the form to be displayed within the site (inside the banner and sidebar) when the user clicks new request instead of opening up in the Drupal modal popup.

Is this do-able?

It is, but you'll need a bit of jQuery:

(function($) {
  $(function() {
    $('a[href="/node/add/client-request"]').addClass('overlay-exclude');
  });
})(jQuery);

That will add the overlay-exclude class to any link that goes to the node add form for your content type; all this is does is force the overlay to close when the link is clicked, and forward you on to the right page. It'll also stop any links on non-overlay pages from invoking the overlay for that path.


Keep showing log message How can I disable this message?

If you have the Click Heatmap module enabled, either disable the module or add clickheat to the libraries folder.

Though, looking at the path that is output in the error, it seems that clickheat is probably being included in a template file somewhere, find the code and remove it. Do a search through your files to try to find 'click.php'.

Just disabling database logging will remove it, but will also not log anything else, so this is probably not your best option. Better to fix the problem rather than just hide it.


Prevent anonymous users from accessing "node/" node/%nid and taxonomy/term/%tid So far, I have been reading some similar questions but I haven't found an elegant and simple way of doing this (if there is any). As I say in the question title, I don't want anonymous users to access the complete list of nodes (in node/) nor a particular node (under node/%nid), nor even a particular taxonomy term. :)

My approach to this is as follows. As far as I know, I can override the default node/%nid system page using a variant in Drupal panels. I actually did this and, if the user is not logged in, when he/she tries to access the node/%nid he/she will see a log in box. For the list of nodes, I removed from the front page all of the nodes and none is shown. I would expect to do with taxonomy/term/%tid the same as I did with node/%nid but, for a strange reason, Drupal panels is not able to create the variant (not sure if it is a bug).

Anyway, I would like to know if you have a more elegant or simpler approach to this (no matter if using panels or not).

Thanks in advance for your help!

Have you tried in the template.php? what if you do something like:

function yourtheme_preprocess_page(&$variables, $hook){
   if(!$user->uid){
      if((arg(0) == 'node') || (arg(0) == 'taxonomy')){
         //redirect to login
      }
   }
}


Linking content of one field to content of another I have a content type with an image field and a file field, being outputted in views. How do I want the image to link to the file.

How do I approach this? Make a template for the image field? And if so, how do I get the file field link from that template?

I'm using Drupal 7.

There are several ways to achieve this. I think the following one may be one of the easiest:

Assuming you have two fields outputted in views: "Image" and "File" make sure to display them in the following order:

Image
File

Edit image field and mark "exclude from display"
Edit file field and mark "rewrite output".
You'll see you can use the image field as replacement patterns so you can print the previous field [image] and link it to the file by writing a bit of html code such as this one: [image].


Table names without using curly brackets I'm working in a project in Drupal6 and we are removing all the curly brackets from the table names in the queries because we don't need table prefixes and supposedly this will improve performance.

Is this reasoning correct or curly brackets should be used even if we don't need table prefixing?

You should always keep the curly brackets in there, if only for maintainability and portability of your system. What if the next release of Drupal requires those curly brackets? I'm not saying it will, but if a framework gives you guidelines it does so for a reason; you should probably follow them.

As for the performance benefit, I think you'll find it's negligible at best. db_query() runs this statement regardless of whether your string contains curly brackets or not in the first instance:

$query = db_prefix_tables($query);

So db_prefix_tables() will get run on the string regardless of whether or not your table names actually need prefixing or not.

I'd advise stepping through db_prefix_tables() and using that to decide whether or not you should remove the brackets for performance reasons; you'll probably be making your decision based on the performance of the lower-level strtr() function, which does all the string replacement work.

There's a condition in that function that depends on a global variable not being empty to continue...if you want to 'turn off' the database table prefixing (and limit any inherent performance losses), ensuring that the global variable ($db_prefix) is empty when you run your query would probably do the trick (though that might make your data susceptible to race conditions; it depends on your setup).

Make sure you don't turn $db_prefix off for the entire site permanently though, or you'll have to go through all core and contributed modules and remove the curly brackets from their queries too!


Can I use custom fields inside custom fields in Drupal 7? I am making a custom field and would like to use other custom fields -- like the Link or Media fields -- inside it. Can I do this, and if so how do I determine what #type to include in my field definition?

For example, the pattern "Image + Linked Headline + Brief Description" happens frequently enough in my content that I am trying to create a custom field that combines these. But a lot of what I need already exists in both Link and Media plugins, and I'd rather not recreate that functionality if possible.

I have already tried using the Field Collection module for this, but can't because it does not support translation.

Edited

I think I have found my way around the Field Collection translation problem by switching to field translation instead of node translation. Field collection seems to be a little buggy there, especially for collections made prior to turning on entity translation, but so far it seems to be working.

A yes/no answer to this would still be interesting, though, for future custom-field development. The more I think about it, the more I think the answer is likely "no."

Please let me know if I'm misinterpreting your question — essentially, you're asking how to group up fields of content that appear frequently together on your Drupal site? Without using Field Collection... hmmm...

Well, first potential option is the Field Group module. However, it may not be exactly what you want seeing as how you mentioned Field Collection. It may be worth looking into though. Not sure it supports translation though.

The next potential option I see is changing the actual Image entity through the File Type interface provided by the Media module. At this screen, you can actually adjust the Image entity to contain extra fields. In doing this, all you would need then is place the Image field in your content type. The user uploading an image via this Media field would then be prompted to add the linked headline and a brief description after uploading the image.

Because the Media module documentation does an AWESOME job of explaining how to modify an Image entity, here is the documentation page about managing/editing file types — scroll down to the start of the section "Manage the Display of Images (Manage File Types)". After adding these fields to your Image entity (or a new entity), you'll be able to manage the display like you would for a content type.


All content types displaying in "Show only items where" search When I log in as a user who doesn't have access to certain content types, I can still see a list of those content types in admin/content under the "Show only items where" search. Also, some of the content types don't have any nodes using those content types, yet they are still listed in the dropdown menu under "type".

Rather than confusing certain users, I would prefer only for the content types they have access to, to be listed here. Is this possible?

Yes. You can alter the form's select box with a hook_form_alter() invocation. All that's needed is to remove the options that aren't relevant to the user.

For example, if you wanted to remove content types where the user didn't have the Edit any TYPE content or Edit all TYPE content permissions, you could do the following:

function token_form_node_admin_content_alter(&$form, $form_state, $form_id) {
  global $user;
  $types = &$form['filter']['filters']['status']['filters']['type']['#options'];
  foreach($types as $type => $type_name) {
    if($type != '[any]' &&
       (!user_access("edit any $type content", $user) &&
        !user_access("edit own $type content", $user))) {
      unset($types[$type]);
    }
  }
}


How to create static breadcrumb I've created a breadcumb using this and I've created one. But I would like to create breadcrumb for each page. I've 3 forms, above the form I need to set the progress of the form in the form of breadcrumb,

Drupal 7

$breadcrumb[] = l('hi', '/hi');
drupal_set_breadcrumb($breadcrumb);

In drupal 8 I've tried to use

$b = new Breadcrumb();
$breadcrumb[] = Link::createFromRoute(t('Home'), '<front>');
return $b->setLinks($new_breadcrumbs);

But this is not working...
how we can show that and where am I doing wrong?

There is a block in drupal 8 for displaying breadcrumb on your pages.
First set visibility of that block on the pages you want to show breadcrumbs.

Then in template_preprocess_breadcrumb in your theme's .theme file you can change the breadcrumbs variables.

For additional functionality you can create breadcrumb.html.twig file in templates folder of your theme.


Using hook_form_alter in overlay admin theme I am using hook_form_alter in a custom module to remove some fields from the block edit screen to clean up the ui for users of a certain role

function module_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (in_array('staff member', $user->roles)) {
    $form['visibility_title']['#access'] = FALSE;
    $form['visibility']['#access'] = FALSE;
    return $form;
  }
}

It works great. However, when the form appears in Drupal's admin overlay using the site's admin theme, Seven, the above code is not applied.

Is this because it's in an overlay? Or because it's a different theme? How can I get the hook_form_alter to apply globally?

FWIW, adding

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

doesn't print anything above the form in the overlay. But when I switch the admin theme to the site's theme, it properly dpm's the form.

Note: The custom module and the site's custom theme have the same name. Is this the problem?

Thanks to Clive's tip I realized that because my module and theme had the same name, the hook was being applied at the theme level. I renamed my module and now it works!


How to make a competition input form and a view? I want to put scores in a form. See screenprint:

Some details about it:

2 pulldown menu's with players.
2 text boxes for the score, example: (8) and (2).

In the above example, the automatically calculated "comp score" will be 3 and 1. If however the score is (6) and (6), then the comp score will be 1,5 and 1,5.

So to summarize (about how to calculate the "comp score":

When the score is equal both players get 1,5.
The winner gets 3, the loser gets 1.

They play in poules, several matches. Each match is put in like in the screenprint above.

The scores will be added up. And in a view they will be shown on the site as a ranking. The best on top.

I don't know how to imput the data, automatically give the comp score and how to add them up (to make the view will go).

To avoid writing a manual (to answer your question), here is a blueprint ...

Content type Game

Create a content type "game", with 2 entity ref fields to another content type like "player", and the other fields like date, etc.

3 Rules Components

Create 3 similar rules components (with parameters the score for player 1, and another parameter for score of player 2):

a 1st Rules Component with a Rules Condition to check if player1 has won, in which case you perform a 1st Rules Action to "set a data value" to set the "comp score" for player 1, and a similar 2nd Rules to set the "comp scrore" for player 2. Then add an extra Rules Action to save the entity (to ensure the comp value is also saved).
a (similar) 2nd Rules Component to check if player2 has won.
a 3rd , and one if the score was equal.

Custom rule

Create a custom rule like so:

Rules Event: before saving content of type "game"
Rules Actions: Perform 3 Actions, whereas each of these action performs one of the Rules Components create as described above.

Create a view games

Create a view of all your games. In doing so, use the Views Calc module to "add up the scores".

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


If I delete openenterprise module from drupal module folder site is collapse I am wrongly paste the open enterprise module in drupal module folder. If I try to delete that folder total site is collapsed. How to fix this issue.

You will need to rebuild the registry. The simplest solution is to use Drush and Registry Rebuild. There's also instructions on that page in case you can't use Drush or the command line.


How to copy/clone menu of a node when clone with Entity Clone module? When cloning a node using Entity Clone module, the menu link are not copied. As menu link item is created and managed on the node form level, there is no reference of the menu link item in the node entity level.
See menu_ui_form_node_form_alter for more details.

Issue #2839833 has a proposal to add entity clone plugin to node entity to handle this special case.

Alternatively, we could use the event. Luckily Entity Clone module dispatches an event before & after clone for the other modules to act. Here is the code for menu copy:

  // mymodule.services.yml

 mymodule.entity_clone.subscriber:
    class: Drupal\mymodule\EventSubscriber\EntityCloneSubscriber
    tags:
      - { name: 'event_subscriber' }

Subscribe to the post clone event:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Entity\EntityInterface;
use Drupal\entity_clone\Event\EntityCloneEvent;
use Drupal\entity_clone\Event\EntityCloneEvents;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\node\NodeInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Crates menu item after node clone.
 */
class EntityCloneSubscriber implements EventSubscriberInterface {

  /**
   * Entity post clone handler.
   *
   * @param \Drupal\entity_clone\Event\EntityCloneEvent $event
   *   An event object.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function onPostClone(EntityCloneEvent $event) {
    $entity = $event->getEntity();

    // Act only on node clone.
    if (!($entity instanceof  NodeInterface)) {
      return;
    }
    $cloned_entity = $event->getClonedEntity();
    $values = menu_ui_get_menu_link_defaults($entity);

    // Copy menu item, if available.
    if (!empty($values['entity_id'])) {
      $this->cloneNodeMenuLinkContent($cloned_entity, $values);
    }
  }

  /**
   * Clones menu link content associated with the node.
   *
   * @param \Drupal\Core\Entity\EntityInterface $cloned_entity
   *   Cloned node.
   * @param array $values
   *   An array of menu link content values.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function cloneNodeMenuLinkContent(EntityInterface $cloned_entity, array $values) {
    $menu_item = MenuLinkContent::load($values['entity_id']);
    $menu_name = $values['menu_name'];

    // Create new menu link content with original value.
    $cloned_menu_item = MenuLinkContent::create([
      'link' => ['uri' => 'entity:node/' . $cloned_entity->id()],
      'langcode' => $cloned_entity->language()->getId(),
    ]);
    $cloned_menu_item->enabled->value = $menu_item->isEnabled() ? 1 : 0;
    $cloned_menu_item->title->value = trim($cloned_entity->getTitle());
    $cloned_menu_item->description->value = trim($values['description']);
    $cloned_menu_item->menu_name->value = $menu_name;
    $cloned_menu_item->parent->value = $values['parent'];
    $cloned_menu_item->weight->value = isset($values['weight']) ? $values['weight'] : 0;
    $cloned_menu_item->save();
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[EntityCloneEvents::POST_CLONE][] = ['onPostClone', 200];
    return $events;
  }

}


How to give class name to the text field in drupal I am new to drupal and I have a problem in drupal text-box.

Question : how to give a class for text box?

my html :

<input type="text" name="uname" class="uclass" id="uid">

i want the same in drupal

My code is :

function my_module_my_form($form_state) {

// This is the first form element. It's a textfield with a label, "Name"

$form['name'] = array(

'#type'  => 'textfield',
                    '#title' => t('Enter Your Name'),
                    '#value' => t('Enter user name'),
                    '#name'  => 'uname',
                    '#id'    => 'uid',
                    '#class' => 'uclass',
                    '#maxlength' => 5
                   );
return $form;

}

Note: through inspect element , i find the class name is "form-text", but actually my class name is uclass, It is not taking, can one help me.

Additional HTML attributes, such as 'class', can be added using the '#attributes' property.

function my_module_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
   $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Enter Your Name'),
      '#weight' => -10,
      '#attributes' => array('class' => array('uclass')),
    );
 }

Please note that when you alter existing form elements (e.g. via hook_form_alter()), you probably want to add (attributes) to the existing array rather than writing over it.

Checkout Form API of Drupal 7 to get more detail.


Access denied hook_menu Drupal 7 I am trying my first module on Drupal 7 on the behalf of experience on Drupal 6.

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

  $items['mypage']=array(
    'title'=>t('Title'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_work_mypage_view'),
    'access arguments' => array('access content'),
  );

  return $items;
}

Upon accessing my page, I get access denied. What am I missing here?

Revised:

Your code looks right

3 Things could be the problem

'mypage' could be a banned link.
you don't have access to 'custom_work_mypage_view' form.
Clear your cache.   Without the 'access argument' line you will get access denied.  If you added it then save your file, you will still get access denied until you clear your cache.

My gut feeling is #3.


"Missing required paramter" with all Social Auth providers The problem: I've just installed social_auth_google, social_auth_twitter and social_auth_linkedin modules. All the modules are configured (Client ID, Client Secret, and other similar fileds). The modules are installed through composer require ..., so I assume that all dependencies are there, but to confirm here's the list of the enabled modules:

  Social              Social API (social_api)         Enabled   8.x-2.0-beta4
  Social              Social Auth (social_auth)       Enabled   8.x-2.0-beta4
  Social              Social Auth Google              Enabled   8.x-2.0-beta3
                      (social_auth_google)
  Social              Social Auth LinkedIn            Enabled   8.x-2.0-beta1
                      (social_auth_linkedin)
  Social              Social Auth Twitter             Enabled   8.x-2.0-alpha2
                      (social_auth_twitter)

Besides these, composer also installed some non-Drupal packages to vendor directory:

  league/oauth2-client (2.3.0)
  league/oauth2-google (2.2.0)
  abraham/twitteroauth (0.9.2)
  league/oauth2-linkedin (2.1.0)

I've embedded "Social Auth Login" block to "Content" region of /user/login and /user/register pages, and I've got a decent-looking login/register pages as the result.

But the problem is that neither of the embedded authentication providers doesn't work. If I click g+, I get "Error: invalid_request. Missing required parameter: client_id". When I click twitter, I get: "You could not be authenticated, please contact the administrator.". With LinkedIn I get: "You need to pass the 'client_id' parameter".

Obviously I'm missing something... Any help?

I've found the reason for the problem: outgoing proxy. The web server where I have my website installed doesn't have direct internet access, but it uses an outgoing proxy.

Regarding social_auth_twitter - it was my mistake - outgoing proxy was blocking access to api.twitter.com. After configuring the proxy to allow this traffic - Twitter authentication started working as expected.

But regarding the other two (social_auth_google and social_auth_linkedin) - no requests ever reached the proxy, meaning that these modules don't know how to use the proxy.

I've ensured that the proxy is configured correctly:

Environment variables http_proxy, https_proxy, no_proxy, HTTP_PROXY, HTTPS_PROXY, NO_PROXY are configured as needed;
In VirtualHost element (Apache configuration) I'm ensuring that these environment variables are available by setting the appropriate PassEnv lines (mod_env module);
settings.php file contains the appropriate $settings['http_client_config']['proxy']['http'] (and other) configuration.

At the end of the day - everything else (installing and updating modules, etc.) is working normally through the proxy, so proxy configuration isn't the problem.

It looks that, at least for now, you cannot have social_auth_google and social_auth_linkedin if your web server is behind a proxy. Another very disappointing fact is that there are no any logs in /admin/reports/dblog, so you cannot know that modules are struggling to access their corresponding API endpoints. Hopefully it'll be resolved in future versions. For now you simply have to allow direct access, and remove outgoing proxy completely.


How do I send a mail with attachment? I try with this, but no success:

$params = [
  'body' => 'My body',
  'subject' => 'My subject',
];

// I check by debug this code and $file get the right file
$file = File::load($myfile_id);

$attachment = [
  'filepath' => $file->getFileUri(),
];

$params['attachment'] = $attachment;

// This send a empty mail, without subject and not body
$send = \Drupal::service('plugin.manager.mail')->mail('mymodule', 'mykey', 'myuser@gmail.com', 'es', $params);

Why doesn't \Drupal::service('plugin.manager.mail')->mail work?

Then I tried this and it worked fine, but without attachments.

$system = \Drupal::service('plugin.manager.mail')->getInstance(array('module' => 'mymodule', 'key' => 'mykey'));

$file = File::load($myfile_id);

$params = [
  'headers' => [
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal',
  ],
  'to' => 'myuser@gmail.com',
  'body' => 'My body',
  'subject' 'My subject',
  // I try with:
  'attachment' => $file;
  // or
  'attachment' => ['filepath' => $file->getFileUri()];
  // with not success
];

// the mail was sent but without attachment
$send = $system->mail($params);

How do I send a mail with attachment on Drupal 8?

Drupal core doesn't support mail attachments/HTML mails.

You need to use an alternative mail implementation, like the Swift Mailer module.

Also, the reason the first implementation doesn't work is because you need to go through a hook_mail() implementation instead. See how core does it.


How can I get an empty region not to render in a field_layout template? I've got a layout_discovery template set up like this, for use in a field layout:

{% if content %}

    {{ content.main }}

  {% if content.sidebar %}

    {{ content.sidebar }}

  {% endif %}

{% endif %}

(I have also tried {% if content.sidebar|trim|length > 0 %} with no change in the result.)

A content type using this layout puts a single, optional field into the sidebar region. If that field is empty, I would expect content.sidebar to be empty, so that the sidebar div won't be output and the main div can expand to fill the space. However, instead I get an empty sidebar div:

Is there any way to accomplish this in a field layout, or do I need to build a custom node template instead?

Use this syntax:

{% if content.sidebar %}
  <div class="layout-region layout-region--sidebar col-sm-4">
    {{ content.sidebar }}
 </div>
{% endif %}

It will remove all HTML (such as the s that appear even if the section is empty and then only display if there is some non-HTML present.

NOTE: This will not work properly if a region contains only HTML tags, such as Search Facets that are completely made up of  options. The striptags call will remove everything from these regions, making them appear to be empty and preventing your facets from showing

See also the discussion here: [meta] Themes improperly check renderable arrays when determining visibility.


Drupal automatically create hardcoded links and do such links impact performance? I have a site which is being developed in Drupal. My developer was developing in the live site directly. No one knew of our existence, so we didn't bother.

I had to change developers midway through the project. When the new developer wanted to develop locally, he had a lot of issues: links not functioning etc. We have found around 25,000 instances of the original site URL.

So what he did was to find and replace all 25,000 URLs with the local site URL in the database itself. Now everything worked fine.

Once the site was perfect locally we moved to live site again by replacing all URLs back to the original URL.

When I checked with my original developer why he had hardcoded, he mentioned that as we wrote a lot of custom code, Drupal automatically created these links. Is this possible?

Will this affect performance or have any long term issues?

If by "a lot of custom code" he meant he created a custom module, then there is nothing that explains why the links were hard-coded. Keep in mind that Drupal has url() and l() to create URLs and links, which removes the need of using hard-coded links when they are links to the same Drupal site. For example, the following code (used by Drupal core) would work correctly even when the code would be moved from a site to another. As a matter of fact, it generates links that work for every site powered by Drupal.

  $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
  $count = count($actions_in_db);
  $orphans = implode(', ', $orphaned);
  watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);

To notice that, Drupal normally (as in the above case) generates links that are relative; that is why they work independently from the domain. l() works in many cases, even in the case Drupal is installed in a sub-directory of the server document directory, or when clean URLs are disabled. On my test site, the above code ($link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');) would create the following link.

Remove orphaned actions

If I disable the clean URLs, the same code would get me the following link.

Remove orphaned actions

The same code would produce the following links, when Drupal is not installed in a sub-directory.

Remove orphaned actions

Remove orphaned actions

The only case I can think where absolute URLs are necessary is when the URL is pointing externally to the Drupal site, for example to a sub-domain (to blog.example.com from exampl.com). That is the only absolute URL I have in my Drupal site, since I have added the link from admin/structure/menu/manage/menu-secondary-menu/add.

I could have used a custom module to add the link, and in that case I would have avoided to use an hard-coded link. For example, I could have used the following code.

global $base_url;
$blog_url = preg_replace('@(https?://)(.*)@', '$1blog.$2', $base_url);

In the case of my local test site, the above code would set $blog_url to 'http://blog.tero.local/dr71', while in the case of my Drupal site, it would set the same variable to 'http://blog.avpnet.org'.

A quicker method would be adding to the settings.php file a function that returns the link.

function _get_absolute_url($type) {
  global $base_url;

  switch ($type) {
    case 'blog':
    $url = preg_replace('@(https?://)(.*)@', '$1blog.$2', $base_url);
    break;
  }

  return $url;
}

In this case, for my test site I could use the following code, since I don't have a blog sub-domain.

function _get_absolute_url($type) {
  global $base_url;

  return $base_url;
}

In that way, I don't hard-code 100 links, but I use a single function that changes basing on the settings.php used from the site. In the case I need a link to the blog site, I would use code similar to the following one.

$blog_first  = _get_absolute_url('blog') . 'node/1';
$blog_second = _get_absolute_url('blog') . 'node/2';
$blog_third  = _get_absolute_url('blog') . 'node/3';

The code is assuming that, in the case of link to a Drupal site, that Drupal site is using clean URLs. If you administer that other site/sub-domain, it would not be difficult to change the code to get the correct URL.


Alternative to libraries_get_path() to get a JavaScript file path I was crafting the following code in order to alter the path to a JavaScript file.

function MY_MODULE_js_alter(&$javascript) {
      $sm_path = libraries_get_path('soundmanager2'). '/script/soundmanager2.js';
      $javascript['sites/all/libraries/soundmanager2/script/soundmanager2-nodebug-jsmin.js']['data'] = $sm_path;
      }

It works fine, but the only thing that bothers me is that libraries_get_path() is provided by the Libraries API module. Is there an internal Drupal 7 function to act the same way?

You can get the same data using drupal_get_library(), but it's not in a friendly format so you'll have to dig into the array yourself. For example, the following code will get the same path as your current code but in a much less less satisfying manner (in my opinion anyway):

$lib = drupal_get_library('soundmanager2', 'soundmanager2_debug');
$sm_path = array_shift(array_keys($lib['js']));

As I understand it this is actually the reason there's a need for the Libraries API to exist...so this sort of thing can be managed in a structured manner.


How to create views with date field of a content type? I am using D6.
I want to create a views with date field using in a content type such as "Photo Gallery".
What i have done are:-

In argument, select Content: Date (Date Appears in: Photo Gallery) then
select granularity as "year", sorted descending, check "Content:Date
save it.
I separately do for both month and day respectively.

What i am getting in URL are like photo-gallery/2010, photo-gallery/2010/2010-10, photo-gallery/2010/2010-10/2010-10/10 for year, month, day respectively.

But i don't want this.

I want Url like for year- photo-gallery/2010, for month- photo-gallery/2010/10 and for day-photo-gallery/2010/10/10
I am stuck here. So how can i do this?

You should be able to do something along these lines in a custom module if the out of the box Date and Views modules don't do it:

First off, create all your Views as Block Displays (eg, not Page Displays with a path defined by Views) with the various arguments in place.  For ease of discussion later on, let's say the View is called photo_gallery with displays of year, month and day.

Then, in your module, define the paths you want, eg:

function YOURMODULE_menu() {

  $items=array();

  $items['photo-gallery/%'] = array(
    'title' => 'Photos By Year',
    'page arguments' => array(1),
    'page callback' => 'YOURMODULE_photos_by_year',
    'access callback' => TRUE,
  );

  $items['photo-gallery/%/%'] = array(
    'title' => 'Photos By Year/Month',
    'page arguments' => array(1, 2),
    'page callback' => 'YOURMODULE_photos_by_year_month',
    'access callback' => TRUE,
  );

  $items['photo-gallery/%/%/%'] = array(
    'title' => 'Photos By Year/Month/Day',
    'page arguments' => array(1, 2, 3),
    'page callback' => 'YOURMODULE_photos_by_year_month_day',
    'access callback' => TRUE,
  );

  return $items;

}

And then for your callbacks, you embed the view you want using the argument styles it wants, which would probably be something like this:

function YOURMODULE_photos_by_year($year) {

  return views_embed_view('photo_gallery', 'year', $year); // eg 2014

}

function YOURMODULE_photos_by_year_month($year, $month) {

  return views_embed_view('photo_gallery', 'month', $year . '-' . $month); // eg 2014-01

}

function YOURMODULE_photos_by_year_month_day($year, $month, $day) {

  return views_embed_view('photo_gallery', 'day', $year . '-' . $month . '-' . $day); // eg 2014-01-04

}

Now the above is all pretty broad strokes typed in directly (typos may abound) and not actually tested (I don't really know the exact format of the dates your Views arguments should be in) but should get you on your way. Things to keep in mind are argument validation (eg photo-gallery/notayear/notamonth/notaday) and paging of results.


Drupal 7 Rule to save node based on fetched entity throwing EntityMalformedException if field empty So I have a rule that attempts to fetch a node using fetch entity by property, and re-save it with a new author if a user field value matches a node field value upon user login.

It works just fine unless it can't find a match, in which case I get the following error:

  EntityMalformedException: Missing bundle property on entity of type
  node. in entity_extract_ids()

I'm kind of surprised I get this error if the value doesn't exist, but now I need a workaround.

Is there some condition I can add here to prevent the error, or am I looking at removing the "fetch entity by property", and adding a db_query()?

Well I wound up writing code to fetch the entity:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_my_field', 'value', $some_value, '=')
  ->range(0, 1);
$result = $query->execute();

I then wound up using $result to update the target node's author:

if($result) {
  $eid=current($result['node']);
  $node = node_load($eid->nid);
  $node->uid = $account->uid;
  node_save($node);
}

I wonder if there's a method to query the database for a single entity? That would save the "hassle" of adding a range, then having to extract the desired value from the $result array.


Some MyISAM tables not converted to InnoDB during 6 to 7 upgrade When I upgraded from Drupal 6 to Drupal 7 using the upgrade script I was under the impression MyISAM tables would be converted to InnoDB. This doesn't seem to be the case. Tables like comment, node, and block and many others remain as MyISAM. Tables like cache and field_* are InnoDB.

As far as I can tell it's best practice to use InnoDB. My website is a blog and forum, so users are posting comments, creating nodes, and voting on content. The site serves up an average of 30k pageviews a day.

Assuming everything was InnoDB I configured MySQL with: innodb_log_file_size = 256M and innodb_buffer_pool_size = 11G.

I believe it makes sense to convert all my tables to InnoDB. I wanted to ask here to see if anyone ran into this issue (conversion not taking place) or if anyone knew why the tables weren't converted. And, if I do convert everything to InnoDB, is there anything I need to know?

It does make sense to convert all tables to InnoDB. The core 6 -> 7 update does not change the engine type; so the reason they weren't converted is that it was not programed to do so.

Use READ COMMITTED for MySQL transactions https://drupal.org/node/1650930#comment-8437127
Use 7.25 Core or higher https://drupal.org/node/937284

By doing both of these you will significantly reduce the number of deadlocks that occur on your database.

Using a non database cache backend like memcache is a good idea, as explained in this presentation: http://www.percona.com/resources/mysql-webinars/drupal-and-mysql-performance


Get content types field in another content type with the entity reference relationship I have two content types. Person and Projects. I use a entity reference for the persons name on the project node so people can select the person that is involved in the project. Now using that reference I also want to get another field from the persons content type, and display this. I can't figure out how to do this. I thought I could do it with a views. I created a view with a relationship and filter with NID but it just doesn't seem to work. Whats the simplest way (view or not) to do this?

With Entity Reference Autofill You can achieve something like you specified.

    The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


How to pass parameters by reference to a batch? I need to process a parameter in a batch function where the result will be kept after the function ends and it should be then passed in the finished function of the same batch.
Is there a way to pass the parameters by a reference, so that any changes to that parameter are saved?

Example:

$params = [$a, $b];
$finishedParams = [$a, $b];
$batch = ['title' => 'Sample processing batch',
          'operations' => ['someFunction', $params],
          'finished' => ['finishedFunction', $finishedParams]
         ];
...
public static function someFunction(&$a, $b){
    $a = 'somethingChanged';
}
public static function finishedFunction($success, $results, $operations){
   // Use $a variable when somethingChanged after the batch process.
}

Alfred is right. You can achieve that by using the $context parameter.

public static function someFunction($a, $b, &$context) {
  // Store data in $context['results'] entry.
  // my_var will keep that value.
  $context['results']['my_var'] = 20;
}


Customize autocomplete field to show children terms depending on another field I have a taxonomy with 2 levels

City1
-Park1
-Park2
-Park3
City2
-Park4
-Park5
-Park6

In my form, I created a field that links to this taxonomy with an autocomplete widget. I also have a second field where the user chooses the city.

I would like to dynamically change the autocomplete value depending on the selected city. Which means if the user selects City1, the autocomplete will only filter through the values under City1.

After checking the form I've found that the widget entity_autocomplete have an attribute #selection_handler. Will it be possible to change this handler and somehow send the value of the selected city?

I think there should be an easier approach. Creating a custom autocomplete field based on a textfield doesn't seem like a good solution since it will not have (or I will need to do it manually) all the error handling and entity links.

Any suggestions ?

You can drop using entity_autocomplete and instead it use custom autocomplete field. Here is an example of using, you can translate this page from Russian to your language. Also the example contains the attached source files.

https://niklan.net/blog/77

In the example you can see a controller what creates the list with values.
I suppose that you can pass a parameter to the controller (city_id) and SQL query will return set of resuts according the parameter.

You can add the parameter to the controller inside function buildForm() of your form. Also you can recreate the autocomplete element with new parameter after you selected a city from the list.


View not displaying correctly for all visitors I have created a simple view that displays upcoming events on a page.  Both the events and the pages are meant to be viewed by all site visitors.  The problem that I am having is that in order to see all the events, you need to be logged into the site.  I checked the nodes and permissions and don't see anything out of the ordinary.  The View is supposed to display 17 events, but for the anonymous user they are only getting 12 events.  Inside the view the access is Unrestricted.  I have tried re-entering the 5 events that are missing and they still do not show in the View.

I also have a calendar that displays the events.  Similar to the view, it is not displaying all events.  The ones that are missing from the View are also missing from the calendar.

Any suggestion on what is causing this and how to fix it?  Thank you.

I am using Drupal 6.2 and Views 6.x-2.16

Chris

Okay, this may or may not work...but...lately D7 has a similar issue.

If you select the view, and click the link "settings" under "Query Settings", you can make the view appear by selecting "Disable SQL Rewriting". There is a security risk, and this issue needs to be solved, ex-post-haste, but it works.

This has been an issue with every View I have seen of late, provided all your permissions are legit.


Automate views and xml sitemap I have a D6 site that uses both a geography taxonomy and a category taxonomy to organize 10s of thousands of nodes.  XML sitemap does a great job with automatically listing the individual taxonomy pages (all of geography A or all of category B) and the nodes themselves.  But I have views set up that show pages for "Category B in Geography A" such as http://example.com/myview/brooklyn/web_designers

I know that you can use xmlsitemap_custom to add these views results one at a time.  Is there any way to automate adding the entire cross section of the two taxonomies?  I want to add the view for every combination of the two taxonomies to the site map.

Drupal 6

Option 1:

Enable the 6.x-2.x XML sitemap custom sub-module.
Manually add the links to your views at admin/settings/xmlsitemap/custom

Option 2:

Enable the 6.x-2.x XML sitemap menu sub-module.
Create a new menu at admin/build/menu/add with the menu name xmlsitemap and title XML sitemap. Make sure that the 'Include this menu in the sitemap.' checkbox is selected.
Edit your view's page view, and add the view to the 'XML sitemap' menu under the 'Page settings'.

Drupal 7

Modules/XML Sitemap: Check "XML sitemap node" (Adds content links to the sitemap.)
Configuration/Search and Metadata/XML sitemap/Settings: Click on the "Content" tab. Go to your View created content, click on it.
In the XML sitemap tab, set Inclusion to Included. Save.
Back to Configuration/Search and Metadata/XML sitemap/ - click on Rebuild Links. You'll now have all of the Views created pages listed in sitemap.xml


Custom Block Form Not redirecting to New Page I have created a form to take a node ID and then you select either edit or delete and then I would like it to go to 'node/[nid]/edit' or 'node/[nid]/delete' depending on the selection of the radio button.
Here is my code:

function edit_node_block_info(){
    $blocks['edit_node'] = array(
        'info' => t('Custom Block to allow edit/delete/copy'),
        'status' => 1,
        'region' => 'Primary',
        'weight' => 0,
        'visibility' => BLOCK_VISIBILITY_LISTED,
    );

    return $blocks;
}
/*
 * Implements hook_block_view: sets how the block is displayed
 */
function edit_node_block_view($delta = ''){
    switch ($delta) {
        case 'edit_node' :
            $block['subject'] = t('Edit Nodes');
            $block['content'] = drupal_get_form('edit_node_form');
            break;
    }
    return $block;
}
/*
 * implements custom form/creating custom form for drupal_get_form named above.
 */

function edit_node_form($form, &$form_state) {
    $form['node-id'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter the Node ID'),
        '#max-length' => 8,
        '#required' => 1,
    );
    $form['edit-node'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array(t('edit'), t('delete')),
        '#required' => 1,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function edit_node_form_validate($form, &$form_state){
    $query = db_query('SELECT nid FROM {node}');
    foreach ($query as $result) {
        if (!($form_state['values']['node-id'] != $result)) {
            form_set_error('node-id', 'Node-id must match a current nid.');
        }
    }
}

function edit_node_submit($form, &$form_state){
    if (form_state['values']['edit-node'] == 'edit'){
        $form_state['redirect'] = 'node/' . (form_state['values']['node-id']) . '/edit';
    }
    if (form_state['values']['edit-node'] == 'delete'){
        $form_state['redirect'] = 'node/' . (form_state['values']['node-id']) . '/delete';
    }
}

In the $form array do I need some sort of redirect handler to make it work? Or a print_r or render?

I also tried $link = (form_state['values']['node-id']);

Looks like the issue I was having was twofold. First I need to add some settings:

$form['node-action'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array (
            edit => t('edit'),
            delete => t('delete'),
            add => t('add'),
            ),
        '#required' => 1,
    );

Then added:

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

And lastly my submit function:

function edit_node_submit($form, &$form_state){
    $node_id = $form_state['values']['node-id'];
    $node_action = ($form_state['values']['node-action']);
    $form_state['redirect'] = TRUE;
    if ($node_action == 'edit') {
        $form_state['redirect'] = ('node/' . $node_id . '/edit');
        }
    if ($node_action == 'delete'){
        $form_state['redirect'] = 'node/' . $node_id . '/delete';
    }
    if ($node_action == 'add'){
        $form_state['redirect'] = 'node/add/hospitalist-schedule';
    }
}

Everything is working for the most part.


How to schedule the execution of a Rules Action based on a webform submission date field? How do I schedule the execution of a Rules Action based on a webform submission date field?

I have installed Webform Rules so I am able to use the Rules Event Webform submitted  to trigger the execution of a Rules Action. In my case, I want to schedule the execution of the Rules Action based on the date input of a webform field.

I have no problem scheduling the execution using node:creation time, but I need to use the date the user inputs.

I have not found any data-selector that let's me do this.

Any hint's will be much appreciated.

EDIT: I have found a link on StackOverflow that seems related to what I want to achieve.

https://stackoverflow.com/questions/5192108/how-do-i-schedule-a-rule-using-fields

That would reduce my question to : how do I use the Entity has field on a webform in order to make the field available ?

I'm not really familiar with Rules but this might be a step in the right direction.

If node:created worked you could give http://drupal.org/project/webform_tokens a try, it should define tokens for your form components, however I'm not sure if the date will be in the correct format.

If it's not in the correct format you could alter it for the compontent in a presave hook.

function hook_webform_submission_presave($node, $submission) {
  // Use dpm() to find out how the date is formatted, and make it into a timestamp.
  $date = strtotime($submission->data['COMPONENT_ID']['value'][0]);
  $submision->data['COMPONENT_ID']['value'][0] = $date;
}

Now you have altered the data for the submisison, converting a date into a timestamp which should then be used through webform_tokens just like node:created.


Adding Node Reference to a Comment If I add a Node Reference field to a node content type (with Reference from URL as a widget,) this field appears in the rendered content and can be used to jump to the referenced node.

I am trying to get a similar result in the rendered comment of the same content type: If I add a Node Reference field with Reference to URL in the Comment Fields edit page of the content type, it doesn't show up in the rendered comment page.

Why do I want to do this? Because when one leaves a comment in the rendered content, a message is sent to the author of the post that a comment was posted. In the email, there is a link to see the comment. The link is of the form example.com/comment/000#comment-000 and that's not the original post with the comments below.

So I am trying to add a link to the comment page that would send the reader to the rendered node where the comment was originally posted.

Does this mean one cannot reference a node from the same node's comment page?

Or does it mean there is another way to accomplish this?

You could achieve this with Comment Notify module.
We use it on few sites and it works great out of the box.

From module page:

  Features

  Mail registered and anonymous users about comment follow-ups

  Allow users to unsubscribe from notifications on a specific post with
  a single click

  Allow registered users to preset their follow-up setting in their
  profile

  Users can choose to get notifications about all comments on a node or
  just replies to their comment
  Registered authors can get notifications about comments on their nodes
  Note: Since it only notifies you about published comments, this is not a solution to notify admins when they need to moderate comments on their site


Allow users to upload files and attach to specific nodes Here's what I'd like to do:

I have nodes A, B, C, and D

I want users to be able to upload files using a file field on node D, but then for those files to actually show on nodes A, B, or C, depending on what the user specifies during the upload process. So node D is just acting as an upload form of sorts -- it wouldn't show any of the uploaded files.

Is this possible to do with existing modules?

In a word, No.

At least not the way you are asking the question...

You need to be thinking about node types as well as just A, B, C & D.

I would look into the views module (tutorial here).

This would mean you could upload your files to nodes of a particular type, and then create several views that display different files uploaded based on your custom parameters.

It's a bit hard to be any more specific based on the broadness of your question.


How to add edit link within add to cart form in ubercart drupal 7? I need to add edit link within add to cart form in ubercart in Drupal 7.
I am using hook_form_uc_cart_view_form_alter() hook but not getting how to add edit link within this hook.

This is probably confusing due to UC's reliance on TAPIr to render the cart items. Anyway, you can modify data inside in the $form['items'] array to change the output of those elements. For example, if you wanted to add an edit link underneath the product description:

function MYMODULE_form_uc_cart_view_form_alter(&$form, &$form_state) {
  foreach($form['items'] as $key => $value) {
    //Check a TAPIr row for a product associated with an editable nid
    if(is_int($key) && isset($value['nid']['#value']) && isset($value['desc'])) {
      if(node_access('update', $value['#entity'], $user)) {
        $form['items'][$key]['desc']['#markup'] .= l('(EDIT)', 'node/'.$value['nid']['#value'].'/edit');
      }
    }
  }

There might be a cleaner way to do this, but I haven't thought about TAPIr in a while.


Creating first module, and How to alter text field on new content creation in Drupal 7? I am trying to set the text in a custom content field when saving a node. I think I need to create a module to do this. (I am new to module creation.)

I started with a blank directory called - let's say myModule. I placed myModule into path sites/all/modules.

I placed into the myModule directory two files that I understand to be required and gave them the following naming conventions which I also believe to be the standard:
myModule.module
myModule.info

myModule.info holds the following text:
name = Some Descriptive Name
description = does stuff.
package = relatedName
core = 7.x

Inside myModule.module I have tried various things that are to much to elaborate , but include these exact functions and parameters.

Attempt 1:

function myModule_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
    if ($node->type == 'theNameOfACustomContentTypeICreated'){
        foreach ($items as $delta => $item) {
          //I am ver unclear at this point, and this function does not seem to be called when creating new content.
        }
    }

Attempt 2:

myModule_nodeapi($node){
    //this function does not seem to be called when creating new content.
}

I am at a loss. Neither function is even getting called - nor working.

Edit, the issue is resolved. The correct start was hook_jba_node_presave($node) , but I had syntax errors.

A couple of pointers:

Use only lower case for module names.
$node is not available in hook_field_presave(). $entity should contain necessary info.
hook_nodeapi() is not available in Drupal 7.
It's possible you can make these alterations in your theme's template.php file as well.

You can use the devel module to help with debugging, e.g. dpm($entity, '$entity contains').

Also see Module developer's guide and Drupal 7 API reference for more info.


How to fetch a list of nodes by content type in a Rules Action set? I am trying to create a Rules Component that fetches a list of nodes based on their content type. But when I try creating it, I get a little stuck. Here's my process:

I create a rules component using "action component"
Then add an action to the component "fetch entity by property"
Select the entity type I would like to fetch "node"

I am then presented with the following:

In the value box I don't have node types nor a way to pass a text string that represents one, I have tried several ways by including introducing a text variable set to the entity type but if I try and use that as the value I get an error which says something about the variable being the wrong type.

Introduce a variable of type Text Token with the content type as the value.

Parameter: Type: Text token, Value: content_type

And then use this new variable as the value for comparison with the property.


How to define a new cache context for a node I am preprocessing a node with some data, i want to define a new cache context  based on this data.

function hook_preprocess_node(&$variables) {
    $variables['change'] = rand(0,5);
}

Once i have defined the new context i think i shuold be able to use it as follows.

function  hook_entity_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode) {
  if($entity->getType() == 'page'){
    $build['#cache']['contexts'][] = 'change';
  }
}

I can't seem to find out how to define a brand new cache context based on the data in my preprocess so that i can use it in hook_entity_build_defaults_alter();

You will need to define a cache context in yourmodule/src/Context. This will be a class implementing CacheContextInterface, as described in the docs here (see 'How to recognize, discover and create?).

If you search for implements CacheContextInterface in your code base you should be able to see some examples. The class will provide getContext() and getCacheableMetadata() methods.


Drupal : How to remove the  and  tag from content when using syntaxhighlighter Used Version 7.14

I am using syntaxhighlighter  for my website. But when I insert some code samples it always producing output with more <p> and <br> also content in single line as well .

I am done just copy paste the code from zend studio editor inside the syntaxhighlighter tag

I've searched over many forums and druapl site itself, but nothing works for me. Please advise me on this

See the picture below  for more

I can't answer this 100% but my first hunch was "hrm, filter ordering" and look, the project page draws your attention to:

  Very important!!!: ordered the input format filters as follow:

  HTML filter or Wysiwyg filter or whatever HTML filters you use. They must come before.
  Syntax highlighter. This come after any and all filters that can modify content input.
  Line break converter. This must be after, If you see <br/> at the end of every line in your output, then you know what's wrong.


Constraint handling for @DataType (Typed Data API) I am creating a new data type, 'duration'. The value will be a duration string that is used by a DateIntervale object.

The value is a string, but with a specified format. I'm assuming that due to it being a string, for my @DataType I should either extend StringData, or PrimitiveData. And I would like to add required validation to this data to ensure that the value contained is in the correct format.

I've been reading through documentation, and reverse engineering other @DataType objects, but I've not been able to find what I'm looking for. So what I want to specifically ask:

Should I extend StringData, or is it better to extend PrimitiveData?
How/where can I add a constraint onto this data. By this I mean, what method should I use to ensure that when someone calls setValue() using this data, the string can be validated using a regex to ensure it's the proper format.
If the value is not the proper format, how is this handled? Is there a way to call an error? Should I throw an Exception? Or should I set a default value instead of the value that was supposed to be submitted?
Am I looking at this the right way?

Thank you.

In abstract class PrimitiveBase that uses PrimitiveInterface... which StringData entends you can see the PrimitiveInterface use of PrimitiveInterface methods:

getValue(); , setValue($value);, getCastedValue();

so you can safely do ether however ... Personally as your data is realy a string  I would go with the extend StringData option

and call
parent functions like

 public function getValue() {
   return parent::getValue();
   or
   $this->parent->getValue();
 }

 public function setValue($value) {
    // CRAZY REGX HERE
   $new_value = $this->getREGXCRAXY($value);

   return $this->parent->setValue($new_value);
 }

 public function  getREGXCRAXY($value) {
    do the things.
  if value !== valid
 throw new \Exception('Invalid data dude must be in format xyz');
  return $new_formated_value;
 }

no i think it is proper to throw the exception because then the person can catch it in an event subscriber .. or learn the right way to set the data.


Which template or include file in Omega subtheme takes hook_form_alter()? I want to use hook_form_alter in my Omega subtheme. I'm trying to put the function in the correct place but I'm getting no results after clearing caches and refreshing.

Here's the code:

<?php function rescue_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
  dsm($form_id);        // HTML5 placeholder attribute
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
}

I don't know whether to include a closing ?> or not. I've tried it both ways. I've tried saving it as preprocess-page.inc and process-html.inc but neither has given any result. Help?

The preprocess.inc and process.inc files are an Alpha/Omega way of organizing template_preprocess and template_process functions.  Basically, if your template.php would have a mytheme_preprocess_node, you would put it in preprocess-node.inc and name the function mytheme_alpha_preprocess_node.  When you clear cache, and Drupal rebuilds the registry, the Alpha hooks will scan all of these files and wire everything up.

This doesn't mean that everything else that you put in template.php goes in these includes.  Your custom theme functions and alters should still stay in template.php.

This can help keep the size of template.php managable, but I always still end up with large files because typically needs lots of theme and alter functions for the projects I work on.


How to setup sitewide keyword search? I am nearly finished with my website on Drupal 8, and one last thing I have to do is optimize the search function. At this moment the search function only searches for node titles.

What I want to achieve is that the visitor can search by words and that the node will be shown as the search result. My website only has 7 seven pages at the moment, and will never grow beyond 10+ pages.

Example : I have a page about motorbikes( lets call the page motorbikes), in this page are some text blocks with motorbike brands like : yamaha and harley davidson and kawasaki. Now if the user is on the homepage and searches for kawasaki it should return the page motorbikes.

At this point the user would have to search for the page name, which in this case is motorbikes, to find the page.

So in short: I want to have a search function that searches the whole site for 1 or multiple words and then displays the page in which the words are found.

Can you guys help me on how to approach this problem, I don't need any code, just a little bit of guidance. Thanks in advance for any help !

You will need Search API and Search API Database for this - though I suggest setting up Apache Solr + Search API Solr instead of Search API Database.

Search API
Search API Database

and/or also:

Search API Solr

Search API provides a lot more flexibility in terms of the types of search you want to configure and setup. Some functionality within say, Solr, allows for defining synonyms and abbreviations, as well as open you up to having facet based searches.


How do I send a command after submitting a form? I need to do something when the user submits a form so that it sends a command to the server, :
 if($_GET["cmd"]=="save")

Got to do something with the thing above,
I thought of using:
Save

But if I do that it will not complete the form action so:
<form action="{{ pageName }}">

Will not be executed...
So how would I fix this problem?
thanks all :)

The Drupal way to do this is to use hook_form_alter() to add a submit hook, and then add your command in the submit hook.  Here's a simple example.
You'll need to add this code to a custom module.
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id') {
      $form['actions']['submit']['#submit'][] = 'MYMODULE_my_form_submit';
  }
}

function MYMODULE_my_form_submit(array &$form, FormStateInterface &$form_state) {
  // Insert command here.
}


Commerce Pricing Rules Not Applying During Checkout I have a pricing rule that's defined essentially along the lines of the one described here, and it appears correctly when I add items to the cart. But as soon as I progress to the check out the prices all revert to their base price not the discounted price.

With the Rules debugging enabled all the rules appear to fire, but the calculation doesn't appear to be saved correctly. Since there aren't a lot of hits in Google for this (or at least for the various search terms I can think of) I presume we're doing something odd that's causing trouble, but I've slowly removed every complexity I can so I'm as close to the user guide example as I can all without success.

The problem was the Rules 2.8 regression resolved by Commerce 1.11.


Display a particular field in a view by a comma separated values using custom code For a partular view  say "abc" I have created a view.

Now I want a particular field in that view as comma separated values.

How can I achieve this. Can I do this with custom coding only for that particular field.

I am learning drupal custom coding. so If this is possible through custom coding Please give me sample code.

Thanks in advance

You could create a template for the field you want to modify.

Click on link Advanced -> Themes -> Information, while editing the view, and select the right template and file name.
Then, in the template you can modify the output of the field.


getting key of submitted entity list field I'm having troubles with the following:
I created a form with entityforms and now i want to send a confirmation email with mimemail.
Getting that to work is no problem.

But i need to perform a small check with the php evaluation function of mimemail.

The form is for customers to place an order, but they have to specify 1 of 2 printing techniques available, 'fdm' or 'polyjet'. This is a 'list' field in the entityform with the two options.
And in the confirmation email i need to check what technique has been chosen so i can display some lines of text depending on the technique.

For my php evaluation i would like to get the key (machine readable name) of the submitted value.

So i can do something like this:

switch ($chosenkey){
    case "pol":
        echo "lines of text for polyjet";
        break;
    case "fdm":
        echo "lines of text for fdm";
        break;
    default:
        echo "error";
}

So basically i just need to know how i can create a variable ($chosenkey) that contains the submitted key of the chosen printing technique.

anyone any idea how i can accomplish this? I have googled around but can't find any relevant answer.

I'm not familiar with entityform so forgive me if none of this makes sense, but I imagine it works much like webform in that it sends the e-mail to the addresses you set up upon a successful form submit with no need for any custom code. So adding another validator or submit function to send the e-mail would result in two e-mails.

What you can do is use hook_mail_alter in a custom module and see what variables entityform passes to its drupal_mail call. With any luck, all the form values from $form_state will be included and you can do the check there and then change the $message['body'] array accordingly.

In the hook_mail_alter you can do a switch statement for the $message['key'] or $message['id'] to make sure you're not running your check for every mail your drupal site sends but only for the entityform in question.

I would also include a custom token of sorts in the template you, presumably, entered when settings up the entityform so you can easily change the e-mail body once you've run the check. I don't know if you could do it with Drupal's Token system, but even just entering 'my_module_custom_token' in the template and then using str_replace on 'my_module_custom_token' with the correct sentence in the mail_alter is better than nothing.

If none of this applies, then naturally disregard this answer entirely.


Disable or hide taxonomy term What is best module to hide or disable or un-publish some terms in taxonomy or vocabulary
like the way in the node tab of publishing in the back end

The taxonomy term status module is aimed at this use case.

There is an issue for that module regarding views exposed filters at https://www.drupal.org/node/1805882

Looking at that issue it is a little unclear the status of it. Some users say they have it working and others say they do not.
I would try adding your experiences to that issue and someone that has experience with that specific problem may be able to help you get it working.


How do I write a custom migrate destination plugin in for a node type? I've got a node type in Drupal 8 that uses field collections (from the module of the same name).  The Field Collections module doesn't yet have a working migration destination plugin, so what I'd like to do is use some kind of post-processing to (ugh) brute-force the field collection data into the nodes (note that I've tried the -dev version of Field Collection, and the destination plugin doesn't appear to be functional).  Note that my source is an SQL database and not a Drupal instance.

Here are the relevant files:

The migration definition file:

id: fm_quiz
label: FM Quiz
migration_group: quizzes
source:
  plugin: fm_quiz
  key: source
destination:
  plugin: fm_quiz
process:
  type:
    plugin: default_value
    default_value: quiz
  title: title
  uid:
    plugin: default_value
    default_value: 1
  sticky:
    plugin: default_value
    default_value: 0

The destination plugin:

<?php

/**
 * @file
 * Contains \Drupal\fm_quiz\Plugin\migrate\destination\FMQuiz.
 */

namespace Drupal\fm_quiz\Plugin\migrate\destination;

use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
use Drupal\migrate\Row;

/**
 * @MigrateDestination(
 *   id = "fm_quiz"
 * )
 */
class FMQuiz extends EntityContentBase {

  /**
     * {@inheritdoc}
     */
  public function import(Row $row, array $old_destination_id_values = array()) {
    $node = $this->getEntity($row, $old_destination_id_values);
    print_r($node);

    return [$node->id()];
  }

}

At the moment, Drupal doesn't seem to want to recognize that this migration exists as written.

If I change the destination to "entity:node", then it imports the nodes as expected.  If I change the destination in both files to "entity:node:fm_quiz", then Drupal says that "Migration fm_quiz did not meet the requirements" (and provides no other information).

Am I doing something wrong, or is what I'm trying to do just not possible right now?  Do I need to just make an end run around the migration system?

It's my understanding that your migration problem lies in the fact that you can't add a custom destination plugin for nodes. Your exact migration strategy is not entirely understood from your question, so I'm going to address only the part related to destination migration plugin, which might help you addressing the problem with adding custom logic to a migration process.

Destination plugins for entity migrations are indeed created by a deriver (see MigrateEntity::getDerivativeDefinitions()) and adding custom destination plugins is not as straightforward as creating, for example, a custom source plugin which extends an existing source plugin, because destination entity type is determined from the ID of destination plugin (entity:[name]).

You can still can create custom destination plugins for entity migrations in the following way:

Migration definition file:

id: fm_quiz
label: FM Quiz
migration_group: quizzes
source:
  plugin: fm_quiz
  key: source
destination:
  plugin: fm_quiz
process:
  type:
    plugin: default_value
    default_value: quiz
  title: title
  uid:
    plugin: default_value
    default_value: 1
  sticky:
    plugin: default_value
    default_value: 0

Custom migration destination plugin:

<?php

namespace Drupal\fm_quiz\Plugin\migrate\destination;

use Drupal\Core\Entity\Entity;
use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * @MigrateDestination(
 *   id = "fm_quiz"
 * )
 */
class FmQuizNodeDestination extends EntityContentBase {

  /** @var string $entityType */
  public static $entityType = 'node';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return parent::create($container, $configuration, 'entity:' . static::$entityType, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function import(Row $row, array $old_destination_id_values = array()) {
    // Add custom code here, if needed.
    return parent::import($row, $old_destination_id_values);
  }

}

Technically, it's the same class that entity:node destination plugin would use, but create() method of the custom class tricks parent class to use storage of node entity type.


How do I hide fields conditionally? i made my own module in my drupal 7 website to hide a boolean when its value is "0"
but something won't work

this is the code

   function MYTHEME_node_view($node, $view_mode, $langcode) {
if($node->content['field_members_only']['#items']['0']['value']=="0") {
                      hide($node->content['field_members_only']);
                    }
}

what's wrong?
i think the conditional part is wrong
if i save the statement without the IF part it's working perfectly

thanks

You need to set access to FALSE.

function MYTHEME_node_view($node, $view_mode, $langcode) {
  if(isset($node->content['field_members_only']) && count($node->content['field_members_only']) && $node->content['field_members_only']['#items']['0']['value']=="0") {
    $node->content['field_members_only']['#access'] = FALSE;
  }
}


media->save gives erros I am able to create a media object with the below code

 $static_media = Media::create([
'bundle' => 'document',
'uid' => $current_userid ,
'langcode' => "en",
'status' => 1,
 'name' => [
    'target_id' =>$title,

  ],
$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

but when I try to do $result=$static_media->save();  I get the error

Error: `Call to a member function isEmpty() on null in Drupal\media_entity_document\Plugin\MediaEntity\Type\Document->getField() (line 43 of profiles\lightning\modules\contrib\media_entity_document\src\Plugin\MediaEntity\Type\Document.php).

How can I debug this to find out what is missing?  I tried putting an echo at that point of the code in the plugin but cannot see anything .  What would you suggest to try to see what field it is looking for at that point?

Thank you .

instead of this part of the array

$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

i had to put the field name , not the file name.

'field_document' => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);