texts: svgicons fieldtype - how to output in template?

texts:
I've added a field called icons of type svg-icons and am able to select icons I've added without an issue. I am having trouble outputting them on the front end however. I get twig errors no matter what I try.

Have done {{ dump(entry.icons) }} and get the following output where you can see 11 lines from the bottom the path and name of the select svg icon.

How do I output that to the template?

D:\path\to\craft\app\vendor\twig\twig\lib\Twig\Extension\Debug.php:56:
object(Craft\SvgIconsModel)[700]
  protected 'classSuffix' => string 'Model' (length=5)
  protected 'strictAttributes' => boolean true
  private '_classHandle' (Craft\BaseModel) => null
  private '_attributeConfigs' (Craft\BaseModel) =>
    array (size=6)
      'icon' =>
        array (size=2)
          'default' => null
          'type' => string 'string' (length=6)
      'sprite' =>
        array (size=2)
          'default' => null
          'type' => string 'string' (length=6)
      'type' =>
        array (size=2)
          'default' => null
          'type' => string 'string' (length=6)
      'resource' =>
        array (size=2)
          'default' => null
          'type' => string 'string' (length=6)
      'width' =>
        array (size=9)
          'maxLength' => int 11
          'min' => float -2147483648
          'max' => float 2147483647
          'decimals' => int 0
          'default' => null
          'type' => string 'number' (length=6)
          'unsigned' => boolean false
          'length' => int 11
          'column' => string 'integer' (length=7)
      'height' =>
        array (size=9)
          'maxLength' => int 11
          'min' => float -2147483648
          'max' => float 2147483647
          'decimals' => int 0
          'default' => null
          'type' => string 'number' (length=6)
          'unsigned' => boolean false
          'length' => int 11
          'column' => string 'integer' (length=7)
  private '_attributes' (Craft\BaseModel) =>
    array (size=3)
      'icon' => string 'general\design.svg' (length=18)
      'width' => float 512
      'height' => float 512
  private '_extraAttributeNames' (Craft\BaseModel) => null
  private '_errors' (CModel) =>
    array (size=0)
      empty
  private '_validators' (CModel) => null
  private '_scenario' (CModel) => string '' (length=0)
  private '_e' (CComponent) => null
  private '_m' (CComponent) => null


texts: How can I perform a RegEx match in Twig?

texts:
Is it possible to perform a RegEx match on a string in Twig?

I'm looking for something like this:

{% set string = "This is **string**. **wer**  qewr **234**" %}
{% set match  = string.matches(/([*][*])(.*)([*][*])/g) %}


texts: How to understand this exception error in context?

texts:
I have been trying to fine tune the performance of a heavy page:
see Category query very slow on multilingual site

It appears that my initial hope of getting the page under 2 seconds was not quite accurate.
After cache tagging the page the performance was great.
However I had left out an {% endcache %} tag - ie not closed it. This makes the performance in the network inspector less than 1 sec to load. Very nice.

However I am using Nginx microcaching set to 1 sec. As soon as I cleared the Nginx cache i started seeing the error in my template tag that was missing the closing cache tag.

So why does it load lightning fast with an unclosed tag?

When experimenting with placement of cache tags, I also managed to generate the following error in dev mode:

An exception has been thrown during the compilation of a template
("Node "body" does not exist for Node "Craft\Cache_Node".").

I was wondering what exactly this means / indicates and if there is some interaction effect I am getting between craft cache and my Nginx server cache?


texts: Craft 3 language switcher with same domain

texts:
Is it possible to create a multi language website in same domain?

In the admin settings, I created a second site with the same domain, but with a different site language.

templates/
├── index.twig      --> default homepage template
└── de/
    └── index.twig  --> German homepage template

and the on section settings for second site Template de/index

How can I toggle specific parts of my templates, depending on the chosen language?


texts: I am unable to pay $99 for Dukt Analytics. Does anyone know of a free alternative that gives me google analytics stats for the dashboard?


texts: Extend order methods to sort numbers naturally

texts:
I've encountered a similar problem as in this post: How to order numbers naturally?

I have some products I need sorted on a page by model number, and currently they sort as ABC-1, ABC-12, ABC-2, etc. instead of ABC-1, ABC-2, ABC-12. Is it possible to extend the existing methods or create a custom sort method to use with the order parameter, rather than using a twig filter as suggested in the link above?


texts: Listing categories with post count in a nav?

texts:
I'm trying to list my categories (and sub categories, just one sub level) as a nav, and have the number of entries in each of those categories beside each one.

There is another question on here which achieves a simple list here but trying to apply that logic to what i have for my nav is scrambling my brain as everything I've tried throws an error.

This is what i have, taken from the Get Help section of the craft site:

{% nav category in craft.categories.group('articleCategories') %}

        {{ category.title }}
        {% ifchildren %}

                {% children %}

        {% endifchildren %}

{% endnav %}

Any thoughts on how i can get the number of entries each category has in it, in this?


texts: Freeform online signing field-type options

texts:
Are there (3rd party) plugins for Freeform where you can add an online-signing field type?

Something like approve.me or docusign?
https://www.approveme.com/gravity-forms-signature/

If not, are there any API services which you would recommend/work best with FreeForm and EE, so we can create a custom plugin/addon?


texts: Automated deployment with content migrations and structural changes

texts:
In the knowledge base article there are 4 steps described to automate the deployment process

Pull updates for git
Run composer install
Run migrate/all
Run project-config/apply

The problem with this is that when you have pushed a structural change (eg. adding a new field) and a content migration (adding new entry using that new field) at the same time, it fails because you cannot migrate into a non existing field of course
You cannot flip step 3 and 4 as in that scenario changes made to Craft CMS are not yet available in the database.


texts:
I dumped from Craft my database from server A and am trying to install it to a fresh copy of Craft on server B.

I've got Craft up and running, and when I try importing my Craft SQL file in PHPmyAdmin, I get an error every time:

Is there something I need to setup in Craft regarding asset files before my import will work?


texts: Craft 3.5.1 CLI Update Error: Failed to instantiate component or class "yii\shell\Bootstrap"

texts:
when I try to update Craft via CLI to 3.5.1. I get the following error:
Failed to instantiate component or class "yii\shell\Bootstrap
in /vendor/yiisoft/yii2/di/Container.php:449

Stack trace:
#0 /vendor/yiisoft/yii2/di/Container.php(374): yii\di\Container->getDependencies()
#1 /vendor/yiisoft/yii2/di/Container.php(159): yii\di\Container->build()
#2 /vendor/yiisoft/yii2/BaseYii.php(345): yii\di\Container->get()
#3 /vendor/yiisoft/yii2/base/Application.php(294): yii\BaseYii::createObject()
#4 /vendor/craftcms/cms/src/console/Application.php(72): yii\base\Application->bootstrap()
#5 /vendor/yiisoft/yii2/base/Application.php(273): craft\console\Application->bootstrap()
#6 /vendor/yiisoft/yii2/console/Application.php(124): yii\base\Application->init()
#7 /vendor/craftcms/cms/src/console/Application.php(58): yii\console\Application->init()
#8 /vendor/yiisoft/yii2/base/BaseObject.php(109): craft\console\Application->init()
#9 /vendor/yiisoft/yii2/base/Application.php(206): yii\base\BaseObject->__construct()
#10 /vendor/yiisoft/yii2/console/Application.php(89): yii\base\Application->__construct()
#11 /vendor/craftcms/cms/src/console/Application.php(48): yii\console\Application->__construct()
#12 [internal function]: craft\console\Application->__construct()
#13 /vendor/yiisoft/yii2/di/Container.php(400): ReflectionClass->newInstanceArgs()
#14 /vendor/yiisoft/yii2/di/Container.php(159): yii\di\Container->build()
#15 /vendor/yiisoft/yii2/BaseYii.php(365): yii\di\Container->get()
#16 /vendor/craftcms/cms/bootstrap/bootstrap.php(245): yii\BaseYii::createObject()
#17 /vendor/craftcms/cms/bootstrap/console.php(51): require('/var/www/client...')
#18 /craft(21): require('/var/www/client...')
#19 {main}

does anyone know what to do about it?


texts: Add options to multi-select with Javascript

texts:
Well, I need to add options to a select field with Javascript. I do that with $(...).append(...), the problem is that I get a "Invalid" message. I think it's because the new option's value is not in the available options.

My question is then: Can I add a wildcard to the options? or bypass the validation for this field?

Any better idea?

Thanks!


texts: How to build a great multi-lingual navigation with channels, structure, and manageable in the CP

texts:
I'm working on a complex website with multi locales, channels, structures and different designs per page. And the site needs a breadcrumb path.

My client needs to manage and add items the to menu.

This is a simple overview of the navigation:

Home
About us

Profile
History (different template)
Staff (listing with entry url's)
Jobs (listing)
etc

investor relations

finance
results (with iframe)

portfolio
press (custom url to external page)
etc

So no hard coding. What is the best solution to build this?

I think this is still a difficult thing in Craft. We need something like Navee or Structure (expression engine) to have a client friendly navigation system.

I've tried CraftNav. But it is still too simple.


texts: Private plugin distribution in Craft CMS 3

texts: what is the best way to install private plugin in Craft CMS 3? The private plugin is installed in private GitHub repo, but we don't have a custom packagist that we would use, therefore I wonder if there is any option to enable private plugins via composer/plugin-installer?


texts: Craft suddenly no longer works on Heroku

texts:
I’ve suddenly started having problems with Craft on Heroku. It worked fine for a while but if I composer install anything later than Craft 3.2 I get the same error back from Heroku:

2020-02-21T01:22:32.775659+00:00 heroku[router]: at=info method=GET path="/" host=connor-heroku-test.herokuapp.com request_id=7df849c1-4f9b-46f3-aaba-2bf88e0f0b1e fwd="151.226.158.115" dyno=web.1 connect=0ms service=52ms status=500 bytes=182 protocol=https
2020-02-21T01:22:32.775695+00:00 app[web.1]: [21-Feb-2020 01:22:32 UTC] PHP Fatal error:  Uncaught Error: Call to undefined function mb_regex_encoding() in /app/vendor/voku/portable-utf8/src/voku/helper/UTF8.php:490
2020-02-21T01:22:32.775707+00:00 app[web.1]: Stack trace:
2020-02-21T01:22:32.775896+00:00 app[web.1]: #0 /app/vendor/voku/portable-utf8/bootstrap.php(7): voku\helper\UTF8::checkForSupport()
2020-02-21T01:22:32.776075+00:00 app[web.1]: #1 /app/vendor/composer/autoload_real.php(66): require('/app/vendor/vok...')
2020-02-21T01:22:32.776292+00:00 app[web.1]: #2 /app/vendor/composer/autoload_real.php(56): composerRequiredcd24579acb46ca3092f278cf90a0024()
2020-02-21T01:22:32.776510+00:00 app[web.1]: #3 /app/vendor/autoload.php(7): ComposerAutoloaderInitdcd24579acb46ca3092f278cf90a0024::getLoader()
2020-02-21T01:22:32.776658+00:00 app[web.1]: #4 /app/web/index.php(11): require_once('/app/vendor/aut...')
2020-02-21T01:22:32.776702+00:00 app[web.1]: #5 {main}
2020-02-21T01:22:32.776885+00:00 app[web.1]: thrown in /app/vendor/voku/portable-utf8/src/voku/helper/UTF8.php on line 490
2020-02-21T01:22:32.777446+00:00 app[web.1]: 10.32.124.137 - - [21/Feb/2020:01:22:32 +0000] "GET / HTTP/1.1" 500 5 "https://dashboard.heroku.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15

Every version I’ve tried works fine on local.

Any ideas about what I can do to sort this?

Thanks!


texts:
I'm working on improving the performance of my website, and for some areas, I believe eager-loading will help. On each page of the site it's possible to bring out related entries at the bottom, but these can appear in different formats: some as just titles with links, others with images, titles.

This is the twig code for bringing out one of the more complex formats:

{% set entries = craft.entries({
                section: 'block.entryTypes',
                relatedTo: 'relatedTo',
                limit: 'limit',
                id: 'notValue',
                order: 'block.order',
                postDate: '">= " ~ now|date_modify{block.until)',
                with: [
                    'leadImage',
                    'type',
                    'indexHeading',
                    'externalRedirect',
                    'posterColor',
                    'noLink',
                    'articleCategory',
                    'price',
                    'addressTable',
                    'brief'
                ]
            }) %}

Is it possible to set the "with:" section depending on the format of the list I choose? So it's something like:

{% if displayType == "teaser" %}
{% set params = "'leadImage', 'type', 'indexHeading', ... 'brief'" %}
{% endif %}
...
with: [ params ]
...

Thanks


texts: Ordering homepage posts by date, but give customized ordering option in CP

texts:
I'm looking to combine three different channels on the homepage, ordered by date, unless the client rearranges the hierarchy in the CP.

Low Reorder for EE had this customization, where entries would come into the plugin ordered by date, but you could drag and drop entries to the top if you wanted to rearrange the hierarchy.

Craft Structures is close, but 1) I need to combine three different channels into one hierarchy, and 2) these channels will grow immensely over time, so Structures will become cumbersome.

What are my options, if any? Is there a Low Reorder-type plugin out there?


texts: Update Asset Indexes not working for large number of assets

texts:
I am trying to index 1.8GB of assets to an asset source on Craft.

I have created an Asset Source which points to the folder with all of the assets. When I select the Asset Source I want to update the index for and select "Go" the loading screen runs for a while, then shows me a confirmation checkbox, but nothing has happened.


texts: How to merge multiple 'relatedTo' queries via query parameters

texts:
I'm trying to augment a Commerce query with additional parameters like so, but I can't get 'colour' and 'range' working together. Clearly my and/relatedTo syntax is wrong but how exactly?

  {% set colour = craft.app.request.getQueryParam('colour') ?? null %}
  {% set range = craft.app.request.getQueryParam('range') ?? null %}

  {% set query = {
    type: 'fabric',
    limit: 999,
    orderBy: 'defaultSku asc'
  } %}

  {% set query = colour is defined ? query|merge({ relatedTo: ['and', { targetElement: craft.categories.slug(colour) }]}) : query %}

  {% set query = range is defined ? query|merge({ relatedTo: ['and', { targetElement: craft.categories.slug(range) }]}) : query %}

  {% set swatches = craft.products(query).all() %}
  {% for swatch in swatches %}

(Also need to add further queries params for texture etc which are also related to categories)


texts:
I'm getting the following message, when I try to access craft admin.
I have both the zip and unzip installed. Not sure why I'm getting this error.

MESSAGE:
Can’t run Craft CMS :(
Your server doesn’t meet the following requirements to run Craft CMS:
The zip extension is required for zip and unzip operations.
Please talk to your host/IT department about upgrading your server.


texts: Has anyone converted a Bootstrap based website to Craft?

texts:
Is there any reason you wouldn't want to do this?

EDIT: More info

I have a website that was built in HTML/CSS and over the years, it's been modified, added to and hacked at to the point where the code is kind of a mess. I'd like to redesign the site using a structured CMS but I want the base HTML/CSS to be well coded and optimized. That's why I'm thinking of building a site using the Bootstrap framework and then rebuilding it in Craft. I realize this seems redundant but I'm not good enough with CSS to just build it from the scratch in Craft. I'm more of the cut and paste kind.

The reason I'm considering Craft is because I like the idea of defining fields and sections I can reuse. I built the site 90% through using ModX, it looked good but the back end and the way it presents Template Variables is not very friendly. I like Craft's approach a lot more.


texts: How to add content to pages using a plugin?

texts:
I am developing a plugin for Craft 3. And I am trying to add some content to all pages in the CMS using this plugin. How can I do that? Is there a method or class call I can use for this? I am not sure where this is mentioned in the docs either.

Basically I want to add a few lines of HTML, CSS and JS in all the pages of the CMS if my plugin is installed and enabled in that Craft installation. Any ideas, anyone?


texts: Use a custom field type in Matrix Blocks - Craft 3

texts:
I'd like to create a field of type Dropdown/Table (or even use a field from a plugin like color-swatches) and have it available when selecting a matrix block element field type:

In this case, it's for creating a field containing a set of color values, a palette.

I'd like to know whether or not this is a common approach and what solutions do you usually give to this.

Thank you.


texts:
I have a URL passing values from form checkboxes to a template. All the checkboxes are grouped with the same name= attribute. When multiple checkboxes are selected, the query string looks something like:

?checkValue=12345&checkValue=23456&checkValue=34567

However, craft.request.getQuery('checkValue') returns only the last value (34567 in this case).

How can I retrieve all the values so they can be used and manipulated?

EDIT: I've corrected the naming of the checkboxes from name="checkValue" to name="checkValue[]", so now my query string looks like this:

?checkValue%5B%5D=12345&checkValue%5B%5D=23456&checkValue%5B%5D=34567

Does that change what can be accessed using craft.request.getQuery('checkValue')?


texts: Invalidate cache from two channel expiry dates

texts:
I have two channels: A event and a news channel which I want the cache to expire based on both their expiry Date.

{% set newsDate = craft.entries.section('newsDate').order('expiryDate asc').first() %}
{% set eventDate = craft.entries.section('event').order('konzertStartdate asc').first() %}
{% set currentTime = now |date('c') %}

{% if currentTime <= newsDate %}
    {% set invalidate = newsDate.expiryDate | date('c') %}
{% else %}
    {% set invalidate = auffuehrung.konzertStartdate |date('c') %}
{% endif %}

{% cache unless invalidate %}
 {# blablabla #}
{% endcache %}

As you can see I create two variables and then check which one is newer. But its not working properly.

The news never seem to invalidate the cache.

Do you know a better way to do this?


texts:
Hey there and thanks in advance. We just moved our site to production as a beta site. The only thing that is different between this site and our local/staging site is the config file. The allowUpdates and allowAdminChanges is set to false. Databases are separate and all sites are running.

We I update entries on prod, they save but my site does not update. When I do the same change on local/dev the changes render on my dev site.

Am I missing something? Does allowUpdates and allowAdminChanges affect whether or not content will be updated on the site? Thought it might be a cache issue but why would it work on dev and not prod?

Any thoughts on this would be greatly appreciated.

Thank you,


texts: Ignore Twig's variable and transform it to Polymer's variable.

texts:
I've encountered on a problem with escaping, where I want some parts of code, not being translated by Twig.

Straight to the problem.

Polymer, uses the same marking for variables as Twig, and I'm not sure, if it's possible to escape variable as a Twig's variable and transform it to a Polymer's variable

By Twig's documentation, I've end up with this:

<iron-media-query query="(min-width: 600px)" query-matches="'{{'{{queryMatches}}'}}'">

where it translates to:

<iron-media-query query="(min-width: 600px)" query-matches="'{{queryMatches}}'"></iron-media-query>

The goal is:

<iron-media-query query="(min-width: 600px)" query-matches="{{queryMatches}}"></iron-media-query>


texts:
I'm having issues with getting results from a query. I have 2 search parameters which i have set to variables. I would like to match both of these to get results.

At the moment the query is returning zero results. I think this is because it is turning the variables into strings. Replacing the variables with hardcoded values does return results.

{% set queryKeyword = craft.request.getParam('q') %}
{% set queryLocation = craft.request.getParam('l') %}

{%
    set entries = craft.entries.section('schools').find({
       search: 'body:queryKeyword categories:queryLocation'
    })
%}

I have tried:

{%
    set entries = craft.entries.section('schools').find({
       search: 'body:' + queryKeyword + 'categories:' + queryLocation,
    })
%}

This doesn't work.

I'm very new to Craft CMS and am not very experienced in PHP/MySQL so any help would be greatly appreciated. Thanks!


texts: How can I import users from WordPress to Craft CMS?

texts: I want to import users from WordPress to Craft CMS. How can I do that?


texts:
Assume a front end registration form. I would like to validate user passwords before posting to the server. I have not been able to find the default password requirements as of yet for craft 3. Could someone fill in the blank?

From what I have found:

At least one capital letter
At least one lowercase letter
No more than 160 characters


texts: How can I get the parent author from sprout forms to send to sprout mail?

texts:
I am including a sprout form on my template like this:

...
{{ craft.sproutForms.displayForm('myForm') }}
...

I am submitting the form via ajax, and when the form is submitted I am trying to set the recipient in Sprout Email to the form's container author.

{author.email}

So it's not the author of the submitted form/entry, it's the author of the entry that the form is sitting on that I'm trying to access.

I'd really like to avoid passing in an email from a hidden input if at all possible. Thank you for any suggestions!

Update

For example, I am on the page a.html which  has an author of damon@email.com. On a.html there is a contact form. When a user submits the contact form, I want a confirmation email sent tothem, and then an email sent to the author of the entry that the contact form is on. The same contact form can live on any page, and each page could have different authors.

a.html has an author of damon@email.com
b.html has an author of foo@email.com

In the above case, a confirmation email needs to go whomever filled out the form, and then a notification email to each of the entries respectively.

Update 2

I am getting closer I think, but struggling to dynamically set the recipient.

Here is my form:

...
{% set form = craft.sproutForms.form('myForm') %}
<input type="hidden" name="action" value="sproutForms/entries/saveEntry">
<input type="hidden" name="handle" value="{{ form.handle }}">
<input type="hidden" name="entry" value="{{ entry.id }}">
<input type="hidden" name="author" value="{{ entry.author.id }}">

Then in my plugin I am doing this:

craft()->on('sproutForms.onBeforeSaveEntry', function (Event $event) {
    if (craft()->request->isSiteRequest()) {
        if (craft()->request->getPost('author') != '') {
            $owner = craft()->users->getUserById(craft()->request->getPost('author'));

            if ($owner) {
                if ($event->params['isNewEntry']) {
                    $entry = $event->params['entry'];

                    $entry->setContentFromPost(array(
                        'ownerEmail' => $owner->email, // damon@email.com
                    ));

                   // Set {ownerEmail} as recipient in notification?
                }
            }

In my ajax response I am seeing:

{"errors":[]}

In the sproutemail.log I am seeing:

[error] [plugin] No recipients found.

In the recipient field I have tried {ownerEmail} and {object.ownerEmail} both having no success.

I have also tried setting field values just in the off chance...

{% do craft.sproutForms.addFieldVariables({ entry: entry }) %}

The whole purpose of this is that I am trying to avoid putting a person's email in a hidden input. Just so that if a user of the site viewed the source the author's email wasn't right out in the open.


texts: How sell products with Craft and secure the product viewing pages?

texts:
I have a client that wants to sell products (digital content) that are only viewable in templates. These are not PDFs. The template page will have content on it that is only available to people that purchased the product. This is not a subscription, but a product sale with unlimited viewing after purchase via a secure login area.

What would be a good Ecommerce option for this project as there could be multiple products purchased at once? How can I make it so only validated purchasers can see the template content of the products purchased? Snipcart looks cool but no idea how to secure the templates for valid purchasers. Any better way to do this?

Thanks

Bryan


texts: Upsell/Cross-sell plugin on Craft Commerce

texts:
I am an end-user and I help run an e-commerce company. We are exploring Upsell/Cross-selling during checkout and I am not able to find a plug-in or documentation on how to implement it.

Has anyone else implemented it?


texts: GoogleMaps plugin marker setOptions error

texts:
There's something that I'm missing in the migration from smartMaps to GoogleMaps. I have a series of points that represent different types/outcomes/modes of transportation crashes. I'm setting options on the markers and then trying to push that back into the googleMaps markers.
This worked with smartMaps but my JS-skillz are not super strong and I'm getting an error:
Example:
Uncaught TypeError: Cannot read property 'mapAlpha.5981.address' of undefined
What am I missing here?
 {% set locations = craft.entries.section('crashes').all() %}

  {% set options = {
    id: 'mapAlpha'
  } %}

  {{ googleMaps.map(locations, options).tag() }}

  <script>

    var crashMarkers = Array();

    {#  Loop through entries and add settings to markers #}
    {% for entry in locations %}
      var markerId = 'mapAlpha.{{ entry.id }}.address';

      // Uncaught TypeError: Cannot read property 'mapAlpha.5981.address' of undefined

      googleMaps.marker[markerId].setOptions(
          {
              'icon': '{{ icon }}',
          }
      );

      crashMarkers.push(googleMaps.marker[markerId]);

    {% endfor %}

</script>


texts:
I want to get entries randomly every minutes like setTimeout in javascript. Like below If possible.

            setTimeout({ {% for entry in craft.entries.section('alumni').order('RAND()').limit(6).find() %}

                    {% set asset = entry.profileImage.first() %} {% if asset | length %}

                    {% else %}

                    {% endif %}

                                {{ entry.title }} {{ entry.lastName }}

                        {{entry.graduateYear}}

            {% endfor %} }, 1000);


texts:
I have installed WampServer in Windows machine.
WampServer services (PHP, Apache and MySQL) started successfully.
When I am trying to access public folder (http://localhost:8080/CraftCMS/public/) from CMS project through web it is showing an error:

  Our site is temporarily unavailable. Please try again later.


texts: Security test generated large compiled_templates directory, site outage

texts:
We just moved an installation of one of our sites to a new server. Previously, it was on a machine where the versions of Ubuntu / PHP prevented us from upgrading the Craft core version from 2.3.x to 2.6.x.

A few days ago, our client ran one of their security penetration tests that result in a large number of 404 HTTP requests against our site. This test generated enough unique cached templates in /craft/storage/runtime/compiled_templates to fill up the remaining disk space on the server - which appeared to take MySQL service down and serve 500 template errors afterwards.

Since bringing the site back up, we've been trying to identify and resolve the root issue behind the template caching that took the site offline. We've read this thread and are trying to formulate the right questions to prevent this from happening to this site the next time the client runs their tests.

Were there any significant changes in how Craft was handling template caching between versions 2.3 and 2.6 that would've allowed the old site to handle a spike in traffic without this issue?
Is there a configuration setting we missed to either avoid caching 404 pages, or reference the same cached template for all 404 requests?
Are there any special directory or file permission considerations to take into account that would prevent Craft from periodically clearing disk space here? Are there any automated cleanup tasks that should have run before the directory filled up?
Are there any OS, PHP or Apache settings that we should compare between the old server and new server that would help clarify the issue?


texts:
As a follow-up to this thread, I would like to know how to create custom validation rules for plugin settings, or at least how to return field errors to the plugin settings view. I currently have:

<?php namespace Craft;

class SamplePlugin extends BasePlugin {

    function getName() { ... }
    function getVersion() { ... }
    function getDeveloper() { ... }
    function getDeveloperUrl() { ... }

    public function getSettingsHtml()
    {
        return craft()->templates->render('sample/settings', [
            'settings' => $this->getSettings()
        ]);
    }

    public function prepSettings($settings)
    {
        // I'm currently doing my 'custom' validation here. But if
        // there's an error, how do I display errors on the settings page?

        return $settings;
    }

    public function rules()
    {
        // Tried this, but since SamplePlugin isn't a Model, it does nothing.
    }

    protected function defineSettings()
    {
        return [
            'mySetting' => [
                AttributeType::String,
                'required' => true,
                // Can custom validation rules be set here?
            ]
        ];
    }

}


texts: Problem adding new locale / Resaving matrix blocks Failed / Table 'matrixcontent_files' doesn't exist

texts:
I've got an error message from my craft (2.6.2990) after adding a German locale:

  Resaving all localizable elements: Failed

  Resaving matrix blocks: Failed

in the sidebar and here is what I found in craft logs:

2017/09/20 14:52:13 [error] [system.db.CDbCommand] CDbCommand::fetchAll() failed: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'zg_blike.craft_matrixcontent_files' doesn't exist. The SQL statement executed was: SELECT `elements`.`id`, `elements`.`type`, `elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_i18n`.`slug`, `elements_i18n`.`uri`, `elements_i18n`.`enabled` AS `localeEnabled`, `content`.`id` AS `contentId`, `matrixblocks`.`fieldId`, `matrixblocks`.`ownerId`, `matrixblocks`.`ownerLocale`, `matrixblocks`.`typeId`, `matrixblocks`.`sortOrder`

I checked the DB and of course did not find table called craft_matrixcontent_files, instead only craft_matrixcontent_file

Any ideas?


texts:
I am moving our current site to a subdomain and get this: "Craft CMS requires the PHP multibyte string extension in order to run."

I have updated the $craftPath variable and System->General->SiteUrl CP setting to the updated URL.

Am I missing something?


texts: How to programmatically add fields to matrix blocks?

texts:
I am easily able to add a Matrix. I am also easily able to add a BlockType to that matrix. → I am fine so far.

But I have no clue what I am missing when I try to add fields to my blocks using the following example (excerpt from a custom plugin).

/**
 * Performs any actions that should occur after the plugin is installed.
 */
public function onAfterInstall() {
    //  create new group
    $fieldGroup = new FieldGroupModel();
    $fieldGroup->name = 'Awesome Field Group';
    //  save group
    craft()->fields->saveGroup($fieldGroup);

    //  create matrix field
    $matrixField = new FieldModel();
    $matrixField->handle = 'myMatrixField';
    $matrixField->name = 'Awesome Matrix';
    $matrixField->type = 'Matrix';
    $matrixField->required = true;
    $matrixField->translatable = true;
    $matrixField->groupId = $fieldGroup->id;
    //  save matrix field
    craft()->fields->saveField($matrixField);

    //  create block type
    $blockType = new MatrixBlockTypeModel();
    $blockType->handle = 'myAwesomeBlock';
    $blockType->name = 'Awesome Block';
    $blockType->fieldId = $matrixField->id; //  also craft()->fields->getFieldByHandle('myMatrixField') possible

    //  save it
    if (craft()->matrix->saveBlockType($blockType)) {

        //  UNTIL HERE EVERYTHING WORKS PRETTY FINE.

        //  on saveField() in fields service the given field's context value is ignored because it's overwritten with "craft()->content->fieldContext"
        //  so, after saving the field's context is "global", but we want something like "matrixBlockType:<id>"
        //  --> temporarily change this value to ensure we cann passe the block type id
        $tmp = craft()->content->fieldContext;
        craft()->content->fieldContext = 'matrixBlockType:' . $blockType->id;

        //  create field
        $field = new FieldModel();
        $field->handle = 'myTestField';
        $field->name = 'Awesome Field';
        $field->type = 'PlainText';
        $field->required = true;
        $field->translatable = true;
        //$field->context = 'matrixBlockType:' . $blockType->id;
        //  … last line is commented out because Craft ignores this value --> see implementation of FieldsService::saveField();

        //  save field
        craft()->fields->saveField($field);

        //  FIELD IS ADDED TO DATABASE BUT I CAN'T SEE IT IN MY MATRIX BLOCK

        //  restore original value of "craft()->content->fieldContext"
        craft()->content->fieldContext = $tmp;
    }
}

I hoped this is enough to add fields to block types. But as you can see in the screenshot below my "Awesome Field" is missing. :(

When adding this field manually in Craft's admin panel the field definitions in my database look exactly the same. So, any other important step is missing here. I have no idea which one.

What do I have to do to add fields to matrix blocks?

I hope someone can lead me into the right direction. Thanks in advance. :)


texts: BE formatted dates not imported correctly (or not at all)

texts:
I've also raised this question / issue at https://github.com/engram-design/FeedMe/issues/255 but this forum might be a better a place as I'm unsure if it is a bug actually

FeedMe uses date_parse to parse dates in an inbound feed. This usually works out great, the problem I have now is a certain XML-feed is using the Belgian date format (dd/mm/yyyy). I'm unable to change that unfortunately.

2 issues:

in case the dd is > 12, the import does not process the date
when dd <= 12, it does import them but for some reason it has an -2h offset. Probably some timezone issue, as the timezone is set to Europe/Brusssels, which is CET+2h

Is there a way to

preparse the dates somehow, to make sure the dates are available in a format that can be understood at all time (eg. yyyy-mm-dd)?
set the timezone somehow, so the feedme / craft knows the dates are being presented in CET+2h already?

EDITED

The timezone issue (second bullet) appears to be a known issue, see https://github.com/engram-design/FeedMe/commit/a923b67350341dcb17a628376bbb9ab4aa373780
This commit did not make it to a release yet (I'm using the most recent one 2.0.7 that doesn't contain this bug fix), if you use the codebase that is currently on the master branch this issue is fixed!
This leaves me with just 1 to go!


texts: How to include a lightswitch for each related entry in the source element of a relationship

texts:
I have a Services section in which I keep a related entry field for News. (News by Service) The News items to be displayed for each service are selected in a "News" entries field in the Service entry. For each related news entry, I need to be able to include Lightswitch booleans for "alert" and "pinned", each with different behaviors on the front end. For instance, when an admin adds a related news entry to a service, they also should be able to determine if that new entry is either an alert or a pinned news item, but only for the current service.

I'm able to included related news in each service template, but I'm unsure how to accomplish having a lightswitch that appears for each related news item in the services cp. So that, for instance, news entry A is only an alert in Service B. Or news entry C is only pinned for Service D.

I guess I could create pinnedInService and alertInService entry fields in the News section, but this seems convoluted. Maybe this is best done in the News item, rather than in the Services entry? I'd also like to be able to expire or unpin the news entries based on a date field (also per service).

Any direction on how to accomplish this? Thanks in advance!


texts: Fatal error: Allowed memory size of 134mb exhausted

texts:
I have a template in my control panel (technically a plugin, but it's just one template) which is running out of memory:

  Fatal error: Allowed memory size of 134217728 bytes exhausted (tried
  to allocate 78 bytes) in
  /var/sites/t/thames-arbitrators.org.uk/craft/app/helpers/ModelHelper.php
  on line 101

In my local dev site, the profiler is giving me the following info:

Time 10.66053s
Memory: 127,544Kb
Total Queries: 381

Is there anything I can do to alleviate this? I've seen the answer to 'PHP Fatal error: Allowed memory size of X bytes exhausted' but there are only two conditionals in this template, it's almost certainly down to the fact that I need to return several hundred entries.

I don't mind posting my template here but there's a big table in it so it's going to make the page super long - let me know which bits you need.


texts:
Has anyone used this plugin recently: https://github.com/ObiruLabs/craft-flickr-photopicker ?
I have just tried to start using it but it does not display any photos - it seems to be looking for photo sets but I don't see an option within Flickr for photosets.


texts:
I'm moving an e-commerce site over from EE. Many of the products have a "product image". Many do not, but we have an assets directory full of images that match their SKUs.

When listing the products by category, I want to call images in the following order:
1. If there's a product image, crop and display the product image.
2. Else if there's an asset filename that matches the product SKU, crop and display that asset.
3. Else, display a stock image that says no image available.

I'm running in to a problem with step 2. I can display the product SKU in lowercase in the template, but I don't know how to make the asset query using the product SKU.

How can I get the results of productPic in to the assets query below it?

{% for rental in rentals %}

        {# If there's a product image, crop and display the product image.#}
        {% if rental.productImage|length %}
        {% set image = rental.productImage.one() %}

        {# Elseif there's an asset filename that matches the product SKU, crop and display that asset. Using rental.title temporarily to trigger this conditional. #}
        {% elseif rental.title|length %}
        {% set variant = rental.defaultVariant %}
        {% set productPic = variant.sku|lower %}
        {{ productPic }}
        {% set image = craft.assets.filename('').one() %}

        {# Else, display a stock image that says no image available. #}
        {% else %}
        {% set image = craft.assets.id(9225).one() %}

        {% endif %}

    {{ rental.title }}

{% endfor %}


texts: How do you use the Element API plugin to output Matrix blocks for an entry?

texts:
I am having a hard time trying to figure out how to pull matrix blocks within an entry into the single entry's endpoint with the Element API plugin.

Is this possible? Or do I need to output the blockId's and then create another API endpoint to query by the matrix block id?


texts: Find entries that have a category selected from a category field within a matrix block

texts:
I've got a Section that uses a Matrix field, that has a block, that has a categories field in it.

I want to find all entries using this Matrix field, who has a categories field and has a certain category selected.

I'm looking at the Relations documentation and trying the following code, but perhaps i'm barking up the wrong tree here?

{% set cat = craft.categories.slug('print') %}
{% set entries = craft.entries.section('projectsEntries').relatedTo({
sourceElement: cat,
field: 'contentBuilder.relatedCategories.content'
}) %}

{% for entry in entries %}

{{ entry.title }}

{% endfor %}


texts: How to disable loops from automatically wrapping non-marked up content?

texts:
So I've got a completely clean install of Craft 3: RC 2. I've installed Redactor, and nothing else.

In the templates/index.twig file; this is all I have:

{% set test = ['one', 'two', 'three'] %}

{% for t in test %}
  {{ t }}
{% endfor %}

Output:

After some trial and error, I figured out that content without any html markup will be wrapped with 'pre' tags by default. Is there an option to stop this behaviour? Maybe a general config option I can disable?


texts: Where exactly are my element type custom statuses stored and used?

texts:
I have custom statuses working on the control panel for my plugin. However, there are a few issues I have with custom statues.

Looking through the database, I am unable to figure out exactly where the custom status is stored. I have my table 'craft_pluginName' with my records. My field layouts exist and so does everything else needed for my element type.

However, I still can't find the custom status. Browsing through the 'craft_content' table I see the content, related to my element type. Yet I still don't see anything related to a status.

Is the assumption that my table 'craft_pluginName' is supposed to contain a column named 'pluginNameStatus' and I then have to hook that into the element type (for a lack of better term)?

Edit:
More research uncovered that 'craft_elements' has id, type, enabled and the typical time stamps. The column 'enabled' is a boolean so it can be only 0 or 1. Updating that value manually in the database updates the 'status' on my element type index view..

I feel that this 'status', which is shown when your element type has 'hasStatus' set to true. I do not feel that this really allows us to use custom statuses as you are more than likely going to have more than two options for a custom status. In my case: 'pending', 'approved' and 'denied'.

So I am still at a loss on how we actually use custom statuses in our element types, as the default right now is either on or off...


texts: How to build a transactional email platform with Craft

texts:
I am building a transactional email platform for my users.
Users will subscribe to a digital program and receive daily emails depending on their profile and parameters.

This email sending will be:
 - time based
 - and user subscription based
 (and not event based)

So I found these plugins:

Sprout Email > for marketing campaigns and email notifications triggered by events
Postmaster for Craft CMS > looks more promising for my need but the plugin seems not maintained anymore (last commit was two years ago)

So do you know another recent Craft plugin to do transactional emails?
Or would you recommend another approach/idea?


texts:
Got the following issue:
Building a site in 3 languages, Dutch, French & English

All working fine, except the siteurl for building the href link that's going wrong.
EN & NL ok, FR won't output.
If I call craft.locale, it says nl_be instead of fr.

Any ideas? I must be missing something...


texts: Help with picking the right template tactic: include, embed, use, macro

texts:
I've run up against the limits of includes and macros for the context before me and can't quite get my head round other options such as use and embed, which I've never had need to use before.
I know that a variable established in a parent template, and subsequently altered in a child include, is not available in its updated state to the parent template later:
{% set var = null %}
{% include 'childTemplate' %} {# <-- do something in there with `var` #}
{# back in the parent `var` is still null #}

So I know the following cannot work but it's the essence of what I want to achieve. (Lots of other conditional complexity not shown.)
{# Compose variable content #}
{% set allPeople = {} %}
{% set programme %}
    {% include 'partials/_programmeList' %}

        {# `_programmeList` scope incorporates #}
        {% for item in progItems %}
            {% set personas = item.fieldHandle.all() %}
            {% include 'partials/_progItemPeople' %}

                {# `_progItemPeople` scope incorporates #}
                {% for persona in personas %}
                    {# run a macro that builds finicky `hCard` markup #}
                    {# want to merge `{(persona.id):hCard}` into `allPeople` #}
                {% endfor %}
        {% endfor %}
{% endset %}

{# Output #}
{% block content %}
    {{ programme|raw }}
    {# want to do something with an updated `allPeople` #}
{% endblock %}

The reason _progItemPeople is a grandchild include is because personas gets set twice within item, once for each of 2 different fieldHandles, and so _progItemPeople gets run twice.
Can use and/or embed help me out with compiling allPeople here? I've done some reading around but haven't managed to join the dots yet.


texts: Can You Make a Custom Field with multiple columns?

texts:
I have a custom field where I'm defining AttributeType::Mixed in order to achieve the affect of saving multiple pieces of data for a single field. The data gets stored as JSON as expected. Quick example shown below:

public function defineContentAttribute()
{

    return AttributeType::Mixed;

}

I was wondering though, is it possible to define multiple columns for a single field? If so will the field then require its own table? Not sure where to begin with this one.

Thanks for any assistance.


texts: Charge 2 form that has multiple one of plan amounts?

texts:
I have been trying to set up a Charge 2 payment form and have it all working except for giving the user 3 different plan amounts at the end of the form.

For example, I need to offer the following in a select box or radio buttons at the bottom:

Plan A at $10.00
Plan B at $20.00
Plan C at $30.00

This is relatively simple using subscription modal, but I only want it to be a one off payment rather than daily, weekly, monthly or yearly.  Is this possible?


texts: Eagerloading Matrix fields resulting in empty array

texts:
I'm trying to eager-load a Matrix field with it's blocktype and related field types. For some reason the _eagerLoadedBlockTypeElements are empty arrays.

If I get rid of the with clause on ElementCriteria and iterate through the items it does work, which is not surprising.

The code I have right now (including dumping the results) are below.

$criteria = craft()->elements->getCriteria(ElementType::GlobalSet, [
        'handle' => 'footer',
        'with'   => ['column1Items.item:itemSection', 'column1Items.item:itemTitle']
    ]);

$found = $criteria->first();
dump($found->getEagerLoadedElements('column1Items'));
exit();

I'm fairly new to Craft and working with Yii hopefully someone can help me out with this one!

Thanks!

P.S. I can dump the query logs if necessary, just shoot!


texts: Upload asset failed to open stream: Invalid argument

texts:
When I try to upload an image, I am getting the following error:

imagepng(C:/wamp/craft/storage/runtime/temp/assets53ebcb012cffa3.92019251-temp.png): failed to open stream: Invalid argument (C:\wamp\craft\app\vendor\imagine\imagine\lib\Imagine\Gd\Image.php:691)

Do you know what is going wrong?


texts: How can I skip a required field if is not in the form?

texts: The problem is that I have a register page where I have 3 fields, Username, Email, Password. There is another page with some more fields which are required. So when I try to register a user form my register page I get errors about my required fields which I don't have in the register page. How can I skip them form cheking on my register page, but still have them as required on my profile page? Thank you in advance!


texts: In a plugin, what's the way in PHP to output a CSRF token?

texts:
My plugin has a tab in the CP. On that tab is a form. What's the way for PHP to generate a CSRF token that can be output to the form with echo?

EDIT to document the final answer

$token = craft()->request->getCsrfToken();
$out .= <<<MYFORM
   <form action="#" method="post">
      <input type='hidden' name="CRAFT_CSRF_TOKEN" value='$token'>
      ...
   </form>
MYFORM;
return $out;

And make sure that /craft/config/general.php includes this:

return array(
       'enableCsrfProtection' => true,
);


texts: Craft 3 on new MAMP Pro 5 installation: "iconv(): Unknown error (22)" problem in /vendor/twig/twig/src/Extension/CoreExtension.php

texts:
I have been fighting with a Craft 3 upgrade of a Craft 2 site on a local dev environment for a while now, though much of the time the problems turns out to be MAMP Pro 5 and/or FastCGI PHP. I'm not sure what's going on with the latest error, and the exact error returns no Google search results at all, so am at a loss for how to proceed.

The error in full is this:

PHP Notice – yii\base\ErrorException
iconv(): Unknown error (22)
1. in /Users/mydir/Sites/mysite/vendor/twig/twig/src/Extension/CoreExtension.php at line 1000

where line 1000 is the return line in this function:

function twig_convert_encoding($string, $to, $from)
{
    return iconv($from, $to, $string);
}

The error only shows up on some pages, not all. Can't figure out a pattern of commonality there. From Googling iconv (where I do see it is a known problem child but couldn't spot anything that shed more specific light) I guess it's a character-encoding utility. We do have some Spanish-language content on the site, but the actual Spanish-language channel displays fine, for whatever that's worth. If it matters at all, all my database tables are encoded UTF8, though collation is sometimes utf8_general_ci and sometimes utf8_unicode_ci.

The whole stacktrace is of core Twig files, no template files where I could go in and flail around with some troubleshooting code to try to narrow down the problem.

Thanks very kindly in advance for any thoughts or ideas. It's begun to feel as if I'll never get this site upgraded (and here's where I'd add the grimacing emoji if this community did not frown-emoji on such things).


texts:
I'm trying to create a site with a gallery, and am investigating the possibility of getting Craft to treat an asset as an entry so I can display a detail page for an image without having to create an entry for it specifically.

I think it might do what I need, but I've fallen at the first hurdle whereby according to the documentation (unless I've missed it) assets don't have a slug. I could use ID, but the client will want keywords in the URL blah blah.

If I pull an asset and output {{ asset.slug }}, it does return what I'd want it to. The problem is, if I edit the title, that value isn't updated and there doesn't appear to be a way to get to it.

Is it possible to get to this somehow?


texts: Sort by MatrixBlock Field / Eager load Matrix Field

texts:
Is there currently a way to eager load the matrix values of an element and thus be able to sort by one of its fields? Imagine you have something like the following:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->type = 'mytype';
$blocks = $criteria->find();

This would create a select from the following tables:

FROM   `craft_elements` `elements`
   JOIN `craft_elements_i18n` `elements_i18n`
     ON elements_i18n.elementid = elements.id
   JOIN `craft_matrixblocks` `matrixblocks`
     ON matrixblocks.id = elements.id
   JOIN `craft_matrixblocktypes` `matrixblocktypes`
     ON matrixblocktypes.id = matrixblocks.typeid

Obviously the most important table for my task at hand is missing: the craft_matrixcontent_mytype table. I'm not able order by mytable.myfield and additionally, while looping those blocks I have the N+1 problem where it builds an extra query to fetch the actual block content.

Am I somehow able to load all MatrixBlocks of a given type, INCLUDING the values?


texts:
In my plugin, I'd like to catch errors when they appear in the control panel, so I can handle them differently. However, from the front-end, I'd like to keep the default Craft-style handling of error messages.

try
{
    // Some code which might produce an error
}
catch (\Exception $e)
{
    if (craft()->request->isCpRequest()) {
        // Do something with $e->getMessage()
    } else {
        // Use default Craft error handling
    }
}

All of that is working for me, just trying to sort out how to do this part...

// Use default Craft error handling

How can I get my error handling to just go back to what Craft was doing by default? I want to make sure my errors still appear in devMode per usual.


texts: Get a defined image-transform's width and height in front-end template

texts: Is it possible to retrieve a control panel defined imagetransform’s dimensions in a front-end template without having to retrieve an asset? Because when there is no asset provided, I can't seem to find a (dynamic) way to get the width and height of the transform in order to calculate dimensions for a placeholder div


texts:
We have a Craft Pro (Craft CMS 2.6.3004) website that has a number of aliases on the URL. For the purpose of this the main URL is awesome.zone which has an alias of myawesomesite.com.

Recently it has started showing the "The license location at config/license.key belongs to myawesomesite.com" when logged into the admin panel of awesome.zone.

Evidently it was registered on the Alias initially, so I went to transfer the domain, but Craft won't do it.

  Craft is unable to transfer your license to this domain at this time.

What's changed recently that my license is suddenly complaining (but has been fine for 2 years) and how do I fix it?

Thanks.


texts: Manually sort entries related to a category in the admin

texts: Is anyone familiar with a way (in the admin) to manually sort the order of entries related to a category? For example, a "Software" entry gets assigned to multiple categories during entry. One category field is "Platforms" where you select "Cloud Based."  I then want to manually order all the software products related to the "Cloud Based" category and output them on the front end in the manual order.


texts: How do I import database using the CMS Craft 3

texts:
We have previously used the Schematic plugin for database import inside a Docker container for a Python script. This is the command used for the importing,

$/data/craft/craft schematic/export --file=schema.yml

The /data/craft/craft means we run the command inside the preceding folder and the command itself is schematic/export --file=schema.yml. The file schema.yml has the database definition.

How do you import and export the databases using the Craft 3.1.x?

Now we use the Craft 3.1 which doesn't work with the Schematic.  I have this project config file after we upgraded to the Craft 3,

dateModified: 1552904208
plugins:
  aws-s3:
    edition: standard
    enabled: true
    schemaVersion: '1.2'
  redactor:
    edition: standard
    enabled: true
    schemaVersion: 2.2.2


texts:
I'm having a little trouble wrapping my head around Relations through a Matrix field.

I have a Structure called exhibitors.

I have a Matrix field on a Page called rooms, This has one block type room and within that block there is an entries relationship field called exhibitors.

What I'm wanting to do is loop through the exhibitor entries and for each one, I want to find the first room they are related to via the matrix field.

I've tried various flavours of the relatedTo method, but I just can't seem to get them related, I just get null back from every one I've tried.

Here's an example of one I've tried:

{% set exhibitors = craft.entries.section('exhibitors').order('title') %}

{% for exhibitor in exhibitors %}
    {% set room = entry.rooms.relatedTo({
        sourceElement: exhibitor,
        field: 'room.exhibitors'
    }).first() %}

{{ room }} <-- Always a null entry

{% endfor %}


texts: Is it possible to create a 3 month membership instead of a subscription using Charge 2 for Craft CMS?

texts:
Here is the scenario: I'm trying to create a gift membership subscription for 3 or 6 months of site access that you can send to somebody. Since the most common scenario is that someone else will be paying & sending this to someone as a gift, we obviously don't want the charge their card again at the end of the period, and the membership access should end unless they update their card details & renew with one of our regular subscription plans.

Charge 2 handles subscriptions (which recurring by definition) and it also handles 1-off charges. It's well documented how to create a membership site that is tied to subscriptions. What I’m trying to figure out is how to provide 3 or 6 months of membership, that does not renew at the end.

The Subscription Model offers planInterval and planIntervalCount, but I don't see an option for something like 'endAfterCount' or something similar.

The one-off charges (1 time charge of $39 for 3 months of access, for example) I don't think have a time interval attached to them.

I feel like I'm probably missing something obvious here... any help is greatly appreciated.


texts:
New to Craft Commerce and doing something pretty template intensive.

I am following this https://craftcommerce.com/support/product-taxonomy  and https://craftcommerce.com/support/products-related-to-category

My categories group handle "productCategories"
My categories field handle "whatFinish"
Categories so far are "metallic" and "standard"

This code returns a short list of both categories from the page above

{% nav category in product.productDepartments %}

    {{ category.title }}
    {% ifchildren %}

        {% children %}

    {% endifchildren %}

{% endnav %}

When I use this code with any of a variety of options to replace(category) I get a template error with a variable issue.

{# Fetch all of the products related to this category #}
{% set products = craft.commerce.products.relatedTo(category) %}

{# Output them #}
{% for product in products %}
    {{ product.title }}
{% endfor %}

Examples things I have tried:

          {# Fetch all of the products related to this category #}
{% set products = craft.commerce.products.relatedTo(standard) %}

{# Output them #}
{% for product in products %}
    {{ product.title }}
{% endfor %}

 {# Fetch all of the products related to this category #}
{% set products = craft.commerce.products('whatFinish').relatedTo(standard) %}

{# Output them #}
{% for product in products %}
    {{ product.title }}
{% endfor %}

{# Fetch all of the products related to this category #}
{% set products = craft.commerce.products('standard').relatedTo(whatFinish) %}

{# Output them #}
{% for product in products %}
    {{ product.title }}
{% endfor %}

Before to get all of the products (not desired as I want just the ones form a specific category) my code worked fine:

{% for product in craft.commerce.products.limit(5).find() %}

        {% set image = product.slider.first() %} {% if image %}
         {% endif %}

{% if product.url %}{{ product.link }}{% else %}{{ product.title }}{% endif %}

{% endfor %}

Do I need to bracket the category code with something I am not aware of? Sorry just completely lost here. I was directed to post form the support email.

Steph


texts: I'm looking to integrate tasks into a plugin I'm building. Whilst I know that the Craft documentation shows the Tasks Service/Model properties/methods in the full class reference, I can't find anything online about best practices regarding using tasks in plugins. Has anyone come across any articles about creating your own tasks?


texts:
I'm new to Twig, and I'm struggling to compare a value from a checkbox with a value from a drop-down

   {# sourceCountry - checkbox with a list of countries #}
   {# currentUser.country - dropdown with a list of countries #}

   {% for sourceCountry in region.targetCountries %}
      {{ sourceCountry }} = {{ currentUser.country }}   <br>
      {{ dump(sourceCountry == currentUser.country) }}
      {% if sourceCountry == currentUser.country %}
         {% set visibility = true %}
      {% endif %}
   {% endfor %}

The result I'm getting from this is:

GB = GB

bool(false)

Most likely something to do with variable types, but no idea how to solve this. I've searched for some Twig 'to string' conversions, but no luck.


texts: Solspace Freeform upload multiple image files

texts:
I've had a good look around and can't find any template reference to uploading multiple images with Freeform.  In settings i've allowed for 5 files in 'File Count'.  I'm using the following template code but it only allows a single file.

  Upload photos of the fault
  <input id="uploadPhotos" type="file" name="uploadPhotos.handle[]" placeholder="Please provide any images of the fault" />

Any guidance appreciated.

Martin


texts:
I have php70 with nginx on vestacp. My admin panel work when url example.com/index.php?p=admin/dashboard, but not work example.com/admin/dashboard

My nginx conf:

server {
     listen      ip:80;
     server_name example.com www.example.com;
     root        /home/User/web/example.com/public_html;
     index       index.php index.html index.htm;
     access_log  /var/log/nginx/domains/example.com.log combined;
     access_log  /var/log/nginx/domains/example.com.bytes bytes;
     error_log   /var/log/nginx/domains/example.com.error.log error;

     location / {
        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
            expires     max;
        }

        location ~ [^/]\.php(/|$) {
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            if (!-f $document_root$fastcgi_script_name) {
                return  404;
            }

            fastcgi_pass    127.0.0.1:9002;
            fastcgi_index   index.php;
            include         /etc/nginx/fastcgi_params;
     }
}

location ~* "/\.(htaccess|htpasswd)$" {
    deny    all;
    return  404;
}

location /vstats/ {
    alias   /home/User/web/example.com/stats/;
    include /home/User/conf/web/example.com.auth*;
}

include     /etc/nginx/conf.d/phpmyadmin.inc*;
include     /etc/nginx/conf.d/phppgadmin.inc*;
include     /etc/nginx/conf.d/webmail.inc*;

include     /home/User/conf/web/nginx.example.com.conf*;

}


texts: How do I get started with Element API plugin?

texts:
I'd like to use the Element API plugin.
I've follow the instructions mentioned here: ElementAPI - Can I use javascript/ajax to load json

Here is my config/elementapi.php file :

<?php
namespace Craft;

return [
    'endpoints' => [
        'news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::getUrl("news/{$entry->id}.json"),
                ];
            },
        ]
    ]
];

and here my ajax request:

    $(function () {
        var data = {
            'CSRF': $('input[name="CRAFT_CSRF_TOKEN"]').val(),
        };

        $.ajax({
            'type': 'post',
            'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cache': false,
            'data': data,
            'url': 'news.json',
            'dataType': 'json',
            'timeout': 50000
        }).done(function (response) {
           console.log(response);
        }).fail(function (error) {
                console.log('totalfail')
            });
        });

But it always returns a 400 error (as the JSON file looks like it doesn't exist).

What have I missed? Could someone provide a working example?

Thanks!


texts:
This works:

            {% set entries = craft.entries({
                section: 'listing',
                listinglatitudenumber: '>=' ~ pluginResults.latmin
            }) %}

But I need to do this:

            {% set entries = craft.entries({
                section: 'listing',
                listinglatitudenumber: 'and', '>=' ~ pluginResults.latmin, '<=' ~ pluginResults.latmax
            }) %}

And I cannot for the life of me figure out the correct syntax for this.

I have been trying many different combos for the 'and' statement based on other answers I have seen in the Craft Stack Exchange but have not been successful. I have not been able to find any docs on this type of query.

Any help much appreciated :)


texts: How to add a unique number for each reiteration and render it multiple times?

texts:
I am working on a testimonial slider and each slide is wrapped in an <li> tag. The JS looks for a similar id number, one for each layer of the slide, in this case I need to change the 1 in the example below.

Example:

"rs-1"
id="slide-1-layer-2"
id="slide-1-layer-3"

I loop through the entries with a normal {% for %}{% endfor %} statement and I tried rendering the required number (1) with the {{ loop.index }} but I guess you can only use this once...

Is there a method do this? Perhaps with Twig?

If I am not clear this is what the result should be:

<li>"rs-1"
        id="slide-1-layer-2"
        id="slide-1-layer-3"
</li>
<li>"rs-2"
        id="slide-2-layer-2"
        id="slide-2-layer-3"
</li>
<li>"rs-3"
        id="slide-3-layer-2"
        id="slide-3-layer-3"
</li>

etc...


texts: Get all orders which contains a certain product type

texts:
In want to print a list of orders:

{% set orders = craft.orders.completed(true).limit(null).all() %}

Now I want to make a list of orders with only the product.type XYZ.

I tried to fabricate something out of this question. But I'd like specific product types:

{% set orders = craft.orders.completed(true).hasPurchasables([type.XYZ]).limit(null).all() %}

This returns:

  Variable "type" does not exist.

How do I have to write this?


texts: Set a Template Variable Based on Breakpoint

texts:
I have a requirement that a menu is open on wider breakpoints and closed on mobile breakpoints. To make it open i have a class i would toggle on my menu.

I can do this with JS but i get a FOUC on the menu on mobile, since it opens at first and then closes. So what i would ideally do is do this server side and exclude the class.

Is there some way with craft templates to set a variable containing the breakpoint or screen size?

Fx..

  {%set isMobileSize =  ??? %}

Ideally this would get the page size in the request and set this when rendering the page/template?


texts: Checking if related entries are live in a for loop and setting a variable based on the results

texts:
So I have a section called children and these are related to various other entries include users.
I am fetching all the children for the currentUser like so and eager-loading all the other relationships.
{% set childrenQuery = craft.entries
  .section('children')
  .relatedTo({
  sourceElement: currentUser,
  field: 'relatedChildren'
})
  .with([
  'associatedTerm',
  'tuitionClass',
  'tuitionClass.location'
]) %}

{% set children = childrenQuery.all() %}

What I then want to do is split out children in to 'Active' and 'Inactive' depending on if the related field associatedTerm is live.
I can do this fine like this;
Children (active)

  {% for child in children if child.associatedTerm|length %}

{{ child.firstName }} {{ child.surname }}

{{ child.tuitionClass[0] }}

{{ child.associatedTerm[0] }}

{{ child.tuitionClass[0].location[0] }}

  {% endfor %}

Children Inactive ()

    {% for child in children if not child.associatedTerm|length %}

{{ child.firstName }} {{ child.surname }}

    {% endfor %}

However, what I want to do is actually do this logic first, so I can then wrap the active/inactive blocks into if statements, if there are in fact any active or inactive children as I have other code (headings and text) I want to show within the block and not appear at all if they are no entries.
So I am stuck on how to do this {% for child in children if not child.associatedTerm|length %} without a for loop and just check if there are any entries that exist.
I can achieve it like this; but it feels a little weird.
{% set childrenAreInactive = '' %}
{% for child in children if not child.associatedTerm|length %}
  {% set childrenAreInactive = 1 %}
{% endfor %}

Anyone have any ideas for a better method?


texts: Displaying notification in control panel

texts: Is there any js function that will display these notifications that appear on top of the screen? Flash messages use these notifications, but I don't want to use flash messages, I want to display notification without refreshing a page.


texts: How Do I Use Channel Entry Data to Create a Dynamic Recipient List in Freeform?

texts: I'm trying to use the Solspace Freeform plugin for Craft CMS to create an email form. My form needs to have dynamic recipients, but I have a channel in the system that has the email addresses I need in it already.I'm not sure how to set up the template to use those email addresses in the dropdown field since the dynamic recipients field isn't supposed to have the actual email addresses in it. I've looked at the docs, but I'm not clear on how to set this up. Can anyone help me sort this out?


texts: Commerce products returning different results on page load

texts:
I have a great many products which have a date field (they're class dates) and I want to show the next three which have any stock left (available places). The following works fine to display the next three products:

{% set earliestDate = now %}
{% set latestDate = now | date_modify('+ 10 days') %}

{% set products = craft.commerce.products({
  type: 'class',
  date: 'and, > ' ~ earliestDate ~ ', < ' ~ latestDate,
  order: 'date',
  limit: 3
}) %}

But of course there's no reference to stock. If I add the hasStock parameter, like so:

{% set products = craft.commerce.products({
  hasVariant: {
    hasStock: true
  },
  type: 'class',
  date: 'and, > ' ~ earliestDate ~ ', < ' ~ latestDate,
  order: 'date',
  limit: 3
}) %}

The results are different every time I load the page! Results vary but include:

showing more than three products, e.g. 5 products
no products being returned at all
three products but products which are an earlier date being skipped

Has anyone else encountered this? I can understand maybe different results than expected if hasStock items were being fetched before the rest of the query, but not why it would be different on every pageload. If it helps, no products are being returned outside the date range I'm supplying.


texts: Guest Entries creating new entry instead of editing the current one

texts: I am using the GuestEntries (https://github.com/pixelandtonic/GuestEntries) Plugin to try to allow guests to update entries. I have it working to where a guest can come to the page and fill out the form but unfortunately it is creating a new entry rather than editing the existing one.


texts: Craft 3 - Cache tag increasing number of database queries

texts:
I have a question about the {% cache %} tag with Craft 3. I am reading this article (https://nystudio107.com/blog/the-craft-cache-tag-in-depth), and trying out implementing the tags; however, when I check the amount of db queries before and after adding the tags, the amount of queries goes up instead of down as suggested in the article.

What would cause this to happen? This is the code I’m currently testing the cache tag on, there are 5000+ entires in the 'articles' section. Without the cache tag there are 19 database queries, with it there are 32 queries.

{% cache %}
    {% for entry in craft.entries.section('articles').all() %}
      {{ entry.title }}<br>
    {% endfor %}
{% endcache %}


texts:
I'm running Nginx on port 8888 locally. fastcgi_params is sending SERVER_PORT to PHP-FPM, which I am able to verify with phpinfo() output and craft/storage/runtime/logs/craft.log. I'm also able to navigate all of the admin pages with the port number intact.

Unless I change General Settings > Site URL to include ":8888", I've noticed that all rendered links (homepage, sample "Recent News" block) do not include the different port. I am new to Craft; am I correct to assume that the Site URL must include the port number manually specified, despite the code having getServerPort() in the core code?

Edit: I added the following to general.php:

'siteUrl'  => 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/',

This seems sub-optimal; is there a better way to do this? What do others do who run Craft on ports other than 80/443?


texts: Missing Download PDF Button in Orders for Craft Commerce

texts:
I'm not sure what happened, but the "Download PDF" button that is on the orders in the CMS is missing. I thought maybe the order PDF template file or path was missing but both of those are there. Is there a true/false statement somewhere I might have erased? I can't find anything on this.

Thanks


texts:
This is a really basic question but I have had trouble finding an answer, or documentation on it.

What is the best way to place a test order with a default Craft Commerce installation? I'm unable to get past the payment page while using the default 'dummy' payment method. I would like to test the order process, including confirmation page, email confirmation, order history, etc.


texts: Error With ContactForm Plugin - Internal Server Error

texts:
Using,
https://github.com/pixelandtonic/ContactForm

I recently migrated the server to a new server and now i get:

2015/12/03 19:21:27 [error] [exception.phpmailerException] exception 'phpmailerException' with message 'SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting' in C:\inetpub\wwwroot\craft\app\vendor\phpmailer\phpmailer\class.phpmailer.php:1256 Stack trace:
#0 C:\inetpub\wwwroot\craft\app\vendor\phpmailer\phpmailer\class.phpmailer.php(1100): PHPMailer->smtpSend('Date: Thu, 3 De...', 'This is a multi...')
#1 C:\inetpub\wwwroot\craft\app\vendor\phpmailer\phpmailer\class.phpmailer.php(1004): PHPMailer->postSend()
#2 C:\inetpub\wwwroot\craft\app\services\EmailService.php(435): PHPMailer->send()
#3 C:\inetpub\wwwroot\craft\app\services\EmailService.php(77): Craft\EmailService->_sendEmail(Object(Craft\UserModel), Object(Craft\EmailModel), Array)
#4 C:\inetpub\wwwroot\craft\plugins\contactform\services\ContactFormService.php(54): Craft\EmailService->sendEmail(Object(Craft\EmailModel))
#5 C:\inetpub\wwwroot\craft\plugins\contactform\controllers\ContactFormController.php(100): Craft\ContactFormService->sendMessage(Object(Craft\ContactFormModel))
#6 C:\inetpub\wwwroot\craft\app\framework\web\actions\CInlineAction.php(49): Craft\ContactFormController->actionSendMessage()
#7 C:\inetpub\wwwroot\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
#8 C:\inetpub\wwwroot\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
#9 C:\inetpub\wwwroot\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#10 C:\inetpub\wwwroot\craft\app\framework\web\CWebApplication.php(282): CController->run('sendMessage')
#11 C:\inetpub\wwwroot\craft\app\etc\web\WebApp.php(805): CWebApplication->runController('contactForm/sen...')
#12 C:\inetpub\wwwroot\craft\app\etc\web\WebApp.php(275): Craft\WebApp->_processActionRequest()
#13 C:\inetpub\wwwroot\craft\app\framework\base\CApplication.php(184): Craft\WebApp->processRequest()
#14 C:\inetpub\wwwroot\craft\app\index.php(62): CApplication->run()
#15 C:\inetpub\wwwroot\public\index.php(14): require_once('C:\inetpub\wwwr...')
#16 {main} REQUEST_URI=/contact HTTP_REFERER=https://soho.infor.com/contact
--- 2015/12/03 19:21:27 [error] [application] SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Is, Some application not installed? Or something not configured? Or could it be a matter that this site requires authentication now to hit it in the browser (https redirects)?

Additionally where is the SMTP server configured?

-Tim


texts: Craft 3 Element API Authentication/Login

texts:
First things first: This is quite similar to this, yet different.

I'm trying to get authentication/login for Element-API for Craft 3 to work. Meaning I would like to restrict access to certain endpoints that require the client to be logged in and also (essentially, this is the question) have a way to login via the API (or a different way, but preferably over the API).

This is what I got so far:

<?php
use Craft;
use craft\elements\Entry;
use craft\helpers\UrlHelper;

function requireLogin(){
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: X-Requested-With");

    if (!Craft::$app->user->isGuest) {
        // you are authenticated
    } else {
        // check params
        $loginName = Craft::$app->request->getQueryParam('loginName');
        $password = Craft::$app->request->getQueryParam('password');

        if (Craft::$app->user->login($loginName, $password)) {
            // login success
            $user = Craft::$app->userSession->getUser();
        } else {
            // login fails echo message
            $errorCode = Craft::$app->userSession->getLoginErrorCode();
            $errorMessage = Craft::$app->userSession->getLoginErrorMessage($errorCode, $loginName);
            Craft::$app->end(JsonHelper::encode(array('data' => array( ['status' => 'error','message' =>'wrong login']  ))));
        }
    }

}

return [
...

using requireLogin(); inside the transformer of the given endpoint.

Most of this is copied from the before mentioned, related link. But as I'm no PHP developer I kind of struggle getting it to work.
The error I get is the following with this code:

  Argument 1 passed to yii\web\User::login() must be an instance of yii\web\IdentityInterface, null given
  as a result of Craft::$app->user->login($loginName, $password)

I do understand whats happening and am capable of reading the error, but I'm not very familiar with yii, nor PHP. If someone could point out what needs to be done, which problems also might occur of if I'm on the wrong track or even post a working solution, I would be very grateful.


texts: JPG upload not completing in Craft 2.6.2789

texts:
When uploading a new asset the loading bar appears complete but does not actually upload the JPG. I've investigated the Craft logs and cannot find any errors regarding this.

In the Javascript console I can see the error:

http://your-domain.com/index.php/admin/actions/assets/uploadFile 500 (Internal Server Error)

I'm using MAMP but this also happens on our development servers running apache.

This issue does not happen with PNG's.

After further investigation I found the Preview for the uploadFile "thing".

This Preview had the content

PHP Error [500]

include(/Users/you/Sites/your-domain/craft/app/vendor/lsolesen/pel/src/PelInvalidDataException.php):
failed to open stream: No such file or directory
(/Users/you/Sites/your-domain/craft/app/vendor/composer/ClassLoader.php:412)

I then looked in the lsolesen vendor folder (which happens to handle stuff for Jpg and Tiff files) and the PelInvalidDataException.php file is missing.

I've copied this file from the git repo into the vendor folder and this now works. However this feels sketchy as hell.

I'm wondering whether it could be a composer install issue

Anyone got any ideas?


texts: Is there a fieldtype in Craft like "Content Elements" or "Bloqs" for ExpressionEngine?

texts:
I have been using EE for over 5 years now, and am just starting to get into Craft (and I love it!).  In my recent EE sites, I've used Content Elements, and it has been a great way to give my clients flexibility in adding content to pages and blog posts, etc.

Is there a similar fieldtype available for Craft? Or is there another simple method to accomplish the same thing?

Thanks!


texts: PHP notice unserialize(): Unexpected end of serialized data

texts:
Ok so this is an incredibly wierd one and I have no idea how to explain the problem in just one sentence so I just put the error message as the title.

So I am building a site with craft...in fact its basically complete. I was developing it in linux ubuntu but also using the vagrant homestead virtual machine to develop from so OS is kinda irrelevant.

Anyway...this is at work and they decided to be nice and get me a mac for work for christmas so I'm just basically trying to set up my working environment on the new computer.

So I set up homestead, pull everything from the git repositories, set up the databases and import everything...go to launch the site and I get the error message that is in the title and it highlights this line: $value=unserialize($value);

ok...interesting...after some googling i read something and decided to try and go into my config file and turn off developer mode...

When I go to a normal page it gives me this error: CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #25 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db_name.structureelements.root' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

I did some research into this and tried to edit my my.cnf file to modify the sql_mode parameter also with no luck although i think the line I was given was not correct for the version of mysql that I have...perhaps this is where the issue is?

...and when I try to log into the back end aka /panel it gives me this:

Your server doesn’t meet the following requirements to run Craft CMS:

Mcrypt is required.

Please talk to your host/IT department about upgrading your server.

Ok...fair enough...maybe I need this mcrypt thing...the thing is I think it is already installed? It is listed in my phpinfo(); I have gone through the steps to install it (and yes I have restarted nginx and php....and mysql and still nothing...)

I really have no idea what the problem here is...the only thing that i can think is that my vagrant environment is different to the one I had in linux as I downloaded it more recently but I have no idea what setting/software version number/whatever somewhere is different that might be causing this?

Please feel free to ask for more info as I really am not sure what I am looking for here...I know that the vagrant environment is working as well as normal php is running (as I was able to run the phpinfo(); function succesfully.

The vagrant box is running php 7.1

Thanks in advance...

Matt


texts: Front end authentication on an entry and its related entries

texts:
I am looking to implement a website where access to pages and their related pages is restricted to certain users.

How I thought it might work is that a user (or users) would be assigned to the entry. This user should then have front end access to this entry and its related entries.

So, the template would check the currentUser value against the user in the entry, and also against the relatedTo entries.

Is there a better, more efficient way? I feel this may suffer from performance problems as the number of related entries grows. Any advice or guidance would be greatly appreciated!


texts: How to save a new entry with custom fields - Craft 3

texts:
I'm trying to create a new Entry via PHP, with custom fields (Craft 3). I can save it, however my custom fields don't appear. I've tried using setFieldValue, as well as $entry->excerpt = 'Lorem...';, however neither work.

My code is below, using craft\elements\Entry:

$entry = new Entry();
$entry->sectionId = 4;
$entry->typeId = 4;
$entry->authorId = 1;
$id = uniqid('product_');
$entry->title = $id;
$entry->slug = $id;

$entry->setFieldValue('excerpt', 'Lorem...');

if(Craft::$app->elements->saveElement($entry)) {
    return $entry;
} else {
    throw new \Exception("Couldn't save new bespoke product: " . print_r($entry->getErrors(), true));
}


texts:
I'm using AM Forms on a site that I've built. The site is now in production.

Via the AM Forms notifications settings, the email I've entered for Email recipients and Sender email address notification email is an email which is hosted with G Suite.

Am I correct in thinking that these notifications are being sent via Craft's email settings (currently PHP Mail)?

G Suite is running DKIM, SPF and DMARC, so the PHP Mail protocol is not the best method for receiving these notifications. If I change Craft's email protocol to GMail, how safe are the credentials I enter and are they encrypted?


texts: Multiple sections, limiting the structure by depth

texts:
I'm trying to pull entries from multiple sections for a list on a page, which works fine:

{% if section is not defined %}
    {% set section = 'events,checklists,opinionPieces,whitepapers' %}
{% endif %}

{% set params = {
    section: section
} %}

The problem I'm having is that the 'checklists' section is a structure with child entries allowed, and I only want the top level entries. I hoped I could get away with this:

{% if section is not defined %}
    {% set section = 'events,checklists,opinionPieces,whitepapers' %}
{% endif %}

{% set params = {
    section: section,
    level: 1
} %}

But that then only returns checklists and whitepapers, presumably because they are structures and the other two are channels.

Is there an easy way of getting this to work, or would I have to pull all entries separately into an array?


texts: How can retrieve users custom fields only?

texts:
I have created fields for users and also entry type.
I want to get only users fields. I have retrieved custom fields but that returns all the fields.

$users = \craft\elements\User::find()->id(USERID)->one();
print_r($users->getbehaviors()['customFields']);

I know how to get user custom fields with field Handle.
I need only users fields (whole users fields not single) that admin assign in the CP. ( settings/users/fields ).


texts:
I'm trying to setup a page where the html will be copied into Mailchimp for a newsletter. The images need to have a full path url. How would I construct the code to provide this? So instead of "/images/something.jpg" it would be "http://domain.com/images/something.jpg".

{% set imageTransform = { width: 520, height: 240 } %}
{% for image in entry.headerPhoto %}
 <img src="{{ image.getUrl(imageTransform) }}"  alt="{{ entry.title }}" style="display:block;" >
{% endfor %}

If there is text inside rich text fields is there any way to output the full url to those images too?


texts:
I am based in the UK Where we format dates for 17th May 2018 like so:

17/5/18

Is it possible for the Craft Control Panel to use a specified format when listing entries' post date / expiry date etc?


texts:
So I just installed the GuestEntries Plugin.
Whenever I submit the form, I get

"POST param “sectionId” doesn’t exist"

      <form method="post" action="" accept-charset="UTF-8">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="guestEntries/saveEntry">
        <input type="hidden" name="redirect" value="success">
        <input type="hidden" name="opiniones" value="3">
        Title
        <input id="title" type="text" name="title">
        Body
        <textarea id="body" name="fields[body]"></textarea>
        <input type="submit" value="Publish">
</form>

-opiniones is the section id.

-Have the section allowed for guest posts, with a user selected.

-Only other plugin Im using is the contact form 1.81

-running Craft CMS 2.6.2964 Personal

Any one can give me hand.?

Thanks


texts:
How can I create a plugin that will let me copy entry?

I found this question but don't have a good answer.


texts:
I am having a problem getting image urls from Craft 3. I understand that there is a new syntax but I cannot find the syntax to use. The craft 2 version of what I am trying to accomplish is

{% set heroImage = entry.heroImage.first().url %}

How do I achieve this in Craft 3?


texts:
Is there a way to send errors back to the set password form?

I am listening to the users.onBeforeSetPassword event in which I want to confirm that the string in a confirm password field is the same as in the newPassword field.

craft()->on('users.onBeforeSetPassword', function(Event $event) {
       // Only do anything if it is a front end submission
       if(craft()->request->isSiteRequest())
       {
           $newPassword = craft()->request->getPost('newPassword');
           $passwordConfirm = craft()->request->getPost('passwordConfirm');
           if(isset($passwordConfirm) && strcmp($newPassword, $passwordConfirm) !== 0)
           {
               $event->params['user']->addErrors(array('newPassword' => Craft::t('Passwords do not match')));
               $event->performAction = false;
           }
       }
   });
  }
}

This does prevent the user from resetting their password but doesn't send a error message back to the template.  How can I pass a variable back to the template so I can show the user their error?


texts: Getting blank screen at domain.com/admin when installing

texts:
I'm trying to install Craft for the first time, I've used Ben Croker's requirements check and everything passes, and I'm pretty sure everything else is set up properly, but when I access domain.com/admin to run the install, I just get a blank screen - no errors, warnings or messages.

I've tried installing in a subdomain (my preference) as well as in the root, with the craft dir both above and below the root, but get the same result no matter what the config.

I've checked the logs (craft.log) and it gets this far (see below). There is no phperrors.log file. Does anyone have any ideas where I should check next?

2014/08/20 11:49:16 [info] [application] $_GET=array (
  'p' => 'admin',
)

$_SERVER=array (
  'DOCUMENT_ROOT' => '/xxx/xxx/public_html',
  'GATEWAY_INTERFACE' => 'CGI/1.1',
  'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  'HTTP_ACCEPT_ENCODING' => 'gzip,deflate,sdch',
  'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8,es;q=0.6,fr;q=0.4,it;q=0.2,ja;q=0.2,pl;q=0.2,ru;q=0.2',
  'HTTP_HOST' => 'xxx.xx.xx',
  'HTTP_PROXY_CONNECTION' => 'keep-alive',
  'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36',
  'PATH' => '/bin:/usr/bin',
  'QUERY_STRING' => 'p=admin',
  'REDIRECT_QUERY_STRING' => 'p=admin',
  'REDIRECT_STATUS' => '200',
  'REDIRECT_UNIQUE_ID' => 'U-SLOlmRTRcABtAqnnkAAAAx',
  'REDIRECT_URL' => '/admin',
  'REMOTE_ADDR' => 'xx.xx.xx.xx',
  'REMOTE_PORT' => '62291',
  'REQUEST_METHOD' => 'GET',
  'REQUEST_URI' => '/admin',
  'SCRIPT_FILENAME' => '/xxx/xxx/public_html/index.php',
  'SCRIPT_NAME' => '/index.php',
  'SERVER_ADDR' => 'xx.xx.xx.xx',
  'SERVER_ADMIN' => 'xxxxx',
  'SERVER_NAME' => 'xxxxxx',
  'SERVER_PORT' => '80',
  'SERVER_PROTOCOL' => 'HTTP/1.1',
  'SERVER_SIGNATURE' => '',
  'SERVER_SOFTWARE' => 'Apache',
  'UNIQUE_ID' => 'U-SLOlmRTRcABtAqnnkAAAAx',
  'PHP_SELF' => '/index.php',
  'REQUEST_TIME_FLOAT' => 1408535356.3350970745086669921875,
  'REQUEST_TIME' => 1408535356,
)
2014/08/20 11:49:16 [trace] [system.CModule] Loading "db" application component
in /xxx/xxx/xxx/craft/app/etc/web/WebApp.php (642)
in /xxx/xxx/xxx/craft/app/etc/behaviors/AppBehavior.php (69)
in /xxx/xxx/xxx/craft/app/etc/web/WebApp.php (799)


texts:
When I try to login to the Craft admin portal, I receive a prompt that my login credentials are incorrect, even though I am sure I have them set to the correct value.

Of note, this site is using a subdomain similar to craft.domain.com


texts: Does Craft support gated content and form fills?

texts:
I'm a content marketer looking to get contact information for customers visiting my site. Does Craft support workflows with form fills?

For example:

User sees an ad for an ebook, white paper, or other marketing content. Goes to landing page > form fill with contact information > thank you page with content
User sees an ad for a webinar or other event. User goest to event page > form fill > thank you page with confirmation time.

Wondering if Craft supports this type of multi-step content workflow.


texts: Dynamically populating select input fields using jquery $.load and twig template

texts:
EDIT: the below code now works!

I have two select inputs, the choice of 1 should populate the second. I have an external twig file (data.twig) (MAKE SURE TO PUT THIS IN YOUR TEMPLATES FOLDER) that loads the options of the second field.

 {% set allBrands = craft.entries()
            .section('brands')
            %}

{% set brands = allBrands.all() %}

test form

    <select id="first-choice" class="select-1">
        <option selected value="base">Please Select</option>
        {% for entry in brands %}
        <option value="{{ entry.brandName }}">{{ entry.brandName }}</option>
        {% endfor %}
    </select>

    <select id="second-choice" class="select-1">
        <option>Please choose from above</option>
    </select>

Then for the javascript:

$(function() {

        $("#first-choice").change(function() {
          $("#second-choice").load("{{ siteUrl }}data.twig?brand=" + $("#first-choice").val());
        });

    });

And lastly the data.twig:

{% set brand = craft.request.getParam('brand') %}

{% set allModels = craft.entries()
                .section('brands')
                .brandName(brand)
                %}
{% set models = allModels.all() %}
{% for entry in models %}
<option>{{ entry.modelName }}</option>
<option>testing</option>
{% endfor %}


texts: Saving Asset field in FEEF ("Front-end entry form") using Plugin

texts:
I'm having issues saving an Asset field in my FEEF using a Plugin. I have a channel with some fields added to it, one of these fields being an Asset field. When using the standard entries/saveEntry build in function in Craft the Asset gets saved.

When I try to run the same form (same channel, same field) through my Plugin everything saves except the Asset field asset. The code I'm using (below) is a slightly changed version of Pixel&Tonics own "Guest Entries" Plugin.

Can anyone help me to figure out whats going on?

/**
 * Populates an EntryModel with post data.
 *
 * @access private
 * @throws HttpException
 * @return EntryModel
 */
private function _populateEntryModel()
{
    $entry = new EntryModel();

    // Set section
    $entry->sectionId   = craft()->request->getRequiredPost('sectionId');
    $this->_section     = craft()->sections->getSectionById($entry->sectionId);
    $this->_entryTypeId = craft()->request->getPost('entryTypeId');

    // Default
    $entry->authorId    = 1;
    $entry->enabled     = true;

    // Set title
    $entry->getContent()->title = craft()->request->getPost('title');

    // Set Entry type
    if($this->_entryTypeId)
    {
        $entry->typeId = $this->_entryTypeId;
    }

    // Add dynamic fields
    $entry->setContentFromPost(craft()->request->getParam('fields'));

    // Return model
    return $entry;
}

This is how my form looks (I've removed some styling and keept the essentials)

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

<!-- Hidden -->
{{ getCsrfInput() }}
<input type="hidden" name="action" value="forms/saveEntry">
<input type="hidden" name="redirect" value="{{ craft.request.url }}?sent=1">
<input type="hidden" name="sectionId" value="13">
<input type="hidden" name="entryTypeId" value="18">
<input type="hidden" name="title" class="title" value=""/>

<input type="text" name="fields[formName]" value="{% if formEntry.formName is defined %}{{ formEntry.formName }}{% endif %}" class="default-field name" />
<input type="text" name="fields[formConfirmationNumber]" value="{% if formEntry.formConfirmationNumber is defined %}{{ formEntry.formConfirmationNumber }}{% endif %}" class="default-field" />
<input type="text" name="fields[formRoom]" value="{% if formEntry.formRoom is defined %}{{ formEntry.formRoom }}{% endif %}" class="default-field" />
<input type="file" name="fields[formFile]">

</form>

The name="title" field gets set dynamic...


texts: Trying to achieve a row column layout with batch

texts:
I tried to code an output in twig that should look the following ( 2 columns in one row), i figured that i will need the batch function

Content

Content

Content

Content

My attempt is :

 {% for block in entry.content1|batch(2) %}

    {% for block in row %}

Content

    {% endfor %}

 {% endfor %}

but it doesn't work like that, i looked it up in the twig documentation, the error from craft i get is "Variable "row" does not exist", so i tried changing it to {% for entry in block %} but that doesn't work either.


texts: Craft update process affecting Element API cache

texts:
I have a site A using the Element API plugin to feed content to site B via JSON and handlebars templates. The process is both sites are up to date with content 'x' and it works fine.

When I run the CP updates on site A and it finishes the data on site B never shows until the site A cache is cleared.

Is this expected behavior?