How do I specify an image reference in a Drupal 8 REST POST request body?

I tried again with just the image ID, and it worked perfectly. Thanks
  very much!

To elaborate...

After the image file has been created in Drupal, and you have the File ID you'll be ready to create/update Nodes. Instead of setting the src value on the image field you just need to set the target_id value.

Change this:

"field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],

To something like this:

"field_product_image": [{"target_id": 123}],

If you're using JavaScript this would typically be accomplished with 2 async calls. The first call would POST the binary file data to Drupal (or base 64 encoded string) to obtain the File ID, the second call (which takes places in the "success" callback of the first call) would then be used to create/update the node's image field with the new File ID.

The following d.o issue is an important one to follow and is very much related to the Question: https://www.drupal.org/node/1927648


How to customize Schema.org at node level?

As I understand your question, you would like to be able to override the Schema.org types per each node separately.

This is not possible at least out of the box. You would have to write custom code to display a tab on each node form, store it somewhere and then load it when the node is about to be viewed.

This is because content types are generally used for storing the content of the same kind. For example: an article, a blog post, a static page, a webform and so on. This means that all nodes of certain type will need the same Schema.org declarations, and that's why it was implemented this way.

You are probably storing different kinds of nodes using one "generic" content type. This is not the most common use case. Unless you have strong reasons for doing this, I suggest migrating the content to separate content types. It will benefit you in case you want to use other similar modules as well, such as Metatag.

Hope I managed to explain it.


I would suggest you to have a look at Chaos tools suite; the module brings an example for a modal form inside a modal window right with it (AJAX example).
It should be not to hard to integrate that, if you're already working on a custom module.

All I've said is valid for Drupal 6; I haven't looked into cTools in Drupal 7.


In mymodule.info file, add following line:

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

Then, in html.tpl.php be sure to print scripts and styles, like that:

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

Failing to output these will break many modules, and make Drupal Core to fallback to non-javascript behavior, and you don't want this to happen.


How do I create a text field in registration that only shows up if a checkbox is checked?

Conditional Fields seems to be what you are looking for.

  Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

Especially their example use case seems to match exactly your checkbox - text field need:

  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
  You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

Emphasis mine.


You need to set a checkbox "Expose this sort to visitors, to allow them to change it" in the "Configure sort criterion" window


Merging output of Print.module's printpdf with existing PDFs

I hacked print_pdf.pages.inc to merge PDFs after creation based on the existence of a filefield:

Starting at line 209, in function _print_pdf_dompdf();

    $node = $print['node'];
    if ($node->field_pdf[0]) {
        $meas_pdf = $dompdf->output();
        file_put_contents($base_path . 'sites/default/files/pdf_temp.pdf', $meas_pdf);
        include $base_path . 'sites/all/libraries/PDFMerger/PDFMerger.php';
        $newpdf = new PDFMerger;
        $newpdf->addPDF($base_path . 'sites/default/files/pdf_temp.pdf', 'all');
        foreach ($node->field_pdf as $attach) {
        $newpdf->addPDF($base_path . $attach['filepath'], 'all');
        }
        $newpdf->merge('download', 'measurements.pdf');
    }
    else {$dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2))); }
}

It'd be great to write a module that undefines Print.module's private _print_pdf_dompdf(); function and replaces it with my own (so I'm not hacking a contrib module); any idea how I'd go about that?


List of referenced entities appended to a node

Create a new view showing tasks nodes. In your view use these settings.

Add a relationship "Entity Reference: Referencing entity".
Add a contextual filter of "Content:nid" with the relationship you previously created as the selected option on the relationship select box. Also provide the default value from "Content ID from URL".

Create another contextual filter with "Content: References".
Choose what fields to show as you normally do in a view.

I think this should do the trick.


Custom #ajax "Add another" button only adds 1

You made a common mistake. In Form API, ['#ajax']['callback'] has only 2 purposes:

Make one-time changes to form, that are not meant to persist form reload, submit or second Ajax request. Good example is adding some classes to freshly modified element.
Return proper part of the form.

To have persistent changes, you need to keep the number of elements you want somewhere, for example in $form_state, and add them in form builder function, buildForm in your case.

My approach would be to check $form_state['triggering_element'] to see if it was your Ajax button to invoke form building, and if so, increase counter. Then simply for($i = 0; $i < $element_counter; ++$i) to add required number of elements.


Can't add assets to my Bootstrap sub-theme

I see that you don't include global-scripts in .info.yml file. You should have something like this at the beginning of your .info.yml file:

global-styling:
  css:
   theme:
    css/style.css: {}

global-scripts:
  js:
   js/URI.min.js: {}
    js/jquery.waypoints.min.js: {}
     js/global.js: {}

If this doesn't work, I would highly recommend you to get a fresh copy of SASS directory of starterkits(it is in themes/contrib/starterkits/sass) then check out all the THEMENAME and replace it with your custom theme name. Kind regards


If you look at the function _user_email_notify(), it checks the variable 'user_mail_' . $op . '_notify' if it should send an email or not. Assuming that you have disabled email confirmation (otherwise, disabling mail notifications would be weird ;)), the $op is 'register_no_approval_required'. So the full variable name is 'user_mail_register_no_approval_required_notify'.

There doesn't seem to be a User Interface for that variable. However, you can set it in your settings.php, adding the following line at the end of settings.php (probably inside sites/default).

$conf['user_mail_register_no_approval_required_notify'] = FALSE;

You can do the same for other mail notifications too; the other possible $op values are listed on the linked page.


How do I add reCaptcha to a custom form?

I added the following form item to my form.

$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);

It's pretty simple but it may trip some others up so hopefully this post saves someone time.

If you want to use some other captcha method you have installed on your site you can easily replace #captcha_type by going to /admin/config/people/captcha and using a tool like Firebug (or just view the page source and do some hunting) to view the options for the "Default challenge type" field on the captcha admin settings page. The values of each option is a valid option for the #captcha_type.


Webform Validation's numeric validator relies on PHP's is_numeric. Thus, any numeric expression (e.g. 1.5) is going to be validated there. In order to validate integers only, you'll need to use Regex validation where only integers character can be valid (e.g. "^([0-9]+)$").


generate or extract a automatic thumbnail for a video file using Video module in drupal 7

Are there any messages in your Drupal error log related to video transcoding? Also, try to update to the latest version of the Video module.


Commerce 2.x attribute translations cause product duplicates in views

I found a way to solve this. You must:

1) ensure you have a variations delta filter set.

2) add the field variations and ensure that the Display all values in the same row is NOT CHECKED under Multiple Field Settings. you can then hide this field if you do not want to display the output.

3) in the view display's Query settings tick the check box Distinct.

This configuration will remove product duplicates when the Product Variation relationship is used. This is the resulting query, i am not sure how efficient this configuration is but at least it works.

SELECT DISTINCT commerce_product__variations.delta AS commerce_product__variations_delta, commerce_product__variations.langcode AS commerce_product__variations_langcode, commerce_product__variations.bundle AS commerce_product__variations_bundle, commerce_product__variations.variations_target_id AS commerce_product__variations_variations_target_id, commerce_product_field_data.product_id AS product_id, commerce_product_variation_field_data_commerce_product__variations.variation_id AS commerce_product_variation_field_data_commerce_product__vari
FROM
{commerce_product_field_data} commerce_product_field_data
LEFT JOIN {commerce_product__variations} commerce_product__variations ON commerce_product_field_data.product_id = commerce_product__variations.entity_id AND (commerce_product__variations.deleted = '0' AND commerce_product__variations.langcode = commerce_product_field_data.langcode)
LEFT JOIN {commerce_product_variation_field_data} commerce_product_variation_field_data_commerce_product__variations ON commerce_product__variations.variations_target_id = commerce_product_variation_field_data_commerce_product__variations.variation_id
WHERE commerce_product__variations.delta = '0'


Different Field information can be displayed in Views by using the Rewrite results and Replacement patterns options in the Field configuration.

Different Field data is usually available as tokens (replacement patterns) that can be used to construct a different output than those available under the Formatter option.

Here's an example for displaying the image Alt text instead of the actual image:

It works similarly for the Video field, and many others too.


Trouble incorporating "Related Articles" block into panel

The problem is that, your view accepts a Term ID which it uses to get other nodes tagged with the same term. But when you are placing the views block (accepting TID asparameter) in Panels, how are you passing the context to it?

This is probably why your dev went in for the code based approach. I think you can create a custom PHP panels content, grab the node from the present path, then grab the tid from term reference field, and the pass in the tid as context while calling the view through views_embed_view() function.

If you want you can paste the code your dev used and I can help you how you can re use the code in panels to get the same result.

Code Should be something like this:

$node = menu_get_object();
if (is_object($node)) {
  $tid = $node->field_yourfieldname['und'][0]['value'];
  $output = views_embed_view('your view name', 'display name', $tid);
}
echo $output;

Put the above code in the panel, using a custom content with PHP.


adding all children node flag count to sort parent

Is it possible to have a hidden field on parent node value for which updates as per the flag counter on referenced node changes.In that case it will be easier to build custom query or even if you use views you can sort by the hidden field  value.

Updated:

  Child node 1 has a node reference to Parent Node.
  Keep flag count as hidden field on parent content type
  The time flag is updated on Child node, you can grab all parent nodes on the updated child node.
  Change the hidden field value on parent node from hidden field value to +1.

Code that can be used to update parent node field
 - you will have all parent node id in child node object, grab the ids.
 - Use the following code to update the parent fields.

  $node = node_load($nid);
  $node->field_flag_count['und'][0]['value'] += 1;
  field_attach_presave('node', $node);
  field_attach_update('node', $node);

  This will save lot more node save processing and unnecessary node
  revisions

SO this way the total flag count will all be present on parent node and sorting will be lot more easier that way!.


Is there a module that provides perpetual results on scroll?

Found it. There are two (quotes included are from their project pages):

Views Infinite Scroll (Requires Views 3):

  ... provides pluggable pagers that enables Views infinite scrolling (autopaging, depaging, endless pages ... you name it) by using jquery.autopager plugin. Using this module with views page display will load another page whenever the user reaches bottom of the page.

Views Infinite Pager:

  ... implements "infinite pager" (earlier called "sliding pager") functionality for Views. Infinite pagers open the next page via Ajax below the current page, each sub-page expanding the page vertically downwards. For a well-known infinite pager example, visit a stream on Twitter.com.


If you're trying to get the view mode of a node you probably want to use a different hook.

function classier_preprocess_node(&$vars) {
    $view_mode = $vars['view_mode'];
}

Should do the trick.


Drupal: User personalization of Taxonomy terms

This sounds like a rather tricky to do.

i18n_taxonomy.module needs to do a lot of hacking and overriding of the taxonomy.module behaviors to always display translated terms. I don't think something like this already exists as a ready to use module.

One option might be to do this using fake translations and building a custom UI which would allow users to create a new personal language and "translate" the terms. However, it won't be able to deal with the merging part. It's also rather hackish...

Another option might be to ditch taxonomy.module completely using either a simple list field (which supports using a callback function for the possible values, but only through the API, see list_field_info()) and then build a UI which allows users to override the default values (and store them somewhere) or maybe even provide custom field widgets and formatters. Depending on your exact requirements, it might be easier to re-implement the features from taxonomy.module you need rather than trying to bend it to your will.


Problems creating Drupal Commerce Product Display, list of available products not populating

This is a bug in Drupal Commerce 1.13. I'll be patching it today:

https://www.drupal.org/node/2697017


Found the readme file online which describes the steps to add theme selection per group.

It can be found @ here.

It uses fields to make the selection as I suspected but the initial configuration is done via a different user interface.

Thanks for your input Steven.


I think I got the answer.. just check for the snapshot. It seems you were using the wrong value of token in menu path. Use user/[user:uid]/edit instead.


View of nodes where content type = Event.

Add a relationship to nodes referenced via the Shops field.

Add a field for Location using the Shops relationship.


What you are calling "URL aliases" are referred to by Drupal 8 as "path aliases."

The path.alias_manager service (\Drupal\Core\Path\AliasManager) allows to lookup path aliases.

$aliasManager = \Drupal::service('path.alias_manager');
// The second argument to getAliasByPath is a language code such as "en" or LanguageInterface::DEFAULT_LANGUAGE.
$alias = $aliasManager->getAliasByPath('/taxonomy/term/' . $term_id);

But what use is a path alias? The end result is probably to put it into a link render element. \Drupal\Core\Url::fromRoute should also be a valid option as that will translate into any path alias anyway. It is not exactly clear from the API documentation that it does this, but it does.

$link = [
  '#type' => 'link',
  '#title' => 'Taxonomy term ' . $term_id,
  // Passing in 'language' key as the third option is preferable here so that a language-dependent alias can be found.
  '#url' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term_id])
];


Solved. I did this: enabled AdvAgg Modifier, Advanced CSS/JS Aggregation. Then I visited settings page

/admin/config/development/performance/advagg/mod

where I checked options:

Enable preprocess on all JS,
Move all inline scripts to the bottom    of the execution order,
Move all browser conditional JavaScript to    the bottom of the    group,
Move JS to the footer - All.

And now i have all JS in the bottom (as google recommends), without need to chane html.tpl.php


sites/drupal folder not pushed to git repository

I would add a README file under sites/default/files
then force the file to be added to the repository by executing git add -f sites/default/files/README and push your files.

The -f flag will allow the file to be added by overriding your .gitignore file.
The next time you clone the repository on a new location the folder sites/default and sites/default/files will be created by git.

When downloading Drupal the sites/default folder contains a file called default.settings.php. And one solution here would have been to add that file. But since your .gitignore excludes sites/*/settings.php default.settings.php file wont be added and Git will not add empty folders to the repository.


Taxonomy Manager makes that pretty easy:

  This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

Or you could do it manually:

foreach (taxonomy_vocabulary_load_multiple(FALSE) as $vocab) {
  taxonomy_vocabulary_delete($vocab->vid);
}

If you have a lot of vocabs/terms it would be better to split that up into a batch job to avoid out of memory errors.


First go to /admin/structure/types and edit your content type.
Click on the "Comment Fields" tab at the top of the page and then edit the comment field.
Here you can choose the text format that your comment field will use.

Now go to /admin/config/content/wysiwyg and choose the text editing you want to use for your text format. You can also edit any configuration setting your editor of choice here.


Maximum on date field and Views aggregation issue

First of all, select "None" for "Thousands marker" to have a properly formatted timestamp value;
In the "REWRITE RESULTS" section you can override the output of the field.
Given I have the aggregated field "created" overriding the field would look as following:

{{ created |timestamp_format('Y-m-d') }}


Why doesn't hook_preprocess_block() alter the block content?

There were two issues, in my case.  For one thing, I was using the wrong key.  I needed to use...

$variables['content']['body'][0]['#text']

...instead of...

$variables['elements']['content']['body'][0]['#text']

The other issue was that I had nothing saved in the body field, and in some cases setting a value for the body field in hook_preprocess_block() has no effect on output unless there is a value saved in the body field.  You must at least save some garbage characters to the field or else setting a value in hook_preprocess_block() will have no effect on the output.


How do I add the JavaScript src file inside a block?

You should add javascript as a library, then attach it to your block in the build array or a preprocess function like this:

$block['#attached']['library'][] = 'mymodule/mymodule.search_filters';
$block['#attached']['drupalSettings']['mymodule'] = [
  'cats' => 'tabby',
  'dogs' => 'dalmation',
];


Where does the profile name on the Status Report come from?

When the status report is rendered, profile info is retrieved from drupal_get_profile() (by referencing the install_profile var) as well as system_get_info() to retrieve all the metadata properties (by referencing the system data table)


Views caching not working for Taxonomy listing pages

Have you tried doing a print_r(), dpm(), etc. on the cache_get() and cache_set() functions to see what's going on? The output of this tends to be somewhat verbose, so I generally like to do an error_log(), then go to the PHP error log and see all the calls to cache_get and cache_set to see if I detect a pattern. This would give you a concrete idea of what and what is not getting cached.


There are also other solutions to your problem.

Field Collection

You can use field collection and field collection views modules to store and organize contents. Using this approach the Issue and Magazine are going to be Field Collection type, Issue is a field of Article and Magazine is a field of Issue. I have experience of implementing such structure. In my case the requirement was a Library that should contain books (with Title, Publisher and ... fields), Every book contains multiple volumes (Number of pages, translator, ... ) and each volume also contains unlimited number of some other items (like the scan of some pages that are not the same among the books).

I implemented this using Field Collection approach and it is very nice. You can easily create a link to edit every individual items of every field collection and you can also filter by items of field collection. I posted an answer to Group items in Views by value in Field Collection which shows how to work with Field Collection Views

Entity View Attachment

Also known as EVA module.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

You can use EVA to display only fields values for a particular piece of content, giving incredible control over the display and formatting flexibility of the fields. For example you may desire to have two fields concatenated in some special way. You can add your fields to your EVA display, set the contextual filter to NID, add a Global: Text Field, and using tokens format your fields with HTML. Don’t forget to exclude your fields from display if you are going to use them together in a Global: Text Field. Example: You may have a city, state, and zip fields. You can combine them in a Global: Text Field in Views to display as “City, State ZIP”. When you manage the display for your content type add the EVA just created to the display and whenever a node the type is displayed it will pass its nid to the EVA and the EVA will return the fields you select, formatted as you desire. (source : EVA and Entity Reference Use Case How-to)

This module is perfect, It attaches a View as a field to nodes of a content type. I used this module to create an Album. The album contains singer (with some information about each one) and songs that contains a File, Title, Rate and ... . So I created a View of type EVA and I attached it to a node. So on the node page of every Singer, I displayed this View which gets it's appropriate information from the node. The Views with Entity Reference is a perfect tutorial of how to use this module.

Taxonomy Terms V.S Entity Reference

I recommend you to read Entity reference vs. taxonomy and Are there any benefits/caveats with using Entity Reference over Term Reference? , As it says Taxonomies are best used when organizing similar items in a hierarchical fashion. Like tags.

Taxonomy allows you to use free tagging (it can be disabled using Content Taxonomy module), which enables the creation of new tags on-the-fly. It is very easy to modify the skeleton of contents. Using this approach, regular or at least some authenticated users (who have no knowledge of programming) can change this skeleton. Hierarchical Select module is perfect example of such approach.

Even though Taxonomy is easy to use but I myself prefer Entity Reference, it opens up lot's of possibilities and scalability and allows of creation very complex structures. The concept of entity in this context is not limited to content. It can be comments, users, taxonomies and ... . It is much more scalable so you will not be worry about the customizing content types, or modifying it in the future (as it was pointed out in Entity reference vs. taxonomy). I believe the Entity approach is more powerful than Taxonomy.

There are also some other combinations of these approaches which it is unnecessary to mention them.

Anyway I recommend you fully understand Entity approach and it's related modules. If you use it in multiple projects, despite of it's complexity it will be very easy to you to use it. Not only in the yours current requirement but also in the future it is going to be a Very Reliable Tool for you.


I'm not sure why you would want to automatically load a modal when the page is loaded, IMO that's a bad user experience. But if you must, you can use a bit of jQuery in the theme to make it happen. Maybe something like the following:

  /**
   * Open Modal window on page load.
   */
   Drupal.behaviors.openModalOnPageLoad = {
    attach: function(context, settings) {
      // Just create some kind of ID or class for the modal link, add whatever extra
      // classes you need to be more specific if necessary.
      $(".page-node-number #myModalLink").click();
    }
  };


How to test Mollom - want to test mollom_form_moderation?

You need to enable testing mode and configure the form protected by Mollom to Retain spam posts manual moderation, e.g. in the below screenshot you see I had it wrong.

Then submit the form with "spam" in the main field and it will call your moderation function.


Cannot add new release for new contrib project

It happens because on Media Entity Remote Image (the project you linked):

You aren't the project owner

The project owner didn't give you the permission to administer releases

As you see in the second screenshot, the checkbox for the Administer releases for the mrweiner account isn't selected.

If it were, you would see an Add new release link right after the Downlaods table, which is empty, for the given project.

If you want to be able to create new releases, you need to get the permission to administer releases too. Otherwise, the project owner needs to create the new release.

[Disclaimer: On Drupal.org I have more permissions than a normal user; that is why I see what project owners would see for their own projects.]


For Drupal 8 most intern values like the revision flag (newRevision) is protected, which means that you aren't allowed to set them directly. There is a good reason for this, as Drupal wants to do stuff in some cases when these values are set.

Instead you need to use the ::setNewRevision method on the entity. This will throw an exception if the entity doesn't support revisions. So if you don't know what entities you are dealing with, you could do something like this.

function save_new_revisions(EntityInterface $entities) {
  foreach ($entities as $entity) {
    if ($entity->getEntityType()->isRevisionable()) {
      $entity->setNewRevision();
    }
    $entity->save();
  }
}


Authorize.net Getting error "A valid amount is required."

I got the solution of this issue.

When we were working in local we have removed orders from CMS before moving database to Dev site. But because of dependency some orders were not removed completely. When Authorize.net finds such orders it has treating them as pending order and was adding payment in new order as Unknown payment method.

Some how this was adding extra amounts to final payment of new orders and was creating negative amount.

To resolve this I have deleted all my dummy orders from CMS and also from Table "commerce_payment_transaction".

This has resolved my issue.
One of the Drupal's Stackexchange answer helped me to resolve this issue, Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111"


Views_view_result and Devel possible incompatibility

The short answer: Devel is not incompatible with Views.

The longer answer:

The difference between views_embed_view and views_get_view_result is essentially that views_embed_view renders the view while views_get_view_result only executes it. The code for the two processes are almost identical, but the difference is that views_embed_view does more as part of the render process. You can see the details in view::render.

The gist of it is that when embedding the view, you get views to do a lot more things, like initializing the theme, invoking more hooks.

Best guess for where your problem lies would be some other module integrating with views and/or devel or some other details you haven't written in your question.

The devel query log works by using the core database log, starting it with hook_boot and getting the info with a shutdown function. There are some scenarios where devel will be silent, fx when doing redirects. There is a good chance, that the issue is related to how devel figures out when to be silent or not. It's near impossible to figure out the exact cause without being able to debug your exact site and configuration as any module / configuration can be the cause to what you are seeing. If you want to investigate you should look into

devel_silent()
devel_shutdown()
devel_shutdown_real()


How do I get an argument of a path with Rules URL Argument?

To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

For an example of a rule (in Rules export format) that uses this module, refer to (Step 4 of) my answer to "How to limit access of a view about Group Memberships to the Group's administrator?".

The above explains How to get AN argument (as in the question title) using this module. However, to my knowledge this module cannot be used to set the ARGUMENT value to "the first Argument" (as in your comment below this answer).


How to add properties to ConfigurableLanguage config entity?

Even if it might be late for the OP, here is the way to achieve this.

As language is stored as ConfigEntity, you can use ThirdPartySettingInterface.

Here is an example entity types are not correctly define in the link. which I based my own implementation on.

Steps to follow to achieve adding properties on language entity are a set of pretty common drupal development actions :

// Step 1 : Altering the configuration form ( language_admin_edit_form ) in this case.

/**
 * Implements hook_form_FORM_ID_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function {our_module_name}_form_language_admin_edit_form_alter(
    &$form,
    \Drupal\Core\Form\FormStateInterface $form_state,
    $form_id) {

  //Step 2. We can retrieve the ConfigEntity the form is working on

  /** @var {\Drupal\language\Entity\ConfigurableLanguage} $language */
  $language = $form_state->getFormObject()->getEntity();

  //Step 3. Add our custom property(ies)
  $form['{name_of_our_property_1}'] = array(
    '#type' => 'checkbox',
    '#title' => t('Our custom property 1'),

    //Ok this is already a step ahead but, for the default_value
    //we can get the stored value in thirdPartySetting property of the ConfigEntity
    '#default_value' => $language->getThirdPartySetting('{our_module_name}', '{name_of_our_property_1}'),
  );

  //Step 4. We will need to hook before the entity is saved as config,
  //in order to retrieve the property values on form,
  //and adding thoses in the ConfigEntity thirdPartySetting property.
  $form['#entity_builders'][] = '{our_module_language_entity_builder_function_name}';
}

This will add form input with previously saved values on thirdPartySetting and add our custom entity builder. So lets define our custom entity builder :

/**
 * Our custom entity builder
 * @param $entity_type
 * @param \Drupal\language\Entity\ConfigurableLanguage $language
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function {our_module_language_entity_builder_function_name}(
    $entity_type,
    \Drupal\language\Entity\ConfigurableLanguage $language,
    &$form,
    \Drupal\Core\Form\FormStateInterface $form_state){

    //If our property can be found from form_state values
    if ($form_state->getValue('{name_of_our_property_1}')) {
        //We can update the linked property on thirdPartySetting
        $language->setThirdPartySetting(
            '{our_module_name}',
            '{name_of_our_property_1}',
            $form_state->getValue('{name_of_our_property_1}')
        );
    }else{
        //User surely wanted to remove the previous value,
        //so remove it from thirdPartySetting property too
        $language->unsetThirdPartySetting('{our_module_name}', '{name_of_our_property_1}');
    }
}

Ok, now the edit form shows our property, our custom entity builder save it.
Last step ahead, using our custom value somewhere else of the language edit form.

//So we have a language, it doesn't matter how you get it.
//Here is from the currentLanguage property

/** @var {\Drupal\Core\Language\LanguageInterface} $language */
$language = \Drupal::languageManager()->getCurrentLanguage();

//The language itself doesn't own the thirdPartySetting,
//So we need to use its matching ConfigEntity

//Getting the ConfigurableLanguageManager
/** {\Drupal\language\ConfigurableLanguageManager} $configManager */
$configManager = \Drupal::entityTypeManager()->getStorage('configurable_language');

//now load the matching ConfigEntity of Language
/** @var ConfigurableLanguage $config */
$languageConfigEntity= $configManager->load($language->getId());

//Do what you want of your property
$ourPropertyValue = $languageConfigEntity->getThirdPartySetting('{our_module_name}', '{name_of_our_property_1}');

//Alternatively we could get an array of all our module thirdPartySetting properties
$allOurProps = $languageConfigEntity->getThirdPartySettings('{our_module_name}');

//And it's done.


Use user/register instead of default login page for anonymous users

Solved it. In case someone looks for something similar, to the rule above I added another condition:

NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user


Caching issue with class extension of RulesDataUI

I think you need to add your rules.inc file to the info files[] array to ensure that the file is included while rebuilding the UI.

See more related: https://www.drupal.org/node/1275958 & https://www.drupal.org/node/1276606


Loop through child elements in Twig like Element::children()

{% for key, child in element if key|first != '#' %}
  <div>{{ child }}</div>
{% endfor %}


How may I schedule when comments can be Opened and Closed?

That should be as simple as:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (/* Your logic to determine that comments are closed here */) {
    $node->content['comments']['#access'] = FALSE;
  }
}

(it'll probably need to be tweaked for your exact requirements, have a look at what else lives in $node->content['comments'] if you want to hide the form/existing comments separately).


Twig field collection theme get field id

You can get The field collection item ID in field-collection-item.html.twig

{{ item['#field_collection_item'].id() }}

or you can get it from field-collection-item--field-name.html.twig, or other field template of field collection item.

{{ element['#items'].getEntity().id() }}

You can find these functions under Available Methods Tab when you printing out variables from twig template. You can use public methods.


How to programmatically create entity with certain language applied to fields?

I have found a solution.
As I have mentioned this was during the profile installation process and it is related to How to get correct language code during installation?

The solution was to make sure the installed language exists before the modules are being installed and set it as default. Normally, translation are the last installation task. So I have copied the following code from install_download_additional_translations_operations() into a task in my profile that runs before modules are installed.

if ($langcode != 'en') {
    \Drupal::service('module_installer')->install(['language']);
    if (!($language = entity_load('configurable_language', $langcode))) {
      // Create the language if not already shipped with a profile.
      $language = ConfigurableLanguage::createFromLangcode($langcode);
    }
    $language->save();

    \Drupal::service('language.default')->set($language);
  }

I have also removed the $langcode from my code since translations were now working as expected.


How can I allow a person to create multiple orders at once, for both themselves and others?

Honestly, this sounds like a place where your best option will be custom code. The only thing I could see you doing without custom code is creating two variants for your event registration products, one that is free as a "reservation" and one that is the full price as an actual registration. This means the line items would be present on the order until the customer completes checkout, at which point you could process the order to split it up and then send out e-mail notifications as needed. To capture the e-mail address information, I'd add a field to your line item type to collect it as part of the Add to Cart form, allowing you to loop over the line items later and create user accounts / generate e-mails on a line-by-line basis. The main challenge there will be grouping multiple "reservations" into a single order via a simple rules loop... at the end of the day, this really smells like an ideal use case for custom code.


This is an existing Drush feature request.  See http://drupal.org/node/1848766 and http://drupal.org/node/1335626.

You could also make a bash alias (one per Drupal site) that set the appropriate environment variables, and then called Drush.


Can't change quantity of line item with rules

I played around with the rules actions and got it to work with these settings & the function I created to manually update the table:

    { "rules_1_gift_card_per_cart" : {
    "LABEL" : "1 Gift Card per cart",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [
      "rules",
      "rules_conditional",
      "commerce_giftcards",
      "commerce_cart",
      "commerce_rules_extra",
      "entity"
    ],
    "ON" : [
      "commerce_cart_product_add",
      "line_item_quantity_changed",
      "commerce_line_item_update"
    ],
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "gift_certificate" } },
      { "AND" : [] },
      { "data_is" : {
          "data" : [ "commerce-line-item:quantity" ],
          "op" : "\u003E",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : {
                "data" : [ "commerce-line-item:quantity" ],
                "op" : "\u003E",
                "value" : "1"
              }
            },
            "DO" : [
              { "data_set" : { "data" : [ "commerce-line-item:quantity" ], "value" : "1" } },
              { "drupal_message" : {
                  "message" : "Only one gift card per order.",
                  "type" : "warning",
                  "repeat" : 0
                }
              },
              { "commerce_giftcards_action_change_qty_one" : {
                  "order" : [ "commerce-line-item:order" ],
                  "line_item" : [ "commerce-line-item" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Change node configuration dashboard UI settings

You can't do this in the UI, you need code.

You could attach some JS to open it, but it's much easier to create a module with a form_alter and then you can make the element expanded by default.

https://api.drupal.org/api/drupal/core%21modules%21path%21path.module/function/path_form_node_form_alter/8.2.x defines the element, you can see that it defaults to open when there is an alias already.


pathauto_clean_string and accents from a bootstrap PHP file

After having a look at the code from the pathauto_cleanstring function, I would suggest testing the following:

Checking the value of pathauto_transliterate prior to calling the pathauto_cleanstring function

variable_get('pathauto_transliterate', FALSE)
If that value is FALSE, you probably found the reason. Try setting that variable to TRUE to force use of transliteration inside the pathauto_cleanstring function. N.B.: You only need to set this value once.

variable_set('pathauto_transliterate', TRUE), or
drush vset pathauto_transliterate TRUE
Try your code again. Fingers crossed!

I suspect that your code never actually uses the transliterate function, but that is something that you can check by dumping the 'pathauto_transliterate' variable in the various scenarios where your code is executed (in-module, custom script, etc.)


You can use a custom sort in your module like

/**
* Implementation of hook_views_query_alter().
 */
function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'your_machine_name_view') {
        $query->add_orderby('node', 'created', 'DESC');
    }
  }
}


How to keep class object during form process

No, if this is a value object then a service not the answer.

I would recommend you look at entities. Drupal will do a ton of work for you if you use (content) entities for your value objects.

See https://www.drupal.org/node/2192175 for example for documentation, also check out the entity module for additional functionality that is not yet in Drupal core.

With content entities, there is a standard EntityForm class that contains an entity and allows you to save it.

That said, what you are doing basically works, $this->student will be available, but be aware that on the first form submission, formBuild() is called again, so it will build another object. The same for entities. If you really want to prevent that, you need to store your object in the database, e.g. with the tempstore API.


When using the boxes module, is it possible to export the region and visibility settings?

Ah, I just realized there is an issue for this in the boxes queue.  As of May 2012, the issue has been resolved and this is now possible.


How to display default value of disabled form elements after failed validation?

The function that builds the form array isn't expecting any params unless you set a param in your hook_menu for instance. Instead you could try to grab the $form variable in the validation handler by reference and setting the value.

function foo_form() {
  return array(
    'foo' => array(
      '#type' => 'textfield',
      '#default_value' => 'foo',
      '#disabled' => true,
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => 'Submit',
    )
  );
}

function foo_form_validate(&$form, &$form_state) {
  $form['foo']['#value'] = 'bar';
  form_set_error('submit', 'You cannot submit this form');
}

This is untested as I have no running Drupal 6 instance at the moment. But I was able to do so using Drupal 7.

Another approach would be to use #value instead of #default_value since you already got your custom validation handler to put some extra logic in (get rid of the form_state value).


List all users who voted on a node with their ratings

If you use node as your base table, you can add the relation Content: Votes. This will expose all Votes on that node. From there you can add the fields Votes: User and Votes: Value that can be displayed in a table or something.


Use the Menu Block module, create a new Menu Block using the Primary Navigation, starting at Level 2.

This will only show the children of the current parent menu item you are in.


Create a PDF with one result from a view

It is just an idea. You need to create a one more view with same field. But you use views contextual filters and also use view pdf in this view . create a link for print with where you pass argument for this view . Print this link in your first view using view php.

You can also do this custom . create a custom menu item .Pass argument (id,nid) load content programmatically and add pdf download option.

Thank you


Can't save location when posting node through services module

How are you storing the location? Node location? Location CCK field?
take a look at:

https://www.drupal.org/node/906968

If you are using a CCK location field you should disable node location module.

Or if you aren't you could switch to a location field.

As a last option you could put latitude and longitude in their own text fields (like field_latitude and field_longitude) since gmaps module can take lat and lng from text fields.

  you can use CCK location which allows you a geolocation field, it
  comes with location module:

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


I tried your custom hook call, just to be sure it was called as you imagine, and to see how the $item array was build.

First, according to the hook_menu_link_alter() documentation, their is only one argument to this method in Drupal 7 (&$item).

And when I print the $item element, I can see that the name of the menu of the current element is not 'menu' but 'menu_name'.

Then your code must be something like :

function mymodule_menu_link_alter(&$item) {
  if($item['menu_name'] == 'custom-menu')
  {
    $item['expanded'] = 1;
  }
}

It is an interesting hook, because it is also called when a user add a menu directly from a node form options.


How to decide between Activity or Heartbeat (or DIY Rules?)

I am developing an SNS site and I chose Heartbeat.  I would choose Heartbeat again today for the following reasons:

Heartbeat has a stable D7 release.  Activity hasn't had any commits in 32 weeks (as of March 24, 2012) and is still in dev; there is no stable release yet.
Acquia chose Heartbeat over Activity for Drupal Gardens.
Heartbeat has rules integration.  This makes it very easy to customize to do what you want it to do, especially because you get access to tokens through the token module.  Activity lacks rules support.
Heartbeat has solid internationalization support.  This was a requirement as my site is multilingual.


How to make booking calendar for accommodation facility

I think the module you mentioned is good for it. Each of the entity can have a boolean field "Booked". So it could have values 0 or 1. You can filter out nodes according this field value in you calendar view.

I suppose, " Apartment house 2nd floor" is just one entity, not a type of entity.


Can I make a search that shows all results, regardless the user's permissions?

You can build this in views. Build your view as you normally would, use an exposed search, then under advanced > query settings > check off "Disable SQL rewriting". This will disable node_access checks as well as other modules that implement hook_query_alter().


After upgrade from Drupal 6 to Drupal 7 search does not work

Reindex the search data in config->search->setting and run cron again and again upto the index percentage reaches 100%.

This will solve your issue.

You can also do it via drush to get around limit on the number of items that get indexed per cron run.

$ drush help search-index

Index the remaining search items without wiping the index.
and/or

$ drush help search-reindex

Force the search index to be rebuilt.

Options:
 --immediate Rebuild the index immediately, instead of waiting for cron.


drupal_alter() ignores more complex function names when the hook is called

It's intentional - a module should only be able to implement a single hook once, and the naming convention requires that the function be called modulename_hookname_alter(). Drupal isn't ignoring your more-verbose function name, but since it doesn't match the name of the hook, it's never going to call it.

You can create other hooks though, based on whatever makes sense to your use case. For example if your module had a bunch of contexts you might create hook_abc_CONTEXT_alter(), and invoke it like so

foreach (mymodule_contexts() as $context_name) {
  $hook_name = 'abc_' . $context_name;
  drupal_alter($hook_name, $ref, $arg1, $arg2);
}

But I think that's as close as Drupal core will let you get to the pattern you're trying to implement.


What do the js-text-full and text-full in the StringTextAreaWidget class do?

These are classes that Drupal sets for its own css and js. For javascript it is always with the prefix "js". At first sight this seems to be redundant. The reason is, if someone wants to override the css class, it doesn't effect the js behavior and vice versa.

If you want to address the field through your own css, you can always target the field name "edit-mytextfield". If you use a class with the name of a text format, there is a chance, that you target other fields you don't want.


How to read input username to drush script?

In your Drush command you need to call drush_get_option('myoption'); to get the value of an input parameter.

To call your Drush command you need to specify your input option as below:

drush mycommand --myoption=myvalue


Autoselect parent taxonomy if child is selected

similar question here: Check parent term when checking subterm

but if you need check all child when parent checked, you need some changes in JavaScript file


How to calculate the average Fivestar rating correctly?

According to me, the insufficient support for anonymous voting is due to an underdeveloped Voting API (see my comment on this issue on drupal.org). Since I am not a professional programmer, I am not able to solve this matter on my own, so I looked for a workaround, using the Rules, Views and Computed Field modules. These are the main steps to solve the problem:

Create a comment View with all the comments on a node which have a non-zero voting field. Compute the average vote with aggregation.
Add a new computed field for nodes, which stores the result of the previously created View. The safest option is to add the code in a custom module (see the module's documentation).
In order to update the computed field from step 2, it is necessary to save the corresponding node again. To do that, I created a simple Rule which launches after a comment is edited or deleted.
Additionaly, if you want users to be allowed to vote only once, you can create a node Flag Reacted and Rules which (un)flag a node when (a comment is deleted) it receives a comment. Next, use HOOK_form_comment_form_alter() in your custom module to hide the voting field in the comment form when the current user has already flagged the actual node with Reacted.


Multiple Field Widget instances on the same page, validation problem

Check out the API page for form_set_error. This bit should help you out:

  $name The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

In your case you'll just want to make sure that the parent item is different for each instance of that field, then set the error with form_set_error($parent_name . '][' . $field_name, '...')


Why can't I delete both account and content when cancelling a user account, in Drupal 8?

Deleting content requires an access check, and as such the Delete the account and its content. option can't be selected as the default. I presume this is because a user can have access to cancel their own account, but not be able to select the method, and there's no mechanism implemented to provide a fallback for the default.

You'll still see it when cancelling an individual account, provided you have the administer users permission:

If you'd rather get control of that process yourself you can implement hook_user_cancel_methods_alter to remove or change the access check.


You can try to merge the existing field items array and the new one, but I would use a loop to add one image at a time:

$node = Node::load($node_id);
foreach ($new_images as $new_image) {
  $node->field_car_picture[] = $new_image;
}
$node->save();

If you want to merge the arrays get the existing one

$existing_images = $node->field_car_picture->getValue();

combine it with the new array and replace the fields content with it.


Views filter out nodes based on taxonomy field

I found a programmatic solution after visiting the Views API page.

Using the following code:

function mymodule_views_query_alter(&$view, &$query){
$types = db_select('field_config_instance', 'fci')
        ->fields('fci', array('bundle'))
        ->condition('field_name', 'field_taxonomy_example', 'like')
        ->execute()
        ->fetchCol();

$query->add_where(0, $query->fields['node_type']['field'], $types);

}

I was able to insert a dynamic list of node types to test my Views again.

Works like a charm.


How to programmatically enable and set taxonomy access control for role

/**
 * Implements hook_node_access().
 */
function accommodation_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  if ($node->bundle() == 'accommodation' && \Drupal::currentUser()->isAuthenticated())  {
    if ($node->get('field_accommodation_category')->entity->getName() == 'Category 1') {
      return \Drupal\Core\Access\AccessResult::allowed();
    }

    return \Drupal\Core\Access\AccessResult::forbidden();
  }

  return \Drupal\Core\Access\AccessResult::neutral();
}


OG "Add people" username predictive searching

The permission to set is "View user profiles".


Process a token from panel context in a ctools content type plugin

The magic function is ctools_context_keyword_substitute

The key to getting this working is to make sure that you use the all contexts flag in your plugin configuration.

$plugin = array(
  'single' => TRUE,
  'title' => t('Instagram'),
  'category' => t('Content'),
  'all contexts' => TRUE,
);

/**
 * Render the custom content type.
 */
function MODULE_PANE_content_type_render($subtype, $conf, $panel_args, $context) {

  ....

  $replaced = ctools_context_keyword_substitute('your_string_with_%keywords', array(), $context);

  ....
}


how to bulk edit all users (change city field for example)

You can use views and views bulk operations for this.

You can create a user view and add a relationship that joins it to the profile2 profile.

Then add the views bulk operations field and configure it to include the "Modify entity values" operation. You could also change the label to "Change profile values" or something if you prefer.

Then on your bulk operations view, select the checkboxed for all the users you want to update a value for, select the "Modify entity values" operation, click the execute button, then complete then next form.

When you do this, you must be setting the fields to the same values for all the users you selected.

If you need to give some users a different value you have to go through the process multiple times.

If you have lots of different data and it wouldn't be feasible to go through this process so many times then you would be better off using something to import your data from csv, like the feeds module or the migrate module.


Change a output value of a field in a view

A possible solution is to use the views feature "rewrite result", combined with Views PHP module.

Note: this module only has an alfa version as of today, but it's used in over 71K sites anyway.


How to print Promoted to front page to new block?

If I understood you correctly, you want to show 10 posts promoted to the front page in a block.

The Views module comes with a "Front page" view. By default, it is disabled, and you need to enable it. Once you did it, you can edit it: Click on edit.

On the next page, click on the "Add" button you see on the top left, and select Block.

On the next page, select "Access: None" under Block settings. (The link is just the None word.) Change the access to Permission (first page), and View published content (second page). (To pass to the second page, click on Apply.)

Save the view. (The button is on the top.)

On admin/structure/block, select the block you just created, and assign it a region where it should appear. Its name is View: Front page, if you didn't change the default one, which is None.

This is the result.

I changed the access settings because I enabled the view which was not enabled, yet. If you are already using the Front page view is not necessary to change the access settings, if not in the case you want the access settings for the block to be different from the page settings. In this case, be sure to select "This block (override) as in the fourth screenshot.


Main content is required. To hide it you can do this (I'm using bartik and hiding only for article) in theme's template.php:

function bartik_preprocess_page(&$vars) {
  if($node = menu_get_object()){
    if ($node->type == 'article') {
      $vars['page']['content']['system_main']['#access'] = FALSE;
    }
  }
}

However, I think you need to rethink your approach and either use Views, Display Suite, or Panels to take over the rendering.


How to insert any view inside of another view?

OPTION 1
If you want to display it after your current view In Views, click on +Add button and select Attachment.
Now go to your page view in the FOOTER add Global: View area and select your attachment.
OPTION 2
Download and enable Twig Tweak
If you want this as a field, add a Global: Custom text and put:

{{ drupal_view('view_name', 'machine_name') }}

Ex:
{{ drupal_view('frontpage', 'page_1') }}

OR
If you want to display it after your current view, in footer add Global: Text area, checkmark ☑ Use replacement tokens from the first row put
{{ drupal_view('view_name', 'machine_name') }}
 and select FULL HTML as your text formatt.


Drush ard is working for D6, not for D7 > bootstrap error

This seems like a permissions' issue on your server. Make sure that the user that you are running the command as, has the appropriate permissions in the Drupal 7 directory.

An easy way to fix it is change the owner of the Drupal7 dir by using something like:

chown -R username:usergroup /path/to/drupal7/dir

or if you are working in a debian based environment you can run the command with super-user-do like:

sudo drush ard


How can I use aggregation in multiple field in view

First you have to enable fields in your view. Then in your formatting settings you can now use "group by". You can also use more than one grouping field. Hope it will help!


Stay with 7.19 or hack 7.22 (to avoid the "itok" issue)

No need to hack, just add the following line to your settings.php file:

$conf['image_allow_insecure_derivatives'] = TRUE;

Source

That will stop the itok parameter from being used.

It's even been wrapped in a module if you don't fancy editing settings.php.

Image Allow Insecure Derivatives

  Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.

As a side note, trying to hide your site's identity as being a 'Drupal' site is pointless. It's known in the field as 'Security through Obscurity', and it's a waste of resources that could be spent solving real security or performance issues.

See How can I obscure what I am using to run my site? for a more in-depth explanation.


Drupal for a portfolio- Images as nodes or something else?

I'd go with the image-per-node option if you think you may at any point want to add additional information per image.  You can call the content type 'Project' or something like that and put an image field on the content type.  You can have an 'unlimited' checked as the number of images allowed in that field or only allow for a single sample image.  Up to you.

The point is - imagine that down the road you want to add extra information about that particular screenshot/project, such as the date you worked on it, or who your client was, or a link to the live site or something like that.  If you make a separate node for each project, you have the flexibility to add fields in the future.

If your entire portfolio is a single node with a bunch of images, you don't have the option to add extra information to explain those images later without re-doing the entire setup.

You can always just display them as a slideshow with no extra information, regardless of which option you choose, but I'd go with the one that allows for flexibility in the long term.  :-)


updating webform submission display by using form

Well, i figured it out myself. After the form submit callback drupal fires a redirect to the same page. So the values set in mymodule_get_key_status are flushed after the redirect.
I add $form_state['redirect'] = false; to my submit callback and now everything works as expected.


Save paragraph widget data in custom form

I found the solution via this article. Though for the solution to work specifically for the paragraph field, I had to add a patch for an issue discussed here.

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#parents'] = array();

  $node_id = 1; // Some node
  $entity = Node::load($node_id);
  $form_state->set('entity', $entity);

  /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  $form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')->load('node.node_type.default');
  $form_state->set('form_display', $form_display);

  foreach ($form_display->getComponents() as $name => $component) {
    $widget = $form_display->getRenderer($name);
    if (!$widget) {
      continue;
    }
    $items = $entity->get($name);
    $items->filterEmptyItems();
    $form[$name] = $widget->form($items, $form, $form_state);
    $form[$name]['#access'] = $items->access('edit');
    $form[$name]['#weight'] = $component['weight'];
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  $form_display = $form_state->get('form_display');
  $entity = $form_state->get('entity');
  $form_display->extractFormValues($entity, $form, $form_state);
  $entity->save();
}


How do I programatically create a node, add a menu item, and add a path alias?

I understand that you have some external database, and your nodes are in relation with some entities from there. You need node 'downloading' some content from other database; for compatibility with Solr.

1) Instead 'hacking' node number, I think you should use create node type for it. Beside distinguishing downloaded nodes for others; you can create CCK field for storing external database id; and setting content edition permission that nobody can edit it.

2) In your custom module you need to implement hook_blocks to put in the menu content that you need.

3) With pathauto module you can simply create automatic path. If you create special content type out of the box pathauto functionality should be enough.


How to add a new user permission "Translate own nodes" ?

The basic method followed by that module should work (custom access callback + hook_menu_alter), but the code would need updating for D7.

From a quick scan of the code (so there may be other things that need updating) hook_perm is now hook_permission and hook_nodeapi has been replaced by serveral hooks (in this case only the 'prepare' op is used, so hook_node_prepare is the only one required here).


Override menu name shown by Superfish in mobile view mode?

You can change this in superfish settings. If you have accordion menu it can be set under "Accordion Menu title".

If you have select menu, there is also an option to change that at "Select settings".


Specify ids for a migration yml file from nested json array

The migration template should include top level source, process and destination sections

It appears in this case you are missing the process section for the field value assignment there.

More info: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview#etl


I cannot create a directory when installing a module

This turned out to be an SELinux issue. SELinux is enabled and running in enforcing (strictest) mode by default in Centos 7 and this will prevent the web user from being able to write to /modules or /files (or anywhere) regardless of the file permissions set.

To see if you may be having the same problem:

more /etc/selinux/config

This will display the SELinux config file and let you know if it is enabled and what mode it is in.

The issue can be corrected with the following commands:

sudo chcon -Rt httpd_sys_content_t /var/www/html
sudo chcon -Rt httpd_sys_rw_content_t /var/www/html/sites/default/files
sudo chcon -Rt httpd_sys_rw_content_t /var/www/html/modules
sudo chcon -Rt httpd_sys_rw_content_t /var/www/html/vendor

This will correct the context of the directories you want to grant write permissions on so that Drupal will work without disabling SELinux. For more information see the man pages for selinux and chcon.


Email sending doesn't work through Webform

It appears you're running your site on Windows. Either IIS or Apache?

Sending mail on windows based servers is a bit different. It cannot used php's normal method for sending mail if it were on a linux server.

You must configure an SMTP server in either your PHP.ini, or leverage the SMTP Auth module and connect to an SMTP server.

PHP.ini setup:

http://www.quackit.com/php/tutorial/php_mail_configuration.cfm
https://stackoverflow.com/questions/112190/php-ini-smtp-how-do-you-pass-username-password


Display the user avatar in  a user panel

There are actually two separate blocks, User login that is displayed only to anonymous users and Navigation that only gets displayed once user has logged in. You are interested in modifying the latter one.

Unfortunately, there's no hook_block_alter() around that you could use to modify the block from a custom module. However, you can do so from within your theme just before the block gets displayed.

Just pop the following function into YOURTHEME's template.php and it should work. Please, note, this adds the user picture to the top of the block content, just below the user name.

function YOURTHEME_preprocess_block(&$vars) {
  $block =& $vars['block'];
  if ($block->module == 'user' && $block->delta == 1) {
    // Navigation block.
    $block->content = theme('user_picture', $vars['user']) . $block->content;
  }
}

If you want it above the username, just replace $block->content with $block->subject.

Or, even better, just create another block, place it above the Navigation, make it only visible specifically to authenticated user role, set the Body title to <none>, and Block body to:

<?php
global $user;
print theme('user_picture', $user);
?>

Make sure to enable the PHP filter module first and use PHP code filter for the Block body input.


The Metatag module has views integration from the box since 7.x-1.0-beta2.

Install the metatags_views submodule and you'll get metatag options in the views UI for any views page display (Paul Querol's comment below).


Use a different template file if use is on a mobile device

To do this you need to setup some method that will detect whether the use is coming from a mobile device and than add a function in your template.php file to switch to your mobile template.

For the mobile detection, there are a number of modules available for this but for this specific use case, I would recommend Mobile Switch because it provides a specific variable you can use for testing in your theme (others like Mobile Tools might as well, this is just one I've used before). From documentation:

Development with Mobile Switch.

The module provides four system variables:

1. mobile_switch_ismobiledevice
2. mobile_switch_istablet
3. mobile_switch_ismobiletheme
4. theme_mobile

From here, you just need to add a template suggestion to your theme through the preprocess_page function using this variable, ex:

function YOURTHEME_preprocess_page(&$variables) {

  global $mobile_switch_ismobiledevice;

  if ((request_path() == 'YOUR_PATH') && $mobile_switch_ismobiledevice) {
    $variables['template_file'] = 'mobile-YOURTEMPLATE';
  }

}

This method assumes you want to specifically switch between two template files, if you would prefer to use a separate mobile theme, than the Mobile Switch or Mobile Tools module have configuration options to help you do this.


Limit of 15 routes in module.routing.yml

It's just you I'm afraid.

Take the system module's routing file for example; there are a few dozen routes in there, plenty more than 15.

Symfony doesn't impose any limits either, so I'd check that your YAML code is properly formatted and valid. If you're positive it's all good, you've probably hit a bug and the best course of action would be to report it.


For a custom template use your own theme hook etypeservices:

function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

Which uses it's own variables space:

public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'etypeservices',
      '#facebook' => $facebook,
   ];
 }
}

etypeservices.html.twig

{{ facebook }}

The content of the block is a normal render array, which can contain one or more custom templates to make them accessible in theming. These custom templates are reusable, not only in blocks.

In a module you can override the block template, as you tried to do by using block__..., but you need this in very rare cases. In drupal core there is only one. Then you will inherit the variables of the base hook block.

But normally you leave the block template as it is, so that it can be themed on it's own.


How to restrict users to view their own custom content type?

When the implementation of hook_node_access() returns NODE_ACCESS_IGNORE, it is not denying the access to a node, but it is letting other modules decide if the user has access to the node. If none of the modules implementing hook_node_access() returns NODE_ACCESS_DENY, and none of the modules implementing hook_node_grants() returns 0 for the node, then the user has access to the node.


Add a custom carousel block with HTML, CSS, and JavaScript

I would not bother with copy pasting HTML/CSS/JS into a block (this is bad practice regardless).

Instead, you might want to try the Owl Carousel or Flickity module for Drupal. You didn't mention your version, Owl Carousel exists for Drupal 7, while Flickity only exists for Drupal 8.


is there a way to generate dummy content for paragraphs?

Paragraphs need a host entity to work normally iirc, so if the paragraph is attached to a node type through a reference field, I've had success creating them with Drupal console's node generator: drupal create:nodes which seems to populate all the fields it can.

Beware though: I've had to drupal create:terms first to generate a few taxonomy terms, or else the node generation takes ages! Your laptop may take off before the process finishes ;)


How to remove an option from an exposed filter with a drop-down list?

You use hook_form_alter:

/**
 * Implementation of hook_form_alter().
 */
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'views_exposed_form':
    // Force
    $form['field_gender_value']['#options'] = array('M' => 'M');
    break;
  }
}


How can I use the Commerce Paypal module module without the Commerce module?

Commerce Paypal has the following dependencies:

commerce
commerce_ui
commerce_payment
commerce_order

Installing/using Commerce Paypal without Drupal Commerce isn't possible; it's a supplemental payment module, and requires Commerce's API to work.

You may instead be interested in something like Webform Paypal

  The Webform Paypal module sends the user to Paypal to complete a payment whenever they submit a webform containing the component on your site.


Try Contact block module, which provides the contact form in a block.

From module documentation,

  The Contact Block module provides contact forms in a block. It uses the contact forms that can be created using the Drupal 8 core Contact module.


A block created with Views is not rendered if the page URL contains "page="

I think I worked out what the problem was. The way the View selected the content, there could only be one result (the View is to show the current exhibition for an art gallery website, and they only ever have one exhibition at once). Because by design it could only produce one result I didn't even think about the pager, which was to Full by default.

This caused problems when that block was rendered on the same page as another View - one which deliberately has a pager. Maybe there's an issue with multiple pagers on the same webpage?

Anyway, I changed the block View's pager settings to "Display a specified number of items | 1 item" and that fixed everything - now there's only ever one pager on the webpage and now my block view is displayed on every page as it's supposed to.

Edit: Will click this as accepted answer in 2 days when I'm allowed to


Programatically get the webform submission "sid" on submitForm

So it turns out i will have to save the webform before i can get its sid since i am using the public function submitForm which is fire in submitting the webform but before saving it.

Final code will be:

public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
// Get an array of the values from the submission.
    $values = $webform_submission->getData();
    // ...
    $webform_submission->save();

    // Get the Webform submission "Sid" after saving the webform submission.
    $sid = $webform_submission->id();

// Show a success message.
    \Drupal::messenger()->addMessage(t("$sid"));

}


Display processors are not used when rendering the node form. It's a completely different process. I'm not aware of any contrib modules that will help you accomplish this. However you can write your own.

You need to start by creating a very simple custom module with just a .info, a .module and a .css file. You can find lots of tutorials online.

Then you want to write that CSS to make your particular form fields inline and attach the css to the form using hook_form_alter. If you named your module "hook" the code would look like this (This code goes in your hook.module file):

// Replace hook with name of module and yourcontenttype
// with machine name of your content type
hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'yourcontenttype_node_form') {
    $form['#attached']['css'][] = drupal_get_path('module', 'hook') . '/hook.css';
  }
}

After that enable the module, clear all caches and it should be including the new CSS in the admin form.


Just migrated to pressflow and now users can't log in.. any ideas?

Not sure if that's going to be of any help for you, but I had kind of similar problem - on staging site, after upgrade from Pressflow 6.16 to 6.26, users were not able to log in anymore - or actually, according to Watchdog, they were logged in, but still being redirected to log in form.

No warning like yours though, although I assume that in your case they we caused by your admin account already logged in.

At this time prod site was still running Pressflow 6.16.

What helped in my case was changing $cookie_domain value in settings.php file on the staging server, which "unlinked" staging and prod cookies.

Essentially, before both staging and prod sites were using the same $cookie_domain (let's say it was mydomain.org), and everything started to work fine after changing it to stage.mydomain.org on the staging server.

Perhaps the problem is with the different way of handling cookies, and once our Pressflow is updated on prod server too it will again work fine with the same $cookie_domain, but this is still to be tested and confirmed.


Force a page to be rendered in admin theme (overlay mode)

You can also do this by making a custom module.

Method 1

Use this if you want to theme an existing page, based on Drupal's internal path (aka path source). This example uses hook_custom_theme.

<?php
function MYMODULE_custom_theme() {
  // match node/1
  if (arg(0) == 'node' && arg(1) == '1') {
    return variable_get('admin_theme');
  }
}

Method 2

Use this if you want to theme an existing page, based on URL path (aka path alias). This example also uses hook_custom_theme.

<?php
function MYMODULE_custom_theme() {
  // get arguments
  $arg = explode('/', substr(request_uri(), strlen(base_path())));
  // match {wildcard}/path
  // Using strpos as $arg[1] may end up having stuff like so ?order=title&sort=asc
  if (isset($arg[1]) && strpos($arg[1], 'path') !== false && !isset($arg[2])) {
    return variable_get('admin_theme');
  }
}

Method 3

Use this if you want to theme and create a page. This example uses hook_menu. To learn more, take a look at another great article on hook_menu.

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

  // match some/path
  $output['some/path'] = array(
    'title' => t('Page Title'),
    'page callback' => 'MYMODULE_page',
    'theme callback' => 'variable_get',
    'theme arguments' => array('admin_theme'),
  )
}

function MYMODULE_page() {
  return 'Hello world.';
}


New URL for the node overrides the URL of existing node using pathauto module

I faced the same problem in my website.
As you mentioned in your question :

  Usually, the Pathauto module doesn't allow to the users to create the node with existing URL by giving the error as "Path already in use"

This is true only when you hand code the URL alias. If "Generate automatic URL alias" box is checked then similar URL's are appended with numbers at the end (like in your case).

The method I used to prevent this problem was to install a module called Unique field which makes sure the no 2 nodes have the same title(and thus unique URL for each node).

In your case, since the damage is already done, the best option for you is to change your title or url to something like /gandhiji-park-state-2

Suggestion :

This is just a suggestion for URL structure and SEO. A general rule of thumb that I follow when creating URL, is to rank the keywords in the URL. The highest ranked keyword should come at the end of the url. For example www.example.com/less-specific-keyword/more-specific-keyword. This way you can rank higher in search engines for the same content and also users can get an idea about your content just by looking at the url.
For example, in your site you can structure the URL like this www.example.com/state/park/park-name.


drupal /?q=user is working but /user not working

As you have checked mod_rewrite settings for your server and .htaccess both it sems that you may have mis-configured  RewriteBase in your .htaccess file.

Please check comments in .htaccess file

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
   VirtualDocumentRoot and the rewrite rules are not working properly.
   For example if your site is at http://example.com/drupal then its value should be:

RewriteBase /drupal

If your site is running in a VirtualDocumentRoot at http://example.com/,
   then its value should be:

RewriteBase /

Try and see if you have something wrong here.


How best to implement a custom variable in the content creation form in D7?

I believe your best bet is to create your own module, with a custom form hook and the form submit which will process your data and do all your calculations and save the new value. The form tutorials in the Form API Examples can give you a lot of good insight how to do this.


Because the image actually does not below at /image.jpg. You need to investigate where you are storing your files at admin/config/media/file-system. And from there you might find where is your files locate.

The default file path is going to be /sites/default/files so it might be ftp://account:123@xx.xxx.xxx.xxx/sites/default/filesimage.jpg.


Sticky at top of lists node at certain time

Looks like Rules Scheduler (part of the Rules module) is what you're looking for. "Publish content exactly 24 hours after it was created" contains step by step instructions about how to do so (using the Rules Scheduler).

Here are some video tutorials about a few variations of your question (some are pretty close to your question), which are all resolved with Rules Scheduler:

Schedule front page publishing.
Publish a newly created Drupal node on a future date.
Send a follow-up email one week after a user registers.

Ps: There is also the rules-scheduler tag, specific to the Rules Scheduler.


overriding submit functions with content types

One way to do it is by using hook_form_alter, we can able to define a custom submit handler.

Find the form_id of that form and define a custom submit handler.

hook_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'custom_add_user_form'){
        $form['actions']['submit']['#submit'][] = 'show_date_submit_handler';
        //for submit $form['actions']['submit']
        //for preview $form['actions']['preview']
    }
}

function show_date_submit_handler(&$form, &$form_state){
    // manipulate the form submitted values over here
   }


How do I choose which module to use when there are several options for the same functionality?

Personally I do a few basic checks before digging deeper.

How many reported installs? (about the same in your example modules).
How long since last update to module? (Spamicide is 5 days ago (from today))
How many open issues?
Who is the developer? (Have they worked on other modules that I use, etc).

Then you can start digging into integration, if I where looking for an inline image management tool I personally would choose something that takes advantage of other modules instead of rolling it's own solutions, something that is features exportable, etc.


Why is the Media module ignoring view_mode display settings?

This is currently not supported in Media module. There is work being done though. Checkout this issue. https://drupal.org/node/1792738


How can I achieve taxonomy workflow (allowed next states of taxonomy terms)?

I don't think there's a ready made solution for this. The maintainer of workbench_moderation has said that a goal is to collaborate with other workflow modules and made one module to rule them all, and one of the primary goals of that initiative is "workflows for non-node entities" but this is still a long way off and doesn't seem to be very far past the planning stages at this point.

So I think the closest you can get currently is the taxonomy_revision module but that just adds revisions and doesn't help in automating a workflow out of them, so you'll have to do some custom development on top of that.


Can Views output clean URLs from titles with quotes, and other special chars?

If you are loading nodes they will already have a path associated with them. Assuming you have setup path aliases (url aliases), and potentially url patterns with the pathauto module) for these nodes there will already be a field (Content: Path). This field will contain a clean and tidy url you can add which will give you the path to these nodes.  If you just want the node title to be linked to itself there is an option to 'Link this field to the original piece of content' when you add 'Content: Title'.

tl;dr Try to keep this stuff out of Views and add the relevant fields that are already available.


How To Place One Forum Topic in Many Forums

I've answered my own question. I used the Rules module (http://drupal.org/project/rules). That thing is GREAT!

First I created my topic that I wanted to show in all forums. Let's call it node/10.

Next I created a topic with the same title in all of the other forums, but the body content just reads, "REDIRECT". Let's call these nodes 11-16.

Then I created a new Triggered rule with one IF and one DO.

IF uses an "Execute custome PHP code" statement which checks the node id to see if it is one of the REDIRECT pages, like so...

return in_array($node->nid, array(11, 12, 13, 14, 15, 16));

When IF returns true, DO immediately executes a System > Page redirect to node/10.

So far, so good.


Add t('String to be translated') to your database

Every single string passed to t($string) function will be added to the database, and you can find it in the path you montioned above "admin/config/regional/translate/translate"

clear the cache, and search it again with help of filters existing on the admin translate page.

[EDIT]

First of all a must have module in multilangual sites is the internationalization module, it's a powerfull and helpfull module...

But the most important thing in your case is that before you can see your string in the transltion page:

you must enable(switch to) the desired language
visit the page that contain that needle string
visit again the translation interface.

That's it you will find your string ;)


You need to use the non-aliased path for the template name.

For example if you are dealing with node 1 (node ID = 1) try naming the file page--node--1.tpl.php and clearing the cache again.

For more info see: https://drupal.org/node/1089656#page-suggestion

If you don't know what the node id is, go to the node edit page and it will be in the url /node/NODEID/edit.


You can change the JSON output of a date field by implementing a custom Normalizer for date fields in a custom module. I got it to work using the following code. This is a bit of a hatchet job, so you'll want to clean up and stuff, but otherwise it should do the job:

/src/Normalizer/DateTimeCustomNormalizer.php:

<?php

namespace Drupal\custom_date_serializer\Normalizer;

use Drupal\serialization\Normalizer\DateTimeIso8601Normalizer;

/**
 * @internal
 */
class DateTimeCustomNormalizer extends DateTimeIso8601Normalizer {

  /**
   * {@inheritdoc}
   */
  protected $allowedFormats = [
    'RFC 3339' => \DateTime::RFC3339,
    'ISO 8601' => \DateTime::ISO8601,
    // used to be 'Y-m-d', so you can use any PHP date format you want
    // I just set it to this because it was easy to test
    'date-only' => \DateTime::ISO8601,
  ];
}

And /custom_date_serializer.services.yml:

services:
  custom_date_serializer.normalizer.datetimecustom:
    class: \Drupal\custom_date_serializer\Normalizer\DateTimeCustomNormalizer
    arguments: ['@config.factory']
    tags:
      # Priority must be higher than other datetime normalizers.
      - { name: normalizer, priority: 40 }

And you'll need an info.yml obviously.


How do I override the base URL for private files?

The private files point to the hostname where the backend server is,
  instead of pointing to the frontend server.

Private files are not directly served to the user. Public files are served directly to the user. With a public file, when a file is requested, PHP is never executed, and therefore Drupal is never executed. By virtue of the files being public, they do not require any access checks, and so there is no reason to bootstrap Drupal. Instead, the server (apache, windows etc) serves the files directly to the user. The proxy can then cache that response, since the response for that file will always be the same for everyone.

Private files on the other hand require access checks. By definition, they are meant to have access checks performed upon them before they are served to the user. With private files, the request for a file is made to a php script (index.php - from which every Drupal request begins). This script (which is Drupal) runs access checks on the requested files. If the the access checks are passed, Drupal reads the data from the actual file, then sends a binary file response to the browser (rather than an HTML response, which would be a webpage). This binary file response is the file, which the browser either then renders or offers to the user as a download, depending on the file type and their browser settings.

An analogy to these files systems is to consider public files to be like wanting a cola, and going to the fridge to get it, while private files are like wanting a beer, asking a server for it, who then checks your ID and if you are old enough, gets it from the fridge, and brings it to you.

So private files by their definition cannot be directly accessed, as a script (Drupal) first needs to check whether the user should have access. As such, private files cannot be cached by the proxy, as the proxy has no means of checking access. This is why the base URL cannot be overridden.


added files to module: use drush to upgrade to a new version of this module will added files be deleted?

If the css files are stored in the quicktabs module directory, yes they will be lost upon upgrade.


How to create nodes automatically using title, fields, etc from some other nodes?

The Rules module is your friend here.

You may use it to create an entity (here a node) after saving a new content of type A B or C (or any other event). Then you can add actions (set a data value) to fetch field values from A, B and C for your new content of type D. The first action would be of course Create an entity, then set data values.

You may find a great set of tutorials about Rules at Learning the Rules framework series.

Here is a short example : after saving a new Drupal Article, create a new Drupal Basic Page with the Body extracted from the Article and an automatic node-title.

{ "rules_automatic_node_creation_based_on_another_node" : {
    "LABEL" : "Automatic node creation based on another node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Basic page from Article [node:title]",
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "entity-created:body" ], "value" : [ "node:body" ] } }
    ]
  }
}


I don't think you can pass an argument into a block like that.

However, you can do it with page manager.

Make sure AJAX is enabled in your view
Install & enable page manager https://www.drupal.org/project/page_manager
You may need to apply this patch with composer for the following steps to work
Go to structure > pages
Add a new page manager page like this

Skip the next screen (click next)
Set up a context like this

Skip the next two screens (click next)
Add your view block like this

Now go to <your_url>/latest/article and the page should list your articles
You can add other pages/contexts for other content types


How to Reduce/Increase module's weight on the module install process?

Use hook_module_implements_alter() rather than changing the module weight.

Sample implementation from content_translation.module:

function content_translation_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {

    // Move our hook_entity_type_alter() implementation to the end of the list.
    case 'entity_type_alter':
      $group = $implementations['content_translation'];
      unset($implementations['content_translation']);
      $implementations['content_translation'] = $group;
      break;

    // Move our hook_entity_bundle_info_alter() implementation to the top of the
    // list, so that any other hook implementation can rely on bundles being
    // correctly marked as translatable.
    case 'entity_bundle_info_alter':
      $group = $implementations['content_translation'];
      $implementations = [
        'content_translation' => $group,
      ] + $implementations;
      break;
  }
}


What wysiwyg editor are you using? In my end I'm using TinyMCE and I have a related task as yours. What I did was I created a plugin to insert a class on a selected texts. Doing this will provide a convenient way to your users to add styles.

Note: you can use hook_wysywyg_plugin() for this.

Hope this help!


As per the FAPI the element textfield has no name attribute

Available Properties are

#access, #after_build, #ajax, #attributes, #autocomplete_path (default: FALSE),
#default_value, #description, #disabled, #element_validate, #field_prefix, #field_suffix,
 #maxlength (default: 128), #parents, #post_render, #prefix, #pre_render, #process, #required,
 #size (default: 60), #states, #suffix, #text_format, #theme, #theme_wrappers, #title,
#title_display, #tree, #type, #weight

I am not sure about the reason that the form is not validating, Excited to know the reason.


Getting error {"message":"No route found for \u0022GET \/standortimporter\/region_node_rest_resource\u0022"} custom rest POST

To create a custom rest resource:

Enable rest module: drush en rest -y
Create the plugin like the following YOURMODULENAME/src/Plugin/rest/resource/RegionNodeRestResource.php:

namespace Drupal\YOURMODULENAME\Plugin\rest\resource;

use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "region_node_rest_resource",
 *   label = @Translation("Region node rest resource"),
 *   uri_paths = {
 *     "create" = "/standortimporter/region-node-rest-resource"
 *   }
 * )
 */
class RegionNodeRestResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->currentUser = $container->get('current_user');
    return $instance;
  }

    /**
     * Responds to POST requests.
     *
     * @param string $payload
     *
     * @return \Drupal\rest\ModifiedResourceResponse
     *   The HTTP response object.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post($payload) {

        // You must to implement the logic of your REST Resource here.
        // Use current user after pass authentication to validate access.
        if (!$this->currentUser->hasPermission('access content')) {
            throw new AccessDeniedHttpException();
        }

      $payload = ["hello here"];
        return new ModifiedResourceResponse($payload, 200);
    }

}

You should enable your resource using restui:
go to admin/config/services/rest you can see your endpoint and enable it.

And configure it like the following:

 4. To test you should use rest client app like Postman like:

For more informations read Custom REST Resources page.


The dev version of jQuery Update for Drupal 6 will get you up to jQuery version 1.7 (but it does break some of the admin UI).

There are a few patches available, (see Fix jQuery 1.7 for Drupal 6 and the Issue Queue in general), with varying reported levels of success.

If you choose to go down the 'manual' route then you'll have a lot of core/contrib javascript to fix. I think your best bet would be to base whatever solution you come up with on the current dev release of jQuery Update.

If you specifically only need version 1.4.2, then there's some instructions on how to do it here.


drush sqlq --file on remote server with local file

you should try with other command:

drush sql-sync --source-dump=src/sql/data.sql --target-db-url=mysql://remoteusername:remotepass@remoteserver/remotedatabase


How to get taxonomy term by description, programatically

Using the EntityFieldQuery (this is untested)

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', array('my_vocabulary'))
    ->propertyCondition('description', 'my_term_description');
  $result = $query->execute();
  $tids = array_keys($result['taxonomy_term']);

  return $tids;

More information https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7


Moving Drupal database from MySQL to Oracle

This may be another long shot and I certainly haven't tried it myself, but assuming that the Features module works on a fresh install on top of Oracle, you may be able use it to export your content types, menus, and views from the MySQL-based site. The Features extra module might allow you to export the taxonomy too.

You could then add the Services module on the MySQL site to serve up content to either the Feeds module or maybe the Web service client module on the Oracle-based site.

Another caveat is that I don't know how well either of these steps would handle the i18n.

Good luck!


The problem is way I used to update,
for this job drupal has syntax, according to  Update query with a dynamic expression in Drupal 7?
I found my solution

$cr_update_no= db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ))
                ->expression('credit', 'credit + :amount', array(':amount' => $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

I submit this answer maybe helpful for another in future.