texts: How to read form response URL variables in template?

texts:
I have a basic login form that's talking to a separate server that's out of my immediate control. I'm trying to read the responses it's sending in the URL within the Craft template.
For example...

http://www.adacore.com/login?login=incorrect

I've only ever done it before in PHP. Is it possible with Craft/Twig to access these variables directly? Or should I just read the craft.request.queryString?

And change the template accordingly as needed.


texts: Part of a website only accessible to users

texts:
Is it possible to restrict a part of a website to craft user-groups?

For instance if I want show an internal Blog to members-only.

And is it possible to moderate user registrations? So when somebody registers an Admin has to approve it first?


texts: How do I get all categories with at least one entry

texts: I want all categories that have at least one entry that uses it.


texts: Twig json array error in javascript with barbs.js

texts:
I'm having issues with the following code every since I added barbs.js (a page transition library) to my site.

Basically I have a js file that controls the transition and ajax. The following code exists within an event that triggers when the page transition has completed. The event works as I've tested it. The son array exists as I have rendered it at the bottom of the page and content is there. My javascript say:

SyntaxError: Unexpected token '{'. Expected a property name.

For the following code:

var jsonMeta = {{ jsonMeta|json_encode|raw }};

This used to work work but doesn't anymore. The full code is:

var Contentpage = Barba.BaseView.extend({
  namespace: 'contentpage',

    onEnter: function() {
       $('#navigation').removeClass('invert-nav-bar');
  },

  onEnterCompleted: function() {
       Barba.Dispatcher.on('transitionCompleted', function(currentStatus) {
        var jsonMeta = {{ jsonMeta|json_encode|raw }};
        $('head').find('title').text(jsonMeta.meta.title);
        $.each(jsonMeta.meta.link, function(k, v){
            $.each(v, function(kk, vv){
                $('head').find('link[' + k + '="' + kk + '"]').attr('href', vv);
            });
        });

        $.each(jsonMeta.meta.meta, function(k, v){
            $.each(v, function(kk, vv){
                $('meta[' + k + '="' + kk + '"]').attr('content', vv);
            });
        });
        });

  }

});

Contentpage.init();


texts: How to exclude certain fields from .search()

texts:
I have an event section in my website with a couple of fields on the entries and one of them is a "related events" field where I can select a other event entries to be shown at the end of the page.

I also use the .search() function to search within events and it happens that events are listed in the results of searches for a certain keyword, where the only appearance is within the related events, which is unwanted behavior.

What I need is to exclude this one field where I can select the related events from the search index.

How can this be solved?


texts: How can I loop through my entries to export them using Beam?

texts:
I want to export my entries to CSV or JSON.  Craft 2 had a plugin.  I can't find one for Craft 3.

I reached out to the Craft community on Slack.  They suggested I try the Craft 3 plugin Beam.

I was told it should be trivia. But, the documentation on Beam is light.

This is the example provided in the Beam documentation to export to CSV:

{% spaceless %}
{% set options = {
header: ['Email', 'Name'],
rows: [
      [ 'test@example.com', 'John Doe' ],
      [ 'another+test@example.com', 'Jane Doe' ],
      [ 'third+test@example.com', 'Trond Johansen' ],
]
} %}
{{ craft.beam.csv(options) }}
{% endspaceless %}

I want the header to be the field names used in an entry and the rows to be values for each entry in my posts section.

I can't use a loop in the option settings.  So, how do I set the options to loop through the entries fields and values?

Thanks


texts:
I am trying to make entries editable from the front end and pretty much follwed the docs.

When i visit my edit view, the entry-from is filled with their respective values but unfortunately no changes are being saved back when i update those and submit. A redirect is also not happening. The old form just loads again.

Not errors too. The site is localized so could this be a problem? Should i add the locale to my inputs?


texts: Currently I have a light switch on some commerce items that make them private to users that are not logged in but they still show up when the user is logged out. Is there a way to do this? I'm continuing development for a webpage and I'm still new to craft so I am sort of lost


texts: Setting up Route for Category-based RSS Feeds

texts:
I think that I need to set up a few routes to handle my category based RSS feeds. I have a current url structure as follows

http://something.com/shows/wmr/marketing pr

http://something.com/categoryGroup/parentCategory/childCategory

I need rss feeds from both the parent and child categories

http://something.com/categoryGroup/parentCategory/feed
http://something.com/categoryGroup/parentCategory/childCategory/feed

The rss template i am using is stored in

categories/_shows.rss

I have munged something together in the cp routes settings but I would prefer to have this in routes.php. Having access to the parentCategory and childCategory values without doing a segments thing would be nice.


texts: Custom data source without options - Sprout Forms

texts: Is it possible to create a custom data source that does not include end user options? I have tried not including the getOptionsHtml(), returning null, returning an empty string, and just return and the all fail.


texts:
When using image transforms, Craft not only doesn't seem to be outputting the transformed image, but the image path it's then giving back to the template is: <img src="http://example.com/cpresources/transforms/1" /> which doesn't exist.

I have a upload path defined, which is http://example.com/assets/uploads/ but obviously it isn't respecting that.

I can't find any docs on where to define the transformations image path so wondered if anyone could shed some light?


texts: Get entries related to tags with a score & order by

texts:
TL:DR; How do I add a custom sorting to Craft?

I am currently building a system which is very tag-centric. I am rebuilding my side project in CraftCMS (https://email.subscribeto.at/) which was custom PHP as a prototype.

Entries are tagged with one or more categories, then on the front-end the user can search for categories and the results are returned.

Currently, the results can be sorted by "relevance" which I would like to replicate on CraftCMS.

I tried to use .search() as it has a score, however this score is not what I want as it is not additive. I want to search with OR but for the score to be additive.

For example, if I have 2 entries, one with tags "a" and on with "a, b" and I search for "a, b", the first one has a score of 50 (as 100% of it's tags match 50% of the search) and the second a score of 17 (not sure how it gets this, would expect 100%)

Also, .search seems a bit fragile when I could us relatedTo().

I have a local module installed for some overrides already, so my question is:

How would I add a custom property to each entry and then order by that?

Thanks in advance for your help


texts: Is there a way to add instructions directly on a entry index screen in the CP?

texts:
I have structure entries that needs to be in a very specific order, following a pattern of horizontal and vertical images to create the right affect on the front-end. I would love a way that I could remind my client of the instructions for the right order of these entries directly on the entries index screen in the CP, sort of like how you can provide instructions for each field. Are there any plugins that would allow the injection of some instructions into the CP page like this?

I've seen option to that allow you to create entire users manuals or help sections in the CP, but that's not what I'm after. I want something that could go inline on just a single CP page.


texts: List entries for a single tag from blog section

texts:
I want to get a list of entries in a template that have one specific tag 'weddings' and exclude entries that do not have this tag.

{% set tag = craft.tags.search('weddings').first() %}

{% if tag %}
  {% set entries = craft.entries.relatedTo(tag) %}
  {% for entry in craft.entries.section('blog').limit(5) %}
    {# get stuff #}
  {% endfor %}
{% endif %}

But this gets me all blog entries - even those without the Tag weddings. What am I missing?


texts:
I am attempting to create a "dynamic" button. By that I mean I want the user to be able to update the text and the target (href) of where the button links to when clicked.

So I created fields: buttonText and buttonTarget.

buttonText is just a plain text field - no problem.

For the buttonTarget field type I chose "Entry" and selected the source(s) in the checklist that follows with a limit of one. So far so good.

In my actual entry, I enter the buttonText of "Hello World". Preview the page and "Hello World" shows up as the button text. So far so good.

Lets say I have a page called "Hello". For my buttonTarget field I click on "Add an Entry" and choose "Hello" from the entry list.

When I preview my site now, I get this error:

Object of class Craft\ElementCriteriaModel could not be converted to string

That makes perfect sense since I need everything to evaluate to a string. I'm not sure how I can output (for lack of better words) the object so that I can see/find what properties are.

Here is what I am using to display the button:

html

{{entry.buttonText}}

I assume I need something like {{entry.buttonTarget.uri}} but I haven't been able to find out what the actual parameter is I need. {{entry.uri}} outputs nothing.

EDIT

Doing this gets the result I am after: {{entry.slug}} This uses the current entry's slug instead of the custom field value. Which is ok - I can use the slug as the href target. Ideally I'd like to use the custom field though.


texts: How to print all possible options of a dropdown field inside of a Matrix field?

texts:
I'm asking this outside an entry context.

My starting point is

  {% set field = craft.app.fields.getFieldByHandle('matrixFieldHandle')
  %}

When I print the data of the field, I find nothing related to the fields that matrixFieldHandle contains.

matrixFieldHandle (Matrix field)

Block Log

Field logValue (Dropdown field)

I know how to print the options in a dropdown field:

How do I output a dropdown's values if I'm on a registration form not tied to an entry?
How do I print the options in a dropdown field?

But how can I print all these dropdown options when it is set inside a Matrix?


texts:
What is the best way to get a random number within a certain range?

I made something but I guess there is a better way:

In this example I want to position some elements randomly. This approach works, but I have to define a variable for each value.

{% set randomizr = range(10, 90) %}

{% set randomHeight1 = shuffle(randomizr) | first %}
{% set randomWidth1 = shuffle(randomizr) | first %}

{% set randomHeight2 = shuffle(randomizr) | first %}
{% set randomWidth2 = shuffle(randomizr) | first %}

{% set randomHeight3 = shuffle(randomizr) | first %}
{% set randomWidth3 = shuffle(randomizr) | first %}

{% set randomHeight4 = shuffle(randomizr) | first %}
{% set randomWidth4 = shuffle(randomizr) | first %}

{% set randomHeight5 = shuffle(randomizr) | first %}
{% set randomWidth5 = shuffle(randomizr) | first %}

Is this somehow possible without writing each variable manually?


texts: variable inside for loop is empty outside the loop

texts:
I need to set a bunch of variables to feed my html head metas. Most of the time the page is directly related to an entry but i also have pages for each user with a route that look like 'equipe/user.username':

{% if craft.request.getSegment(1) == 'equipe' and craft.request.getSegment(2) is defined %}
    {% set user = craft.users.username(craft.request.segment(2)).first()%}
    {% set title = user.username %}
    {% set description = user.description %}
    {% set resume = user.resume %}
    {% set url = siteUrl~'equipe/'~user.username %}
    {% for asset in user.imageHeader %}
        {% set imageUrl = asset.getUrl('header') %}
        {{ imageUrl }}
    {% endfor %}
{% else %}
    {% set title = entry.title %}
    {% set description = entry.description %}
    {% set resume = entry.resume %}
    {% set url = entry.url %}
    {% for asset in entry.imageHeader %}
        {% set imageUrl = asset.getUrl('header') %}
        {{ imageUrl }}
    {% endfor %}
{% endif %}
{{ imageUrl }}

Everything works fine except for the imageUrl variable. it behave like a local variable. I can retrieve the value just after it is set, but not outside of the for loop... any idea why ?


texts:
I am transferring a site from CakePhp to Craft CMS. The old site has a ton of images which I need to import into the new site. I know i can drop the images in the right folder and do an "Update Asets Indexes", but I also need to bring across some meta data, which will end up as field values.

I am new to Craft, but from what I can tell, I need to create console plugin, and from within that plugin do all the neat stuff to do the actual import. I have come across this blog entry

http://spin.atomicobject.com/2015/06/16/craft-console-plugin/

which I think looks pretty solid.

But, once I get a bare bones plugin up and running, what is the code I need to import an image file on disk into the Craft database, with field values set as required?

Thanks!


texts: Can’t run Craft CMS on my local machine, keep getting message "The Mcrypt extension is required"

texts:
I try to run Craft on my local Windows server and I keep getting message:

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

I tried installing Mcrypt, but I am having no luck... Any suggestions?


texts:
I have created a site for searching nearby restaurants and order items.

After ordering I wanna send a mail "Order received" with receipt attached in mail (if possible) to the customer + a mail to the respective restaurant which is in Craft->User "New Order" + a mail to site admin contains customer info and restaurants info + what I code in email template.

All these function will be done in single click. I mean when customer click on Order Now. These all mail will sent.

I am try to search email template and tutorial but I haven't found anything.


texts: How can I make the broadest search possible?

texts:
I have three (3) different channels. One (1) channel have Assets attached to it, and those Assets have a couple of fields attached to them as well.

How can I make the broadest possible search on all these channels (and the channels Assets and fields) using the .search() function?

For clarification; I want to make a search in all channels, and their Assets (and the Assets own fields) with (if possible) one single line of code.


texts:
There are a number of answers here about how to send CSRF tokens along with AJAX requests, but I think my question is a little different. Please excuse the abstractness here:

In a headless application, I'd like to be able to log users in via AJAX, and keep a fresh CSRF token in the client-side application's state.

Is there a way to get a new token, once one has been consumed?

Imagine a case where a customer adds an item to their cart—that token is consumed, and a new one is issued on the next page load… but what if there isn't a new page load?

Am I even thinking about this the right way?

In looking at the UsersController, I noticed that the get-remaining-session-time action sends a csrfTokenValue. Any chance this is part of the answer?


texts: How can I embed Image into Craft Commerce 2 PDF Receipt

texts:
How do I embed an image (PNG,SVG or JPG) into a CraftCMS Commerce 2 PDF receipt? I tried importing the svg using an includes. I tried using an img tag and referencing a local file. Nothing seems to work.

David


texts: Getting the first and last days of a multi-day event - Solspace Calendar

texts:
Is there a way to get the first and last days of a multi-day event? I want to be able to style the first and last days differently. I don't see anything like this in the docs.

This is in Craft 3 and Calendar 2.0.17


texts: Creating an onSaveEntry event in Guest Entries Plugin

texts:
I'm currently working on a plugin that sends an email before the Guest Entries Plugin saves the entry. But one of the fields is an asset field and the file may be renamed when uploaded so I need to switch this up so the email being sent after the entry is saved.  I tried creating an onEntrySave event in the Guest Entries plugin by doing the following.

Added to GuestEntriesService.php:

/**
     * Fires an 'onSaveEntry' event.
     *
     * @param GuestEntriesEvent $event
     *
     * @return null
     */
    public function onSaveEntry(GuestEntriesEvent $event)
    {
        $this->raiseEvent('onSaveEntry', $event);
    }

In GuestEntriesController.php I've added

$this->onSaveEntry(new GuestEntriesEvent($this, array('entry'=> $entry,'isNewEntry' => true)));

to the section of the code where the entry is saved.

if (craft()->entries->saveEntry($entry))
{
     $this->onSaveEntry(new GuestEntriesEvent($this, array('entry'=> $entry,'isNewEntry' => true)));
     $this->_returnSuccess($entry);

}

But this is where I've gone wrong as I get the error:

Craft\GuestEntriesController and its behaviors do not have a method or closure named "onSaveEntry".

How do I go about modifying the plugin to trigger an onSaveEntry event?


texts: Is it possible to populate a user field in the CP using custom logic upon registration?

texts:
Whenever a user is registered in the control panel, we'd like to have a special field (something like a special member id) that is populated either by manual entry or, if the field is left empty, run custom logic to generate a new value for that field.

Is this possible using Craft's events or by extending the existing user registration form available in the CP, or would it be easier to create a separate plug-in to handle the user creation process?


texts: How to copy Matrix from one entry to another in Craft 3

texts:
I've got $entryA with a Matrix field.

I want to programatically create a new $entryB and copy the Matrix field from $entryA to $entryB.  How do I go about this?


texts:
I've got a Quick Post widget for notes (tweet-like posts). Is there any way to make the titles optional? I've tried adding the id as an auto-generated title but it doesn't appear to work?

Update:
It actually appears that the auto-generated title is now working (thanks to carlcs) but it only works through the entries menu item rather than the quick post widget despite the widget's type being correct.


texts: Q: Error 400 Bad Request on basic admin actions like admin/actions/elements/get-modal-body

texts:
Context:
The client recently upgraded their Craft version along with several of their plugins. I believe this issue started post-upgrade. They are now on Craft 3.4.26.
Problem:
Certain admin actions, like opening a modal or quick saving an entry result in an error 400. We thought it was a CSRF issue so we disabled that in general.php, but still get the same result in Chrome (oddly, disabling CSRF works in Firefox). Also oddly, there is still a cookie called CRAFT_CSRF_TOKEN and if you delete that before performing your action, it will work.
The last piece of information is that I began disabling plugins one by one to see if the functionality was being affected by any of them. We figured out that disabling SEOmatic (v3.3.8) resolved the issue. I've also submitted an issue with NYStudio107, but I'm curious how/why a plugin might affect basic functions of the admin like opening a modal.


texts: How can I output a specific field in Sprout Forms email notifications?

texts: I'm trying to override a Sprout Forms email notification template. The example template loops over tabs and fields and outputs them all, that works. I'd like to manually reference specific fields in specific places (like first_name). How can I reach the field values?


texts: Commerce filter with width, height and length with tolerance

texts:
Hope you guys can help.

I need to create a search feature on a craft commerce site that will allow the user to search for products in this principle:

Product Type

Width +- value

height +- value

length +- value

Here is an example of the data.

Front Door

100cm +- 10cm (90cm - 110cm) width

300cm +- 100cm (200cm - 310cm) height

10cm +- 4cm (6cm - 14cm) length

This will be using parameters just not sure how to write the query for this


texts: What does defaultTokenDuration affect besides hidden entries' share links?

texts:
Per this answer, configuring defaultTokenDuration is the way to change the lifespan of hidden entries' share links from the default 24 hours. The v2 docs describes this as affecting "system tokens" but no further explanation of system tokens is provided. The v3 docs refers simply to "tokens."

[edit: I believe one other thing this controls is the lifespan of password reset tokens.]

I'd like to increase the lifespan of draft entries' share links, but wonder what other consequences I should take into account before changing defaultTokenDuration. What all does it affect?


texts: How to output a tweet URL in a user timeline using the Dukt Twitter plugin

texts:
I'm just trying out the Dukt Twitter plugin. Is it possible to output a link to a tweet within a timeline? I've tried guessing {{ tweet.url }}, but that doesn't work. I don't want to auto-link the tweet itself using {{ tweet.text|autoLinkTweet) }}, as I'm wanting to output the entire tweet as plain text. I've included my code below and thanks for any help in advance.

{% set tweets = craft.twitter.get('statuses/user_timeline', { screen_name:'craftcms', count: 3, trim_user: false }) %}

{% if tweets %}

Recent Tweets

    {% for tweet in tweets %}

{{ tweet.text }}

    {% endfor %}

{% endif %}


texts: Migrations running on their own causing site down

texts:
I'm a bit stumped with this one and wonder if anyone else has come across it.

I've a site live which is using the 'Formerly' plugin amongst others, since a recent update the site has gone offline twice in the last week do to the formerly plugin needing to make changes to the database.

I didn't think this could happen on it's own? It's like the plugins migration wants to run on it's own at weird intervals.

Not sure how to debug this, anyone else had this issue?


texts:
I have a situation where I wish to automatically set entry title based on locale entry was created in. This is what I use for title:

{{ object.locale == "jp" ? "Japanese title" : "English title"}}

This works fine but when I create an entry in Japanese locale and open it in English locale and resave it the title changes to "English title" and that's not what I want, I wish to preserve the original title. Is that possible somehow?


texts: I am unable to render new entries on the browser (demo version)

texts:
I just started using craft and am still exploring the Happy Lager demo version. I can create new sections, fields and entries. However, when I try to render the entry on my browser by clicking on the globe icon, the URL takes me to "Page not found" error.

Am I not allowed to create new entries on the demo? or am I missing something?


texts: Translating Craft form error message labels

texts:
I am trying to change the label for Craft's form errors. My site local is currently fr_CA, and when I try to submit a form with an error, the error message returned is in french, but the label of the field is in english.

I have managed to translate field labels for plugins, such as the Contact Form plugin by P&T, without any issues by using static translations. All I simply did was create a file with the plugin translation category as a name such as 'contact-form.php' and it works flawlessly.

However, with the forms included in Craft, it doesn't seem to work. For example, with the user registration form, if I submit it without a password, it will come up with an error saying the password needs to have at least 6 characters. Here is the message I receive :

  New Password doit comporter au moins 6 caractères.

The 'New Password' is in english while the rest of the message is in french.

If I try to create a file called 'site.php' or 'app.php' in the translations folder under the right locale, it doesn't translate the 'New Password'. Here is the content of the file :

<?php

return [
    'New Password' => 'Nouveau mot de passe'
];

It's like none of the translations supplied to Craft are being recognized. Has anyone run into this problem or have a solution?


texts: Event Listener for Publishing Scheduled Posts

texts:
For performance reasons I'm caching full HTML responses to Redis. This does wonders for response times, but cache invalidation becomes a bit tricky... I'm currently purging the entire cache on 'entries.saveEntry' which will suffice most of the time.

The problem is with scheduled posts. Scheduled posts are not saved when they're published so the cache is not invalidated and the post doesn't show up unless I clear the cache manually. I need to register 2 events listeners to clear the cache: one on entry save and one one on publish. Does this second event exist? If not, is there a way to create one?


texts: Charge events are firing in live mode but returning as test

texts:
I am having a major issue with craft subscription. All data in stripe shows it as live mode and in craft it is showing as test payment. Also the subscription url points to https://dashboard.stripe.com/test/plans/plan-name-here instead of https://dashboard.stripe.com/plans/plan-name-here

if someone has run into the problem please shed some light


texts:
So I'm trying to build a query based on events and their start and end dates. Once a user selects a year, I want to display all events that took place in that year, but also display events that might have spanned across multiple years and include that selected year. For example, if a user selects 2012. I should display all events starting in 2012, but also events that might have lasted from say 2010-2013.

What I'd like to do is query all event entries and return only events whose startDate is less than or equal to the select year AND whose end date is greater than or equal to the selected year:

{% set startDateParam = '<=' ~ yearParam ~ '-01-01' %}
{% set endDateParam =  '>=' ~ yearParam ~ '-01-01' %}

{% set pastEntries = craft.entries({
   startDate: startDateParam,
   endDate: endDateParam
}).section('events').order('endDate desc') %}

However, this doesn't seem to work. What is the correct way to query for entries that satisfy both the startDate AND endDate?

Any and all help is greatly appreciated. Thanks.


texts:
I'm making a blog.

I have a wheelform comments input type that needs to be stored as utf8mb4 in the local database.

My MySQL database version 5.6 is configured to utf8mb4 in the database, tables, and columns.

Every time I send an emoji to the database it is stored as four question marks ????.

Is there a way to save emojis correctly in the database? Perhaps using encodeMb4(), but I don't know where and how to apply it.


texts: Receiving 'template loader exception' when trying to view asset (image) after upload

texts:
Anyone ever encounter this error when trying to view an asset (image) after upload? I'm working in homestead and everything appears to be compiling correctly, however the images don't render in the browser. The path shows up in dev tools and looks correct...any thoughts?

Craft\TemplateLoaderException
Unable to find the template “_layout”. (/home/vagrant/sites/my-craft-sites/wcs/craft/app/etc/templating/twigextensions/TemplateLoader.php:123)
#0 /home/vagrant/sites/my-craft-sites/wcs/craft/app/etc/templating/twigextensions/TemplateLoader.php(71): Craft\TemplateLoader->_findTemplate('_layout')
#1 /home/vagrant/sites/my-craft-sites/wcs/craft/app/vendor/twig/twig/lib/Twig/Environment.php(265): Craft\TemplateLoader->getCacheKey('_layout')
#2 /home/vagrant/sites/my-craft-sites/wcs/craft/app/vendor/twig/twig/lib/Twig/Environment.php(323): Twig_Environment->getTemplateClass('_layout', NULL)
#3 /home/vagrant/sites/my-craft-sites/wcs/craft/storage/runtime/compiled_templates/fc/9e/d83ba99cc7bfbe696da10fbdcf65536dc4ae270165035f00e6cfb3c5b953.php(10): Twig_Environment->loadTemplate('_layout')
#4 /home/vagrant/sites/my-craft-sites/wcs/craft/app/vendor/twig/twig/lib/Twig/Environment.php(345): __TwigTemplate_fc9ed83ba99cc7bfbe696da10fbdcf65536dc4ae270165035f00e6cfb3c5b953->__construct(Object(Twig_Environment))
#5 /home/vagrant/sites/my-craft-sites/wcs/craft/app/vendor/twig/twig/lib/Twig/Environment.php(292): Twig_Environment->loadTemplate('404')
#6 /home/vagrant/sites/my-craft-sites/wcs/craft/app/services/TemplatesService.php(220): Twig_Environment->render('404', Array)
#7 /home/vagrant/sites/my-craft-sites/wcs/craft/app/controllers/BaseController.php(74): Craft\TemplatesService->render('404', Array)
#8 /home/vagrant/sites/my-craft-sites/wcs/craft/app/controllers/TemplatesController.php(203): Craft\BaseController->renderTemplate('404', Array)
#9 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/web/actions/CInlineAction.php(49): Craft\TemplatesController->actionRenderError()
#10 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#11 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#12 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#13 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/web/CWebApplication.php(282): CController->run('renderError')
#14 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/base/CErrorHandler.php(331): CWebApplication->runController('templates/rende...')
#15 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/base/CErrorHandler.php(204): CErrorHandler->render('error', Array)
#16 /home/vagrant/sites/my-craft-sites/wcs/craft/app/etc/errors/ErrorHandler.php(128): CErrorHandler->handleException(Object(Craft\HttpException))
#17 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/base/CErrorHandler.php(129): Craft\ErrorHandler->handleException(Object(Craft\HttpException))
#18 /home/vagrant/sites/my-craft-sites/wcs/craft/app/framework/base/CApplication.php(732): CErrorHandler->handle(Object(CExceptionEvent))
#19 [internal function]: CApplication->handleException(Object(Craft\HttpException))
#20 {main}


texts:
I'm using tags to do some Javascripting.

Is there any way that I can tell Craft to remove whitespace from {{ tag.name }} if the tag.name has spaces (for example 'apples and carrots'), and add dashes ('apples-and-carrots') ?


texts: How can I add custom validation rules to my plugin settings?

texts: I have a plugin that needs to perform some custom validation on one of its settings. How would I go about doing that?


texts: How do you get ahold of a TagModel in a template?

texts:
I have a route that matches:

/blog/tagged/{tag}

And in my template I would like to pull up all blogs that are related to the tag:

{% if tag is defined %}
    {% set blogTag = craft.tags({ name: tag, group: 'blogTags' }) %}
    {% set filter = filter|merge({ relatedTo: blogTag }) %}
{% endif %}

{% for entry in craft.entries(filter).find() %}

But this doesn't work since craft.tags() gives me an ElementCriteriaModel, but I need a TagModel to work with relatedTo().

I can't figure out how to get the TagModel here.


texts: How to search on multiple (custom) fields using Element API

texts:
I am using the Element API to search for entries that match a search query: either the title OR the excerpt should contain the query term. The entry is very simple and has these fields:
-title
-excerpt
-link
when I use this to only search in the title field it works:
$section_handle = ['item'];
$q = Craft::$app->request->getParam('query');

$criteria = [
   'section' => $section_handle,
   'search' => 'title:'.$q
];

So I thought I just add the excerpt field like this:
$criteria = [
   'section' => $section_handle,
   'search' => 'title:'.$q.' OR '.'excerpt:'.$q
];

but this did NOT work and I found out that it just won't search that excerpt field, this also does not work:
   $criteria = [
   'section' => $section_handle,
   'search' => 'excerpt:'.$q
];

After some research I found out that when I use this as the 'criteria' it works:
$criteria = [
    'section' => $section_handle,
    'excerpt' => "*{$q}*"
];

And now I wonder how to proceed. How can I either get the first example to work to search in the excerpt field, or add the OR title clause to my latest example where I am able to search in the excerpt field...
I hope this makes sense and that someone can point me in the right direction!
Thanks very much,
Wouter


texts: Getting my head round installing plugins from the command line

texts:
My command line skills are limited but I’m trying to be better. I’ve been using composer successfully for a while to initiate Craft installs, but then subsequently using the Craft web GUI to install plugins.

Today I thought I’d try and use the command line on a fresh local install, which has DB connection details stored in .env as is usual. The host is configured through MAMP Pro on Mac OS Mojave.

I’ve run composer update on my install and it reported there was nothing to update.

I then used the web GUI to install craftcms/contact-form and all went fine, so there is no doubt that my local DB credentials are correct.

Then, in the command line I invoked:

composer require craftcms/contact-form-honeypot

…which ran fine. And then:

./craft install/plugin contact-form-honeypot

…and got:

  "failed to install contact-form-honeypot: Craft CMS can’t connect to the database with the credentials in config/db.php."

What am I doing wrong?


texts: Where do I put code to use hooks and events from Squarebit's 'Charge' plugin?

texts:
I would like to update a specific entry upon the completion of a successful payment through the charge plugin. For this, Charge provides the callback 'charge.onCharge,' as detailed in the 'Hooks & Events Page' of the documentation.

The issue is that I have no idea where to put PHP code to utilize this callback, nor what this code would look like. Is there an example that would explain exactly how to use the callback, and exactly where the code would go?


texts: I was wondering if there is way to enable CORS for the ElementAPI plugin? I want to be able to call the API from the website and not allow external client to access the API


texts:
We have a Sprout Forms form being used for gated content access. The form appears to work correctly but none of the entries are appearing in the database/CMS.

Here is an example URL with the form: http://thisisbeyond.co.uk/blog/feel-good-brands-report-2015/

Below is a CMS screenshot of the form settings.

Below is the template code we are using to generate the form:

{% if craft.request.getParam('message') == 'success' %}

Thank you for your message, we'll get back to you as soon as possible.

{% else %}

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

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="sproutForms/entries/saveEntry">
<input type="hidden" name="handle" value="gatedForm">
{% set gated = entry.gatedDocument.first() %}
<input type="hidden" name="redirect" value="{{ gated.url }}">

    Full Name *
    <input type="text" name="fields[fullName]" id="fields-fullName" class="form-control" value="{% if gatedForm.fullName is defined %}{{ gatedForm.fullName }}{% endif %}" required/>
    {% if gatedForm is defined %}{{ errorList(gatedForm.getErrors('fullName')) }}{% endif %}

    Company Name *
    <input type="text" name="fields[companyName]" id="fields-companyName" class="form-control" value="{% if gatedForm.companyName is defined %}{{ gatedForm.companyName }}{% endif %}" required/>
    {% if gatedForm is defined %}{{ errorList(gatedForm.getErrors('companyName')) }}{% endif %}

    Email *
    <input type="text" name="fields[email]" id="fields-email" class="form-control" value="{% if gatedForm.email is defined %}{{ gatedForm.email }}{% endif %}" required/>
    {% if gatedForm is defined %}{{ errorList(gatedForm.getErrors('email')) }}{% endif %}

    <button type="submit" class="btn btn-primary">Submit</button>

</form>

{% endif %}

UPDATE: re-installing the Sprout Invisible Captcha plugin and including the following line before the closing  tag got it working:

{{ craft.sproutInvisibleCaptcha.protect() }}


texts: I am looking for a simple solution & if possible resources on how to go about getting Craft CMS setup behind a load balancer. Craft CMS is going to be hosted on AWS EC2 instance, I have MySQL on a different instance. I have read about setting up and using shared storage variables but I haven't really found a way to setup a shared storage. Anyone has any idea on where to begin?


texts:
We have web site with CraftCMS Pro 2.6.2930. Due to development of new site, we set test web server (Centos/Apache/mariaDB) in our local network and migrated whole site there for testing (2.6.2993 with trial license). Site is working, but logins to craft admin webpage are rejected (log in button is greyed out).

For migration i have followed this Migration of Craft CMS from one host to another (we deleted license.key file)

Craft/storage/runtime/logs shows

2018/05/17 13:45:58 [warning] [application]  tried to log in unsuccessfully.

Site content is migrated successfully.

PS: I've already tried this and it isn't working: Reset password with MySQL

Any ideas?

PS: It seems my problem is very similar to this one Control Panel access. Greyed out button since i see (almost the same) errors


texts: Error:unable to open using mode r:fopen() :filename cannot be empty(1)

texts:
This is my problem please give me solution
My process is in this url
http://solution.ap-south-1.elasticbeanstalk.com/solutionpage.php


texts: How to use assets while building Craft CMS plugins?

texts:
I am trying to build a basic plugin, when installed has a single nav bar item, and of course a twig template which shows up on clicking on that navbar item.

I have used the basic template to extend to make my page:

{% extends "_layouts/cp" %}
{% set title = "Page Title"|t('plugin-handle') %}

{% block content %}

Page content goes here

{% endblock %}

The resulting page for the plugin looks like shown in the screenshot attached below:

Now I am trying to add content in the content section, but I am not sure how to add my assets

This won't work, and I am guessing I need to get the paths using some variable in the twig templating system, but I am not sure how. And the documentation is not clear on this part, or maybe I don't know where to look right away.

How to include my assets on the page, like images, js and css files?


texts:
I've transferred a Craft site (I didn't build it) from staging to production. All the existing content is showing up on the front end but when I try to edit entries that aren't static pages, the edit pages are 404'ing.

Any tips would be greatly appreciated.

-- Update

Here's the contents of the .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

general.php

<?php

/**
 * General Configuration
 *
 * All of your system's general configuration settings go in here.
 * You can see a list of the default settings craft/app/etc/config/defaults/general.php
*/

return array(

);


texts:
I don't understand what's going on in my code logic because I'm getting unexpected output.

I'd like to sum up three number fields in entries loop for the given post date range. Output gets almost doubled as expected. What am I missing here?

{# Get this month's data #}
{% set thisMonthStatistic = orders.postDate('and', '>= ' ~ firstDayOfMonth, '<= ' ~ lastDayOfMonth) %}

{% if thisMonthStatistic|length %}
{# We must set variable "0" and pass it in for the looping's variable #}
{% set thisMonthEarning = 0 %}

  {# looping in "thisMonthStatistic" #}
  {% for statistic in thisMonthStatistic %}

    {% set aPrice = statistic.aPrice %}
    {% set bPrice = statistic.bPrice %}
    {% set cPrice = statistic.cPrice %}

    {% if aPrice > 0 %}
      {% set aPrice = aPrice + thisMonthEarning %}
    {% endif %}

    {% if bPrice > 0 %}
      {% set bPrice = bPrice + thisMonthEarning %}
    {% endif %}

    {% if cPrice > 0 %}
      {% set cPrice = cPrice + thisMonthEarning %}
    {% endif %}

    {% set thisMonthEarning = aPrice + bPrice + cPrice %}

  {% endfor %}

{% else %}

  {% set thisMonthEarning = 0 %}

{% endif %}

{# Final variable output #}
{{ thisMonthEarning }}


texts:
I'm trying to setup a multi country site running off one Craft install.

example.com
ca.example.com
uk.example.com

Each countries content will be translated into five languages (English - en, Spanish - es, French - fr, German - de, Japanese - ja).

example.com/en
example.com/es
example.com/fr
example.com/de
example.com/ja

ca.example.com/en
ca.example.com/es
ca.example.com/fr
ca.example.com/de
ca.example.com/ja

uk.example.com/en
uk.example.com/es
uk.example.com/fr
uk.example.com/de
uk.example.com/ja

Entries will be translated into all five languages. But, entries should also have the ability to display in one or two or all of the countries etc. I understand how the locales (translations) functionality built into Craft can handle the languages but how would the countries be handled at the same time?


texts: How to update Craft CMS/plugins without downtime?

texts: On our production server, we have strict SLAs concerning when our site can be down.  I've noticed that when I update Craft CMS 3 (using "./craft update all" on the server), the site will go down for anywhere from 1-30 seconds.  Once the update is completed, everything returns to working.  Has anyone seen this before?  How can I update Craft without downtime?


texts: User Registration - Keep as inactive until verified by admin

texts:
I have set up a public registration form simply using the User registration form: https://craftcms.com/docs/templating/user-registration-form

Is there a way to set it so that when users register they need to be activated by an admin account?

Currently when they register they get an email to verify email address and when they do they get activated.
If I turn off verify email addresses in user settings they simple get activated automatically.


texts: Assets are not loading anymore (maybe an update)

texts:
I just noticed that I can't see my files if I go into the assets section.
An Error blinks up and says "An unknown error occurred". In the front-end, I see every file and I can upload files to an asset too and see there uploaded files and selecting it.

The log file says nothing.
I use for Image Transforms Imager without imgix.
If i want to edit an Image i get a error too:

  Getting unknown property: aelvan\imager\models\ConfigModel::imgixEnableAutoPurging

It has always worked.

I can only imagine that an update has changed something?!

Thanks for any help. Really big problem


texts: Multisite, second language Live Preview not working

texts:
I have an English site - https://dev.mysite.com and a Japanese site - https://dev.mysite.com/jp.

Live preview works great for the English site, but the Japanese site has the following error:

Mixed Content: The page at 'https://dev.mysite.com/admin/entries/home/3-home?site=japanese&draftId=90' was loaded over HTTPS, but requested an insecure resource 'http://dev.mysite.com/jp?x-craft-live-preview=dbSSGfPfBY&token=LTNsMdKk-I8XWFyoh7ozK2akf4Hy_oOO'. This request has been blocked; the content must be served over HTTPS.

I have the Base URL set within the Sites admin panel to https, as well as the siteUrl within general.php.

What am I missing?

Thank you!
Kelly


texts:
Migrating Plugins to Craft 3 starts bugging me, seems that really everything changed.
Is there an equivalent to IOHelper::ensureFolderExists in Craft 3?


texts: query orders by date AND time in craft commerce

texts:
How can I query all completed orders within the last hour? It seems craft is only comparing a date by YYYY-MM-DD.

Following query collects all orders from the same day, as {{dateFrom}} would output 2017-10-13 and not eg. 2017-10-13 11:22:08

{% set dateFrom = now|date_modify('-3600 seconds') %}
{% for order in craft.commerce.orders.dateOrdered( '>= ' ~ dateFrom) %}
  ...
{% endfor %}

adding something like
craft.commerce.orders.dateOrdered( '>= ' ~ dateFrom|date('c')) would find any orders at all.


texts: Select Related Entries from a specific category in CP

texts:
I'm creating a site which has a products section.

I have created an entries section called 'Products'.

I have set up some categories, i.e. 'Category One, 'Category Two', 'Category Three'

I have also created a related entries field so I can related products to each other.

When the client adds a new product in 'Category One', they should only be able to relate entries that are in 'Category Two' or 'Category Three'.

Is there a way that I can restrict the results returned in an entries field in the Control Panel to a specific category?


texts: Hidden files are no longer accessible with AJAX in Craft 3

texts:
I'm not sure if this is a bug, a security feature, or something to do with Twig 2; but since Craft 3 (RC3) I'm no longer able to access hidden twig files via ajax.

This works fine:

  $.ajax({
    method:'GET',
    url:'/blog/test',
    success:function(data){
      $('body').append(data);
      console.log("SUCCESS", data);
    },
    error:function(data){
      console.log("ERROR", data);
    }
  });

However, when I point the url to a hidden file with this:

url:'/blog/_test',

I get a 404 (Not Found) error. For my example, I have both '_test.twig' and 'test.twig' files in the 'blog' directory.

Am I missing a breaking change?

Update:

I didn't really know what it was for, but 'enableCsrfProtection' => true has always been set in my config/general.php file. (In both Craft 2 and 3). I've tried setting this to false too, and I'm getting the same results.

Following Robins comment, I've attempted to follow these instructions: Enabling CSRF Protection.

I've set the global variables window.csrfTokenName and window.csrfTokenValue. And now I'm stuck.

I'm pretty new to ajax, and I'm not sure how to extrapolate the example in a way where I can add the CSRF Token correctly in my 'GET' method.

This is the response I'm getting:

ERROR
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort : (statusText)
always : ()
catch : (fn)
done : ()
fail : ()
getAllResponseHeaders : ()
getResponseHeader : (key)
overrideMimeType : (type)
pipe : ()
progress : ()
promise : (obj)
readyState : 4
responseText : "
Not Found: Page not found.
"
setRequestHeader : (name,value)
state : ()
status : 404
statusCode : (map)
statusText : "Not Found"
then : (onFulfilled,onRejected,onProgress)
__proto__ : Object


texts: Adding reCAPTCHA to the admin login page

texts:
Is there any plugin or relatively straightforward and accepted way to add a recaptcha to the login for the admin page?

My research so far has come up with nothing. I'm curious if others have looked into this with any result.


texts:
Plugins are able to extend Craft and embrace the existing UI nicely. While I'm comfortable extending it in many ways, I don't feel like I could clearly explain to somebody else how the grid system works on the back end and have recently seen a few CP UIs rendered on larger screens (2400px+) that suggest that I may not fully understand how it behaves between devices.

After you extend the CP layout:

{% extends "_layouts/cp" %}

You can build a grid using grid, item, and pane classes and various attributes. Here is an example with likely too many attributes just to put several of them out there into the discussion:

      ...

      ...

Here are a few of the questions I wonder about while working with the grid:

How many columns does the grid support?
Are there any considerations to keep in mind as our plugin's UI adjusts to mobile layouts or big screens with high resolutions?
How do data-position="left" and data-position="right" work? When do we need to use them?
How do the data-colspan attributes work? Are there defaults in place for data-colspan, data-min-colspan, data-max-colspan?
Are there any other features of the grid I'm overlooking or leaving out?


texts:
I have a plugin that extends various Craft templates and styles, however, in one area it requires some custom Control Panel styles that Craft has not already created. As the Craft Control Panel is responsive, I'd like the UI elements I'm creating to also be responsive.

It appears Craft makes it's UI components responsive using a combination of @media queries and javascript.

What is the best way for me to build out a custom plugin UI that is consistent with the breakpoints that Craft is using and will be least likely to break if Craft updates anything down the road?


texts:
I have been all over the docs page and various other topics across the web on this, and nothing seems to solve it for me. It's probably something obvious, but I am stuck. I recently installed Craft 3 on an Amazon Lightsail LAMP server. My file structure is like this:

/opt/bitnami/apache2/htdocs/ (My root folder)

Inside that root folder, I have this structure:

cms (contains all of the Craft installation files)
web (contains index.php, cpresources,.htaccess)

When I load my site at www.example.com, I arrive at a page that just shows my file structure. Only when I click into the web folder (www.example.com/web), does my initial page of my site load up. I want that page to load up without showing "web" in the URL. I have tried the following things with no success:

Changing the Base URL
Changing my httppd.conf file to point to "web" as the root
Moving all of the files inside the web folder into my root folder (htdocs)

And a few other random things. I really am having a hard time pinpointing this exact issue in any of the documentation. Looking for any advice anybody can offer.


texts: How to include JS and CSS resources for a plugin variable

texts:
I've got a variable (widget is a better word) that I want to output with accompanying CSS and/or JS.

I'm rendering the variable (widget) with the following

return TemplateHelper::getRaw($output);

I realize the following exists but other than inline js/css is there a way to output the widget and include CSS/JS by only using a single variable? I want to make this as simple as possible.

<script src="{{ resourceUrl('plugin/js/public.js') }}"></script>

`


texts: How do I find the path to the public folder?

texts: Within my Craft plugin code, how do I find the path to Craft's public/ folder? There doesn't seem to be a constant listed in Craft Docs: PHP Constants like there is for all the other key folders.


texts: Is there a way to check if a value exists in an array in twig?

texts:
Done some searching on this but can't quite find what I'm looking for. Most threads are regarding keys.

I want to know if there is a way to test if a value exists in a twig array.

It should be able to check whether the value is a variable, object or an array.

So for example:

{% if value not in array %}
    .... do someting
{% endif %}

Any suggestions welcome.


texts: What are the issues with adding Craft Commerce to an existing Craft CMS site?

texts:
We are about to start on a project that will include a complex product catalogue, with multiple product categories and loads of relationships. The client has stated that they may want to create an online store to sell catalogue items at some point in the future.

The thought at this point is to create the product catalogue using standard Craft CMS features like Structures and Categories. Anyone have any experience or guidance on adding Craft Commerce to an existing Craft site? Will I have to recreate product structures or can build the initial version in a manner that allows Craft Commerce to work with an existing product schema?


texts:
I am building a section in which a client will list their various social network connections. There are fields for each social network's name and icon, as well as a field with the URL to the client's page on the specified network.

I also need a field that contains the code needed for each network's "Share" button. The code for "Share" buttons varies, but typically includes some HTML as well as <script> tags. When I output this field in a template, its contents are HTML encoded and displayed literally.

How can I keep this from being encoded so the HTML and Javascript can be parsed by the browser?


texts:
Is it possible to change the cookie timeout just for the cart?  E.g. I'd like to clear abandoned carts after X hours and keep all the other sessions untouched (e.g. user sessions etc).

Please advise anyone!


texts: Error: Call to undefined function Craft\mb_convertOcase() after updating to 2.6.3017

texts:
Just updated Craft 2.6.3002 to 2.6.3017 and am getting the following error in the CP & front-end: Call to undefined function Craft\mb_convertOcase() /craft/app/helpers/StringHelper.php(558). On line 558 of this file, I have return mb_convert_case($string, MB_CASE_UPPER, static::UTF8);. Where is O coming from?

Screenshot of error & stack trace:


texts: Why isn't my Twig replace filter working with craft.request.getUrl()?

texts:
I'm rendering some HTML into a variable. On this HTML I want to replace a value using craft.request.getUrl() but the value doesn't seem to get replaced. Any idea what I'm doing wrong?

{% set pages %}
    {% set entries = craft.entries.section('pages') %}
    {% for entry in entries %}
         {{ entry.title }}
    {% endfor %}
{% endset %}

{{ pages|replace({'data-url="{{ craft.request.getUrl() }}"': 'class="active"'})|raw }}


texts: Has anyone tried a port from Expression Engine to Craft using Verbb's Feed Me plugin?

texts:
I'm in the process of scoping out a project in Craft, which requires porting an existing site built in EE. The EE site in question relies quite heavily on relationships (using Playa) and not I'm 100% sure how/if Feed Me will be able to retain those relationships when importing into Craft.

Is this possible? Or will we have to remap the relationships after importing the content?


texts: In Craft 3 plugins, should CRUD operations go in Controllers or Services?

texts:
The documentation states:

  Many service methods perform some sort of operation for a given model, such as a CRUD operation.

(Link)

But browsing through existing plugins, I see the CRUD logic is most often done in controllers.

What's the best practice here?


texts: Can I Create a Way for Users to Add Fields from the Dashboard and/or create Fields with Same Handle?

texts:
I'm trying to create a Matrix field containing plain text blocks of two kinds, one for providing Youtube video embed codes, and one for providing a description. What I want to know is, is there a way to make it so users can add another field of either kind if they want to embed another video and/or provide another description, or do I have to "build" each field option in manually?

For example, the less elegant way I tried to solved this problem involved creating multiple fields, but since the handles all have to be different, I tacked a number onto each (mainYoutubeEmbed, youtubeEmbed2, youtubeEmbed3, and etc.) This just seems so clumsy and is completely non-DRY. The other option I considered to make it slightly better was to create a bunch of generic fields all with the same title and handle (so I could just loop through them), but Craft says that the handles must be unique.

Is there any way around this or a way to make it at least a little better, or is the best approach really to just create a bunch of fields and hope that my users don't need more in the future? Maybe a plug-in or magic incantation of some kind?? :)

PS. I know the titles can be the same, but I changed them to match the handles because if I find that I'm stuck with this janky method, I want it to be as easy as possible to "see" how it's laid-out.

Thank you in advance for all constructive advice.


texts: How to authenticate as a Craft user with a frontend tool like Next.js, Nuxt.js, or create-react-app?

texts:
We're looking to use Craft CMS as an application platform (handling content storage, user authentication, etc) for an upcoming project while leveraging something like Next.js on the front-end.

Here's a very basic gist of how the application will work:

A user can sign into (or create) an account
An authenticated user can create a job post

We'd love to use a frontend tool like Next.js, Nuxt.js or create-react-app. If we use this what's the best way to authenticate to the Craft back-end since the front-end and back-end are separated?


texts:
I'm writing a plugin where I need to render some semi-complex HTML clientside at runtime (all inside the CP).

Does Garnish (or any other library/framework/JS-thingamabob shipped with Craft) offer any built-in JS templating functionality a'la Handlebars or Underscore?


texts: Using Twig to merge an array and remove duplicates

texts:
Problem

I'm building a .json file for a search component of a used cars website. The file needs to be built from the output of two sections within CraftCMS, Used Cars and Vans & Trucks. It outputs the "make" of vehicle and it's "models".

My problem is that there are duplicate "makes"/"models" because they exist in both sections.

Code:

{% set allStock = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
{% for stock in allStock %}
{% set models = stock.getChildren() %}
"{{ stock.make }}" : "{% for stock in models %}{{ stock.model }}{% if not loop.last %}, {% endif %}{% endfor %}"
{% endfor %}

Output:

"Holden" : "Commodore, Ute, Viva"

"Nissan" : "ATLAS, CARAVAN"

"Mazda" : "ATENZA, Axela, CX-7, MAZDA 6, MPV, RX-8, mpv"

"Nissan" : "CARAVAN, DUALIS, FAIRLADY, Liberty, Maxima, NAVARA, NOTE"

Updated

{% set allStock = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
{% set newArray = [] %}
{% for stock in allStock %}
{% set models = stock.getChildren() %}
{% if stock.make not in newArray %}
"{{ stock.make }}" : "{% for stock in models %}{{ stock.model }}{% if not loop.last %}, {% endif %}{% endfor %}"
{% set newArray = newArray|merge([stock.make]) %}
{% endif %}
{% endfor %}

This code will remove the duplicate 'make' and merge but it also removes the models with it.

Output:

"Holden" : "Commodore, Ute, Viva"

"Mazda" : "ATENZA, Axela, CX-7, MAZDA 6, MPV, RX-8, mpv"

"Nissan" : "CARAVAN, DUALIS, FAIRLADY, Liberty, Maxima, NAVARA, NOTE"

Any help or direction on how to go about merging the models would be greatly appreciated.


texts:
I am receiving this error when installing via shell:

PHP Warning:  Unsupported declare 'strict_types'

PHP Fatal error:  Default value for parameters with a class type hint can only be NULL

Each error references "Bootup.php on line 3" and "Bootup.php on line 24" respectively.

I am running php v7.2


texts:
I try to load a entry after a button is clicked, currently my code looks like this:

This is generating a 404 error. Dunno why?

<?php
/**
 * PopUp plugin for Craft CMS 3.x
 *
 * test
 *
 * @link      https://digitalwunder.io
 * @copyright Copyright (c) 2020 digitalwunder.io
 */

namespace digitalwunder\popup;

use Craft;
use craft\base\Plugin;
use craft\services\Plugins;
use craft\events\PluginEvent;
use craft\web\UrlManager;
use craft\events\RegisterUrlRulesEvent;

use yii\base\Event;

/**
 * Class PopUp
 *
 * @author    digitalwunder.io
 * @package   PopUp
 * @since     0.0.1
 *
 */
class PopUp extends Plugin
{
    // Static Properties
    // =========================================================================

    /**
     * @var PopUp
     */
    public static $plugin;

    // Public Properties
    // =========================================================================

    /**
     * @var string
     */
    public $schemaVersion = '0.0.1';

    /**
     * @var bool
     */
    public $hasCpSettings = false;

    /**
     * @var bool
     */
    public $hasCpSection = false;

    // Public Methods
    // =========================================================================

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        self::$plugin = $this;

        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            function (RegisterUrlRulesEvent $event) {
                $event->rules['siteActionTrigger1'] = 'pop-up/default';
            }
        );

        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_CP_URL_RULES,
            function (RegisterUrlRulesEvent $event) {
                $event->rules['cpActionTrigger1'] = 'pop-up/default/do-something';
            }
        );

        Event::on(
            Plugins::class,
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
            function (PluginEvent $event) {
                if ($event->plugin === $this) {
                }
            }
        );

        Craft::info(
            Craft::t(
                'pop-up',
                '{name} plugin loaded',
                ['name' => $this->name]
            ),
            __METHOD__
        );
    }

    // Protected Methods
    // =========================================================================

    public function actionCheckStatus()
    {
        $this->requireAcceptsJson();

        $response = [
            'status' => 'open'
        ];

        return $this->asJson($response);
    }

}

And the script like this

    <script type="text/javascript">
      $('#test').click(function(e){
        e.preventDefault()
        var x = {{ entry.id }};
        $.ajax({
            'type': 'post',
            'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cache': false,
            // 'data': data,
            'url': '/actions/pop-up/checkStatus',
            'dataType': 'json',
            'timeout': 50000
        }).done(function (response) {
          console.log(response);
            // Success
        }).fail(function (error) {
           // Total fail.
        });
      });
    </script>

Can anyone see why I get a 404 error?


texts: How to check custom field not empty within params?

texts:
The following returns entries correctly:

{% paginate craft.entries.section('sectionName').customField(':notempty:').limit(10) as products %}
    {% for product in products %}
        {% include 'incs/_productSnippet' %}
    {% endfor %}
{% endpaginate %}

But the following returns empty:

{% set params = { section: 'sectionName', customField: ':notempty', limit: 10} %}
{% paginate craft.entries(params) as products %}
    {% for product in products %}
        {% include 'incs/_productSnippet' %}
    {% endfor %}
{% endpaginate %}

It's the latter I'm after because the customField I want to check varies. Removing the customField: ':notempty', from params in the second example returns entries, so I'm guessing it's the way I'm using customField within params?


texts:
I'm working at a large organization, where the servers are managed by an IT department. I want to migrate some websites to Craft and asked the IT department to install Craft on a server. The IT department tells me that Mcrypt is not supported by RedHat Enterprise/PHP5.6, so Craft can't be installed

I'm not familiar with server software, are they right? And is it easy to add Mcrypt?

Thank you for helping!


texts:
Guess this is a stupid question, but I'm trying to sort a table based on which column the user wants to sort.

Tried:

{% for row in entry.tablefield|sort %} (No effect)

{% for row in entry.tablefield.order('firstName') %} (Error message)

Anyone who know if this is possible or know how to do this?


texts: Craft Commerce: Wrong payment currencies in orders

texts:
I have Craft Commerce installed on my site (which uses Craft CMS 3.5.14).
I have set up multiple payment currencies for it (NZD - which is the base currency, AUD, EUR, GBP, JPY, USD).
When I go to Commerce -> Orders -> All orders, the total price of the order is rendered as expected in the grid as shown in the picture:

But when I click on the order, the order summary always shows
in NZD even if it was paid for in another currency:

I'm not sure if this is a bug or I am missing something.
Thank you


texts: How do I upgrade the MYSQL database from Craft 2 to Craft 3 on GoDaddy

texts:
How do I upgrade my MySQL DB for a Craft 2 site to Craft 3. I don't have access to the SSH server or use of Composer, so I have to move files via FTP and do everything manually.

My client is on GoDaddy, and need to resolve this as efficiently as possible.


texts: Show only children of current page in submenu

texts:
I have checked the official documentation and also these pages:

How do you only show children of "active" parent in a Structure section's nav?

How to output a structure sub-navigation of current page

I still can't get this to work though. I have tried various code and currently have this (from official docs):

{% set pages = craft.entries.section('pages').level('>1') %}
{% nav entry in pages %}

    {{ entry.title }}
        {% ifchildren %}

               {% children %}

         {% endifchildren %}

{% endnav %}

This outputs all the children whenever I'm on any top level page. My structure is a little different though, like so (shortened for brevity):

Home
About (structure: 'pages', entry type: 'aboutPage')
  - Aims (structure: 'pages', entry type: 'aboutPage')
  - Governance (structure: 'pages', entry type: 'aboutPage')
Services (structure: 'pages', entry type: 'servicesPage')
  - Residential (structure: 'pages', entry type: 'servicesPage')
  - Homecare (structure: 'pages', entry type: 'servicesPage')
Resources (structure: 'pages', entry type: 'resourcePage')
  - Health (structure: 'pages', entry type: 'resourcePage')
  - External (structure: 'pages', entry type: 'resourcePage')

You can see I have a tree which uses a single 'pages' structure to keep everything obvious in the admin section. I then just create an entry, choose the parent and choose the entry type to add content.

I use a structure 'mainMenu' to add links manually to the main menu using a related entry field. So I have:

Home - About - Services - Resources

As top level pages. When I'm on a top level page, I want to show children of this current page and to hide the unordered list element when there are no children of the current page, and I'm stuck.

Can anyone point me in the right direction? Thanks in advance.


texts:
I’m struggling with getting the next block inside of a loop of a Matrix-Field. I’ve tried this:

{% set nextBlock = entry.articleContent.offset(1).limit(1) %}
{% if nextBlock.type == "textBox" %}
 {{ nextBlock.textTitle }}
{% endif %}

This produces an ArgumentCountError. Can someone help me with this issue?


texts: Craft 3 / Craft Commerce Installation - Can't see products

texts:
I recently tried to install Craft Commerce onto Craft 3. I installed the plugin via the plugin store and added in the templates folder which I downloaded straight from https://craftcommerce.com/ and also tried the one from https://github.com/craftcms/commerce

However, when I did so, the pages seemed to work OK, but I can't view any products. I don't think I've got the right templates/shop folder, but I'm also not sure how to get the correct version for Craft3.

This is what my products page currently outputs:

0/5 of the example products are displayed.

I did try to follow the installation guide on the website, but it seems to only work for Craft2.


texts: Entries from different category levels brought together

texts:
I have an issue with categories with different levels:

I have a group of categories which have a structure like this:

First form:
1.0 Group –
1.1 Subgroup –
1.2 Items in subgroup

Second form:
 - 1.0 Group –
   1.1 Items in Group

In some groups are subgroups in others aren't. But I need to list all the items, regardless if they are in a subgroup or not. How can I adress them correctly. Can I do an if statement like: if there is no 1.2 level, take the 1.1 level and treat it like a 1.2 level?

How can I do this?


texts:
I am trying to upload/add an asset to an entry via a form on the website. The entry saves fine when I don't include the asset field but as soon as I add the asset field and try to upload a file I get this odd SQL error.

  CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (housewares.craft_relations, CONSTRAINT craft_relations_targetId_fk FOREIGN KEY (targetId) REFERENCES craft_elements (id) ON DELETE CASCADE).
  The SQL statement executed was: INSERT INTO craft_relations (fieldId, sourceId, sourceLocale, targetId, sortOrder, dateCreated, dateUpdated, uid) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='4', :row0_col1='27', :row0_col3='Golfclubs.jpg', :row0_col4=1, :row0_col5='2014-09-03 23:36:06', :row0_col6='2014-09-03 23:36:06', :row0_col7='a1e565e1-f6d3-4f3b-8a6f-2c049d236b13'

The field works fine in the CP.

This is the field

<input class="form-control" type="file" id="image" name="fields[image][]" />

Any ideas?


texts: Sorting Entries field results by category

texts:
I have an entries field 'physicians'. I want to output the selections from that field and sort them by category (also named 'physicians') - with the category heading above each category group.

I can't figure out if I should just output the category list and filter the result by the field or if I should output the entries field and then sort them by category. I'm trying the latter right now but not sure of how to get the categories to work.

{% set phyGroup = craft.categories.group('physicians') %}
{% set phyList = craft.entries.relatedTo('physicians').order('lastName asc') %}

{% for physicians in phyGroup %}
   <h3>{{ category }}</h3>
   {% for entry in phyList %}
      {{ entry.lastName }} ...
   {% endfor %}
{% endfor %}


texts: Register multiple TwigExtensions in one plugin in Craft 3

texts:
In my plugins init() function I have this:

Craft::$app->view->registerTwigExtension(new TestTwigExtension());

If I duplicate that and change the Twig Extension class name, I just get an error:

  Class 'marknotton\test\Test2TwigExtension' not found

In Craft 2.x, this worked:

  public function addTwigExtension() {
    Craft::import('plugins.test.twigextensions.test');
    Craft::import('plugins.test.twigextensions.test2');
    return array(
      new test(),
      new test2()
    );
  }

It seems that approach has completely changed. I can't rename any file names, Craft::import doesn't exist anymore, and I can't pass an array into the registerTwigExtension() function. (Craft 3 is scary).

What I'm trying to achieve is a way of organising my Twig Extension files, rather than having everything in one file.


texts: What is the expected data type to be returned when using the prepValue() method?

texts:
So while building a field type (FT), what is the expected data type of the returned value from the prepValue method? I am not sure I am using this method right, as I am running into a PHP error when trying to save the FT.

My FT stores data in two ways, the first as a JSON string stored in the element content table. When my FT is saved, I used the onAfterElementSave() method for additional processing. During this method, I am creating rows in a db table created by my plugin. What I desire to happen is when I call my field from the template on the front-end, it returns a data model which I can then pass to other methods for further manipulation (in the template). All this works great.

Here is my prepValue() code in my FT.

public function prepValue($value)
{
    $value = json_decode($value);

    return new MyPlugin_MyModelNameModel((array) $value);
}

All this works fine until I go to save my entry, which is producing this error "Internal Server Error - Object of class stdClass could not be converted to string". When I return the data from the prepValue() method as a string, it works fine when saving but then break in the template because it's expecting to be a model.

I even added a __toString() method to my model in hopes that if the data needs to be a string, my model could dynamically pass the JSON back as a string but that isn't working either.

Here is the stack trace from the craft.log

2014/08/14 19:28:35 [error] [php] Object of class stdClass could not be converted to string (/Users/justinkimbrell/Sites/craft_dev/craft/app/helpers/StringHelper.php:61)
Stack trace:
#0 /Users/justinkimbrell/Sites/craft_dev/craft/app/fieldtypes/BaseFieldType.php(148): arrayToString()
#1 /Users/justinkimbrell/Sites/craft_dev/craft/app/services/ContentService.php(366): Craft\GoogleMaps_GoogleMapFieldType->getSearchKeywords()
#2 /Users/justinkimbrell/Sites/craft_dev/craft/app/services/ContentService.php(137): Craft\ContentService->_updateSearchIndexes()
#3 /Users/justinkimbrell/Sites/craft_dev/craft/app/services/ElementsService.php(898): Craft\ContentService->saveContent()
#4 /Users/justinkimbrell/Sites/craft_dev/craft/app/services/EntriesService.php(141): Craft\ElementsService->saveElement()
#5 /Users/justinkimbrell/Sites/craft_dev/craft/app/controllers/EntriesController.php(440): Craft\EntriesService->saveEntry()
#6 /Users/justinkimbrell/Sites/craft_dev/craft/app/framework/web/actions/CInlineAction.php(49): Craft\EntriesController->actionSaveEntry()
#7 /Users/justinkimbrell/Sites/craft_dev/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams()
#8 /Users/justinkimbrell/Sites/craft_dev/craft/app/framework/web/CController.php(286): Craft\EntriesController->runAction()
#9 /Users/justinkimbrell/Sites/craft_dev/craft/app/framework/web/CController.php(265): Craft\EntriesController->runActionWithFilters()
#10 /Users/justinkimbrell/Sites/craft_dev/craft/app/framework/web/CWebApplication.php(282): Craft\EntriesController->run()
#11 /Users/justinkimbrell/Sites/craft_dev/craft/app/etc/web/WebApp.php(865): Craft\WebApp->runController()
#12 /Users/justinkimbrell/Sites/craft_dev/craft/app/etc/web/WebApp.php(254): Craft\WebApp->_processActionRequest()
#13 /Users/justinkimbrell/Sites/craft_dev/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#14 /Users/justinkimbrell/Sites/craft_dev/craft/app/index.php(196): Craft\WebApp->run()
#15 /Users/justinkimbrell/Sites/craft_dev/public/index.php(14): require_once()
REQUEST_URI=/index.php/admin/entries/news/47

******************************************************************************************************

Hopefully the issue is clear. I am just unsure of how to properly use this method, and wondering how I can return data in a model and not as a string.


texts: Unchecking Rich Text option to clean up HTML still cleaning?

texts: We've unchecked the clean HTML feature on a few rich text fields but our attempts to add some html (span tags) keep getting cleaned out. Is there another setting we should be looking for?


texts: Uploaded images are saving to the server's temp folder and throwing 500 errors

texts:
I've got a wordpress site that is live and am building a craft site to replace it on a subdomain and am having a strange issue that I've never had with any other craft sites I've built. Sometimes when images are uploaded the craft site the upload fails and I get a 500 error which crashes everything on the server including the live wordpress site. This has happened several times and the only way I can fix it is by asking Bluehost support to clear the server's temp folder for me. They have told me that for some reason images are being saved in there and aren't getting cleared which is causing the error. It seemes to be happening randomly, some days it happens every time I try to upload, other days it happens only after a few hours. I've looked through both Craft's error logs and my server error logs and can't make anything out. I've been troubleshooting several causes:

Incorrectly defining the image directory?

Initially I was storing images in a public folder and pointing craft to it with "../assets" because index.php is in a subdomain folder. Then I put the assets folder in the subdomain folder and it seemed to be working fine, till it crashed again. So I don't think this would be causing the issue

Multiple users on the same account?

I've enlisted a handful of people to help me port over content from the wordpress site to the new craft site and I tend to get these 500 errors when we're all uploading stuff together. However there have been times when we can work for over an hour without any problems.

Some conflict with Wordpress or other old files?

I'm not super familiar with PHP, could some server-side configuration be screwing all of this up? I've also got lots of old sites on the server from past developers that I have no idea what they do. I'm planning on wiping them all after this craft site is up.

I've configured something wrong in Craft?

Maybe?

Thanks guys


texts:
I'd like to get Craft working with New Relic so I can play with my two favorite apps.  My web host (EngineHosting) got the New Relic daemons et al going; has anyone tackled getting the Craft side going so that it reports in?

Let me know, please? I may be doing some learning in order to do this integration down the line; but if someone has tackled it, I could dive right on in a bit more quickly.


texts: Get entry field data via a plugin. ( For specific image assets )

texts:
I've got an asset field on a channel entry called "thumbnail". I'm using it to return a singular image, specifically for an image transform called "thumb". Looks a little like this:

{{ entry.thumbnail.first().getUrl('thumb') }}

This works fine. But I'd like to get the same information/url using a plugin (so I can perform some colour validation and other checks via PHP).

Can anyone share some wisdom on how best to approach this please?


texts: Entries field templating only when entry is added

texts:
I have a section type Structure called How to videos, in which I have field type Entries.
Now, when I select "Products" in the field type 'Entries'. I only want the selected Entries Products to show text "Click here to view". If there is no entry added in entries fields it should not show text "Click here to view".
How can I template the Entries field?


texts: Need help: Multiple Listing channels with one template. DRY

texts:
I have several Listing channels that all use the same templates:

E.g.

Templates:

/templates/view/overview.html
/templates/view/detail.html

Channels

News
Research Updates
Upcoming Events

How can I only list the entries for each channel at their respective URL without having to duplicate the templates?

E.g.

"http://mysite.com/news" should only list the the latest 20 news stories with links to the detail page.

{% for entry in craft.entries.section('news', 'research', 'events').limit(20).find() %}

{{ entry.title }}

{{entry.postDate|date('M j, Y')}}

{{ excerpt|length > 250 ? excerpt|slice(0, 200) ~ '...' : excerpt  }}

Read More

{% endfor %}


texts: Q: Freeform - have users update form on the frontend

texts:
I was wondering if it is possible to have users update their own entry on the front end with the Solspace Freeform plugin.

I get as far as getting all the necessary data of the user (freeform.submission) in a form (freeform.form) and I have added an input with the id of the entry to the form:
<input type="hidden" name="id" value="{{submission.id}}" />

When submitting this form it will save the data, but as a new entry instead of updating the existing one. So is there a way to update the existing id, similar as to what is happening in the cp?

Thanks!


texts: Change the URL of nav child entry conditionally

texts:
I want to change the URL of a li from a nav menu conditionally (using a custom field where the user sets the URL), but I don't see how to use conditionals with {% ifchildren %}?

{% nav entry in entries %}

        {{ entry.title }}

        {% if entry.id in craft.entries.descendantOf(4).ids() %}
            **change the url of all child entries**
        {% endif %}

        {% ifchildren %}

                {% children %}

        {% endifchildren %}

{% endnav %}

ID 4's children is the entry which I want to display custom URLs.


texts: Create nested categories with Feed Me plugin

texts:
I'm trying to import nested categories. My JSON is like:

[{"title":"Title""location":[{"Florida":["Key West"]}]}]

I want to be created "Florida" category and nested child "Key West"
But plugin offers me to import that like this:
https://d.pr/free/i/NvgGOm

Only "Key West" category will be created.

Is it possible to import nested categories? What is the right JSON structure for that?

Additional info:

Plugin version: 4.1.2
Craft version:3.3.18.4


texts:
I'm keen to set my image variants dynamically from content editor and not quite sure how I do this in twig.

I have three variants. They are named imageVariantsThumb, imageVariants16by9, and imageVariants3by2 in craft.

To render the variant on the image I use the following.

{% set optimizedImages = item.itemImage.one().imageVariantsThumb %}

Depending on the dropdown selected in the editor (say the values are thumb, 16by9 and 3by2) I want to change the variant name in this line of code. How do I use the value from my drop-down field to change the variant name on the end of the code above?

I have tried defining a variable using the value and replacing imageVariantsThumb above but it doesn't work:

{% if block.listImageRatio == '16by9' %}
  {% set imageRatio = 'imageVariants16by9' %}
{% endif %}

{% set optimizedImages = item.itemImage.one().imageRatio %}


texts:
Is it possible to call a method of a plugin's controller from within a plugin? I don't plan on making a habit of this but sometimes it may be needed. Just trying to plan ahead.

Thanks!


texts:
I'm trying to do something like this in general.php config for a multi-site setup:

// ...
'production' => array(
    'myVariable' => array(
        'site1Handle' => '111',
        'site2Handle' => '222',
    ),
),
// ...

So, when we do:

{{ craft.app.config.general.myVariable }}

We can get different values ("111" or "222") based on which site I'm on.

I believe that we can do something similar to this in Craft 2 (was multi-lingual though). See https://docs.craftcms.com/v2/localization-guide.html#step-4-define-your-site-urls

Can we still do this in Craft 3?


texts: Generate PDF's (Printmaker plugin) with a static header and footer

texts:
Does somebody know if it's possible with Printmaker to provide each page, of the PDF you generate, with a static footer and/or header?

Printmaker makes use of the dompdf library. In the documentation of this library I found that this is supported by the library.

But I cannot find in the Printmaker documentation that you can also use this option with the plugin.

I hope somebody can answer this question.

Or does somebody know a plugin that I can use as an alternative, that does support this?


texts: Restrict Permissions Per Entry Rather Than Per Section

texts:
Working in Craft 3, I have a requirement to restrict user access (in the CP) per Entry rather than per Section.

In this case Users in Craft will belong to Department (Channel) and Resources (Channel). They should only be able to administer the Entries in those Channels for which they are responsible.

I suppose the ideal would be to create a User Group per Department and then be able to select the individual Entries within the Department & Resources Channels here:

Is that possible via a Module/Plugin and if so can anyone provide any pointers on how to get started? I presume I'd need to loop through all Entries in the Channels and output them in this list to be selectable and then have access permissions applied. Any examples or pointers would be appreciated.

Any other suggestions or workarounds also welcome.

Thanks


texts: Best way to re-populate input field with Model data on front-end?

texts:
I have a Plugin which saves data from a form the user enters on my front-end. When the input data is wrong and I display my validation errors using getErrors from the Model I want to re-populate all my form fields with the submitted data in my Twig template.

Right now I'm doing this like this:

<input type="text" name="fieldName" value="{% if model is defined %}{{ model.fieldName}}{% endif %}"/>

Is this the correct way of doing this or is there a better practice?

Seems like there's to many unnecessary if statements going on...

Thank you


texts: Craft 3 CMS Solo setting general Logo option

texts:
I have installed Craft 3 Solo and it's installed on my local machine. I would like to know how can I get an option in Setting -> General to Logo (upload Login Page Logo).

I am new to Craft, so would like to get a little bit of guidance.

Thanks.


texts: I would like to know that do we have Google XML Sitemaps plugin for Craft CMS. If yes is there an tutorial that how I can use it. I would like to use it for SEO purpose so that Google can easily crawl my website. A short explanation or video tutorial would be really nice. Thanks in advance.


texts: How do I pass a hidden input value to plugin onSaveUser event handler?

texts:
I'm writing a customer portal plugin, utilizing Crafts user registration form: https://craftcms.com/docs/templating/user-registration-form

{# User registration form: #}
<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="">

    {# What do I add / change ? #}

    {# ... #}
</form>

My plugin has two different types of account profile records, .._OrganizationProfileRecord and .._UserProfileRecord. What I want to do is send a variable to the onSaveUser event handler in my plugin main class, to tell it what type of user was just saved ("org" or "user"), and then take appropriate actions, i.e. create either an organization or user profile.

class myPortalPlugin extends BasePlugin
{
    public function init()
    {
        craft()->on('users.onSaveUser', function(Event $event)
        {
            $craftUser = $event->params['user'];
            $isNewUser = $event->params['isNewUser'];

            if ($isNewUser)
            {
                // Check if user is an organization or a regular user, and
                // create the appropriate profile record.

                // How do I check?

                // ...
        }
    }

    // ...
}

Questions:

How would I go about passing data/variable from the form to the onSaveUser event handler?
Is there a better / more convenient way to do this?

Many thanks in advance for any help you can provide in this matter!  bowing

/Monkey


texts:
I'm setting my categories by matching the third segment to a category slug. How do I get the category title?

{% set catSlug = craft.request.getSegment(3) %}
{% set category = craft.categories.slug(catSlug) %}

{{ category.slug }} returns the slug, but {{ category.title }} returns nothing.


texts: Selling products with a digital variant using Craft Commerce

texts:
Is it possible to sell products using Craft Commerce, where the product may have digital AND non-digital variants?

For example, a greeting card, might be available as a printed card but also as a digital download.

I know there is a Digital Products plugin - however, this seems to require that the product is either digital OR not (it can't be both):

  Digital products are similar to Commerce’s core products, except that
  they don’t have variants


texts:
Just wondering if there's a way to return the matrix block number during the loop?

For example:

{% for block in entry.myMatrixField %}
  {% if block.type == "quote" %}

{{ block.quote }}

  {% endif %}
{% endfor %}

Might return something like this:

Curabitur aliquet quam id dui posuere blandit.

Curabitur aliquet quam id dui posuere blandit.

Curabitur aliquet quam id dui posuere blandit.

Thanks, Mark


texts: How can we move a Craft-built website to a new web designer?

texts: We have a new website waiting to be published, and we would like to hire a new web design team, who is not a Craft Pro User...Is there anyway to get our website off of Craft or are we stuck with getting our own Pro Account? Please HELP!


texts: Running into permission issues using Vagrant on Ubuntu

texts:
I am having issues running CraftCMS in a vagrant environment.

For reference:
    I am using ubuntu 17.04
    Vagrant version 1.9.5
    ubuntu/xenial64 (virtualbox, 20170525.0.0)
    Relevant initial provisioning here

After the vagrant box is booted up I wget the lastest CraftCMS files.
I then run chmod -R 777 /craft/app/ (+/config/ /storage/)

From that point on I would normally be able to complete the installation but instead I am met with a RuntimeException (paste here, screenshot here)

I've tried setting the permissions inside and outside of the environment. I have also tried changing ownership to www-data. And even put the user in the www-data group.

I'm pretty baffled, as I have no problems running my craft install on my production servers. Any help would be appreciated.


texts: Displaying one site's content in another site (Craft 3 Multi-site)

texts:
I've got a bunch of entries in Site 1. I need to display them in Site 2. If I specify the site, I get the entries.

{% set entries = craft.entries.section('cenicNews').site('cenicOrg').limit(10) %}

However, they are pointing to Site 1's domain, using Site 1's template:

site1.com/news/new-library-initiative

I want them to be loaded on Site 2's domain, using Site 2's template:

site2.com/news/new-library-initiative

Note, if I remove the site parameter from my query, I get no results.


texts: On the P&T form add-on you have to use a message field is there a way round this?

texts:
Unless I am misunderstanding the docs for the P&T form, it says you have to include the message field, if some forms don't have a message field is the only way to not show this hide it with CSS?

Just wondered what other people are doing for forms - I am also looking at the Sprout form add-ons.


texts: ElementAPI: Include author/user data with entry?

texts:
Searched around online and couldn't find an answer to this question. I want to be able to include some data from the author/user account associated with an entry.

Here is the basic working version of an individual entry, which does display the 'author' name, but no idea how to display that user's data, such as; profile photo, first name, last name, and custom member fields.

'listings/<entryId:\d+>.json' => function($entryId) {
  return [
    'elementType' => 'Entry',
    'criteria' => ['id' => $entryId],
    'first' => true,
    'transformer' => function(EntryModel $entry) {
      return [
        (int)$entry->id,
        (int)$entry->year,
        $entry->manufacturer,
        $entry->model,
        $entry->author
      ];
    },
  ];


texts: Are there any advantages of updating from PHP 5.4.40 to 5.6?

texts: Simple question, are there performance gains or any other benefits to make it worth the effort of updating the server?


texts: How does a plugin include it's own config options?

texts:
When building a plugin, how does one define user editable config files? Would it be better to create a settings UI in the plugin and have the user edit those variables in the CP? Or is there a way to do it properly with a config file?

The reason I want to opt for a config option is so the value can be localized for the specific environment to set different options. I need to add the ability to define a public directory that will be used to store generated images and obviously that path could be different on local and production environments.


texts: How to get all available tax rates in a Commerce site?

texts:
Is there a way to retrieve and loop through all the available tax rates that have been set up in Commerce 1?

I had thought I could loop through the adjusters like so;

{% for adjustment in cart.adjustments %}
    {{ adjustment.name }}
{% endfor %}

In fact, I'm doing this on one site with no problems but having just tried the same thing on another project I am running into errors. I'm guessing because no adjustments exist unless there is actually a cart object.

I am trying to retrieve its value in order to display the price including tax on my product page template. For this particular case I only have 1 tax rate, so there is no problem with regionality. I figured that I could loop through the adjuster, check the name and retrieve the value.

If there's another way to do this I'm all ears!


texts: craft_cache / Integrity constraint violation: 1062 Duplicate entry, Serialization failure: 1213 Deadlock

texts:
Noticing these errors a lot it my logs. Any idea why, or how to stop it from happening?

Jan 27 15:02:58 myapp.com ool: myapp: [craft] [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'b790ee3c633c1693d2140bfae35b65fe' for key 'PRIMARY'. The SQL statement executed was: INSERT INTO craft_cache (id,expire,value) VALUES ('b790ee3c633c1693d2140bfae35b65fe',1485633775,:value).

Update - also seeing:

Jan 27 15:49:58 myapp.com ool: myapp: [craft] [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction. The SQL statement executed was: DELETE FROM craft_cache WHERE expire>0 AND expire<1485550196.

Notes:

I'm not using any template level caching (site is Varnished)
My cacheMethod is 'db'
Load balanced setup (1 LB, 2 web heads, 1 LB, 1 DB)
Looking up the key in the latter example, it is a serialized object of Craft\SearchPlus_AlgoliaMapModel (plugin). However, looking at the SearchPlus code I'm pretty it the plugin itself isn't storing this. It has one call to craft()->cache->set and it just stores a string.


texts: How to use a table field in custom plugin's settings (Craft 3)

texts:
I need a table field in my plugin's settings, but when I make 2 rows and save the settings, only the first row is shown when I go back to the settings page.  When I dump the values, my second setting is still in there. Here's my code:

{% import '_includes/forms' as forms %}

{% set name, rows = 'myCustomSettingsTableField', [] %}

{% if attribute(settings, name) != null %}
   {% for value in attribute(settings, name)[0] %}
      {% set rows = rows|merge([value]) %}
   {% endfor %}
{% endif %}

{{ forms.editableTableField({
   label:  'My Settings Table Field',
   id:     name,
   name:   name,
   cols:   [
              {heading: 'Column 1', handle: 'column1', type: 'text'}
              {heading: 'Column 2', handle: 'column2', type: 'text'},
           ],
   rows:   [rows],
}) }}

Dumping settings.myCustomSettingsTableField gets me this even though I can only visually see the the first row in the table when I re-enter the settings page.

array(2) {
   [0]=>
   array(2) {
      [0]=>
      string(15) "Row 1, column 1"
      [1]=>
      string(15) "Row 1, column 2"
   }
   [1]=>
   array(2) {
      [0]=>
      string(15) "Row 2, column 1"
      [1]=>
      string(15) "Row 2, column 2"
   }
}

How do I configure my Twig code so that it saves and displays correctly?


texts: Does anyone have a working example of frontend form with multiple file upload, drag & drop etc?

texts:
I'm trying to create a frontend entry form for a logged in user, with a field to upload multiple assets to that entry.
I've tried using the Jquery FileUpload plugin, but can't seem to get that working.
The situation:

The entry type contains an Asset Field, called photos. This field creates a new folder based on the entry's ID;
Users have to be able to select multiple images, with a nice process-bar showing while uploading;
I've tried uploading directly to actions/assets/uploadFile, but I get a permission error;

Does anyone have something similar working with Craft?


texts: Redirect user to the page they wanted after login

texts:
I have some pages that require login from the user. What I'd like is for the user to get redirected to the page that they wanted after they've logged in rather than sent to the page that they were on before they attempted to view a 'login required' page.

At present I have this in my login form:

<input type="hidden" name="redirect" value="{{ craft.request.getUrlReferrer }}">

Is there a craft request method I can use instead of getUrlReferrer to accomplish this?


texts: Can't seem to output fields related to the current category page

texts:
I'm struggling to output images and other fields that are related to the current category page.

So {{ entry.title }} is outputting as expected, and displays the title of the related items to that category. But any other fields do not output.

{% set shopEntries = craft.entries.section(shop).relatedTo(category) %}
{% for entry in shopEntries.limit(16) %}

    {% set image = entry.shopImage.first() %}

    {% set shopImageTransform = craft.imager.transformImage(image,
    { width: 130, height: 170, mode: 'crop', position: 'center-center', jpegQuality: 90 }
    ) %}

{% endfor %}

This snippet is appearing on a category page, e.g domain.com/category/fashion.


texts:
I ask this question a few weeks ago, but could not fix this problem. Now i have minimize my code.
i use this loop:

{% for program in craft.entries.section('program_point').order('program_number') %}

and it takes 25s. The loop returns 81 data.

Is there a way to speed this up?


texts: I'd like to create a field type for my plugin called "location" with two text boxes: one that holds a coordinate for latitude, and one for longitude. I haven't figured out yet how to map those two values from HTML input elements in a template to a JSON array in the database.  Is there an elegant way to achieve this with the Craft API?