admin/content customizing I need to add some new filters to the admin/content (or admin/content/file) page. Standardly, it offers me just type and status. Let's say, I would like to add the filter "name", that shows just the files of specified author. I am able to generate all the possible authors (their names) from SQL table, as well as showing them on the page (simple add it to $form['filter']['filters']['status']['filters'] with hook_form_alter function).

But now I do not know, what to do next. The submit button calls some function to generate some filters (but then it seems pretty difficult to change everything).

Do you know any way to do that?

Try Administration Views module. It comes with views based listing. Which can be easily modified based on our requirements.


How to embed javascript into content region I am trying to embed javascript into the content page of my page. I decided to use php filter and the following is my code:

<?php
$scripty = "http://blah.com/plugins/embedvanilla/remote.js";
drupal_add_js($scripty, array(
'type' => 'external',
'scope' => 'content',
'group' => JS_LIBRARY,
'every_page' => FALSE,
'weight' => -1,
)
);
?>

The script shows on this page if scope is not set (which means it defaults to header).

How can I get it to display in the content region?

Never use php filter, it's one of the worst inventions in Drupal.

You can create a region in your info theme.  Then, use the preprocess hook like that:

function hook_preprocess_region(&$vars) {
  // Region names of (header|footer) collide with drupal_add_js()'s
  // (header|footer) labels.
  $scope_theme = 'your_region';
  if (!empty($scope_theme) && $scope_theme != 'footer' && $scope_theme != 'header'
    && $vars['region'] == $scope_theme) {

    // Inject javascript into page.
    $javascript = drupal_get_js($vars['region']);
    $vars['content'] = $javascript . $vars['content'];
  }

}

And finally, fire your drupal_add_js using the region you defined wherever you prefer... But never in php filter


How to use drupal_get_token() within custom user registration email I'm in the process of writing a custom user registration module for Drupal 7. I currently have my own custom form which calls the function user_save within it's submit handler to create the new user account. The account is initially created as "disabled", and will only be activated once the user verified their account via a link in a custom welcome email.

I have generated a token to append to the URL query string (contained in the email generated by hook_mail() using drupal_get_token()):

$myToken = drupal_get_token('email_verify_'.$params->uid);

Unfortunately I'm always getting an Access Denied message when following the registration link within my custom email. I've checked both values storing the UID within the hook_mail and page callback and they're indeed correct.

Is there anything I'm missing here? I considered using user_pass_reset_url() instead, but we capture the user password on registration so we don't want them to have to re-enter their password twice.

Thanks in advance!

EDIT #2: adding more code for Pontus

hook_menu implementation:

//callback to verify user via email link
$items['custom_user/signup/verify/%'] = array(
  'title' => 'Activate your Account',
  'page callback' => 'customer_user_signup_verify_email_page',
  'page arguments' => array(3),
  'file' => 'includes/custom_user_signup.verify.inc',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

Check if valid token within customer_user_signup_verify_email_page() callback function  drupal_valid_token():

if (empty($_GET['tok']) || !drupal_valid_token($_GET['tok'], 'email_verify_' . $user_id)) {
    drupal_access_denied();
}else{
    //enable account now that we know you're a valid user
}

URL printed in email:

http://mysite.com/custom_user/signup/verify/10?tok=Zh2MmBHLnjvd3Dq9KcDxkwJ0lmk_QmMg5QNZomC7Okw

The reason this is failing is because drupal_get_token() and drupal_valid_token() use the value of session_id() to generate and validate the token.

The problem is that session_id() will return a different value for anonymous users on each page load. So the token generated by drupal_valid_token() is different from the one that is generated in drupal_get_token() because the input (sessoin_id()) is different.

For form submits where you want to compare a token on the next page load for anonymous users, you can call drupal_session_start() on the form page which will start a session and ensure that the results of session_id() are the same on the form page and the result page. But in your case, where the user is clicking on a link back to the site from an email, the value of session_id() will only be the same if it's the exact next page load. My tests indicate that Drupal destroys the session created by drupal_session_start() on the next page load.


CKEditor - Alignment I' trying to set up CKEditor options as in the following screenshoot:

Everythings works fine except the alignment buttons:

I saw that an issue (2649546) about this has been created but it seems that is still pending.

Any suggestions about how I could solve this?

You need to download the Full Package of the CKEditor library.

You can download it at the official website.


How to print the paragraph field translation value in twig template I am trying to access the nested paragraph field inside my twig template.
{% for items in item['#paragraph'].get_aw_title_details%}
  {{ item.entity.field_award.value }}
{% endfor %}

When I am using this syntax it is always returning the English content. Translation content is not visible for me. For chinese also it is giving the english content

Normally it's a better idea to process (or even better let Drupal process) the field values in PHP.
If there is no other way you can use Twig Tweak and its newly added entity translation filter:
{% set entity = item.entity|translation %}
{{ entity.field_award.value }}

See https://git.drupalcode.org/project/twig_tweak/-/blob/3.x/docs/cheat-sheet.md#entity-translation


Cannot alter output of a view under any circumstances I am running into a repeat issue with views and the lack of ability to apply or stick additional classes to a field. We have a "view all content" page that renders fields pertaining to a certain content type and its views through a "Custom Text" field and a variety of excluded fields (so we can render them inside our Custom Text field, to better resemble what the front-end team expects). One of these rendered fields is a hyperlink, and the design team would like to see a class added to it so they can limit a broad set of CSS rules for it.

Okay, simple right? Just go into the field, style settings, and customize its HTML. Done, added classes. But they aren't showing up for this hyperlink. I even tried a more untenable approach of applying a class through a tpl.php rewrite and a Regex. But as long as this field is being displayed through a "Custom Text" field, it does not assign any classes.

The design team has informed me there is no other approach for this given the use of Global Text here. Is there any way to alter what the tokens used by other fields in Drupal output in terms of raw HTML markup, including the addition of other attributes such as classes when taking this design approach?

When you use Custom Text, you are telling Views to override anything it does and display only what you have provided it plus the addition of your placeholders. So what you should do here is exclude the original field from the display and write your HTML with the class into the custom text field. Then, include the field placeholder.

Like this.

  [field_link_title]

I am pretty sure this gets you the intended result. Note I am making up those placeholders and you should see what your available replacement patterns are. :)


How to create internal and external links In drupal 4.x, in contents, links are created like this
[url=1]Some text[/url]
So when "Some text" click it open node 1.

Sometime it may link to external url also. like below:
[url=http://www.abc.com/somepage.html] external link [/url]

same thing how can i do it in drupal 7.x

To be honest, I don't know anything about Drupal 4.  I don't regard it as a platform to build on in 2014.

In Drupal 7, out of he box, you create links using plain HTML:

internal link
external link

There are a bunch of modules for Drupal 7 you can install that gives you other syntaxes for adding links to content. To mimic the square brackets around tags syntax you cite as example. Install the Bbcode module.  It uses markup based upon BBCode.  For a more modern style, similar to StackExchange, install the Markdown filter module. It let content authors use markup based upon John Gruber's Markdown.


How can I load the #totals property for the receipt theme in a custom module? I am trying to manually output the customer's receipt on the checkout complete screen in a custom module.
I have the receipt printing nicely except for the "totals" variable.
My current custom code is the following.
$renderable = array(
      '#theme' => 'commerce_order_receipt',
      '#order_entity' => $order,
      '#billing_information' => NULL,
      '#shipping_information' => NULL,
      '#payment_method' => NULL,
      '#totals' => $this->orderTotalSummary->buildTotals($order), // <-- this is the problem
    );

 return array(
      '#theme' => 'custom_blocks_checkout_complete',
 '#order' =>  \Drupal::service('renderer')->render($renderable),
    );

As you can see, it's using $this->orderTotalSummary->buildTotals($order) to generate the #totals property and this was copied from the OrderReceiptMail class in the Order module. How can I get this property to populate from my custom module please?

Use the service
'#totals' => \Drupal::service('commerce_order.order_total_summary')->buildTotals($order),


How are the templates in the js_example module retrieved? I installed js_example, one of the sample modules in the Examples for Developers module.

In this module I found the following configuration:

css
 - jsweights.js
js
 - black.js
 - blue.js
 - brown.js
 - green.js
 - js_example_accordion.js
 - purple.js
 - red.js
src
 Controller
  - JsExampleController
templates
 - accordion.html.twig
 - description.html.twig
js_example.info.yml
js_example.libraries.yml
js_example.links.menu.yml
js_example.module
js_example.routing.yml

I do not understand how the template description.html.twig and accordion.html.twig are retrieved.

I miss this piece to understand the example completely.

In which file do I find the configuration I am looking for?

Inside js_example.module there's a function which declares how a render array using a certain '#theme' is to be rendered as HTML and which variables might be available. This function is hook_theme. It also can define a template that Drupal will look for inside the module's template folder.

function js_example_theme() {

  return [
    'js_example_accordion' => [
      'template' => 'accordion',
      'variables' => [
        'title' => NULL,
      ],
    ],
  ];
}

Next there is the src/Controller/JsExampleController.php which has a function to output stuff and is told to use the 'js_example_accordion'-'#theme' for that.

  public function getJsAccordionImplementation() {

    $title = $this->t('Click sections to expand or collapse:');

    $build['myelement'] = [
      '#theme' => 'js_example_accordion',
      '#title' => $title,
    ];

    $build['myelement']['#attached']['library'][] = 'js_example/js_example.accordion';

    return $build;
  }

That's the basics.

The description.html.twig is used a little bit differently but maybe just skip that for now as its some kind of advanced exception you'll understand later.


Choosing between stable and development snapshot releases for a new high trafficked site After some research, I am planning to start the migration of a high trafficked site from Pressflow 6 to Drupal 7, as the current implementation (Pressflow 6 + 200 modules) is making it crawl. I've read that most of Pressflow 6 (if not all) performance changes have made into Drupal 7, and that's awesome. I will be starting the project in a day or 2 and I was wondering if I should be starting with the stable version (Jan 5, 2011) or the latest development snapshot.

There is a gap of over 3 months, and I am wondering if I will lose on fixes that made into the 7.x branch in these 3 months (that's a long time for a open source project so popular) and if a new stable release is around the corner.

I would also like to understand the impact on frequency of code updates on drupal core ( in case I use dev snapshot) and ways to manage it properly.

It's a difficult question to answer, because the status of a release (dev, beta, RC) is not necessarily a measure of it's stability, but rather an indication how well it has been tested before the maintainer released it. A module's dev version can (but does not need to be) more stable than the latest beta, RC or stable release.

IMHO, 200 is a huge amount of modules. If it's an option, consider reducing the number of modules. Often, 80% of a site's functionality is created with 20% of the modules, so the question is if the last 20% of functionality justifies the other 80% of modules.


How to create a page without any theme via custom module? I created a page using a custom module, it has a template file too and it works well. But when i visit my page it shows wrapped by my default theme, it's obvious. The thing is that i would like to show that content in a clean page.

Is there a function or something that lets me do it? without modules like ThemeKey

If you want to show content in clean page you can use theme_hook_suggestions in THEME_preprocess_html and THEME_preprocess_page with passing some GET variable.
For example for clean pages you can add $_GET['embed'] = 1 and in preprocess functions write the following code:

function THEME_preprocess_html(&$vars) {
  if (isset($_GET['embed'])) {
    $vars['theme_hook_suggestions'][] = 'html__embed';
  }
}

function THEME_preprocess_page(&$vars) {
  if (isset($_GET['embed'])) {
    $vars['theme_hook_suggestions'][] = 'page__embed';
  }
}

Then copy paste html.tpl.php and page.tpl.php and rename to html--embed.tpl.php and page--embed.tpl.php. Ultimately remove unnecessary code from template files.


Button in form not working properly I am unable to get a button to work as I intend it to in Drupal 7.

I am adding the button to the add content page of a specific content type using form alter:

function charlie_get_form_article_link_node_form_alter(&$form, &$form_state, $form_id) {

    $form['add_button'] = array(

        '#type' => 'item',

        '#markup' => '
            <script>
                function getArticleInfo() {
                    jQuery.get("articlegrabber.php?url=TEST", function(articleHTML) {
                        console.log(articleHTML);
                    });
                    return false;
                }
            </script>

            <button type="button" onclick="getArticleInfo()">
                Submit URL
            </button>

        ',

    );

}

I have simplified the articlegrabber.php file down to just this (though I don't think it matters, because the button click does not seem to be executing the JS):

<?php

$ogLink = $_GET['url'];

echo $ogLink;  ?>

Instead of my intended results (which the code delivers independent of its implementation in Drupal), the console logs the HTML for the add content page that the button is on.

I have read a lot about how Drupal likes to make all button types "submit", but my button is actually rendering as type="button". The HTML from the rendered page (as you would expect):

                    <script>
                        function getArticleInfo() {
                            jQuery.get("articlegrabber.php?url=TEST", function(articleHTML) {
                                console.log(articleHTML);
                            });
                            return false;
                        }
                    </script>

                    <button type="button" onclick="getArticleInfo()">
                        Submit URL
                    </button>

Any ideas about how to get it to execute the code on click rather than returning the HTML for the page would be much appreciated.

You need Simple Drupal AJAX load with jQuery and delivery callback  which is explained in  5 simple steps this page.

So include a anchor link through the form alter and have the link render the content through attached javascript file through jQuery.load() function.

To attach js file,

$form['#attached']['js'][] = array(
  'data' => drupal_get_path('module', 'module_name') . '/some_file.js',
  'type' => 'file',
);

For Drupal ajax forms refer this official documentation.


field->raw problem with date in views-view-field.tpl.php (add classes to day and year in date) I have a template (views-view-field.tpl.php) and I'm trying to get the raw value of the date field so that i can reformat it and add classes to each seperate part of it (ie day, date, year).

This is what I'm doing:

foreach ($fields as $id => $field)
{
if  ($id == 'field_date_published')
{
echo $field->content //outputs string to page as themed expected ie 23 Oct
echo $field->raw     //simply outputs 3 digits ie 234
}
}

My question is how can i get the raw value of the time so that i can manipulate day, month and year with specific css classes.

Please do not suggest i solve this problem in any way other than getting the raw data in the template file.  I know there are other methods to solve this but i have come to the limit of my understanding in the template file and need to find new avenues of learning to progress.

Thanks in anticpation,

This looks like a "feature" in views, for some reason the entity_id is returned in the "raw" property, instead of anything related to the date.
So you will have to work with the "content" property and just make sure you get what you need there - in the view fields settings, set formatter to "plain" and in style settings HTML to none. This way the content will be just the date value from the database.
Check what type of a date field you are using - some of them are stored in the database as the integer timestamp, some as the textual representation of the date. If you want to work with the timestamp, you will have to either change the type of the field, or convert it in the template (probably not very good performance).
For the formatting, you can use the DateObject from the date module, it even has the handy to_array which might be of help :).


How do I add an image field to my node.tpl.php template using render($content['field_example'])? I am creating a Bootstrap sub-theme and want to customize my node.tpl.php template. I have an image field with a machine name of 'field_poster'. According to the default node template:

$content: An array of node items. Use render($content) to print them all,
or print a subset such as render($content['field_example']). Use
hide($content['field_example']) to temporarily suppress the printing of a
given element.

So, doesn't this mean I can add print render($content['field_poster']); to my node.tpl.php and it will output the image, right? Well, I've tried that and it does nothing!
How can I get my image field to render in my template?
Update
My field_poster was set to display within a Field Group in Display Settings. This changes how things work in the template. See below for my solution.

Ok, so here was the problem. My field_poster was nested in a Field Group under display settings. Apparently, you need to include the parent field group if you want to render child fields outside the group.

So, if my container field group is named group_fieldgroup1 I need to use the following to render my field:

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

You can render the entire field group by using the following.

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


Only load Views Slideshow JavaScript when needed Does anyone know how to only load the Views Slideshow JavaScript on certain content-types, pages, or the front page?

If you want to only enable a Views Slideshow (or any other object) on certain pages, I recommend having Views output a block and then setting that block to display only on the necessary pages. It should only call the js (which should reside in sites/all/libraries) on pages that load the block. You can then set the block to display or hide by role, page, etc.


Get or Create a Node in a Custom Module This is my first time doing any custom module work in Drupal and need some advice.  I have a django background.

I am accessing data on an external non-Drupal server to display on the Drupal site.  I think I want to create a custom field type that holds the unique integer mapped to the data's ID on the external site.

  1) user visits /mymodule/1234 where 1234 maps to the external data
  source (not the drupal node)
  2) module performs a kind of
  get_or_create and either gets the node that matches the unique ID or
  creates one
  3) the user will see get a node returned to them (can
  handle comments, statistics, etc) that also displays the external data
  (which I will query via REST)

I'm basically asking for advice if this approach is tenable in Drupal and how to implement the get_or_create part of this if it is.

what I can imagine so far

First, custom module and a url handler:

<?php
function mymodule_menu() {
    $items['mymodule'] = array (
        'testing' => 'I am just testing',
        'page callback' => 'mymodule_view',
        'access callback' => TRUE,
        );
    return $items;
}

Then a custom view function to do the heavy lifting when user visits /mymodule/1234:

<?php
function mymodule_view($data_id = 0) {

    // custom REST function to get the data via the $data_id
    $data = get_my_data_cleverly($data_id);

    if (!$data) {
        //return 404
    }

    // not sure about this part
    get_or_create_node($data_id);

    // then return output to theme combining both node and $data
    // this is an oversimplified render array output that doesn't
    // work mostly because I don't understnand how Drupal does this yet
    $output =  array(
        'node' => $node,
        'data' +> $data,

    );
    return $output;

}

The result would be a node, with additional non-node information passed to the template.

Thanks

Create or use an existing content type for your nodes.
Add a field (field_ext_id) on the content type to track your external content id.
When building your page, use EntityFieldQuery (note that it may have performance implications on very large sites) to look for a node with field_ext_id = your id.
If no node found, create one:

$node = new stdClass;
$node->type = 'your_content_type';
$node->status = 1;
$node->uid = 1;
$node->title = 'my node';
$node->created = REQUEST_TIME;
$node->updated = REQUEST_TIME;

// set your other field values (including field_ext_id), as necessary

node_save($node);

// your new node's id is now available as $node->nid

For working with fields, have a look at Rendering Drupal 7 Fields The Right Way and Entity Metadata Wrapper.


moving *.tpl into "templates" folder, but Drupal does not recognize them. How? I am building a custom theme. Currently, I put all the overridden *.tpl files under the theme root folder; it would be more clean and meaningful to put those files under "mytheme/templates", but Drupal does not recognize them after I move them. (I did clear the cache.)

Did I miss any steps?

I've also run into a situation where I had to create a page.tpl.php file before Drupal would recognize other page--foo.tpl.php files.


Unset email address requirement on User Form not taking The scope of our project doesn't require users to have an email (they can use phone instead), therefore, I'm trying to unset the email requirement like so:
function my_module_form_user_form_alter(&$form, &$form_state, $form_id) {
   $form['account']['mail']['#required'] = false;
}

However, this doesn't seem to actually change the requirement because when I submit the form without an Email I still get the error Email field is required... I used kint to view the form object $form['account']['mail'] and it shows that the required attribute is set to false, yet I still get the error that it's required...
How can I make it so that I can save a user record without an email using this form?

The email field is one of the entity fields added by User::baseFieldDefinitions(), which sets it with a constraint.
$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

The UserMailRequired constraint does what its name suggest: It checks if the user's email address is provided if required. It isn't required if the account originally had no mail set and the user editing the account has the administer users permission.
That constraint needs to be removed from the entity field, to allow the email field to be empty. (It still necessary to mark the email form field as not required, though.)
use \Drupal\Core\Entity\EntityTypeInterface;

function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'user' && !empty($fields['mail'])) {
    $constraints = $fields['mail']->getConstraints();
    unset($constraints['UserMailRequired']);
    $fields['mail']->setConstraints($constraints);
  }
}


how to custom position drupal login field How do I custom position default login form that (in my case with BLUEMASTERS theme) pops up down below the title of the content page like: ABOUTUS. I want to position it in the sidebar.

Go to "Blocks" under "Structure" (admin/structure/blocks if I'm not wrong). You'll find the "User Login" block and you can position it where you want, depending on the theme you have. It might be named "Sidebar" or "Sidebar Left (Right)" or "Sidebar First (Second)".


Alternative admin-side content browsing - module? Does anyone know of, or is working on a Drupal 7 module which would provide alternative, hierarchical content browser on the admin side?

While the filter in the Find Content section is a great aid for unrelated pages, I'd really love to be able to browse through taxonomy-bound PAGES (rather than terms), just like I browse through folders and files in Windows Explorer or Mac's Finder.

What bites me most is that in default Drupal installation, the taxonomies are too much separated (in terms of managing and reviewing the content) from the actual pages. And the pages bound to vocabulary terms are browsable as unrelated ones.

I would be curious to see if anyone found a solution for that.
Regards,

Artur

I'm not sure if I understand what you're looking for in the admin pages, but I do know that Views is a great tool to build custom admin pages, especially when combined with Views Bulk Operations.


Why is the login redirecting to the access denied page? This question has been asked before but I see only D7 versions of the question, and none of their answers have helped me in D8.
I log in perfectly fine with Chrome or Firefox, but IE 11 redirects to the /user/1 page (or /user/2, or whoever you are logging in as) and states 'Access Denied.'  If you enter incorrect credentials it states "unrecognized user/pass," but if you enter correct ones it just does the redirect and nothing happens.
This is on a fresh install of D8 RC2 and what's worse is I can do a fresh install of D8 RC2 on a different server and IE 11 login works fine.  It's something about my server that's causing this. I thought it might be cleanURLs but mod-rewrite is on for both servers.
D7 solutions seem to say, check settings.php and the cookie_domain or base_url variables, but those don't seem to be a part of Drupal 8.
I have cleared IE's cache/cookies about a thousand times.

I had the same issue but for Chrome and this was caused by the old cookies since it perfectly worked on the other web browser (Opera). When I've removed old cookies while being on that page, it worked as well.

If this doesn't work on one browser, but not on the other, definitely it's related to the invalid cookies.

If this doesn't work for all web browser, then most likely it's invalid cookie_domain setting in your services.yml file. By default Drupal automatically generates a unique session cookie name based on the full domain name used to access the site and it's sufficient for most cases. However if you're re-using across different subdomains, then you need to set your cookie_domain.


How to export recent logs report in csv file drupal 7 Download all recent logs messages into csv file which is stored in database in Drupal 7
admin can filters records  and all records and filters records should be export in csv format

Assuming that you're looking for a module-driven solution to export the content of the 'watchdog' table, you could combine Views, Views Watchdog and Views data export.


Where is the Drupal Syslog module log file in Cpanel? I disable dblog module and want to enable syslog module instead of it.
After enabling that ,I can't see any drupal Log in error_log file in cpanel .

what is reason? where is Drupal log file for cpanel shared hostings?

My drupal version : 7

thank you

As mentioned on the documentation page for the syslog module, syslog is generally not suitable for shared hosting.

This is because it requires access to server level functionality and configuration that you aren't allowed to access on shared hosting.


Fetch user id on behalf of the non-drupal php I want simply to provide user id to php application that resides under my files/ folder. It is php that one flash app uses to create xml. This script, in my drupal root folder, works:

<?php
define('DRUPAL_ROOT', getcwd());
require_once '/var/www/drupal/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
$user_uid= $user->uid;
echo $user_uid;
?>

but when i try to include whole script in that php app in my files folder, it fails, with many include type errors.

I am searching for simple solution to provide that app with user id!

Thanks!

If you copy that code/file to another directory, DRUPAL_ROOT will be set to that directory, not that of drupal's... so I'd change up that first define to point to where drupal is and you should be all set.


Where do I store classes and ids that the user inputs in my custom module? I am creating a module that I would like to submit to the drupal.org repository. In the admin section of the module there are various input fields where the user is able to enter classes and ids for various elements that appear on specific nodes. It's basically a module that enables the user to do theming that would otherwise require custom code.

Since I'm not a Drupal rock-star in any way, and I have only worked in custom code and website specific modules, I have a very important question:

How do I store the classes/ids that the module's user will submit?

I guess that there are 3 options here:

Store the classes/ids in a module-specific table in the database
Store the classes/ids in the "Variable" table of the database
Store the classes/ids in a file, in the module's directory

I have some pros/cons in mind about each case (e.g. I don't like the idea that a theming element would be stored in the database) but I would like your input too: which one of the methods above is the best and drupal-friendly? If I missed an option, please feel free to list it.

Of your three options, 2 would be a huge burden to a site in performance, and 3 will likely be a security issue. So I'd go with 1.

For reference, see the Block Class module.


How to set different form displays for creating and editing an entity? I see we can configure multiple form modes for an entity bundle.

We want to utilize that to create two form modes for Image bundle of Media entity. One to use while creating a new Image media and other to use while editing existing one.

How can we achieve that?
Are there exist configuration ways to do it?

The media entity has already specific form handlers add and edit, so you can configure them right away.

Add both form modes to the media entity at /admin/structure/display-modes/form and enable them for the media type at /admin/structure/media/manage/image/form-display in CUSTOM DISPLAY SETTINGS.


Multiple aliases with single login I have three domains that are pointing to the same website like this:

example.com
example.org
example.net
All of those work from the same db.
But If I login to the example.com website and then go to example.org I have to login again.

The second question:
If I'm logged in example.com and then go to www.example.com I have to login again!
Is it a server that misconfigured or what should I do?

If you want a simple solution I can suggest what I did before is to redirect both domain.org and domain.net to domain.com using .htaccess redirect rule then all users will be reffered to domain.com first and then log in once there.

You need something like that in .htaccess (or simillar in your httpd configuration file):

RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com [NC]
RewriteRule ^(.*)\.html$ http://domain.com/$1.html [R=301,L]

Or do you need more complex set up and have separate 3 domains with single sign on ?
Then try to use Domain Access module (http://drupal.org/project/domain).


Create imagefield with maximum number of values programmatically I've created an imagefield in my own module, like this:

$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
      ),
    ),
);

Sometimes I need more heading images. Is it possible to make this field unlimited?

So you could click on a button: Add an other image. Something like this.

When scanning though the field definition of the media fields, you'll notice the multiselect property on line 118. Which gets the value of $multiselect from line 103:

$multiselect = ($field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED);

So in your definition you could try adding this multiselect property with an integer value (eg. 5 to allow 0-5 images), or FIELD_CARDINALITY_UNLIMITED.

$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
        'multiselect' => FIELD_CARDINALITY_UNLIMITED
      ),
    ),
);


How to allow anonymous user register Civicrm event without create drupal account I'm using D7 CiviCRM 4.4.6.

I had a civicrm event with profile fields for user to fill in.

Anonymous users are allowed to register the event and create civicrm profile.

But there is a "Username" field, which force anonymous user to create a drupal user account when registering the event.

Is there anyway which anonymous user can register in my event, creating profile, without create a drupal user account?

Edit the profile that you are using for the event registration and under advanced settings (at the bottom)

select "No account create option" radio and "save"

Good luck!


how to create categorized webforms in drupal? I want to create a multiple Forms in my site . so i am going with the webform module , i want webforms in such a categorized as display below ,
general inquiry  Forms

general feedback
general inquiry
Training request

Product  Inquiry Forms

Product 1 Inquiry

Product 2 Inquiry

Product 3 Inquiry

Product 4 Inquiry
Service

Service Request

service Feedback

online parts request
In this  general inquiry  Forms is like  a category and genaral feedback and inquiry is webforms. so how can i create that for prodcut inquiry and service categorized multiple form.

and there are many fields are common in that different form , so if i have to create different fields for different form or can i use one field in a multiple time in different forms.
Thanks,
vipul.

With Views, you can group the results by the value of a field, so create a field for your Forms and then group by that. You will have to get creative (custom templates) to get the numbering, if that's important to you.

As for sharing fields between Forms, I don't know of an easy way to do that.


Drupal 8, make comment subject a required field I am pretty new to Drupal and simply cant figure it out. I've set up a comment type for a content type. I want to use the default subject field as comment title and want to make it required.

I know, I could simply create a text field named "title" and make it required. But if I manage the comments in backend, there will always be (no subject) in the comments overview list. Is there any way to set it to required?

Thanks in advance!

Here is how, you will need to create a custom module , and add this ... to yourmodule.module file ...

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
  if ($form_id === 'comment_comment_form') {

    $form['subject']['widget'][0]['value']['#required'] = TRUE;

  }
}


How to add custom class to a  fileds on the renderable array of user_profile_form I have a requirement to add a class to  ul  li  on the user_profile_form edit page on admin side.
Using Hierarchical Select Taxonomy module regions are listed on this form.The purpose is to modify  the listing of the regions by adding different classes for the regions based on the taxonamy id.

You can do it 2 ways. One is to modify the element attributes, like this:

$form['textfield'] = [
  '#type' => 'textfield',
  '#attributes' => [
    'class' => [
      'ul',
    ]
  ],
];

Or, another way, wrap the elements with '#prefix' and '#suffix'.

$form['textfield'] = [
  '#type' => 'textfield',
  '#prefix' => '
',
  '#suffix' => '
',
];

I would use the first preferably when I can.


Add show more/read more to CKEditor Drupal How can I add a button to CKEditor so users can use read/show more in their editor.
This would help me a lot.
I have looked in a lot of places, but no succes.
I am no programmer, so I'm not familiar with drupal/php code.

I don't think this is possible within CKEditor and even if it's possible you need to make sure that your theme understands the tags inserted by CKEditor which is not always the case.

This is because when the text content is displayed on the theme layer CKEditor is not involved at all at that point and Drupal, the Text Formats you define, views if configured, and the theme layer take care of displaying the text.

Possible solution: by default Drupal gives you the body text as "Long text and summary" with the widget "Text area with a summary" and hence your editors, by default, can click on "Edit Summary" on top of the editor to input summary text. I highly recommend you stick to inputting the summary text here and then the "read more" text in the body as most themes and views use that functionality by default. Some don't, but I see this as standard most of the places.

Good luck.


how to add newsletter subscription during registration? Here what I want to do. I loaded a checkbox list of taxonomy term on the registration form. Also I have a check box for "subscribe newsletter". so the user can check the his favourit taxonomy and "subscribe newsletter". I want to know how can I alter the submission of register form to gather this data?

you can achieve this either by using Mailchimp Module

                          OR(by custom coding)

You can alter your registration form using hook_form_alter. Now in your form you can add add two new elements that is :-

A checkbox saying- Signup to receive alerts.
A text field to capture email address.

Now you can override your form on submission and pass the email captured above to mailchimp function that adds users to email lists via ajax call.

Hope this helps!!!


How to unblock my own admin account after 5 failed login attempts? I entered the wrong admin password more than 5 times, so Drupal has blocked my entry.

I've change the user password directly in MySQL and then tried to login, but is still doesn't work. Also, if I click the request new password link, I don't get an e-mail.

How can I unblock my account?

To answer the question in your title (which appears to become more complicated following your actual question), you just need to clear the flood table in your database.  If you're running Drush, then the following should sort you out:

  drush php-eval 'db_query("DELETE FROM flood");'

Failing that, just clear the flood table from your database manually :)


How to set an AJAX callback for my drop down list select in my form? I am about to create a filter views handler extended from views_handler_filter_string
(you can see the class under views/handlers), so I have to override my method value_form to create a new value form form my filter handler.

function value_form(&$form, &$form_state) {
    $countries = _prepare_countries_list();
    $selected_country = isset($form_state['values']['value']['country'])?$form_state['values']['value']['country']:key($countries);

    $values = array(
        'country' => array(
            '#type'    => 'select',
            '#title'   => t('Country'),
            '#options' =>$countries,
            '#ajax'    => array(
                'callback' => 'country_state_dependent_dropdown_callback',
                'wrapper'  => 'dropdown-states',
            ),
        ),
        'state' => array(
            '#type'    => 'select',
            '#title'   => t('State'),
            '#prefix' => '
',
            '#suffix' => '
',
            '#options' => _country_state_get_second_dropdown_options($selected_country),
        ),
    );
    $form['value'] = $values;
    return $form;
}

I am trying here to set an ajax callback for my drop down list select. Usually we implement our callback function and we return $form['element'], but in my case it gives no result.

Anyone who has tried to override the value_form before to add some AJAX able to help me resolve this issue?

This is untested but at least, you get the logic. I'm sorry if I edited your coding style convention.

function value_form(&$form, &$form_state)
{
    $form = array();

    $countries = _prepare_countries_list();
    $selected_country = isset($form_state['values']['country'])?$form_state['values']['country']:key($countries);

    // Country dropdown list
    $form['country'] = array(
        '#title' => t('Country'),
        '#type' => 'select',
        '#options' => $countries,
        '#ajax' => array(
            'event'=>'change',
            'callback' =>'country_state_dependent_dropdown_callback',
            'wrapper' => 'dropdown-states',
        ),
    );

    // Wrapper for state dropdown list
    $form['state_wrapper'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );

    // State dropdown list
    $form['state_wrapper']['state'] = array(
        '#title' => t('State'),
        '#type' => 'select',
        '#options' => _country_state_get_second_dropdown_options($selected_country),
    );

    return $form;
}

/**
* Function for handling ajax request
*/
function country_state_dependent_dropdown_callback($form, $form_state){
    return $form['state_wrapper'];
}


Twig templates for nodes in different views I have a content type, blog_post, that is displayed by a number of different views.

I'm having a problem that the node template that gets used first after clearing the cache will then be used for all other views.

For example one page displays a view called "Blog Posts". If I load this page after clearing the cache, it correctly uses the template node--view--blog-posts.html.twig.

Another page uses the view "Latest Blog Posts", and this should use the template, node--view--latest-blog-posts.html.twig. However if I load this page without clearing the cache first, it uses the node--view--blog-posts.html.twig template.

If I clear the cache and reload the second page, it will then use the correct template, but if I go back to the first page, it will be using the template for the second!

I have twig debugging enabled, and it shows the wrong view name under "FILE NAME SUGGESTIONS" as follows:

<!-- FILE NAME SUGGESTIONS:
   * node--view--blog-posts--page.html.twig
   x node--view--blog-posts.html.twig
   * node--20--teaser.html.twig
   * node--20.html.twig
   * node--blog-post--teaser.html.twig
   * node--blog-post.html.twig
   * node--teaser.html.twig
   * node.html.twig
-->

I expect that lots of other sites theme nodes in multiple views, so I expect I'm done something wrong. Any suggestions how I can debug this?

Do not use node--view-* templates. They are broken.

Two views with entity view mix up rendered templates

The quick solution:

create unique view mode for your CT
display views with content
use unique view mode for your view


How to display the node id as a field (with label) This question is really simple, i need to use the node id as an identifier and so i need to display it whenever a certain content type is shown. What's the best way to do this?
i need to display the node with label and so on, i just don't want to make a custom field for something that's already a field.

Create a template for the content type and use <?php print $node->nid; ?>

Make a copy of node.tpl.php from modules/system and paste in your theme directory.  Copy the code from inside node.tpl.php and create a new file called "node--YOURTYPE.tpl.php" (replace YOURTYPE with the name of the content type).

Inside that file you can place <?php print $node->nid; ?> wherever you want the nid to be seen.  You can add a label, wrap it in HTML to style it, whatever you like. Save the file and clear the cache to see the changes.  Take a look at a node of that content type and you will see the node's nid.


Is it possible to run a Drupal 7 site without jQuery? Possible Duplicate:
  Remove jQuery and find out what is asking it to be included

I'm building a simple site that is focussed on performance and must run well on mobile and other low-power devices. I want to avoid jQuery if I can, and want to know if it's even possible or whether it's simply a compromise I'll have to live with. I don't want to start building with jQuery removed and have to carefully engineer things to avoid it, only to find I'll need it later, thus wasting effort better spent elsewhere.

If it can be removed, are there any gotachas? Any modules to avoid? Anything else to bear in mind?

Another thought: Can it be restricted to certain pages only, where the interaction it provides is required?

UPDATE

There is a similar question that also touches on the issue of jQuery dependency, but where that one broadly asks about dependency tracking and CSS files and theming, this one is focussed on the feasibility of removal of jQuery in Drupal and its performance implications. The accepted answer here is substantially different from the one there, as is the theme of the discussion here. Therefore I'd argue that this is not a duplicate and offers value to the community.

jQuery is part of Drupal core - and because of this, you can't tell WHAT contrib modules are going to be using it.  Well, you can, but it'd involve checking any included scripts of any module. Also, you wouldn't remove poll.module or blog.module just for server side performance if you're not using them - I would suggest the same applies to jQuery.

I don't think removing jQuery is an option at all realistically, it's not worth the hassle of even trying.

The following, however, are MUCH better options.

For starters, get your hands on the jQuery Update module if you're not using it already. One of the best things you could do to improve jQuery performance is use the most up to date version of the library possible.

Next, try Boost:.

  Boost provides static page caching for Drupal enabling a very
  significant performance and scalability boost for sites that receive
  mostly anonymous traffic.

or Varnish if you are on a dedicated hosting plan and have the resources to set it up (Drupal module here).

Serving static HTML pages will take substantially less time, than serving a full dynamic page.

Lastly, if it's a REALLY simple site, evaluate whether or not you even NEED Drupal?

Could you perhaps use a Drupal back-end to manage your content and combine it with the Services module to supply your content to a more performance focused site with a lightweight framework such as Laravel?  I've run into situations before where I've used Drupal because "IT'S WHAT I KNOW DAMMIT", where I could realistically have used a much lighter framework and removed a lot of overhead.

EDIT

I forgot to mention the performance tag.  Check out other questions tagged with performance and there will be a plethora of people who might have similar front-end performance issues/ideas!


How do I remove required fields (or a required attribute) from customer profile in Drupal Commerce? I only need customer to fill in name, phone and MAYBE address. Is it doable in Commerce?

The only data required for the commerce profile is defined by the fields you attach to it. By default that is the addressfield. You make the field required or not required, which will result in some fields being required or not required.

You have two ways of solving this. You can either change the behavior of the address field by creating a plugin (code).

Or you can choose to only store the address in the address field and make it options and create a separate field for name that you can make required.


How do I update a field value in hook_entity_insert()? I want to update an field in hook_entity_insert(). The following code doesn't work.

$entity->field_range->value = 'test';
$entity->save();

I also tried loading from node object, but still it doesn't work.

$node = \Drupal::entityManager()->getStorage('node')->load($entity->id());
$node->set('field_range', 'test');
$node->save();

After inserting the node only I will get the text "test" dynamically and it won't work in hook_entity_presave().

Any help on how to update an field on hook_entity_insert will be nice. Thanks in advance.

From this solution we can able to do like below to update an field on hook_entity_insert

$entity->field_range->value = 'test';
drupal_register_shutdown_function('_cc_custom_post_insert',$entity);

function _cc_custom_post_insert($entity) {
    if($entity) {
        $entity->save();
    }
}


Disabling authoring information in Omega 3.x does not work from content type; how can I disable it? I see no way of successfully disabling, through the user interface, the author information, wheb using an Omega 3.x sub-theme. The standard method of disabling it from the content type settings is not functional.

So is my only option to use a theme suggestion?

Don't know how exactly it looks in your Omega theme, but in Zen you just remove/change the following snippet in templates/node.tpl.php (or templates/node--content_type.tpl.php):

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

In Bartik it's equivalent would be:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php print $submitted; ?>

<?php endif; ?>


Views 3.8 hook_views_default_views() stopped working I have a default view made using the views hook hook_views_default_views().

It was working right and when I updated to Views 7.x-3.8 it stopped working.

It is not shown in structure -> views, the routes don't work too (site_url/calendar)

Seems the hook is not launching, or if it is, it does not load the view.

Updated drupal to 7.31 version, and CTools to 7.x-1.4.

Erased all the caches, drupal, views, memcached.

And it is not working.

The code looks like this:

// code included in my_module.views_default.inc
function my_module_views_default_views()
{
  export = array();
  $view = new view();
  $view->name = 'planning_calendar';
  $view->description = 'Calendar with planning dates';
  $view->tag = 'Calendar';
  $view->base_table = 'node_revision';
  $view->human_name = 'Planning Calendar';
  $view->core = 7;
  $view->api_version = '3.8';
  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

  // view code ......

  $export[$view->name] = $view;
  return $export;
}

There is also this hook on the module:

// code included in my_module.module
function my_module_views_api() {
  return array("api" => "3.8");
}

See the API documentation: The correct way to declare the version is by the major number only (i.e. an integer) not the entire version as a string.

// code included in my_module.module
function my_module_views_api() {
  return array('api' => 3);
}


Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website! Every time I use a redirect from an URL alias i receive the foloowing report of:

Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!

Ive tried clearing all the cache and ran cron.

I've tried searching everywhere and can't seem to fix it. Thank you kindly for your support.

This is because you're using the Redirect mudule, this issue has been posted here already.. Installing the latest dev version, and applying this patch should fix it..


Workbench section PHP assignment I have problem similar to this one.

I want assign node to section while being created. During php node creation I use:

    $node->workbench_access=array('1067');

which should assign node to certain section, but after script execution I see "Section: Unassigned".

When I do separately:

$node = node_load(823);
$node->workbench_access=array('1067');
node_save($node);

..it works. Section gets assigned. As I read Workbench access there might be some bugs preventing this from working (comments like "// Workbench Moderation submits the node twice???" and deleting of redundant nodes?)..

If it was matter of 1 node I would drop it and use second code.. But it seems like I need hundrets of nodes to be created at once so I'd rather avoid loading and saving node only for section assignment.

Where are you doing the call to workbench? Have you tried doing the call in the postprocess of the node creation. Maybe you don't have the proper database object yet when you do it?


Can I clear cache only for particular domain / URL? I'm using domain module with several domains. With drush you can clear cache using cc command. I have only one database for all domains.

I'm wondering can I clear cache using only specific domain (with -l option) if I'm using same DB for all domains?

e.g: $ drush -l http://www.example.com cc all

With just core this is not possible. If you where to write your own cache backend then what you're asking for could be done. An example of a custom cache backend is http://drupal.org/project/adbc


How to handle duplicate .module files that live in 2 places? I have not used Drupal before and have been thrown a project to fix up some things.

But I noticed the file I need to edit lives in two places:

one in includes/jobs.module.
another one in sites/all/modules/jobs/jobs.module.

Is one meant to be a sym link of the other or something? As this is not the case in the project I have been given. What file should I be editing?

I'm sure this is basic stuff for and Drupal dev. An suggetions?

There shouldn't be a job.module in the includes directory at all, your module files for your job module should all be in sites/all/modules/jobs.

You generally shouldn't put anything in (or modify anything in) the includes directory or you will make it harder for yourself to upgrade drupal core in future.

I would say you should:

check for any differences between the two files.
If they are different determine whether or not anything in includes/jobs.module should be in sites/all/modules/jobs/jobs.module. If so add it.
Delete includes/jobs.module


Drupal 7 Migrate: How do I migrate a mult-field key into a single taxonomy term Background:
I am doing a migration on Drupal 7 using Migrate 7.x-2.5.  And I am migration a Sql table into a Drupal taxonomy.  The key to my source SQL table is comprised of three fields:  element_id, scale_id, and category.

The taxonomy term name must be element_id-scale_id-category so that I can properly reference the taxonomy.  Here is some sample data:

3.A.1   RW   1   None
3.A.1   RW   2   Up to and including 1 month
3.A.1   RW   3   Over 1 month, up to and including 3 months

So the taxonomy name for the first line above will be "3.1.1-RW-1" and the description will be none.

Here is my code so far:

$query = Database::getConnection('default', 'external_db')
         ->select('ete_categories', 'ete')
         ->fields('ete', array('element_id', 'scale_id', 'category', 'category_description'))
         ->orderBy('element_id', 'ASC');

// Create the source data feed using the variable $query

$this->source = new MigrateSourceSQL($query);

//       D E F I N E       T H E       D E S T I N A T I O N

$this->destination = new MigrateDestinationTerm('ete_categories');

//       D E F I N E       T H E       K E Y S

$this->map = new MigrateSQLMap(
  //  We have to tell migrate what the source key is
  $this->machineName,
  array(
    'element_id' => array(
      'type' => 'varchar',
      'length' => 20,
      'not null' => TRUE,
      'description' => 'Element Id',
    ),
    'scale_id' => array(
      'type' => 'varchar',
      'length' => 3,
      'not null' => TRUE,
      'description' => 'Scale Id',
    ),
    'category' => array(
      'type' => 'decimal',
      'length' => 3,
      'not null' => TRUE,
      'description' => 'category',
    ),
  ),

  MigrateDestinationTerm::getKeySchema()
);

//       M A P       T H E       F I E L D S

//  So let's map the fields

$this->addFieldMapping('name', CONCAT(`element_id`,'-',`scale_id`,'-',`category`));
$this->addFieldMapping('description', 'category_description');

My Question
I can concatenate the three fields into one using command line SQL.  However, I do not know how to do this within the confine of the migration modules.(I realize that the code "CONCAT(element_id,'-',scale_id,'-',category))" is not valid migration code.)

So how do I concatenate the three fields together into a single field and set the destination field "name" equal to the concatenated fields?

Thanks

In your migration class, you can override the Migration::prepareRow() method to add a new name field to your rows:

  public function prepareRow($row) {
    $row->name = "{$row->element_id}-{$row->scale_id}-{$row->category}";
    return parent::prepareRow($row);
  }

And then simply map that field:

    $this->addFieldMapping('name', 'name');

But for simple concatenation, you can also use SelectQuery::addExpression() to add the CONCAT(...) to your SQL query:

    $name_alias = $query->addExpression(
      "CONCAT(element_id,'-',scale_id,'-',category)",
      'name'
    );

And then simply map the expression to the name field:

    $this->addFieldMapping('name', $name_alias);


How can I provide an optional link to a Forum from a node (D7)? I have custom node types 'foo' or 'bar', and each node should have its own associated forum you can easily navigate to from that node. I was hoping to eventually use the rules module to generate the forum upon 'foo' or 'bar' creation.

To both 'foo' and 'bar' I've added a custom Term reference field which is validated against the Forum taxonomy, and I have not marked the custom field as required. But when trying to save any of these content types, it's making this forum reference required. Why?

Possibly related - when I add this custom field to a pre-existing content type and then view a node of that type, I get the following error:

  Notice: Undefined property: stdClass::$forum_tid in forum_node_view() (line 271 of modules/forum/forum.module).

And if I try to edit, I get the following errors:

  Notice: Undefined index: und in advanced_forum_type_is_in_forum() (line 1038 of sites/all/modules/advanced_forum/advanced_forum.module).
  Warning: Invalid argument supplied for foreach() in advanced_forum_type_is_in_forum() (line 1038 of sites/all/modules/advanced_forum/advanced_forum.module).

(Yes, I'm also using Advanced Forums, but I think this is more fundamentally a base Drupal 7 Forum module issue.)

This topic (which is marked as a duplicate of this) is as close as I could come to finding a similar error, but seems to imply that I'm trying to save a forum node (as opposed to 'foo' or 'bar') without linking it to a forum term (forum or container). Which makes some sense as when I do provide a valid value to the custom Term reference field, the 'foo' or 'bar node will show up as a thread in the associated forum and the breadcrumb on node 'foo' or 'bar' acts like a forum node breadcrumb. However, I really don't want my 'foo' node to act like a forum node.

So I'm guessing that trying to link to a forum from an arbitrary node using a Term reference custom field is a Bad Idea. How can I do this without hardcoding a URL?

Use entityreference. Create a rule that generates the forum on node creation and then an action that creates an entity reference in the original node.


Can we configure Devel module to pick up images for the image field of a content type only from a specific directory containing images? A Yes or No question.
Using Drupal 7.43. Devel module generates polycolor image content of a content-type which has an image field. But I need only a few specific images on my contents of that content type and I need Devel module to pick up images from a specific directory on my system(in the same drupal environment directory) and then randomly associate them with contents. Can this be done by changing Devel's configurations? Suggestions are welcome for alternative solutions to this problem.

Yes.

There are at least two modules providing this or similar features:

https://www.drupal.org/project/realistic_dummy_content
https://www.drupal.org/project/devel_image_provider

HTH


drupal_render($node_view); is not working Node page is not loading once I add below code

 drupal_render($node_view);

I was referring https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_view/7
and added below code in my node--type.tpl.php

<?php
  $node = node_load($nid);
  $node_view = node_view($node);
  $rendered_node = drupal_render($node_view);
  echo $rendered_node;
?>

As I don't have the Drupal sources at hand right now, I didn't digg into it yet. But I'm pretty sure the node_view() function is using your node--type.tpl.php for rendering its output.

So calling it within your template will lead to a recursion. You might want to check on that.


How to access data from a page on a form hook? I have a page that has a $_GET and I would like to use that value on the form that is used on that page, but I do not know how to pass a variable to that form for use. usually I can just get the data from elsewhere, but the $_GET is NULL when I run it in the form itself.

function mymodule_menu() {

   $items = array();

   $items['sample'] = array(
    'title' => 'Title',
    'description' => '',
    'page callback' => 'mymodule_page',
    'access arguments' => array('access content')
  );
}

function mymodule_page() {
    $variable = $_GET['variable'];
    return theme('mymodule_page', array(
       'form' => drupal_get_form('mymodule_page_form'),
       'variable' => $variable
    ));
}
function mymodule_page_form(){
    var_dump($variable); <-- not defined.
}

I tried variable_get and variable_set, but it's not reliable because it seems to hold values for a while.

By default variables defined in one function aren't available in any other functions (see PHP: Variable scope), which is why your variable is undefined in the form function.

You can declare $variable as a global (see the link above) to make it available in both your functions:

function mymodule_page() {
    global $variable;
    $variable = $_GET['variable'];
    return theme('mymodule_page', array(
       'form' => drupal_get_form('mymodule_page_form'),
       'variable' => $variable
    ));
}
function mymodule_page_form(){
    global $variable;
    var_dump($variable);
}

But to be honest there's no good reason why $_GET would be empty when it reaches your form function, so it might be worth seeing if you can find out why that's happening.


media_youtube plugin doesn't work with ckeditor 4.3.x I try to setup D7 + ckeditor 4.3.x in conjunction with wysiwyg + media (v1) modules.

Everything is ok for text edition and image insertion with the media browser button in ckeditor.

The problem is: I try to add the media_youtube plugin and videos do not show in content. Instead I have a placeholder.

Downgraded to ckeditor 3.6 and everything worked perfectly again.

But I'd like to keep the new features in the newer version of ckeditor.

Any idea what the problem could be?

thks

pl.

This just may be a temporary problem with the editor, or a preference setting that may be overlooked. I know the Media module and related modules have had some significant updates and changes, so if that preview feature was unreliable at some point then deactivating it would be the right solution until a better solution comes around.


drupal files directory I have a Drupal site and I am unsure of how the files directory works.

It seems at the moment all files uploaded to the site go to the files directory. If I create a new node and upload fish.png which goes to the files directory another user also uploading a file called fish.png will overwrite my file.

Have I missed something here???

You can see the how to set the file system settings on File system settings. You can also change it, and specify the other folder for the files as per your requirement.


How can I ensure that a user account on my local dev server has the same uid as an account on my production server? I have a local dev server that I use for testing and a production server.  I have written several rules (with the rules module) that send private messages (using the private message module) to users.

I want these messages to be sent from a special administrative support user; the problem is that this user has a uid of 7 on my local site and 9 on the production site.

Since I am still early in the development process, it is simple enough for me to reset the databases and start over so that the uids are in sync.  However, since this may come up again at a point where it is not convenient to reset, is there a good way to ensure that accounts on different servers have the same UID?

It's not currently possible to export Users into a Feature.

There's an open issue for adding support to uuid_features.module.


Using field_create_field and field_create_instance to add a checkbox to a content type I've written the following update hook to add a field to a content type. In an ideal world I'd like that field to be a single on/off checkbox. However, the code I've written outputs three radio buttons - with options for Yes and No, as you'd expect - but one for NA, too. I don't really want my users to have an NA option. Any idea how to achieve this? I'm guessing it's either the widget or display attributes, but I don't know where to find a list of what options are available to me.

Update:

Marcel's suggestion worked just fine - it doesn't provide a checkbox, but it removes the NA option, and that's good enough for me. Adapted code is below - I've also made some changes to the rest of it that ensure the title and summary text are displayed properly in the editor UI:

$field = array(
  'field_name' => 'field_maxy8',
  'type' => 'list_boolean',
  'settings' => array(
    'text_processing' => 0,
  ),
  'widget' => array('type' => 'options_onoff'),
  'settings' => array(
    'allowed_values' => array(
      '0' => 'No',
      '1' => 'Yes',
    ),
  )
);

$field = field_create_field($field);

$instance = array(
  'field_name' => 'field_maxy8',
  'required' => 'true',
  'label' => 'Maxy 8',
  'description' => st('Maxy 8'),
  'entity_type' => 'node',
  'bundle' => 'article',
  'display' => array(
    'teaser' => array(
      'label' => 'hidden',
      'type' => 'hidden',
    ),
    'default' => array(
      'label' => 'hidden',
      'type' => 'hidden',
    ),
  ),
);

field_create_instance($instance);

In order to use this you'll need to:

1) Put it in a <modulename>.install file

2) Put it in a hook_update_n function

3) Save it, and run UPDB through Drush

This is how you create a single boolean checkbox field and field instance: I have excluded checking whether the field or instance exists, for brevity.

field_create_field(array(
  'field_name'  => "my_bool",
  'type'        => 'list_boolean',
  'cardinality' => 1,
  'settings'    => array(
    'allowed_values' => array(
      /*
       * The docs say that this is optional, but without it,
       * the value is never saved to the datbase (tested with Drupal 7.28)
       */
      0 => '',
      1 => '',
    ),
  ),
));

field_create_instance(array(
  'field_name'  => "my_bool",
  'entity_type' => 'taxonomy_term',             // or 'node'
  'bundle'      => 'my_vocabulary_machine_name, // or 'my_content_type'
  'label'       => t('My boolean checkbox'),
  'required'    => false,                       // because not ticking a checkbox omits the value from $_POST
  'display'     => array(
    'default' => array(
      'type' => 'hidden',                       // optional. I want to hide it
    ),
  ),
  'widget'      => array(
    'type'     => 'options_onoff',              // gives you a checkbox
    'settings' => array(
      'display_label' => 1,                     // uses 'My boolean checkbox' as the label next to the actual checkbox
    ),
  ),
));


What's the difference between private message & message? In my user backend I have a tab named 'messages' (mysite.com/user/uid/messages) and a second named 'Private messages & invitation' (mysite.com/user/uid/contacts).

For what I see private messages is where users can message each others when there are trusted contact.

Now I want to know the use of 'Messages'. Also I've seen that there is two modules message & Privatemsg.

By using the Message module, you can create your own custom "Events logging" (to register things that happened in a site).

A great sample of this you can find in Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

The Message module is an amazing module, though there is not a lot of documentation about it. It is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules. And to give you an idea of the kind of things you can use it for, have a look at the answers to:

How to create a basic message - notifications system displaying a real time message counter badge?
How to show message view containing own and following activity?
How to integrate messaging into a custom module?
Is there a simple way to notify users about new posts on the site?


Error when I edit a block: Notice: Undefined index: und in eval() I don't understand why I put $node->field_test['und'][0]['value'] appears the next error:

  Notice: Undefined index: und in eval()

The field "field_test" is a boolean field. The code is the following one:

$node = node_load(153);
if ($node->field_test['und'][0]['value'] == 1) {
  echo "test";
}

What is my error?

You must pay attention to the node's language. 'und' is for nodes which don't have a language set. If you set one, then the values will be in 'en' or 'de' or whatever the node's language code is.


Media module browser iframe opens with wrong domain I have a site that is accessible from a subdomain and www. and when accessing from the subdomain the media module's file browser for file uploads/library opens using the wrong domain and so it fails due to security risks for cross domain iframe access. All I get is a white empty box in the modal. On the main site with www. it works fine.

I'm sure this is a fairly common problem, but I'm unable to find anything.

Anyone able to offer some help?

This ended up being caused by a custom module we had on the site that performed url inbound and outbound alters to direct certain node types, paths etc. to certain domains. All we needed to do was add an exception to the handling for media paths.


How I can change the value of a commerce product field after Completion process? I want to change the value of one of my product custom fields when "Checkout completion". I created that custom field myself, with machine name field_prodstat.

How I can do that with the Rules module?

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

Create a custom rule (using the Rules module) like so:

Rules Event: checkout completion event.
Rules Condition: entity has field, for the field with machine name "field_prodstat" (which will make that field available as a token you can select in subsequent Rules Events and/or Rules Actions).
Rules Action: set a data value, for the field with machine name "field_prodstat".

Update

Below is an attempt to also address your comment below this answer, the relevant part of that comment is like so:

  I have a content type called "Appointment". When that appointment status = "Accepted Pending Payment" I created a rule to build a new product for that "appointment". So now I have a product related to that appointment. I just want to update "Appointment" status to "Paid" when his product appear in an order with status = invoiced. I don't know if you have any other proposal to do that.

That comment starts revealing your real question, which is pretty different from your original question. To answer your real question is not something that can be explained in just a few phrases. I suggest you have a look at the video tutorial about Removing Items From the Cart Using Rules which demonstrates a scenario which is pretty similar to what you're asking for (in your extra comment). Here is part of what is shown in that video (quote is from that link):

  Create a rule that loops through all the line items when the order is about to be saved. Have it call a component (rules subroutine) for each line item to see if that line item should be removed.
  Create the component that does the work. It needs to take two arguments (line item and the order-about-to-be-saved).

To make this also work for your case, I think you'd be close if you only replace the last Rules Action in the used Rules Component by a Rules Action that applies the update you're asking for in your comment.


Commerce View + Multiple products on product_reference field i'm having troubles at making a custom view of some products i have in my commerce.

Here is a simple example:
I have 1 T-shirt, with 4 colors. Each color has it's own price (they are all different), and it's own images (4 images per t-shirt).

Now, i need something like this

And my real design is this one

I just seen, that Views can't be used since there is now way to replicate the default node functionality, since every field won't refresh (remember there are 4 variables...prices and images)

I can use a "custom node-type.tpl.php", and make some custom "field-field-name.tpl.php" too, to make my design.......BUT how do i add an image gallery per product???

hope it's clear, i do not speak english.
thanks for everthing.

If anyone need an image gallery for commerce, and you have a node referencing multiple product which have multiple images, Image zoom is the correct module.


Drupal cron is running very frequently Drupal cron is running every 10 minutes in my site but i have set-ed 1 day time for cron,
i have cleared cache and fix all the major php error logs, please help me how to fix this issue.

i have set-ed 1 day time for cron

Presumably you mean you've set the "poor man's cron" value at admin/config/system/cron to 1 day - that value controls how often Drupal will run cron itself as a reaction to people actually visiting pages; it's not full-automated, hence "poor man's".

Assuming the value is being persisted (i.e. you don't have a global conf override or something for that var), then Drupal will respect it, and only run cron itself when more than a day has passed since the last run.

If it's still running every 10 minutes, then you have another process somewhere doing that - not Drupal.

Check your crontab/pingdom account/your usual alternative to find the culprit. If it's being invoked via URL, not drush/other script via crontab, then you can enable/inspect access logs to get an idea of where the request is coming from. Pingdom's IP ranges are public, for example, so you'd be able to determine if it's coming from there easily enough.


Google Page Speed Insights recommends Leverage browser caching Google complains on leverage browser caching on the following files:

Leverage browser caching for the following cacheable resources:
https://www.googletagmanager.com/gtm.js?id=GTM-xxxxxx (15 minutes)
https://www.googleadservices.com/pagead/conversion_async.js (60 minutes)
https://www.google-analytics.com/analytics.js (2 hours)

I have the following in my .htaccess file which should set all files to 2 weeks:

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

I verified that I have the mod_expires module enabled.

In Cloudflare I have Browser Cache Expiration set to 2 hours.

As these files ain't located on your server you can't do anything about it except wondering why Google Page Speed isn't smart enough to distinguish between on-site resources and external resources. Or why Google itself doesn't do with these files what it suggests should be done with them. I guess, that's some weird kind of paradox ;)

All you could do (highly hypothetically) is to download these files and  add them to your own server and let Drupal use these local copies instead of the remote files. But I assume very strongly that this would break the functionality of these services.


error SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry I'm currently migrating my website to D8 and I'm having some issues updating my NEW nodes to match with my live D7 site.
I get a few of these for each content type. I think it's from creating "test page" and the node ID is taken.
I get a few of these warnings:
 [error]  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'e0891884-4da7-45c9-a1b5-808c8f821cfa' for key 'node_field__uuid__value': UPDATE {node} SET vid=:db_update_placeholder_0, type=:db_update_placeholder_1, uuid=:db_update_placeholder_2, langcode=:db_update_placeholder_3
WHERE nid = :db_condition_placeholder_0; Array
(
 [:db_update_placeholder_0] => 61287
 [:db_update_placeholder_1] => festival
 [:db_update_placeholder_2] => e0891884-4da7-45c9-a1b5-808c8f821cfa
 [:db_update_placeholder_3] => und
 [:db_condition_placeholder_0] => 3943
)

I tried drush migrate-import upgrade_d7_node_festival --update , but that didn't work. Is there a way to overwrite my test nodes when migrating? Do I have to go and delete all the table nodes in my DB then rerun the migration?
Thank!

sadly there is no "vanilla" way in migrate / migrate_tools / migrate_plus, to achieve this, at least that i know of.
I think the best solution is to create a custom plugin and append it to your yml file at the uuid field.
I should probably look something like this.
Disclaimer: The following snippet is derived from https://www.drupal.org/project/migrate_plus/issues/3060320 and modified to suit your case specifically. It is not tested though.
<?php

namespace Drupal\your_module\Plugin\migrate\process;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Skips processing the current row when a same entity already exists.
 *
 * Examples:
 *
 * @code
 * process:
 *   name:
 *     plugin: skip_on_duplicate_entity_exists
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "skip_on_duplicate_entity_exists"
 * )
 */
class SkipOnDuplicateEntityExists extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $storage;

  /**
   * EntityExists constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityStorageInterface $storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->storage = $storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      // Use configuration instead of "node" for a mode generic solution
      $container->get('entity_type.manager')->getStorage('node')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $entityQuery = $this->storage->getQuery();

    $existingEntities = $entityQuery
      ->condition('uuid', $value)
      ->execute();

    /* The result is either an entity id string,
    or an array of entity id strings.
    If either one is not empty, there's a duplicate. */
    if (!empty($existingEntities)) {
      throw new MigrateSkipRowException();
    }

    return $value;
  }

}

You can find more on custom migrate plugins here https://www.drupal.org/docs/8/api/migrate-api/migrate-process/writing-a-process-plugin.
Let me know it it helped, or if you need any further assistance / clarification.


Can't get drupal_array_get_nested_value to work I'm trying to use this helper function drupal_array_get_nested_value  and I can't seem to get it to run.  http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_array_get_nested_value/7  I have a specific field type I am looking for, and I can find it using a recursive array search, but I would rather use the helper function.  Essentially this is what I want

$field_type = "my_field_type";
$value = drupal_array_get_nested_value($field_type, $form);

but that is not working, it's wants me to pass an array.  How can I use this function to search for a string, or am I using the wrong function?

The function actually takes an array as the input and the first value is the array to be searched.

so your code should be as follows

$field_type = array('my_field_type');
$value = drupal_array_get_nested_value($form,$field_type);


Granularity of content types Let's say you want to have a set of multimedia galleries, that contain a texts, photos and some youtube films. At the phase of creating content types, I can imagine few approaches. For example - we can create the whole gallery as a one content type, with few optional multivalue fields, or we can create separately content types for photo gallery, separate content type for texts, and all that would be linked by using taxonomy, or we can go even more granular - with content type for ONE photo, ONE text etc, and all that would be linked with each other by taxonomy. How granular content types should be and what are advantages?

As Eugene Fidelin said, we'd really have to have a better feel for the site in order to give you the best advice. It depends - will each gallery have the same fields for each entry? Or does one gallery have videos while another does not? However, I will try to do so anyway.

If there are only a few galleries AND they differ in their fields, I would create a content type for each gallery entry and use them to populate a page with a view. I would do this because otherwise you're going to have to create a single content type with each type of field used by every type of gallery entry, and then for each one you're going to end up having a bunch of empty fields since they are used by the other types of entries.

However, assuming each gallery entry across all galleries has the same fields for the most part, I would just create one content type for gallery entries and then use taxonomy terms and then just use radio buttons to specify what type each entry is (so you might have Animals, People, Places, etc.) and then have views for each type that just filters by the taxonomy terms.


Missing Main Page Content Block in Blocks List I have the region for Main page content in my theme.info file which is regions[content] = Content. But still, in Blocks list, there is no Main page content block. This is causing me problems.

Can i re-create a new block with the same name. What should i do?

Recently had this issue. When I enabled my custom theme some files were missing and Drupal threw some errors and warnings. After adding the files everything worked fine except the Main page content block was missing.

To fix, I did the following:

Set Bartik as the default theme
Navigated to the block interface and configured the Main page content block (which was showing now that Bartik was the default theme)
My custom theme was still enabled so it showed up in Region settings and I was able to select a region

Set my custom theme as the default again and all was good. Main page block was showing again.


I don't understand module_load_include() I believe it is meant to be used as follows, in loading a module include file into the calling scope:

function mymodule1_myfunction1(){
    ...
    module_load_include($type, $module, $name);
    ...
}

But looking at the code of module_load_include():

function module_load_include($type, $module, $name = NULL) {
  static $files = array();

  if (!isset($name)) {
    $name = $module;
  }

  $key = $type . ':' . $module . ':' . $name;
  if (isset($files[$key])) {
    return $files[$key];
  }

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      $files[$key] = $file;
      return $file;
    }
    else {
      $files[$key] = FALSE;
    }
  }
  return FALSE;
}

We see that

require_once $file

is used to load $file into the scope of module_load_include(),  not  mymodule1_myfunction1() so $file is not available to mymodule1_myfunction1(). Is this not how module_load_include() is meant to be used?

We see that require_once $file is used to load $file into the scope of module_load_include()

Not quite. This is from the include docs (identical to require in this respect)

  When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Emphasis mine.

So functions/classes defined in an a file sourced with include/require will be available to all subsequent code. Or more specifically, all functions/class defined in the file you include via module_load_include will be available in mymodule1_myfunction1() after the call.


Drupal 7 Get field value by machine name and pass to javascript I have tried to do this a couple of different ways, but I will just include the latest.

My task is to build a module that will get the STRING value of a taxonomy term by the machine name of the field when the page is rendered, and pass that STRING value to a javascript function to output data in a block.

Most recently, I have tried adding the code to the template.php file in the preprocess_html, page, node and process_html:

*The field is called 'field_test'

global $nid;
$node = node_load('12');
$test = $node->field_test['und'][0]['value'];
drupal_add_js(array('mymodule' => array('test' => $test)), 'setting');

Error in processes was a call to undefined index.
Error in page.tpl was a call to non object.

I also tried field_get_items:

$items = field_get_items('node', $node, 'field_test');
$first_item = array_shift($items);
$test = $first_item['value'];

In the node.tpl file, I tried adding this code:

<?php
  $test = $node->field_test['und'][0]['value'];
  drupal_add_js(array('mymodule' => array('test' => $test)), 'setting');
?>

No errors, but Drupal.settings.test returns undefined in the browser console.

I'll admit I am still new to the Drupal API. In addition to the correct code, I may also lack an understanding of the order in which Drupal components are loaded, and specifically where the code should be placed.

I would really appreciate any help you can provide.

It should be Drupal.settings.mymodule.test not Drupal.settings.test. All of this code should live in a preprocess hook (either page or node, whichever is more appropriate for your use case). For the node, you can try $node = menu_get_object('node');.

Example:

if ($node = menu_get_object('node')) {
  $tid = $node->field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
}

In your console (like Google Chrome) you can type Drupal.settings to see the entire object, and you should see mymodule as a part of it. Within that you will find test with the term name as a value.


How to convert Json data directly into xml - standardized way? I'm having a Json:

[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]

And I want it to convert into XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Us>
    <U1>
        <S>a</S>
        <D>b</D>
    </U1>
    <U1>
        <S>s1</S>
        <D>m1</D>
    </U1>
</Us>

I know the php way, first decoding json using Json_decode() and a bunch of foreach loop that finally generate XML.

But I want in Drupal way. There is a module serialization in core of Drupal 8. But don't know how can I take the services from that module in my custom one.

Also, I got a link, How to get it done using symfony, but again it seems like Drupal 8 standards are lacking somewhere by me.

What's the right approach to achieve this in Drupal way.

The Serializer component is a tool in your Drupal toolbox that should be used when you need to serialize and deserialize data from and to Drupal data such as entities. Unfortunately you cannot deserialize into a \StdClass without implementing your own normalizer.

Inject the serializer service into your class, and use the serialize method to normalize the non-Drupal decoded JSON array into XML.

// Inject this instead of using \Drupal
$serializer = \Drupal::get('serializer');
// Use json_decode or @4k4's example above and use associative arrays instead of object.
$json = json_decode('[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]', TRUE);
// Unfortunately it seems that for an array serializer xml_root_node_name won't work so wrap $json in the root name.
$data = ['US' => $json];
// Serialize into XML.
$xml = $serializer->serialize(
  $data,
  'xml',
  ['xml_root_node_name' => 'US']);


Can't set PHP block visibility programatically Heres my code:

$blocks['membership_package_information'] = array(
    'info' => "Membership Package Information",
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => membership_block_visibility(),
  );

function membership_block_visibility() {
  if(arg(0) == 'checkout' && arg(2) == null) {
    return true;
  }
  else {
    return false;
  }
}

I'm trying to limit the block to only show on the first page of the drupal commerce checkout page (checkout/[order-id]) and not the second (checkout/[order-id]/review) but its not working. When I put this code in the PHP visibility section of the block UI page, it works. I'd rather it be in my module, why wont it work? It seems that the UI settings are being picked up and not whats in my block.

Re: https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_info/7 you have to put the actual PHP code "in" the pages array key...

  For BLOCK_VISIBILITY_PHP, the PHP code's return value should be TRUE if
  the block is to be made visible or FALSE if the block should not be
  visible.

...not set it to the return of a function, eg, something along these lines:

$blocks['membership_package_information'] = array(
    'info' => "Membership Package Information",
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => '<?php return membership_block_visibility(); ?>' // ADDITION: you need the <?php ?> brackets :)
);

// make sure this function is in a module file that is always loaded...

function membership_block_visibility() {
  if(arg(0) == 'checkout' && arg(2) == null) {
    return true;
  }
  else {
    return false;
  }
}

Do also note the caveat off the api page:

  Most modules do not provide an initial value for 'visibility' or
  'pages', and any value provided can be modified by a user on the block
  configuration screen.


Only front page shown? I designed my site with Acquia Dev Desktop on my PC and now it's finished and I uploaded folder of my site to public_html folder in cpanel. I export my database on my computer and import it to my host. but now when I enter my url in address bar of a browser only front page shown, for example when I click on other content of my site it gos to a white page and nothing will loaded.
what should I do? pleas help me.
which command of setting.php file should change after importing database on server?
this is my site: http://www.setareonline.ir

A possible reason can be missing .htaccess file in the drupal root directory or if it is present than possibly your web server is not able to read it. For example web server apache reads .htaccess file with help of mod_rewrite module or even if mod_rewrite module is installed on Apache , Apache server do not have Allow override all permissions. One of the way to check issue is related to .htaccess or not can be accessing internal pages with query parameter, for example www.yoursite.com?q=user and see if it works! then chances are issues with .htaccess file.just check you have shared the URL, for me reason looks like to be .htaccess file check your drupal install is having .htaccess file or not if so ask your web master to let your web server to read your .htacccess


Back button form in node linking back to view I think the user who asked https://drupal.stackexchange.com/questions/49853/how-to-setup-go-back-button-in-views is trying to do a similar thing.

Is there a way within the Views module to add one to the node content output content from a view?

I don't want to use the Back Button module for this; I would prefer to use the Views module, if possible.

You can not do this with the views module alone. A views link will simply link you to a node page and when you are on the node page, it does not know how you got there.

you could do this, which is basically the same as pressing the browser back button:

<input type="button" value="Go Back" onclick="window.history.back()" />

or this:

<?php
  $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
  echo 'go back';
?>


How to get the standard text format widget for a custom field type? I've created a custom field that loads content from a given URL. The content is rendered with the given input format. That works fine.

Currently, I just gabe a list of available text input using filter_formats and show this with a select widget. How can I replace this with the standard input format widget that is available underneath the node body textarea?

This is how it's done now:

/**
 * Implements hook_field_widget_form().
 */
function remote_content_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $url = isset($items[$delta]['url']) ? $items[$delta]['url'] : '';
    $tformatter = isset($items[$delta]['tformatter']) ? $items[$delta]['tformatter'] : 0;

    $widget = $element;

    $widget += array(
        ...
    );

    $widget['url'] = array(
        ...
    );
    $widget['tformatter'] = array(
        '#type' => 'select',
        '#title' => t('Text format'),
        '#options' => _remote_content_create_format_options(),
        '#default_value' => $tformatter,
        '#description' => t('Choose the appropriate text format.'),
    );

    $element = $widget;

    return $element;
}

function _remote_content_create_format_options() {
    global $user;

    $formats = filter_formats($user);
    $options = array();

    foreach($formats as $f) {
        $options[$f->format] = $f->name;
    }

    return $options;
}

You are looking for '#type' => 'text_format'. Usage example:

$form['text'] = array(
  '#type' => 'text_format',
  '#title' => t('Text'),
  '#default_value' => $text,
  '#format' => $format,
);

You will get the text in $form_state['values']['text']['value'] and the format in $form_state['values']['text']['format'].