Snippets

06 May, 16

Snippet: How to check for user access or permission in Drupal 8

1
2
3
4
5
6
7
  1. <?php
  2. // Get current user
  3. $user = \Drupal::currentUser();
  4. // Check for permission
  5. $user->hasPermission('administer content');
Read now
02 Jun, 15

Snippet: Setting HTTP_AUTH in Apache2

1
2
3
4
5
6
7
8
  1. # Put these lines inside <Directory> tag of your virtual host file:
  2. AuthType Basic
  3. AuthName "Private Club Entrance"
  4. AuthUserFile /var/www/example.com/.htpasswd
  5. Require valid-user
  6. # Create a new user via command:
  7. htpasswd -c /var/www/example.com/.htpasswd username
Read now
28 Apr, 15

Snippet: Regex Characters Cheat Sheet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
  1. . Any character except newline.
  2. \. A period (and so on for \*, \(, \\, etc.)
  3. ^ The start of the string.
  4. $ The end of the string.
  5. \d,\w,\s A digit, word character [A-Za-z0-9_], or whitespace.
  6. \D,\W,\S Anything except a digit, word character, or whitespace.
  7. [abc] Character a, b, or c.
  8. [a-z] a through z.
  9. [^abc] Any character except a, b, or c.
  10. aa|bb Either aa or bb.
  11. ? Zero or one of the preceding element.
  12. * Zero or more of the preceding element.
  13. + One or more of the preceding element.
  14. {n} Exactly n of the preceding element.
  15. {n,} n or more of the preceding element.
  16. {m,n} Between m and n of the preceding element.
  17. ??,*?,+?,
  18. {n}?, etc. Same as above, but as few as possible.
  19. (expr) Capture expr for use with \1, etc.
  20. (?:expr) Non-capturing group.
  21. (?=expr) Followed by expr.
  22. (?!expr) Not followed by expr.
Read now
13 Mar, 15

Snippet: Auto select current user in Django admin form

1
2
3
4
5
6
  1. # file: models.py
  2. class Post(models.Model):
  3. title = models.CharField(max_length=255)
  4. content = models.TextField()
  5. date = models.DateField()
  6. author = models.ForeignKey(settings.AUTH_USER_MODEL)
Read now
06 Mar, 15

Snippet: Override field widget in Django admin form

1
2
3
4
5
6
  1. # file: admin.py
  2. class BlogAdmin(admin.ModelAdmin):
  3. formfield_overrides = {
  4. models.TextField: {'widget': CKEditorWidget},
  5. }
Read now
18 Feb, 15

Snippet: Django post_save signal on parent class with multi-table inheritance

1
2
3
  1. # Propagate signal across all children of a polymorphic parent.
  2. for subclass in Entity.__subclasses__():
  3. post_save.connect(delete_comments, sender=subclass)
Read now