texts: How to set up a social media feed with vue and axios

texts:
What I need is a social media stream with posts with the Hashtag mnbasel form Instagram, Facebook and Twitter. I couldn’t find any good tutorial. Hopefully someone can tell me what I miss or lead me to a tutorial.

I signed in to Instagram as a developer and got my Access Token using Client ID and Client Secret.

Then I created a Vue component with this script:

 module.exports = {
  name: 'socialstream',
  data: function () {
    return {
      instagram: []
    }
  },
  mounted () {
    this.getEntries();
  },
  methods: {
    getEntries () {
      axios.get('https://api.instagram.com/v1/tags/search?q=mnbasel&access_token={access-token}')
        .then(response => {
          this.instagram = response.data.data
        })
    }
  }
}

What I get from this is the following error message:

Uncaught (in promise) Error: Request failed with status code 400

And this is the Result I get when I paste the URL in the Browser:

"code": 400,
"error_type": "OAuthPermissionsException",
"error_message": "This request requires scope=public_content, but this access token is not authorized with this scope. The user must re-authorize your application with scope=public_content to be granted this permissions."

I also installed the OAuth Plugin from Dukt and configured Instagram. Not sure if I need that and how to connect this information with the Vue component.


texts: Get user data in Craft CMS Personal edition

texts:
Like I am stating in the title, I am using the free Craft Personal edition which is perfect for my portfolio.

I already (and obviously) have an account and only one.
So I cannot have access to craft.users but this account already have my Full Name and Email written in it and I want to use those in my website without having to redo them as Globals.

Is that possible in Craft Personal?

I thought I will be able to use {{ account }} but it is only accessible in the Registration Form as I can see.

Thanks for your time.


texts: Migrated Server, Now Getting Logged Out Constantly

texts:
I just moved my site from one MediaTemple (gs) instance to another. I copied and recreated the database on the new server, moved over all the files, and updated the internal references that pointed to the old site. I even cleared out the 'craft/storage/runtime/' folder.

Whenever I am logged in, I almost instantly get logged out. Typically, this is after 30-60 seconds.

Whether or not I enter in the correct password, the same message comes back up. However, I can go back to the main admin page, and I'm still logged in.

Any ideas what's going on? It seems to be a caching and session issue of some sort, but there is no caching setup on our server, and I cleared my browser cache completely.


texts:
I need some help. Really struggle understanding how to build relationships between channels/entries.

Context/Want:
I have two separate channels:
1. "Plant catalogue"
2. "Plant care"
I want to re-use the entries from "Plant catalogue" across the whole website wherever I need it accesing speicifc fields.

What I have:
"Plant care" has an entries field type to help build the relationship with "Plant catalogue": field name: "plantEntity"
"Plant catalogue" has an asset field that include a photo of the plant. fiel name: "plantPhoto"

My code so far:

{% set plantcareListing = craft.entries().section('plantCare').limit(null)%}
{% set entries = plantcareListing.all() %}

{% for entry in entries %}
  {% for image in entry.plantEntity %} {# how do I access the asset field "plantPhoto" here? :( #}
    <img src="{{ image.getUrl() }}" alt="{{ image.title }}">
  {% endfor %}

  {{ entry.title }}
{% endfor %}

I would appreciate your advice. Thank you!


texts: How can I convert text into a URL-friendly string?

texts: If I want to convert text into a URL friendly string for sharing text in a social media link, how would I go about that?


texts: Use Twig's batch filter with conditional

texts:
I am trying to make a grid of blocks using Twig. I have different types of blocks so I am using a conditional to test the block type and render different components per block type.

The problem I am having is I want to batch my blocks (columns) in twos so that I can have two blocks per row, so I can do {% for row in entry.curatedContentBlocks|batch(2) if row.type == 'halfWidthBlock' %}, add a row and then nest {% for block in row %} and add my block styles. This should work but when I try to test the block type with row.type, I get an error saying Key "type" for array with keys "0, 1" does not exist.. I'm thinking this is something to do with the batch filter returning an array.

I think the following code is the closest I've gotten, but I am still getting an error saying Key "1" for array with keys "2, 3" does not exist.. Here's the code:

{% for i, row in entry.curatedContentBlocks|batch(2) if row[i].type == 'halfWidthBlock' %}

      {% for block in row %}

{{ block.titleText }}

              {% if block.ctaUrl|length and block.ctaText|length %}

                  {{ block.ctaText }}

              {% endif %}

      {% endfor %}

{% endfor %}


texts:
I would like to count comments that belong to a certain entry (product). I have this so far:

{% set comments = craft.entries().section('productcomments').all() %}
 {% set counter = 0 %}
  {% for comment in comments %}
   {% if comment.title|length and comment.title == entry.title %}
    {% set counter = counter+1 %}
    {{ counter }} comments
   {% endif %}
  {% endfor %}

This actually works, but it displays the results after each other (like this:1 comment 2 comment 3 comment - if i have 3 comments).
I would like to show only "3 comments". Actually display the max result.
Twig's "loop.last" doesn't work because of the condition.
Is there another way?
Thank you very much!


texts: How to get latest entries by particular field?

texts:
I have 4 fields in my section:

-Images

-Videos

-GIFs

-PNGs

On my homepage, I have a section where I have to show 5 latest entries of Images, Videos, GIFs & PNGs. How can I do that ?

I tried:

 {{set entries = craft.entries.section('works').order('fieldname desc').limit(5) }}

But that didn't work. Please Help. Thanks in advance !!


texts: What is the best way to number form entries in Freeform?

texts:
I am trying to number Form submissions using an incrementing number that would display in Email Notifications.

Increment Plugin Field produces an incrementing number and would be ideal but it doesn't work because Freeform uses its own field type set.

What would be the best way to generate and associate a unique number per form entry that could then be displayed?


texts: Looking for tips on cleaning up craft_content and craft_entryversions tables after spam attack

texts:
Long story short, a client had 300,000+ entries come in through a form, which caused the database size to swell, exceeding the storage capacity of the VPS and causing the site to crash.

I was able to manually delete all the entries from that channel from the craft_entries table, which got them back within storage limits and got the site back online. Rebuilding the search index got that table back down to a normal size. However, both the craft_content and craft_entryversions tables are still measured in GB.

I don't know much about the database architecture in Craft, and raw MySQL is not my strong suit. Is there anyway to cleanup those tables based on a channel? As in, I need to remove any stored content that's related to a specific channel and leave the rest of it in tact.

Any help would be greatly appreciated. Thanks.


texts:
Not specifically a Craft problem but I'm struggling to find an answer from Redactors site.

I've got over 100 occurrences of class="redactor-inline-converted" littered throughout the markup of Rich Text fields. How can I stop Redactor adding this class?

Update 2016-04-26

Here's the steps to recreate this. It's an odd thing between Redactor and Word.

Have styled text in Word with a superscript
Copy / paste in to Craft
Add some text and format it
Check the source and Redactor will add class="redactor-inline-converted"

This happens randomly on all tags:

Superscript

list item

Video example:
http://sendvid.com/h41rosb3


texts: Call plugin controller from frontend with ajax

texts:
I want to send an automatic back office email when user click on a button (to request support) on frontend. Then I just display a confirmation message (we ll get back to you shortly).

So I made a plugin controller sending email.
And my idea was to attach an ajax call with a jquery on click stuff to that button.

So I did this.

// SUPPORT ADHERENT button click
$(".call-support a").on("click", function(e, visible) {

    e.preventDefault();

    var data = {
        // ...
    };

    $.ajax({
        method: 'POST',
        url: '/actions/unep/toolBox/requestBrandingHelp',
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
        .success(function(data) {
            console.log('success', data);
        })
        .error(function(data) {
            console.log('error', data);
        });

});

My controller is called and send an email but I got a 404 error from the ajax call in console:

I checked that ajax call with Craft.postActionRequest here below but it is for back-end scope only.
http://buildwithcraft.com/docs/plugins/controllers#posting-to-controller-actions-with-javaScript
How reference "Craft" js object in jquery scope

I am a bit lost how to do that correctly...


texts: How to set selected elements when creating modal with "createElementSelectorModal()"?

texts:
I'm showing a modal using "createElementSelectorModal()"

In some cases I need to pass ids of elements which should be selected right after the modal is created. Is it possible?


texts: Plugin: Fill Record with data (auto generated form)

texts:
Is there a way to generate a form based on my record-attributes ? Like a quick and dirty CRUD-Interface to get started ?

And otherwise: where would I create such forms ? Are those Controllers ?


texts:
When I type mydomain.dev/blahwrongurl - for some reason .htaccess doesn't redirect to the 404.html file, but just write the blahwrong url out on the page and nothing else?

I get the feeling that I messed up routes somewhere, but I deactivated all of my plugins but nothing changed.

Does anyone know why?


texts: Redactor - doesn't generate unordered list

texts: I'm using Redactor v2.8.5. it doesn't render an unordered list in HTML? How do I fix it?


texts:
Is there a specific way I can have a development and live version of a website with Craft Pro running simultaneously.

We have multiple clients, and so using craft.dev for our development is not really feasible.

Can I duplicate the production license over to dev to unlock all features?


texts: Getting $craftPath error on server trying to get Craft running

texts:
Trying to get my Craft site running on my server for the first time.

Getting the error Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /var/www/dev.mysite.com/htdocs/public/index.php

However, there is nothing different to the folder structure on my server than I have locally.
i.e. the $craftPath set in index.php is still ../craft which is correct... my Craft folder sits beside my public folder as per default installation.

What can I try to get this working?


texts: How to list out entry types in a section

texts: Something like craft.entrytypes.section('sectionHandle') and then loop through them to list out their names.  I'm looking through the docs and can't see how to do this with just the craft.entries code.


texts: Copy of Craft instance generates "An unknown error occurred" for login

texts:
I needed to create a second instance of a craft 2.0 instance and so I copied the current instance to a new instance. I followed the directions found here: https://craftcms.com/guides/duplicating-a-craft-site

The structure is like this:

/var/www/html/my_site (original - contains the craft and public folders)

copied to:

/var/www/html/new_folder/my_site (this contains the craft and public folders)

There is a reverse proxy (Apache) that handles routing of the URL's.  The website comes up with no problems.  But, I cannot sign into the site to administer the site.  All I see is "An unknown error occurred."  There is nothing in the craft.log in the instance that indicates what the unknown error is.

Is there a value in the database tables that might be incorrect?  I have scanned for references to the original path and I don't find anything.  The document root in the Apache config files for the instance is correct.  There was a recommendation to delete the runtime folder after copying a Craft install and I have done that but I still get the error and there are no errors in the craft.log file.

One last interesting observation.  When I try the admin URL for the copied site e.g. http://copy.mysite.com/admin the login page for the original site is  displayed e.g http://orig.mysite.com/admin/login.  So, somewhere there is a reference lurking to the old site I copied.  I have changed general.php, db.php and search for references to the old host name but found nothing.


texts: I am developing a property listing website that imports properties from XML files (i.e there is one XML file for each property). Is there any way that we can do an import from more than one file using FeedMe plugin?


texts: How do I enable redactor rich text editor in a front-end form?

texts:
I have a front-end form for registered users to submit entries, however I'd like to have a WYSIWYG editor like the dashboard. How would I get redactor working with this form?

My form:

<form method="post" action="j" accept-charset="UTF-8">
        <input type="hidden" name="action" value="entries/saveEntry">
        <input type="hidden" name="redirect" value="/">
        <input type="hidden" name="sectionId" value="3">
        <input type="hidden" name="enabled" value="1">

        Title
        <input id="title" type="text" name="title">

         {% set jobTypeDropdown = craft.fields.getFieldbyHandle('jobType') %}
        Job Type
        <select name="fields[jobType]">
            {% for option in jobTypeDropdown.settings.options %}
                <option value="{{ option.value }}">{{ option.label }}</option>
            {% endfor %}
        </select>

        {% set jobCategoryDropdown = craft.fields.getFieldbyHandle('jobCategory') %}
        Job Category
        <select name="fields[jobCategory]">
            {% for option in jobCategoryDropdown.settings.options %}
                <option value="{{ option.value }}">{{ option.label }}</option>
            {% endfor %}
        </select>

        {% set jobStateDropdown = craft.fields.getFieldbyHandle('jobState') %}
        Job State
        <select name="fields[jobState]">
            {% for option in jobStateDropdown.settings.options %}
                <option value="{{ option.value }}">{{ option.label }}</option>
            {% endfor %}
        </select>

        Job City
        <input type="text" name="fields[jobCity]">

        Job Overview
        <textarea id="jobOverview" name="fields[jobOverview]"></textarea>

        Job Description
        <textarea id="jobDescription" name="fields[jobDescription]"></textarea>

        How to Apply
        <textarea id="howToApply" name="fields[howToApply]"></textarea>

         <button class="button login-btn" type="submit">Post Job</button>
    </form>


texts: Is there a way in Craft Commerce to apply discounts to the net order total (eg the subtotal/before tax is applied to the order)? Out of the box this seems to discount from the basket/order total.


texts:
I have a checkbox field to enable my client to choose what entry categories to have as an article feed on a page. How can I output the checked option categories when setting the entries in the for loop? Below is what I have done to return the checked option's value but what I want to do is use the checked options value to filter through entry categories.

What I'm looking to do is set the entries as below:

{% set entries = craft.entries.relatedTo(category, 'checkedOptionValue','checkedOptionValue','checkedOptionValue').limit(10).find() %}

<!-- This is returning the checked options value -->
{% for option in checkboxFieldHandle.options %}
    {% if option.selected %}
        {{ option }}
    {% endfor %}
{% endfor %}

Any help would be greatly appreciated


texts: How can I order entries by title when each title is numeric?

texts:
I originally asked this on Stack Overflow, but I'm hoping for more response here.

In Craft, I'm trying to order entries by the title. Each title is a number, but the sort function handles it like a string. Because of that 100 shows up before 2, 31 before 4, and so on.

{% for entry in craft.entries.section('mySection').order('title').find() %}
    <h2>§{{entry.title}}</h2>
{% endfor %}

Is there a way to do this without extending  twig?


texts: Remove the last comma in an inline list of tags?

texts: In a list of tags I'd like to remove the last comma. So is there something that works like the Ee backspace parameter?


texts: Craft 3 - custom callback after Garnish onDragStop

texts:
I would like to trigger a custom javascript function after an element in a matrix block was moved in the matrix but I'm not sure how to attach the event without changing the MatrixInput.js.

So far I've tried the easy way with attaching element handler in my plugins init() function

Garnish.$doc.on('dragStop', '.matrixblock > .actions > .move', this.onMoveEnd.bind(this))

But of course that did not work. The Craft.MatrixInput contains a the function

this.blockSort = new Garnish.DragSort($blocks, {
    handle: '> .actions > .move',
    axis: 'y',
    filter: $.proxy(function() {
        // Only return all the selected items if the target item is selected
        if (this.blockSort.$targetItem.hasClass('sel')) {
            return this.blockSelect.getSelectedItems();
        }
        else {
            return this.blockSort.$targetItem;
        }
    }, this),
    collapseDraggees: true,
    magnetStrength: 4,
    helperLagBase: 1.5,
    helperOpacity: 0.9,
    onSortChange: $.proxy(function() {
        this.blockSelect.resetItemOrder();
    }, this)
});

Can anyone please tell me how to extend this without breaking Craft updates?

Accessing this event with Craft.MatrixInput.blockSort to attach something does not work either and I'm not sure how I can make use of the this.trigger('dragStop'); event.

I've tried to dig into Garnish events to attach the handlers, but I'm not sure how. Garnish.on does not work, Garnish.Drag.on either, Garnish.Base returns a function but Garnish.Base() returns undefined.


texts:
Installing Craft-2.4.2723 on Centos 6.5 MySql 5.6.27 PHP 5.4.45 gets hung in 'Oops' monkey screen. Minimum requirements are met. Permissions are wide open. Database exists but no tables are created. Collation is set to utf8_unicode_ci. Following is craft.log:

2015/11/13 21:51:08 [warning] [application] Skipping record /var/www/craft/app/records/BaseRecord.php because it’s abstract or an interface.

2015/11/13 21:51:08 [error] [exception.ReflectionException] exception 'ReflectionException' with message 'Class Craft\EntryLocaleRecord does not exist' in /var/www/craft/app/services/InstallService.php:125

Stack trace: 0 /var/www/craft/app/services/InstallService.php(125): ReflectionClass->__construct('Craft\\EntryLoca...')
1 /var/www/craft/app/services/InstallService.php(47): Craft\InstallService->findInstallableRecords()
2 /var/www/craft/app/controllers/InstallController.php(159): Craft\InstallService->run(Array)
3 /var/www/craft/app/framework/web/actions/CInlineAction.php(49): Craft\InstallController->actionInstall()
4 /var/www/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
5 /var/www/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
6 /var/www/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
7 /var/www/craft/app/framework/web/CWebApplication.php(282): CController->run('install')
8 /var/www/craft/app/etc/web/WebApp.php(805): CWebApplication->runController('install/install')#9 /var/www/craft/app/etc/web/WebApp.php(772): Craft\WebApp->_processActionRequest()
10 /var/www/craft/app/etc/web/WebApp.php(193): Craft\WebApp->_processInstallRequest()
11 /var/www/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
12 /var/www/craft/app/index.php(62): CApplication->run()
13 /var/www/html/index.php(19): require_once('/var/www/craft/...')
14 {main}

REQUEST_URI=/index.php/admin/actions/install/install
HTTP_REFERER=http://myserver.com/index.php/admin/install

2015/11/13 21:51:08 [error] [application] Class Craft\EntryLocaleRecord does not exist

It appears that it's not being passed the 'Locale' record. Any ideas on this?


texts: adding font family drop downlist to redactor craft cms

texts:
this options to craft cms i was only succeful to add align and bold option i want to add font family video and image upload options

1: https://i.stack.imgur.com/F71TL.jpgthis options to craft cms i was only succeful to add align and bold option i want to add font family video and image upload options


texts: I cannot get the email address to properly update from my user account management form

texts:
I figure I must need to pass the current user's password along with the updated email address upon form submit. However, I cannot get the email address change to take. Any help is greatly appreciated. Here's my code snippet:

<form action="" method="post" accept-charset="UTF-8" enctype="multipart/form-data" class="account-edit">

    {{ getCsrfInput() }}

    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="password" value="{{ currentUser.password }}">
    <input type="hidden" name="redirect" value="account">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">
    <input type="hidden" name="deleteUserPhoto" id="deleteUserPhotoInput" value="">

    {% if currentUser.firstName %}

            First Name

            <input name="firstName" value="{{ currentUser.firstName }}" class="form-control">

    {% endif %}

    {% if currentUser.lastName %}

            Last Name

            <input name="lastName" value="{{ currentUser.lastName }}" class="form-control">

    {% endif %}

    {% if currentUser.email %}

            Email

            <input name="email" value="{{ currentUser.email }}" class="form-control">

    {% endif %}

    {# Check to see if the user has a photo  #}
    {% if currentUser.photoUrl %}
        Edit Photo

                Delete

            {# If a photo exists, give the option to change the user photo #}
            <input type="file" name="userPhoto" value="Change Photo">

    {% else %}

    {# If no photo exists, give the option to upload a new one #}
        Upload Photo

            <input type="file" name="userPhoto" value="Upload">

    {% endif %}

    <input type="submit" value="Update Account" class="btn profile-save">
</form>


texts: Console script tags garbling up non-html output (e.g. json) when in devMode

texts:
I have a plugin returning json from a controller action using $this->returnJson(...).

Works great in production, but when devMode = true, the json is invalidated because Craft is still dumping the console debugging script at the end of the content.

What's the best way to avoid this?


texts: Custom validation rules on frontend form

texts:
What would be the best way to add some custom validation rules on forms submitted on the front-end without using specific field types for it?

I'm using the Guest Entries plugin that allows anonymous posts to the targeted section.  I'm new to Yii and Craft CMS and I cannot seem to find a way to extend the validation rules for the EntryModel (at least I suspect it needs to get done there).


texts: How do I hide tags in a category that have no entries?

texts:
Entries can have one of two categories and one tag.
(People = entries | program = categories | year = tag)

On the pages I'd like to display entries related to the category and grouped by tag. However, I don't want the tag to display if there are no entries with that tag and in that category.

The following code works, but it displays empty tags that I'd like hidden.

{% set entryIds = craft.entries.section('fellows').ids() %}
{% set tags = craft.tags.relatedTo({ sourceElement: entryIds }).groupId(2).find() | reverse %}
   {% for tag in tags %}
      <h3>{{ tag.slug }} {{ category.title }}</h3>
          {% for entry in craft.entries({
                            relatedTo: [
                              'and',
                              { targetElement: category },
                              { targetElement: tag },
                              ],
                              limit: (null),
                              }) %}
           {% include '_entryblock.twig' %}
           {% endfor %}
    {% endfor %}

This currently displays the following — but I don't want it to display 2018 in Program A or 2017 in Program B since neither of those have entries.

Program A:

/program-a (category)
  |__2018 (tag)
  |__2017
       |__Bono (entry)
       |__The Edge
  |__2016
       |__Ringo
       |__Paul

Program B:

/program-b
  |__2018
       |__Chris Martin
       |__Jonny Buckland
  |__2017
  |__2016
       |__Florence
       |__The Machine


texts:
Am suddenly finding lots of core..xxx files dumped in the root of my site.
In devMode cant see any issues. Assume this is serious issue and memory dump?

Where to start? Logs have loads of stuff but nothing that gives me a clue to this.


texts: Caddy seems to be an easy to use alternative to established web servers. How does the Caddyfile look like for a Craft site?


texts:
I'm trying to update Craft, but I'm getting an error while updating stating it's not possible to make a database backup. I've therefore gone for the suggestion to revert back instead of pushing on. Back in the CMS now when I try to create a backup manually (utilities-> database backup) it tells me:

there was a problem backing up your database. Please check the logs.

I've done that and it says this:

2018-11-30 11:43:57 [-][1][-][error][yii\base\Exception] yii\base\Exception: Could not create backup: proc_open() has been disabled for security reasons in /home/bxrdvjsx/xxxxxx.de/vendor/craftcms/cms/src/controllers/UtilitiesController.php:382

Does anyone know how I can fix this? If it isn't obvious from my question I'm not very familiar with Craft and have inherited this website from the person who built it.


texts: Write into Sprout Forms from another plugin

texts:
I'd like to be able to create a Sprout Forms entry from another plugin I'm working on. Is this possible?

I had a bit of a look at the SproutForms_EntriesController->actionSaveEntry() action but it's kind of all bundled up.

This other plugin is a self contained booking system that I don't want to use an actual Sprout Forms form for - but to keep it consistent for the client I'd like to write (for reference) these entries into a pre-existing form I've set up.

Thanks!


texts: Uploaded .gif only loops once instead of infinitely

texts:
Having a problem where uploading an infinitely looping gif only loops once.

I've tested it with and without image transforms and get the same issue.
I know there there was an issue previously stated here
Specify number of loops for animated GIF (ImageMagick)? and that was fixed in a recent release. Any thoughts on what the issue could be?

Craft CMS 2.6.2931 (multilingual)

ImageMagick 6.7.7-10 (dev)

ImageMagick 6.7.8-9 (staging)


texts: Is there a template conditional to determine whether a plugin is installed?

texts:
Let's say I've got a hot plugin called Cornballer, and I'd like to avoid embarrassing template errors if I refer to it in a template without yet installing it.

I'd like to get away with this...

 {% if craft.cornballer %}

 {{ craft.cornballer.simulate('little') }}

 {% endif %}

...so that any cornballing is simply ignored and no errors result. But Craft allows no such thing:

  Method "cornballer" for object "Craft\CraftVariable" does not exist

Is there a way?


texts: Trying to style Printmaker Plugin PDF by linking css in head of PDF template

texts:
Similar to this issue Render styled output using Printmaker plugin

I am having the same issue and can't seem to figure out how to style the PDF.

Here is my code to generate the PDF:

    {% set html %}
        {% include '_includes/_pdf/social.twig' %}
    {% endset %}

    {% set pdfUrl = craft.printmaker.pdfFromHtml(html).url %}

    Print Page

This opens the PDF in a separate tab.

and then I am loading pdf.css into the head of _includes/_pdf/social.twig but the PDF is not styled.

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>PDF Template</title>
        <link href="pdf.css" rel="stylesheet" type="text/css">

        // PDF HTML

and here is my directory structure

_includes
    _pdf
        pdf.css
        social.twig

Is it possible to style the PDF this way or do I need to use


texts: Display first image from matrix field of a related entry to current tags

texts:
I want to display on entry view page, related entries to current tags.
So far, I came to displaying basic entry's object, but I don't know How to get in matrix field and pull the first image.

Images are stored in matrixFieldHandle -> blockTypeHandle -> imageFieldHandle.

For outputting related entries to current tags I use:

{# Set ECM for related entries to current tags #}
{% set tag = entry.keywords %}
{% set relatedEntries = craft.entries.relatedTo(tag).id('not ' ~ entry.id).limit(8).find() %}

{% for entry in relatedEntries %}
    {{ entry.title }}
{% endfor %}


texts: I would like to change the root folder name where my Craft install is currently at.  for example: website.com/dev to website.com/draft1.  When changing the folder name on my server and the site URL in the Craft admin settings to match, I get an error.  What am I missing?  Will I need to reinstall Craft from scratch under the new URL?


texts: I need to add an event handler for the onSaveEntry event in order to integrate with another system. In the admin screens for the form where and how do I add this event handler?


texts: Filtering Matrix through field value and multiple relations

texts:
I've the following situation:

Accommodations (entry)

title
description (textfield)
...
linkedTo (matrix block)

Sport (category)
targetGroup (category)
minimumAge (number)
maximumAge (number)

What I'm trying to do is fetch all entries (accommodations) related to a sport and targetGroup for a person of a certain age. E.g.: Entries for children with the age of 11 years in the targetGroup 'men/boys' and the sport 'football'.

Finding elements using relatedTo works for me, except I'm not able to filter the age. I'm pretty sure I'm doing something wrong here. I think it's not possible in craft to find textfield values via the relatedTo method, but the question is: How should I do this?

private function get ()
{
    $sport      = $this->findSelectedBySlug('football');
    $targetGroup    = $this->findSelectedBySlug('men-boys');
    $age            = 11;

    $wheres = [
        "and",
        [
            'targetElement' => $sport,
            'field' => "linkedTo.sport"
        ],
        [
            'targetElement' => $targetGroup,
            'field' => "linkedTo.targetGroup"
        ],
        [
            'targetElement' => "<= {$age}",
            'field' => "linkedTo.minimumAge"
        ],
        [
            'targetElement' => "> {$age}",
            'field' => "linkedTo.maximumAge"
        ]
    ];

    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'accomodations';
    $criteria->relatedTo = $wheres;

    return $criteria->find();
}
private function findSelectedBySlug ($slug)
{
    $criteria = craft()->elements->getCriteria(ElementType::Category);

    $criteria->slug = $slug;

    return $criteria->first();
}


texts: This page isn’t working // I think it's my .env?

texts:
Been struggling for hours to solve this with no solution and I'm under a deadline for a client. Any help would be so amazing.

Here's what happened:

I set up the initial craft project with craft create
This got pushed to Github and other devs have been continuing work
We were collaborating just fine on the project back and fourth with changes.
In my development I somehow deleted my .env file.
Now - I can't get my /admin/dashboard to show up or the craft site at all.
I've been playing with the settings in the .env I've been going back and fourth with the /phpMyAdmin/?lang=en page trying to set up and link a database.
It seems: the project is fine, the database is fine, but I can't seem to link my database and the craft project and get craft to run at all.

Any tips? Any direction? I am just seeing this in the browser:

This page isn’t working localhost is currently unable to handle this request.
HTTP ERROR 500

Help please! Thanks.

FYI - I am on MacOS running MAMP (From my applications folder) and I have PHP 7.2.11 all installed and running.

Thanks!


texts: Template loads via jQuery .load(), but no {% js %} tags are included

texts:
Inside of a modal window I'm loading a form template via jQuery .load. For reasons I don't know, the {% js %} tags that need to come with the form template are not being loaded, even though the {% js %} tag is placed at the bottom of the loaded partial.

Here's the loading code

{% js %}
  MicroModal.init()

  $(document).ready(function() {
    $('.trigger').click(function() {
      event.preventDefault();

      MicroModal.show('addressModal');
      $('.c-modal__content').load('account/profile/billing/add #newAddressForm');
    });
  });
{% endjs %}

On click a modal will open, retrieve the template, look for the #newAddressForm ID element, and an address form template  will load within it. The HTML part of the form loads fine, but no JS is brought with it.

The loaded partial template:

<form method="post" id="newAddressForm">
  <input type="hidden" name="action" value="commerce/customer-addresses/save">
  {{ csrfInput() }}

  {% include "shop/_inc/addresses/form" %}

  <button type="submit">Save</button>
</form>

And lastly, the {% include %} has the form fields and {% js %} tag inside.

To reiterate, the HTML of the form loads fine. The JS does not come with it. I'm not sure if this is an issue with Twig, Craft, or jQuery. Help would be appreciated!


texts: How do I get past this MySQL error installing Craft 3 using CLI

texts:
I am using https://box.scotch.io/ (vagrant).

I'm trying to install Craft 3 with the cli, but can't get past these errors:

Connection refused
No such file or directory

One or the other error shows up depending on what I use for the host name.

I have tried the answer here.
I can connect fine with Sequel Pro using the same credentials.

(Note: I did intentionally change the db name and password from the defaults that came with Scotchbox, and have successfully connected with those new details using Sequel Pro).

See log:

Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [192.168.33.10]
Database port: [3306]
Database username: [root]
Database password:
Database name: [craft]
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] Connection refused
Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [192.168.33.10] localhost
Database port: [3306]
Database username: [root]
Database password:
Database name: [craft]
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] No such file or directory
Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [localhost] 127.0.0.1
Database port: [3306]
Database username: [root]
Database password:
Database name: [craft]
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] Connection refused


texts: Caching matrix that contains Freeform field

texts:
I've got a matrix block that most pages on my site are built from, and one of its blocks is a Solspace Freeform form field. I want to be able to cache the entire output of the matrix, but that makes Freeform see all form submissions as spam, since their hash gets cached too.

So I tried https://github.com/benjamminf/craft-nocache but couldn't get that to work as the whole matrix (including the form) gets cached outside of the {% nocache %} tag. So then I tried:

{% set bodyIncludesForm = entry.body.type('form') | length > 0 %}
{% cache globally using key craft.request.path unless bodyIncludesForm %}
...

... which seems to work, but that entry.body.type('form') call adds 32 queries which kind of defies the point of the caching!

Any idea how to get round this, without turning off Freeform's spam check?


texts:
For theming, I need to get the Section Handle for the current Entry. When using dump(entry), I see sectionId is available. This works fine:

{{ entry.sectionId }}

But I'm not seeing a way to get the sectionHandle. Does anyone know a quick way to get it?


texts: getCriteria not working as expected with boolean field types

texts:
I have a custom content table for an elementType. I have a few fields set up in my Record as boolean. The two fields are approved and denied I have to search the database where both fields are set to zero/false.

I can only get the values to show up in $query->params inside my modifyElementsQuery() method when I set $criteria->approved/denied to (string)"1". Setting these to true, false, or (string)"0" cause them to not show up in the $query->params list.

How do I work with a boolean field in this manner? I need Where denied = '0' to show up in the query when i set $criteria->denied = false


texts: How to create a user editable dropdown field?

texts:
Trying to figure out the best way of handling this scenario:

We have a data field for a entry type that should allow an editor in the CP to select one option from many (ie. a dropdown). However, we want to give the editors the ability to modify the options for this select list - and can't let them into a superadmin mode in the CP where they'd edit the original field parameters (if this were a dropdown field).

To do so, we're considering using categories. That presents easy UI in the CP to allow them to manage the list of options as needed, from which they'll select one when creating a new entry in the CP.

However, this piece of data isn't a category (as far as a user would think of it) so I am not certain if there is a more elegant way to handle this and avoid using categories? I looked for a field type that might do something like that but couldn't find one.

Thanks!


texts: What's the most efficient way to handle a redirect of the home page?

texts:
I dont't currently need a home page on the personal site I'm working on but I want to be able to keep the option open in the future. I currently have

{% redirect 'portfolio' %}

as the only code on the index page but Craft seems to take a while before it redirects to the portfolio page.

I tried a rewrite rule and while it worked it doesn't change the URL and I didn't see much difference in the time it took to load the page. In fact, it seemed to take longer on my local machine running MAMP Pro 3 then the redirect tag did.

I also looked into Reroute plug-in by Trevor Davis which seemed to work about as well as the redirect tag, maybe slightly better.

Any thoughts as to which is a better approach and why a simple index page with a redirect tag on it would take so long to process?


texts: How would I create unique fields for different user groups programmatically?

texts:
I understand this isn't possible from the Control Panel, I'm developing a custom plugin for this specific client project. Essentially these user groups won't need access to the Control Panelat all, but will have unique permissions within the site and will have a few custom fields.

Can I create custom fields per user group? Or do I just need to create relationships between these fields and the users when they create their profile? Trying to figure out the proper way to go about this.

EDIT:
After watching the Element Type hangout as suggested, they explain why this isn't possible with the current implementation of User Groups, if you are curious.
https://youtu.be/hU_wduMEimY?t=27m44s


texts: Show tags in tag group only being used on live entries

texts:
Looking to loop through tags from entries but limit to only show tags that are being used on entries. Right now this just loops through any and all created tags.

I tried limit to null but have had no luck getting that to work.

{% set categories = craft.categories.group('storiesCategories').find %}
{% set tags = craft.tags.group('storiesTagGroup').find %}
{% set elements = categories|merge(tags) %}

All

    {% for element in elements | supersort('natcasesort') %}

{{ element.title|capitalize }}

    {% endfor %}


texts: CP form submissions occasionally reaching PHP's 300 second timeout

texts:
Occasionally—I'd say about 30-40% of the time—when submitting a form in the backend, be it saving an entry, updating a custom field, etc, the page will just sit there, loading. This can and often does continue for ~ 299.88 seconds, after which it will proceed to the next screen as if nothing ever happened.

I've looked through the console log, but all the timestamps seem to be within a second of each other, so nothing jumps out as the step where things are getting hung up. I suspect a server problem, but I'm posting here just in case anyone can point me in a more specific direction than "there's a problem somewhere".

To date, this has not occurred on the frontend, but there aren't any frontend forms to submit, either.

Pastebin of the console log (the load time is on line 725): https://pastebin.com/aB4JkrBv


texts: Rich Text Field Adding Tags around script

texts:
I'm trying to add some embed code/script and the rich text field on save puts misc <p> tags around my code.

How do I save code so it keeps it's code formatting without adding an extra stuff?


texts:
I am trying to output a list of entries from a channel section that DO NOT have a certain tag.

I am able to output the entries that have the tag assigned by setting the tag as a variable and using relatedTo to filter the entries out. For example:

{% set tag = craft.tags.search('All-Stars').first() %}

{% if tag %}
{% set relatedEntries = craft.entries.section('news').relatedTo(tag) %}
{% endif %}

What is the best approach to output entries without the tag?
I've tried the following:

{% set tag = craft.tags.search('All-Stars').first() %}
{% set allEntries = craft.entries.section('news') %}
{% set taggedEntries = craft.entries.section('news').relatedTo(tag) %}
{% set untaggedEntries = allEntries|without(taggedEntries) %}
{% for feedItems in untaggedEntries.limit(5).offset(1) %}

This however doesn't work and throws out some errors, the first being:

array to string conversion

craft/app/vendor/twig/twig/lib/Twig/Template.php(525)

$message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s")', $item, gettype($object), $object);

I tried many other ideas like .relatedTo('not' ~ tag) and |without with no avail.

Is it something obvious I am missing or more advance than that?

Thanks in advance


texts: How can I show multiple entry types in the same page

texts:
I have two entry types in a same structure, I want to get some values from these two types in a same page. Is it possible?

I tried:

{% set entry = craft.entries.section('businessProfile').type(['type1','type2]) %}

And the entry.type still shows only one type. Thanks in advance!


texts: How to search for Entries that have a particular Category set within a Matrix field in the Control Panel?

texts:
I have an arrangement like this:
Entry type 'people'
└ Matrix field 'offices'
  └ Block type 'office'
    └ Category field 'building'

On the Entries screen, how can I search for people that have a particular building Category assigned within the offices Matrix?
Note: the offices and building fields both have "Use this field’s values as search keywords" checked.


texts: When creating a new entry, what controls field focus?

texts: When I create a new entry, I noticed that the focus jumps to a field within the first matrix block. This is not something I explicitly set, I can't find anything in the documentation about what controls it. I would prefer to have the first field in the list, the title feel that is, be focused on load.


texts: Craft Commerce update variant field in plugin

texts:
I'm trying to get, update, and save products &/or variants in my plugin controller, and am stuck on accessing/changing/saving updated fields.

// get product ID from post
$variant_id = craft()->request->getPost('variant_id');

// create criteria
$criteria = craft()->elements->getCriteria('Commerce_Variant');
$criteria->id = $variant_id;

// query
$variant = $criteria->first();

The above works just fine and gets the variant. But now I need to update a few fields and save it. Any idea how to do this?

$variant->getContent()->myCustomField = 'new value';

How would I then save $variant?


texts: Max character limit on WYSIWYG text editor plugin?

texts:
Is it possible to add a max character limit to CKEditor, Redactor, or any other rich text, or WYSIWYG plugin??

I've searched around, and I'm surprised that I have not been able to find a solution. Seems like a pretty basic feature. I would like to not have to use a third-party plugin for this one thing. But if that's the only way to do it, please indicate that. Thank you!


texts:
I was using this code in the past and it worked well

        {% set assets = craft.assets.limit(null) %}
        {% set entries = craft.entries.section('menu').limit(3).order('RAND()').relatedTo({
            targetElement: assets,
            field: 'assets'
        }) %}

        {% for item in entries %}
                {% set i = item.assets.first() %}

                <img width="{{ i.getWidth('medium') }}" height="{{ i.getHeight('medium') }}" src="{{ i.getUrl('medium') }}" alt="{{ recipe.title }}" />

        {% endfor %}

However, in the new version the standalone "assets" field became a part of the matrix field so this piece of code doesn't work anymore. Please advise :)


texts: Contact form: Twig_Error_Runtime error upon submission

texts:
Using the standard P&T contact form, I'm getting the following error when form is submitted (running locally):

Twig_Error_Runtime

Impossible to access an attribute ("fromEmail") on a string variable ("") in "_layout" at line 149 (C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Template.php:460)

#0 C:\xampp\htdocs\mysite\craft\app\etc\templating\BaseTemplate.php(41): Twig_Template->getAttribute('', 'fromEmail', Array, 'any', false, false)
#1 C:\xampp\htdocs\mysite\craft\storage\runtime\compiled_templates\3\5\352f325e7c58d6329a0dbf553a172b2811c881b391a544d0f295665ec793e2af.php(251): Craft\BaseTemplate->getAttribute('', 'fromEmail', Array)
#2 C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Template.php(340): __TwigTemplate_352f325e7c58d6329a0dbf553a172b2811c881b391a544d0f295665ec793e2af->doDisplay(Array, Array)
#3 C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Template.php(314): Twig_Template->displayWithErrorHandling(Array, Array)
#4 C:\xampp\htdocs\mysite\craft\storage\runtime\compiled_templates\2\a\2a1532ab9a7fc5ec6775a274eca668a2af4e295ac7764368b23c762497284924.php(27): Twig_Template->display(Array, Array)
#5 C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Template.php(340): __TwigTemplate_2a1532ab9a7fc5ec6775a274eca668a2af4e295ac7764368b23c762497284924->doDisplay(Array, Array)
#6 C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Template.php(314): Twig_Template->displayWithErrorHandling(Array, Array)
#7 C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Template.php(325): Twig_Template->display(Array)
#8 C:\xampp\htdocs\mysite\craft\app\vendor\twig\twig\lib\Twig\Environment.php(293): Twig_Template->render(Array)
#9 C:\xampp\htdocs\mysite\craft\app\services\TemplatesService.php(223): Twig_Environment->render('404', Array)
#10 C:\xampp\htdocs\mysite\craft\app\controllers\BaseController.php(74): Craft\TemplatesService->render('404', Array)
#11 C:\xampp\htdocs\mysite\craft\app\controllers\TemplatesController.php(201): Craft\BaseController->renderTemplate('404', Array)
#12 C:\xampp\htdocs\mysite\craft\app\framework\web\actions\CInlineAction.php(49): Craft\TemplatesController->actionRenderError()
#13 C:\xampp\htdocs\mysite\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
#14 C:\xampp\htdocs\mysite\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
#15 C:\xampp\htdocs\mysite\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#16 C:\xampp\htdocs\mysite\craft\app\framework\web\CWebApplication.php(282): CController->run('renderError')
#17 C:\xampp\htdocs\mysite\craft\app\framework\base\CErrorHandler.php(368): CWebApplication->runController('templates/rende...')
#18 C:\xampp\htdocs\mysite\craft\app\etc\errors\ErrorHandler.php(264): CErrorHandler->renderError()
#19 C:\xampp\htdocs\mysite\craft\app\framework\base\CErrorHandler.php(351): Craft\ErrorHandler->renderError()
#20 C:\xampp\htdocs\mysite\craft\app\framework\base\CErrorHandler.php(218): CErrorHandler->renderException()
#21 C:\xampp\htdocs\mysite\craft\app\etc\errors\ErrorHandler.php(128): CErrorHandler->handleException(Object(Craft\HttpException))
#22 C:\xampp\htdocs\mysite\craft\app\framework\base\CErrorHandler.php(131): Craft\ErrorHandler->handleException(Object(Craft\HttpException))
#23 C:\xampp\htdocs\mysite\craft\app\framework\base\CApplication.php(740): CErrorHandler->handle(Object(CExceptionEvent))
#24 [internal function]: CApplication->handleException(Object(Craft\HttpException))
#25 {main}

Running latest Craft Pro 2.4.2700 and latest contact form plugin. What could be causing the error?


texts: Caching variables for use elsewhere in a template?

texts:
I have a long if/else block within a for loop in my template and I wanted to cache all of it (it loops over a Matrix field, checking for different block types on each row and outputs the correct code as needed). However, in one of the ifelse blocks, I have a statement with a RAND parameter that I don't want cached. Something like this:

{% for block in entry.sidebar %}
    {% if block.type == "someType" %}
        ...Presentiaon code
    {% elseif block.type == "someType" %}
        ...Presentiaon code
    {% elseif block.type == "someType" %}
        {% set randomEntry = craft.entries.section("testimonials").order('RAND()').first() %}
    {% endif %}
{% endfor %}

My challenge is trying to find a way to cache this long block but still let the RAND work. My solution was to try to put the matrix field into a variable, cache that variable and then iterate over the variable's data (the thinking here that the variable has all the process-intensive DB queries). Something like this:

{% cache %}
    {% set myField = entry.myMatrixField %}
{% endcache %}

{% for block in myField %}
    {% if block.type == "someType" %}
        ...Presentiaon code
    {% elseif block.type == "someType" %}
        ...Presentiaon code
    {% elseif block.type == "someType" %}
        {% set randomEntry = craft.entries.section("testimonials").order('RAND()').first() %}
    {% endif %}
{% endfor %}

However, this fails after the template has been cached with an error that the 'myField' variable does not exist. So I'm thinking I can't do this?

Is there another way I could cache this? I considered breaking up the ifelse blocks into separate if/endif clauses and caching each except the one with the RAND paramater in it but I'm thinking that won't improve performance much if the for loop still has to run outside of it uncached.


texts: Developers or experts for Craft CMS V3 in Costa Rica

texts: I am looking for a Craft CMS developer in Costa Rica to help us with occasional issues


texts:
I'm trying to pair all my custom product entries to all my dealers with 2 extra fields per product: price per day and price per week. The condition is that all my products are paired to all my dealers in advance. So when adding a new dealer I would like to show a table or some sort listing with all my products with the 2 fields in different columns.

I've tried to do this with a static table (Super table plug-in) and sort of succeeded:
I made a new field for my dealers with each field named after a product and the field type set to a normal table with 2 columns for my 2 fields. In my templates I would query based on my product name and match the correct row from my Super table field, but it just seems error prone and not managable.

Does anyone have any advice on how to implement this in a correct way?


texts: Get categories ordered by the associated entries' postDate

texts:
I'm looking to show recent categories ordered by their associated entries' postDate.

Is this possible?

I don't want to list the entries within the category
I simply want to list 4 categories that have recently updated related entries.
Entries from any section can be associated to my site's global categories.


texts: How can I dynamically set checkboxes to be named variables?

texts:
If I have a field of checkboxes, I'd like to be able to access them by the name of each checkbox as the variable name, and the 0 or 1 checked state as the value. Said variables need to be accessible beyond the for loop.

For example (doesn't work):

{% for checkbox in checkboxes %}
    {% set {{ checkbox }} = checkbox.selected %}
{% endfor %}

I've looked into things and seen answers mentioning _context, attribute(), and the like, but haven't been able to get anything to work.

In short, if I have a checkboxes field with a single checkbox whose name is my_checkbox, label is "My Checkbox", and is checked in an entry, I'd like to be able to use {{ my_checkbox }} to output "1" (i.e. it's checked).


texts:
Hi I'm getting this error when I try to validate a model.

Craft\mymodelModel and its behaviors do not have a method or closure named "getTableSchema".

I'm using the following code in the controller function that calls the save. It saves the data fine but I want to validate the model first before it does so but this is throwing the above error. What am I missing?

$model->setAttributes($attribute);

if($model->validate()) {
    // code that sends model off to be saved
} else {
    $model->getErrors();
}

Cheers

Model class code:

namespace Craft;

    /**
    * myModel Model
    *
    * Provides a read-only object representing a myModel, which is   returned
    * by our service class and can be used in our templates and controllers.
    */
    class myModels_myModelModel extends BaseModel
   {
    /**
     * Defines what is returned when someone puts {{ myModel }} directly
     * in their template.
     *
     * @return string
     */
     public function __toString()
   {
       return $this->name;
   }

   /**
     * Define the attributes this model will have.
     *
     * @return array
     */
     public function defineAttributes()
     {
        return array(
            'id'    => array(AttributeType::Number, 'required' => true, 'unique' => true),
        'field1'    => array(AttributeType::Number, 'required' => true),
        'field2' => array(AttributeType::Enum, 'values' => "value1,value2"),
        'field3'  => array(AttributeType::Enum, 'values' => "value1,value2,value3", 'required' => true, 'default' => 'value1'),
        'field4' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field5' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field6' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field7' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field8' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field9' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field10' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field11' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field12' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
        'field13' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false)
        );
    }

    /**
     * Get User
     */
    public function getmyModel()
    {
        if ($this->userId)
        {
            return craft()->users->getUserById($this->userId);
        }
    }

}


texts: Upgrading site from 2.3.2636 to 2.4.2684

texts:
I have an older site that has been chugging along nicely so I haven't updated it in a while. I had an issue with an older version of SmartMap that was suddenly causing a 503 on the site so I fixed that and while I was updating things I thought I'd go ahead an update Craft to the latest version. When I do the automatic update I get the following error message and the update fails:

CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

Before I do a manual update I wanted to see if there was something I could do to resolve this and still have the automatic update work.


texts:
I know that it is possible to let user comment entries using the guest entries plugin or to implement a third-party solution.

But I wonder if is someone working on a dedicated comment plugin?


texts: Plugin won't enable on remote dev enviornment

texts:
I've got exactly the same issue reported here:
Plugin won't enable

I've created a really simple plugin that works fine on my local environment but won't enable on my remote dev server. I've followed the advice in that Question and checked all the file and class names but with no success.

There doesn't seem to be any indication of problems in the logs either. I'm stumped. =(

Here's the code as requested:
FirstImagePlugin.php - http://pastebin.com/ehVHF9vk
FirstImageTwigExtension.php - http://pastebin.com/D5C8QnjK

The directory structure is simply just:
/plugins/firstimage/twigextensions


texts:
I need some help with coding the navigation.

This is the markup:

home

about

services

signs

printed decals

vehicle &amp; fleet graphics

banners &amp; posters

magnetics

vinyl graphics

construction and job site signs

business cards &amp; flyers

sign hardware

testimonials

contact

get quote

And here's a sample of my entries, channels and structures: http://grab.by/Awx8

This is what I have so far, but it's not really working at all:

{# get menu items #}
{# {% set pageItems = craft.entries.section('services').level('<= 2') %} #}

{% set pageItems = craft.entries.level('<= 2') %}

{# Output the sub menu #}

Home

    {% nav page in pageItems %}

                {% if page.navigationTitle %}
                    {{ page.navigationTitle|nl2br }}
                {% else %}
                    {{ page.title }}
                {% endif %}

            {% ifchildren %}

                        {% children %}

            {% endifchildren %}

    {% endnav %}

testimonials

contact

get quote

Any help is much appreciated.


texts:
First time here so excuse me if I get the etiquette and protocols wrong.

I am trying to pull eight featured stories into a page, the first two into a large two column grid and the rest into a three column grid.  Try as I may I can not get this to work... I have searched around here for various solutions but none seem to be exactly what I am trying to achieve, or I have the know how to adapt.

I am trying to exclude the first two entries from the second section but want the whole display to be random. I am guessing the array string of ids() is not being parsed or set up correctly but frankly I am a bit lost so any help would be very much appreciated.

So far I think this is the closest I have come.

    {% set featuredStories = craft.entries.section('work').type('projects') %}
    {% set big = featuredStories.order('RAND()').limit(2) %}

    {% for entry in big %}
        <— stuff —>
    {% endfor %}

{% set bigIds = big.ids() %}
{% set bigIdsString = bigIds | join(', not ') %}

{% set allEntries = featuredStories.id('and, not '~bigIdsString) %}

    {% for entry in allEntries %}
        <— stuff —>
    {% endfor %}


texts: Trying to Add a Specific Menu Depending on User Group

texts:
I'm trying to show a menu based on what group a user is in once they have logged in.  However, I'm not having any success.  Here is an example (for one of the groups) of what I have in my _base.html file, which I'm extending in my other pages:

{% if currentUser.isInGroup('advisors') %}

Advisors

Advisors Home

Education

Blog

Events

Nav 5

{% endif %}

Any suggestions would be most welcome!


texts: Redirect to url based on current year/month

texts:
I've got a calendar template set up and would like to have http://domain.com/calendar redirect to http://domain.com/calendar/current_year/current_month but am having trouble getting this to work.

My current code is:

{% if craft.request.segment(2) == "" %}
  {% redirect "calendar/{{ now.year }}/{{ now.month }}" %}
{% endif %}

But this ends up going to a 404 with this url:
http://domain.com/calendar/%7B%7B%20now.year%20%7D%7D/%7B%20now.month%20%7D/


texts: Eager loading on entry not reducing queries

texts:
Using this snippet returns me 38 queries on my homepage without the Eager Beaver plugin.

{% do craft.app.elements.eagerLoadElements(
    className(entry),
    [entry],
    ['headerImage', 'image1', 'image2']
) %}

Without the above loading all three images with .one() gives me 33 queries.

Is this expected behavior or am I doing something wrong?


texts: My month/year archive template code no longer works in 3.2

texts:
My blog has a date archive page that uses a variation of this code. Here's the code that I've been using:

{% set allEntries = craft.entries.section('entries').type(['posts','reviews']).limit(null).all() %}

{% for year, entriesInYear in allEntries | group("postDate.year") %}

{{ year }}

        {% for month, entriesInMonth in entriesInYear|group("postDate|date('F Y')") %}

{{ month|date('M') }}

        {% endfor %}

{% endfor %}

Basically, it printed out a list of the years and months in a grid a la kottke.org's "Monthly archives" section. But after upgrading to Craft v3.2.9, the code no longer works. Instead, the page just displays a generic "Internal Server Error" message.

Looking at the error logs, the server ran out of memory trying to run the above code. If I remove the above code, then the page loads in a snap.

As a test, I streamlined the code by removing the nested grouping:

{% set allEntries = craft.entries.section('entries').type(['posts','reviews']).limit(null) %}

{% for year, entriesInYear in allEntries | group("postDate.year") %}

{{ year }}

{% endfor %}

But that still results in the same memory-related error.

FWIW, my blog has 4,100+ entries spanning 22 years, so is there just too much content for the above queries to handle? And if so, are there ways to optimize the code and/or make it less dependent on DB queries? While I can increase the server memory, I'd prefer to find a template-based solution first.


texts: Freeform Pro Plugin Mailchimp integration

texts:
Got issues with Freeform Pro Plugin, no matter what settings I set on status in the plugin the subscriber goes right into the list on Mailchimp even though status is set to 'pending' on plugin both at default and form setting level.No double opt-in verification.

Any ideas guys?

Plus unrelated, the user when sends also gets a notification of what they have sent, we don't want this. And if we ever did, we would want a custom template for it. any help would be great.


texts: Is it possible to limit how many times and entry type can be used?

texts:
I've structured my site so that most of the pages are in a single structure section (easier to manage that way and it means all my pages can be outputted and organised in the navigation's {% nav %} tag).

I've set up pages that have their own templates and would have been singles as new entry types (e.g. contact page, register form or members area) but it means that the user might try to add another one of those sections in, which I don't want them doing.

So is there a way to limit how many times an entry type can be used?


texts:
I am creating a blog with an index page that links to individual blog show pages. I'm having a weird issue where when I click on the title on the index page instead of it linking to: my_current_website.com/blog/blog_post_title it is linking to: my_live_website.com/blog/blog_post_title, which doesn't even exist. Any thoughts on why this would occur?
In the template I am setting up the link with entry.url.


texts:
I have channel X set up where it's entries have a "users field", an "entries field" (that are picked from channel Y) and a whole bunch of other data with regards to the how a defined user has interacted with the defined entry.

Whilst viewing an entry from channel Y I wish to dig into the data kept in channel X, more specifically the entry in channel X that has both the same users field as the currentUser AND the same entries field as the entry viewed.

My current solution is the following and makes me cringe with the thought of things getting bigger...

{% set fetchedResults = craft.entries.section('channelXhandle').relatedTo(currentUser) %}
{% for resultEntry in fetchedResults %}
    {% if resultEntry.member.first().id == currentUser.id %}
        {# grab the fruit #}
    {% endif %}
{% endfor %}

It's done the trick up until now, but now I want to find out if there is an entry in channel X that has both the channel Y entry and currentUser defined together.

I've tried the following but it didn't help. It retrieves all the entries as though the relatedTo params are currentUser or entry rather than currentUser and entry that I'm looking to retrieve.

{% set fetchedResults = craft.entries.section('channelXhandle').relatedTo(currentUser, entry) %}

Any pointers in the right direction much appreciated!

Solution in light of Steve's Answer

{% set fetchedResult = craft.entries.section('channelXhandle').relatedTo('and',
    { sourceElement: currentUser, field: '[users field handle]' },
    { targetElement: entry, field: '[entries field handle]' }
).first() %}

Note, I tagged on .first() in the above since in my case there should only be one resulting match anyway.


texts: How to build a multipage form using Freeform?

texts:
I've been trying to search for some instructions on how to build a multipage form using Freeform in Craft CMS.

The official documentation is very light on the subject; https://solspace.com/craft/freeform/docs/multi-page-forms/ and there seems to be a general lack of information on the subject elsewhere.

Can anyone explain the steps I need to take in order to create a multipage form?

The form I'm creating is 2 pages in total. I need it to validate page 1 when the 'Next' button on page 1 is clicked, and then validate page 2 and submit the entire form when the 'Submit' button on page 2 is clicked.

Can anyone help or point me in the right direction to some information on the subject?


texts: Set a route for all requests within a plugin

texts:
I’m trying to use a plugin to set up a site route that will direct every page request to a special template.

This is what I’ve set up in my plugin file.

public function registerSiteRoutes()
    {
        return array(
            '*' => 'special/index',
        );
    }

Using the above doesn’t seem to do anything. If I replace * with a word, then try to visit that URL I get something different but not my template.
would love it if someone could put me right here

UPDATE
If I change tact a bit and route to a controller using a specific url then I can see it gets there

public function registerSiteRoutes()
    {
        return array(
            'beer' => array('action'=>'beer/index'),
        );
    }

But I can't figure out how to catch all requests  using * doesn't appear to do anything

UPDATE
@robin helped me out massively here with some more info outside the comments.

Basically  in Craft 2 the plugin routes get called first no matter what. So I can hijack the init method to load my special template

UPDATE 2
I made this into a Craft 2 plugin.
https://github.com/moresoda/craft-emergency-mode

Craft 3 plugin coming soon.


texts: Detaching onSaveEntry events from craft()->entries->saveEntry($entry)?

texts:
I have a plugin that does a bunch of stuff with external APIs onSaveEntry and then saves some of the gathered information back into the entry. I currently use craft()->entries->saveEntry($entry); but I obviously create a loop.

I saw this answer (Updating an entry after an event action within onSaveEntry) but since there is a nice detachEventHandler method I was wondering how to use it.

I tried hammering it with various combinations but I can't figure it out.

Right now, my plugin does this on init :

public function init(){
    craft()->on('entries.saveEntry', function(Event $event) {
        craft()->rmsLink->rmsLinker($event);
    });
}

Then rmsLinker, which is in my RmsLinkerService, checks if the entry comes from the right canal and if so calls another function who is also in the RmsLinkerService like so :

$this->sendShowToRmsV1($settings, $entryAttributes, $entry);

It's then in sendShowToRmsV1 that I need to do craft()->entries->saveEntry($entry) and prevent it from running the plugin all over again.

Any suggestions would be greatly appreciated.


texts:
I need to be able to display the Category Title of a single category (as a h1 tag for a page displaying a list of the entries for that category).  I can successfully display the relevant entries for the category on the page, but when I have tried to display the category title it displays all of the categories titles (in a loop), not just the single category title.

My code:

{% if craft.request.getParam('category') is not null %}

        {% set category = craft.categories.slug(craft.request.getParam('category')) %}

        {% set products =  craft.entries.section('products').relatedTo(category).find() %}

        {% else %}
               {% set products = craft.entries.section('products').find() %}
        {% endif %}

     {% for category in craft.categories.group('productType').find() %}

{{ category.title }}

     {% endfor %}

Any help would be very much appreciated!
Many thanks!


texts:
Hi I'm having major problems trying to get my .htaccess file to rewriteRule or redirect one url to another. I've used .htaccess before on other cms installs and always work but for the life of me I cannot get it to work on my craft install.

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]

    RewriteRule (.+) index.php?p=$1 [QSA,L]

    Redirect /outdoor-furniture/all-garden-benches https://www.mywebsite.co.uk/outdoor-furniture/garden-benches

</IfModule>

This should redirect /outdoor-furniture/all-garden-benches to /outdoor-furniture/garden-benches (getting rid of the 'all-' bit).

This actually redirects to this:

https://www.mywebsite.co.uk/outdoor-furniture/garden-benches?p=outdoor-furniture/all-garden-benches

which is obviously wrong and still throws up a 404 error. I've tried everything now and what was supposed to be a 5 minute job is sending me round the bend so if anyone could shed some light on this then that would be great thanks!

EDIT The only thing that will help is if I take off ?p=$1 from this line:

 RewriteRule (.+) index.php?p=$1 [QSA,L]

Once I do that the redirect works fine, however I'm reluctant to do that as it might break the site somewhere.


texts: How is "craft()->fileCache" different from using cookies?

texts:
Just looking for a little clarification on the craft()->fileCache method...

Everybody already knows that when a cookie is set, that cookie only exists on the end-user's computer. No one else using the website can access that cookie.

But if I were to replace that cookie getter/setter with the craft()->fileCache getter/setter methods, is that data now available to everyone? Where a cookie is stored on the client machine, the fileCache data is stored on the server?

This is what I suspect is happening, just trying to be sure that I'm interpreting this correctly.


texts: What's the best way to skip CSRF for plugin controllers?

texts:
I'm working on a plugin that'll create a private API for content authors to post entries to Craft from desktop-based scripts. These scripts post data to plugin controller actions (anonymous-allowed), where the plugin will first check for valid Craft user account details or a plugin-generated key.

Since I'm still enforcing authentication, what's the best way to disable CSRF checks just for these posts when CSRF is globally enabled?

Thoughts I've had:

Attempt to put the CSRF key and token in the $_POST data as early as possible. (Probably not even possible.)
Have the client (desktop) script grab the CSRF key+token just before posting. (Inconvenient, potentially failure-prone.)
Somehow prevent CSRF protection from being enabled for requests passed to this controller.


texts:
I want to return JSON with some asset URLs, but i want these URLs to be transformed asset URLs.

Is there some way for me to get the asset transformed URL in the controller? Will the assets be automatically transformed or i need to somehow do it manually ?


texts:
I am trying to save comments using the core method "entries/saveEntry", but every time I submit the form the last comment is overwritten, is there a simple way of submitting this information to insert instead of update all the comments?

I the form working in that it relates a comment to an entry using the following form:

<form method="post" accept-charset="UTF-8">
    <input type="hidden" name="action" value="entries/saveEntry">
    {{ getCsrfInput() }}
    <input type="hidden" name="entryId" value="{{ entry.id }}">
    <input type="hidden" name="fields[usercomments][new1][type]" value="comments">
    <input type="text" name="fields[usercomments][new1][fields][commentuser]" value="">
    <input type="text" name="fields[usercomments][new1][fields][commenttext]" value="">
    <input type="submit" value="Publish">
</form>

I just dont get why the comments are being overwritten and how to just insert a new entry.


texts: Is it possible to change the group that a user belongs in the front-end?

texts:
A little background:

The website runs on Craft v.3 Pro and Commerce v.2 Pro
The user can register as a member from the front-end.
They will be able to select only one of 3 different groups to register to. (eg. Bronze, Silver, Gold member)
None of the groups will allow access to the CP.
The group type will control what content they can access on the website and what kind of discounts they can get on the online store.

Is it possible to let the user switch between those 3 different membership types via the front-end?

If this is not possible out of the box, then is it possible by writing a plug-in or via an existing one?

What is the recommended way to achieve this type of functionality?


texts: Adding a County input field into Address in Craft Commerce

texts:
Any ideas how to add custom fields to the address Model?

I want to add a free text input for County, so that it can be used for the equivalent in any country, as the shop sells to more than UK.

Upon doing so, I get the following error when trying to edit an address;

Craft\Commerce_AddressModel and its behaviors do not have a method or closure named "county".


texts: Search results query text fields and tag fields

texts: My expectation with searching was that in addition to fields marked for inclusion in search, I would be able to have a tags field, add tags, and those tags would be included in the search to display entries. Using the example search code from the documentation, when searching for a specific tag, it does not pull the entry that has that tag. What do I need to do in order to have those entries that have the tags shown in the search results?


texts: {% requireLogin %} not returning to original page

texts:
According to the Craft docs {% requireLogin %} on a page should return the user to the same page after login. This doesn't work for me - the returned page is always the one set in 'postLoginRedirect'.

In the config file, I've got this setup:

    'postLogoutRedirect' => 'members/logout',

    'postLoginRedirect' => 'members',

    'loginPath' => 'members/login'

What am I missing?


texts:
I have a 'Profile' channel that gives the profile of people.

I have 'Last name' as the title, 'first name' and I'd like to use first name in the slug rather than have to add the first name to the title and then need to create another field to store the last name.

I thought, similar to {entry.type} I could've gone for {entry.firstName} but that doesn't work.

Possible?


texts: Order entries based on last string of title

texts:
I would like to get the last string of a entry title and order entries based on that. Basically the people title are their full names and I am trying to find their last name and filter based on that, instead of their first name.

{% set entries = craft.entries.section('people').order('title').limit(0) %}

similar to this entry.title|split(' ')|last


texts: Excluding Array of Entry Ids Not Busting Cache

texts:
-- UPDATED --

My understanding of how the cache busting works is to make sure the query is within the {% cache %} tag. When looking into how it works I may not really be understanding the ins and outs of using the cache tag properly. Correct me if I'm wrong.

The goal with this example is to show posts on the index and any category page that excludes cateogry-one unless a user is viewing the category one page.

If I have an entry that is initially not tagged with category-one and it will output as expected as well as when I tag that entry with that category. However if I were to again edit that entry and remove category one the cache doesn't bust and won't output the entry.

Blog Index Code:

{# Get all the categories you want to INCLUDE #}
{% set categoryIds = craft.categories()
    .group('categories')
    .slug('category-one')
    .ids() %}

{% set excludeIds = craft.entries()
    .relatedTo({
        targetElement: categoryIds
    })
    .ids() %}

{% cache globally using key craft.app.request.pathInfo ~ '/p' ~ craft.app.request.pageNum %}

    {% set blogEntriesCriteria = craft.entries({
        section: 'blog',
        id: ['not']|merge(excludeIds),
        with: ([
            ['image', {
               withTransforms: ['medium']
            }]
        ])
    }) %}
    {% set isFirstPage = craft.app.request.pageNum() == 1 %}
    {% set limit = 10 %}
    {% paginate blogEntriesCriteria.limit(limit) as pageInfo, blogEntries %}

    {% if blogEntries %}

        {# Loop through this page's News entries #}
        {% for entry in blogEntries %}

            {% include 'includes/components/_news-card' %}

        {% endfor %}

    {% else %}

Sorry, no posts found.

    {% endif %}

{% endcache %}

Blog Category Code:

{% set catIdCheck = false %}

{# Get all the categories you want to INCLUDE #}
{% set categoryIds = craft.categories()
    .group('categories')
    .slug('category-one')
    .ids() %}

{% set excludeIds = craft.entries()
    .relatedTo({
        targetElement: categoryIds
    })
    .ids() %}

{% if category.id == categoryIds[0] %}
    {% set catIdCheck = true %}
{% endif %}

{% cache globally using key craft.app.request.pathInfo ~ '/p' ~ craft.app.request.pageNum %}

    {% if catIdCheck == true %}
        {# If true show category-one entries
        on Category One Page #}
        {% set blogEntriesCriteria = craft.entries({
            section: 'blog',
            relatedTo: category,
            with: ([
               ['image', {
                   withTransforms: ['medium']
               }]
            ])
        }) %}
    {% endif %}

    {% if catIdCheck == false %}
        {# If false show all posts that
        do not include category-one on all other
        category pages #}
        {% set blogEntriesCriteria = craft.entries({
            section: 'news',
            relatedTo: category,
            id: ['not']|merge(excludeIds),
                with: ([
                    ['image', {
                        withTransforms: ['medium']
                    }]
                 ])
          }) %}
    {% endif %}

    {% set isFirstPage = craft.app.request.pageNum() == 1 %}
    {% set limit = 10 %}
    {% paginate blogEntriesCriteria.limit(limit) as pageInfo, blogEntries %}

    {% if blogEntries %}

        {# Loop through this page's News entries #}
        {% for entry in blogEntries %}

            {% include 'includes/components/_news-card' %}

        {% endfor %}

    {% else %}

Sorry, no posts found.

    {% endif %}

{% endcache %}

I have had success with the busting the cache for the category page when I use the following code, which does not include id: ['not']|merge(excludeIds)

Any insight about the cache tag and if the id not array would be really helpful.

NOTE:
I have updated my Blog Category file to have the if statements outside of the cache tag recommended by @RitterKnight but this did not fix the cache issue related to excluding entry ids.


texts:
I have several sites running under one Craft install. Two of them are for our internal use, and one is public-facing. On the public-facing site, I need to provide a reset password function. When the email is generated to the user, it looks like this:

{Name of primary site} info@primarysite.com
Wed 2/24/2021 1:13 PM
Hey Ben,
To reset your {name of primary site} password, click on this link:
https://public-facing-site.edu/admin/set-password?code=nwKE16ULcdBfj30IDhfZWz4IOjlhkkjlf8hi75fi87aw5f8o75of757i8

Is it possible to customize this email to reflect the site which the user has accessed? Note that the domain name part of the password reset URL is the correct public-facing one. I see the area Utilities > System Messages where I can customize this, but the email still includes reference to the primary site.


texts: How do set multiple entry relations using checkboxes on a front end form?

texts:
I want to set up a form on the front-end of a site to allow logged in users to choose items from a list which represent entries in a channel using checkboxes, then save those entries as relations to an entry that the user is editing.

Using the docs and various questions here I have got setting a relationship to one entry working. However, I want to allow up to 5 relationships to be set and I can't figure out how to add further relationships.

The entry field containing the related choices is called choices.

Here's the template code I've got at the moment (simplified):

{# Get current list of choices to pre-set checkboxes #}
{% set choices = entry.choices %}
{% set choiceList = '' %}

{% for choice in choices %}
    {% set choiceList = choiceList ~ choice.id ~ "," %}
{% endfor %}

<form id="entry-edit-form" method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="choices-saved">
    <input type="hidden" name="sectionId" value="8">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="entryId" value="{{ entry.id }}">
    <input type="hidden" id="choicesList" name="fields[choices][]" value="">

    {% for choice in choices %}

            <input class="choice-checkbox" type="checkbox" id="choice{{ loop.index }}" data-id="{{ choice.id }}" {% if choice.id in (choiceList|split(',')) %}checked="checked"{% endif %} />
            {{ choice.title }}

    {% endfor %}

    <input type="submit" class="button" value="Save choices">
</form>

Then I've got some javascript that runs on form submit to loop through the checkboxes and grab the ids of the checked boxes. What format do these need to be saved in as a value to the hidden choicesList field so that an array of related ids is saved to the correct field in the edited entry?

Or is there another, simpler, way of doing this?


texts: How do I set site-specific field data via a plugin

texts:
I'm writing a custom importer plugin.  How do I import localized content into different Craft 3 sites?
Specifically, I'm writing to a Matrix field.  I've used https://craftcms.stackexchange.com/a/1414/10495 as guidance for how to write to a Matrix field and it works great.  But I'm unclear how to update a Matrix element with different content for my non-primary site.


texts:
Is there a way to dynamically get all the related products based on the product type?

I seem to be getting all the products regardless of product type when I use:

{% set products = craft.commerce.products.relatedTo(category).order('postDate desc') %}

(obviously since I don't have any categories).


texts: list entries by category, including uncategorized entries

texts:
I have a channel that is essentially a list of companies participating in an event.

Within that channel is a category group of sponsorship levels.

Companies that are sponsors are assigned a category. Companies that are just participants are not categorized.

I need to output a list of companies beginning with the categorized entries, and then the rest of the uncategorized entries.

The code I'm using below outputs the categorized list, but then I'm doing another loop for all companies (not just uncategorized).

Is there a better way, where I can exclude the categorized companies from the second loop (or include the uncategorized companies in the first loop?

{% set allCompanies = shuffle(craft.entries.section('companies').all()) %}
{% set sponsorCats = craft.categories().group('sponsors').relatedTo(allCompanies) %}

{# Loop the categories #}
{% for category in sponsorCats.all() %}

    {# Get and loop through entries related to this cat #}
    {% set sponsors = craft.entries.relatedTo(category) %}

    {% for entry in sponsors.all() %}
        entry details
    {% endfor %}
{% endfor %}

{% for entry in allCompanies %}
    entry details
{% endfor %}


texts: Laravel Homestead & Craft: Craft can’t connect to the database with the credentials in craft/config/db.php

texts:
I'm following these instructions to Setting up a local dev environment for Craft CMS with Laravel Homestead.
When I go to http://my-craft-site.dev/admin, I get:

  Craft can’t connect to the database with the credentials in
  craft/config/db.php.

Not having much luck with Google/Stack searches on the error message. I can connect to the Homestead DB via Sequel Pro using the credentials in db.php so I’m a bit confused by the error message.
DB Credentials:

u: homestead
p: secret


texts: Prevent direct access to a web page except redirect

texts:
I have redirect to a web page upon successful form submission using guest plugin. The redirected page is in announcement tone so I'd like to prevent it from direct access with exception that comes from form submission.

Is there something Craft can do?


texts: Dynamic subject for form notification email

texts: Is there a way to have a dynamic notification subject in Sprout Forms via custom fields, eg if I have a field called subject can I use this in the Subject option under Notifications as {{ subject }}?


texts:
I have a 100 articles, and with for each article 1 author. Authors can only edit their own entries.

Every article as an Asset directory called "Photo Album". This works fine. Beautiful, even.

The problem is that, when I enable

- View source
--- Upload files

.... every author from the group has access to the entire Assets, Photo Album folder, globally, so to all folders. I need to enable the "View source" part because they also need to be able to add a Caption and Copyright notice for each picture.

Under Sections, one could finegrain this

- Edit other authors’ entries
- Edit other authors’ drafts

But not with Assets.

Does anyone have a fix for this?

I don't really expect my editors to start sabotaging each others's articles but it's not very elegant, and mistakes can be made, esp with 100 directories in there.

Thanks


texts: Redactor Link Encoding create 404 errors


texts: Access pages data with fewer queries by creating an object in Twig

texts:
I have the goal of querying the database once for page info, and then using it to display information on select pages site wide.

For example, I want to link the the contact page with using a url slug like "contact" (which might change)

My thinking is to query for pages, then loop over them in twig and create an object which I can access as needed.

Here is some example code, my question is - is the best Craft like way to do this? Am I missing something that should make this easier?

{#
 # Query for all the Pages
 #}
{% set navigation = craft.entries.section('pages').all() %}

{#
 # Create an object to quickly reference pages without making additional DB queries #}
 #}
{% set pageData = [] %}

{% for item in navigation %}
    {#
     # create a dynamic property if one doesn't already exist
     #}
    {% if not attribute(pageData, 'pageId' ~ item.id) is defined %}
        {% set pageData = pageData|merge({ ('pageId' ~ item.id) : {
        'id':item.id,
        'slug':item.slug,
        'url':item.url,
        'title':item.title} }) %}
    {% endif %}

{% endfor %}

{#
 # Use the pageData object to reference pages by id as needed
 #}

Request a Bid


texts:
Is there any way to get Craft 3 to display 404.html and 503.html for the 404 and 503 pages while in devMode, as it did in Craft 2, rather than returning the entire Yii 2 error stack?

Sometimes, we have to bring a site temporarily offline (by way of toggle in the general settings tab) to add features, and we have to put it into dev mode for debug. We want the site to show the branded 503 page to the public instead of the stack page.


texts:
I am attempting to replicate the example from https://docs.craftcms.com/v3/templating/filters.html#group

However, I am unable to access the {{ year }} in the first for loop inside the h2 element. It just shows up as an empty string. Anyone have an idea whats going on?

Here is my code:

{% set allEntries = craft.entries.section('weeklyDigests').all() %}
{% set allEntriesByYear = allEntries|group('postDate.year') %}

{% for year, entriesInYear in allEntriesByYear %}

{{ year }}

   {% for entry in entriesInYear %}

{{ entry.title }}

   {% endfor %}

{% endfor %}


texts:
If have this in a template:
{% for mainLink in section.links.limit(4).all() %}
{% endfor %}

{% for secondaryLink in section.links.offset(4).all() %}
{% endfor %}

Which I thought would show the first four in the first list and however many from 5 onwards in the secondary list. But what's happening is that the second list is limiting the output to 4 as well. Why is that?


texts: Focal Point - Changes don't take effect when Saved a second, or third time

texts:
When I set the Focal Point for the first time, it works. If I change the Focal Point and save again, the changes do not take effect.

Now, if I set the Focal Point and "save as a new asset", I can use that new file and its Focal Point. But, if I change that Focal Point, I have to "save as a new asset", which creates multiple copies of the same image.

I'm also using ImageOptimize plugin. Any ideas why my Focal Point changes don't take effect?


texts:
Wondering if there is any way to force Craft to update the search index for an entry when it is saved.

Reason I ask is that on our site we have a Location entry type with lat/lon inputs that we use to maintain store locations and plot them on a map. However, when we update the lat/lon coordinates, it does not update the search index and continues to plot the old location on the map even though it is displaying the new address in the text.

We can force it to update by rebuilding the search indexes, the only downside is that it takes a few minutes and renders the site search functions useless until it is done. If there's some way for the entry to automatically update the index when lat/lon coordinates are changed, that would be awesome. Any ideas?


texts:
I am using Craft Commerce for the first time and am trying to dynamically generate a dropdown menu that contains links to each product type. I thought the best way to accomplish this would be by using a parameter in the URL i.e.

myurl.com/commerce/products?cat=books

I would be able to get the handle of the selected product type by using:

craft.commerce.products.type(productType).find()

I have two roadblocks that are preventing me from implementing this:

How do I get an array of all the product types so I can build the dropdown?
How do I get the name of a product type once I have the handle so I can display a Header at the top of the page based on the selected product type?

Also, is there a better way of implementing similar functionality that I am simply overlooking?

Thanks!


texts: Exclude certain entry types from Entry URL format?

texts:
I’m trying to find a way to ‘group’ pages in a structure, where that group page has no function other than to visually organise the entries in the structure, and does not need to be part of the url structure.. eg:

- Major Campaigns
   type: landingPageGroup
   slug: major-campaigns

    - Moving Office
       type: landingPage
       slug: moving-office
       uri: /moving-office

        - Your Moving Checklist
           type: landingPage
           slug: your-moving-checklist
           uri: /moving-office/your-moving-checklist

- Major Events
   type: landingPageGroup
   slug: major-events

    - Conference 2016
       type: landingPage
       slug: conference-2016
       uri: /conference-2016

        - Agenda
           type: landingPage
           slug: agenda
           uri: /conference-2016/agenda

If I set the Entry URL Format to:

Top level: {% if entry.type != 'landingPageGroup' %}{slug}{% endif %}

Nested: {% if object.parent.type != 'landingPageGroup' %}{parent.uri}{% endif %}/{slug}

...the URLs look correct in the entries listing, but it will throw a 404 when you try to access them... is there anyway I can get around this with some custom routing maybe?


texts: Apply updates automatically when available

texts:
Is it possible to automatically apply Craft CMS updates when they become available?

At the moment, I have to go into the CPanel and apply updates with the one-click option.

Maybe I can do this with a cron job?


texts:
I am having some issues understanding why validation is not working on my entry forms.

I've got an entry with several field types which aren't of type "entries" and the required validation is working properly on my front end forms using craft's error macro

{% macro errorList(errors) %}
    {% if errors %}
        {% for error in errors %}
        {% endfor %}
    {% endif %}
{% endmacro %}

The validation is NOT working on my fields which are of type "entries". Do you have to pass in the error object differently to the macro since "entries" are an array?

I have tried calling the error macro like this...

{% if entry is defined %}
    {{ formErrors.errorList(entry.getErrors('houseCollege[0]')) }}
{% endif %}

and this...

{% if entry is defined %}
    {{ formErrors.errorList(entry.getErrors('houseCollege[]')) }}
{% endif %}

and this...

{% if entry is defined %}
    {{ formErrors.errorList(entry.getErrors('houseCollege')) }}
{% endif %}

and yes, I have this field marked as required in the CP.

Also I don't know how relevant this is, but in the form this value is being filled by a select element.


texts:
This should have been simple.  A client's site is required to display current weather observation data retrieved via XML from w1.weather.gov.  My solution was to use the on-demand features of FeedMe in a twig template to accomplish this.

As it turns out, weather.gov recently began requiring inclusion of a user agent string in the header to identify the requestor of any XML feed.  If no user agent string is present, it returns error 403.

Is it possible to configure Craft or FeedMe to send a custom user agent string in all GET requests for external data?


texts: Sort and display panel in CP does not show all the fields

texts:
When I try to arrange some entry field in the CP's sort and display panel, the panel does not show all the fields in the server version, while it display all the fields in my local version. Although, all the fields are in sync between the two databases.
How can I get all the fields back in the panel?

Thanks for your help.


texts: Getting PHP errors to log in Nginx/PHP-FPM

texts:
Under Nginx/PHP-FPM, I can't get PHP errors logged to craft/storage/runtime/logs/phperrors.log as they should be.

Initially, errors weren't logging anywhere, but I discovered I needed:
catch_workers_output = yes in our PHP-FPM config.

Errors are now logging to /var/log/php7.0-fpm.log, but not to Craft's custom location.


texts:
How would I access a custom product field in the cart. I did it with the snapshot attribute like so:

{# cart.html #}

{% for item in cart.lineItems %}
  {{ craft.commerce.products.id(item.snapshot.product.id).first().myCustomField }}
{% endfor %}

But is that the right way to do it?


texts: How can I use the Embedded assets plugin to save assets on the front-end?

texts:
I am using the Embedded Assets plugin to get YouTube videos and its working great within the CP.

I am able to show the asset(s) on my page by using

{{ embed.safeHtml|raw }}

Which works great. I'm able to see the YT video that was uploaded in the CP. It's huge but it is getting rendered.

I would like the user to be able to "upload" videos from the front-end so reading this:

  As embedded assets are stored as JSON files

The instructions above are pretty clear - I just don't "get it". I have clicked the oEmbed page as suggested for more info to see an example json output, but I guess its getting from point A to B is what I'm not sure about.

Do I create a plainText field, and have the user paste in a video url? Then my controller method (somehow) creates the json file and saves it somewhere? I'm not sure where/how to start.

I would also like to specify a width on the rendered iframe that is getting generated, but I'm not sure how to incorporate that either.

Thank you for any suggestions!