texts: When a user installs my plugin, I would like the plugin to create an entry type on install. First of all, is this possible? If so, can someone point me in the direction of where I would find documentation on how to do this? Thanks!


texts: Commerce email receipt not sent after order, but manual Send Email in Order screen works

texts:
I have placed a successful order in Commerce and it's settings have an email setup to send an email to the customer and use the example special/receipt email.
But the receipt email is not sent once the order is placed.
If we login to the admin and go to the order page, selecting Send Email and choosing the customer receipt then it does send it OK.
So the receipt email is all setup OK and sends using the function in the order screen, its just not sending after the order is placed.
There is no commerce.log in storage.
web.log doesn't have any logs related to commerce or the order.
There is nothing in the Queue related to this (only loads of failed "Updating search indexes" and "Generating products sitemap" which is a whole other issue).
Does anyone know what it could be or how I could even go about debugging this when email works and I can't find any logs about its not sending?
Thanks


texts:
I posted this on github already but I thought I would ask her as well to see if anyone has any ideas

Im trying ot do a simple import of some organizations with categories and parent organization

Here is the CSV

https://www.dropbox.com/s/irh8cno9eh536su/testImport.csv?dl=0

Everything goes in (including the parent which is an entry field and works great) but the categories always end up blank.

Any ideas what might be wrong?  The importer isnt showing any errors.


texts:
I'm trying to pull all events where the event's year from endDate matches the queried year (yearParam). When I have this, it's pulling in all events before the yearParam:

{% set pastEntries = craft.entries({endDate: '<' ~ yearParam}).section('events').order('endDate desc') %}

However, what I'd really like is to get entries that match the yearParam (so if the yearParam is 2017, then any events from 2017 should be pulled in).

Any and all help is greatly appreciated. Thanks!


texts: I want to have a button on order information page when clicked the same order should be repeated. How can I put the same products again in the cart or simply re-order again?


texts: Craft 3 cannot find mysqldump command, console works

texts:
I want to use Feed Me with Craft to import my old database, but neither Feed Me nor Craft can find mysqldump.

I know this is a known problem, and I have successfully added the path to $PATH and verified that this is set in my .bash_profile.

When I execute mysqldump on the console I get the familiar usage hints. Executing which mysqldump gives me /usr/local/mysql/bin/mysqldump.

Yet when I go to Craft > Database > Backup it fails. In web.log I find:

  2018-07-18 21:01:10 [::1][1][-][error][yii\base\Exception] yii\base\Exception: Could not create backup: The shell command "mysqldump --defaults-extra-file="/Users/xxx/mysite.com/code/craft/storage/runtime/temp/my.cnf"
  [snip]
  _180718_110110_rig2b5xl4z_v3.0.15.sql"" failed with exit code 127: sh: mysqldump: command not found in /Users/xxx/mysite.com/code/craft/vendor/craftcms/cms/src/controllers/UtilitiesController.php:383

Why can I run the command in the terminal but Craft cannot? I've checked the permissions, and they should be ok:

-rwxr-xr-x   1 root  wheel   4062128 29 Sep  2016 mysqldump*


texts:
I have the following category https://www.ticketstoday.co.uk/theatre which has around 600/700 Entries, this is paginated at 30x Entries a page. Unfortunately, it's loading rather slowly. It's not a huge entry count so I'm unsure what's happening.

  {% set entries = craft.entries ({
          section: 'events',
          limit: '30',
          order: 'postDate desc',
          with: ['eventMediaTile'],
          relatedTo: category
      }) %}

  {% paginate entries as pageInfo, pageEntries %}
  {% do seomatic.helper.paginate(pageInfo) %}

  {% for entry in pageEntries %}
    {% include '_card' %}
  {% endfor %}

Is there anything at all I can do to speed up the query, or, is it a limitation of Craft?

  Added Card Template below

{% if entry.eventPercentageSaving > 0 %}

{{ entry.eventPercentageSaving }}% Off

{% endif %}
{% for asset in entry.eventMediaTile %}

{% endfor %}

{{ entry.title }}

{{ entry.eventVenueName.one().title ?? 'N/A' }}, {{ entry.eventCity.one().title ?? 'N/A' }}

From £{{ entry.eventMinimumPrice }}


texts:
I have a couple of sites that are being attacked (for the last 4 months), about 50k requests from about 3k unique visitors a day. The format of the url from the referrer is:
domain.org.uk/?URL=google.com.iq for example.
I have the sites on Cloudflare to reduce the bandwidth drain but am wondering if there is something I can do to prevent the URL redirect feature of Craft from responding to this format of URL or respond in a better way?
I'm looking at adding this to the htaccess file:
ErrorDocument 403 default
RewriteCond %{QUERY_STRING} URL
RewriteRule ^.*$ - [F,L]

But wonder if there is something better?
I'm concerned that the sites will get blacklisted as a source of spam.


texts: What does the error "Use of undefined constant CRAFT_BUILD - assumed 'CRAFT_BUILD'?" mean?

texts:
Accessing my /admin of a craft site and i get this error.

Internal Server Error

Use of undefined constant CRAFT_BUILD - assumed 'CRAFT_BUILD'

Never happened before today, I'm running PHP v5.6.30.

Thanks


texts:
I have a checkbox field that is populate with user choices.  I need to get the values they have selected from within a plugin. Here is my attempt. Not working.

    $entry  = craft()->entries->getEntryById($entryId, $localeId = null);
    foreach ($entry->storyCategories->options as $option) {
     var_dump($option);
    }

Can somebody please show me how to get these selected values?


texts:
I have just one page on my site with only one language:

Every other page has two languages.

I want to disable certain things on that page (like language switchers). How do I determine this?

This just returns all avalable languages no matter what languages are activated:

{% set otherLocales = craft.i18n.getSiteLocaleIds() %}
  {% for locale in otherLocales %}
    {{ locale }}
  {% endfor %}

I tried to do it with status:

{% set otherLocales = craft.i18n.getSiteLocaleIds().status('live') %}

but that returns an error as well. I tried status because it's labeled that way in the cp.

This returns the opposite language although the other locale doesn't exist on this page.

{% set otherLocales = craft.i18n.getSiteLocaleIds()|without(craft.locale) %}
{% for locale in otherLocales %}
  {{ locale }}
{% endfor %}

Any other ideas?


texts:
I have a plugin that starts a task and subtasks from a CP widget AJAX call. The tasks are running without a hitch, but for some reason on production, the icon does not appear when the tasks start running unless I refresh the page.

On my local dev site (MAMP), the task icon appears as soon as the code below is called.

I am using this code to start the pending tasks I created:

Craft.cp.runPendingTasks();

Any ideas? Is there a different JS command I should be using?


texts: How do I talk to Smart Map in JavaScript?

texts:
Well, I know for a fact I am doing this incorrectly & it's going to be painfully obvious. I can see why (I think) but to be honest I just don’t “get it”.
I’m trying to style a Google map using Smart Map & JavaScript, but keep getting the JS error:
Uncaught ReferenceError: smartMap is not defined(…)

This is what my template looks like:
{# Google Map of location. #}
{% set options = {
    height: 500,
    width: '100%',
    zoom: 15,
    markerOptions: {
    },
    infoWindowOptions: {
        maxWidth: 200
    }
} %}

    <div id="mapCanvas">
        {{ craft.smartMap.map(product.address, options) }}
    </div>

    <script src="/assets/js/app.min.js"></script>
</body>

Within app.min.js I am doing this:
if ($('#mapCanvas').length) {
    var styles = [{
        "featureType": "all",
        "elementType": "geometry",
        "stylers": [{"visibility": "simplified"}, {"hue": "#ff7700"}]
    },

    ...

    smartMap.map['smartmap-mapcanvas-1'].setOptions({styles: styles});
}

I've been reading this post which literally has the answer to my problem I believe. I just don't understand how to tell the system where/what smartMap is.
Thank you for any suggestions!
EDIT
Here is what the rendered page looks like:
<script src="/assets/js/app.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://mysite.dev/cpresources/smartmap/js/smartmap.js?d=1449217510"></script>

EDIT 2
Just for future reference in case someone else comes across this thread. It ended up being the way I was initializing my js file.
// This executes before we're ready
(function () {
    'use strict';
    ...

})();

// This works
$(function () {
   ...
});


texts: How do I setup an assets feed using the FeedMe plugin?

texts:
I want to setup an assets feed using the FeedMe plug-in.  Everything is well documented, but the documentation for assets is still TBA.

I previously created and updated entries using FeedMe.  Now, I want to add a PDF asset to each entry.

My PDFs are already uploaded to an S3 bucket assigned to the asset field I want to FeedMe to update.  But, I can take them down and start clean if that works best.


texts: How to filter the entries in redactor link "Link to an entry" based on the category tagged in the content

texts:
I have entries that should not be shown to other users that not is not tagged to it's category.
Any idea on how to deal with this issue?

I've checked this issue How to remove Link To Category from Redactor but I think there's more to it, played upon the fix but no luck.
Please help.
Thanks in advance.


texts: How to rename filename of asset before (or after) upload in Craft 3

texts:
I want to change the filename before the file is stored, to prevent ugly, long and weird filenames uploaded by users.

I've found an example for Craft 2, but because of the changes for events I can't rebuild this for Craft 3 (Change asset name on upload)

I also tried to change it a event, no luck;

Event::on(
    Asset::class,
    Asset::EVENT_BEFORE_HANDLE_FILE,
    function(AssetEvent $event) {

        $asset = $event->asset;
        $filename = 'filename'.md5(time()).'.'.$asset->getExtension();
        $asset->filename = $filename;
    }
);

Apparently the filename property is read-only, so you can only change properties like the title.

Any help is appreciated!


texts: Feed Me - importing Commerce variants from Google Sheets?

texts:
Is there a way to automagically create variants from a Google Sheet when importing via Feed Me?

The docs at https://docs.craftcms.com/feed-me/v4/guides/importing-commerce-variants.html#setup-your-feed only mention JSON and XML

Thanks :)

EDIT FOR CLARITY: I can't figure out how to relate a Variant row in the spreadsheet to the parent Product row, I guess this is inherent in XML/JSON because of the nested structure...


texts: Taxcloud.net integration for Craft Commerce?

texts:
We have a lot of exemptions, re-seller and agriculture, as well as states to report. this tool calculates and accepts the customers exemptions. We are looking at making a plugin but wanted to see if it has already been done.

The service is no or low cost and does the filing for a good number of states. So this is a great alternative to other sales tax services.


texts: I'm writing another plugin for my craft app, this time I'm attempting to reuse a MySQL table that's used by other applications as well. I've a class extending the BaseRecord, and getTableName() will return differentdb.tablename. Does Craft handle this, or do I have to make a copy of that table in the craft database? (MySQL permissions for the craft user already give it read access to that database)


texts: How to identify the recurring payments that happen after the initial subs creation payment the in Commerce Subs

texts:
I've got a custom module that I have written to inject data into various places in my site when events happen with Commerce Subs.

As per the question title, I need to update an entry when a recurring payment happens (not the initial payment as I'm already doing something with that event).

I cannot see how to identify the subsequent payments from the events I have available to me in Craft Commerce


texts: How can I disable sessions for most of my Craft site?

texts:
We're running a craftcms-backed site that uses sessions only for the admin pages.

For a few reasons, we'd like to disable session logic for all other urls:

the Set-Cookie header that craft uses to initiate a session makes responses uncacheable in our fronting cache layers
the code path under Craft\UserSessionService is unnecessary overhead for most of our logic, and occasionally adds considerable latency

We've been using HeaderHelper::removeHeader('Set-Cookie'); on a per-controller basis to turn off this behavior, but that only gets us so far - for example, 404 responses seem to try to initiate user sessions as well, before any of our custom logic can be used:

(This is a screenshot of newrelic transaction trace for a 404 response)

How can we get craftcms to stop trying to set these sessions?

I should note that we're looking into getting session storage out of the filesystem and into redis, which should also help - but most of the sessions we're keeping are meaningless, and I'd rather not keep track of them at all.


texts: Getting an asset Url from an entry loop into a meta tag

texts:
I found it pretty straightforward to get something like dynamic page titles working by setting a variable at the template level and pulling that into my site's meta tags:
My _layout.twig:
<head>
{% if title is defined %}
<title>{{ title }}</title>
{% endif %}
</head>

My template.twig:
{% set title = entry.title %}

But what's the best practice for pulling something like an asset URL that needs queried from within {% block content %}? I'm running a for loop on my asset field to grab the Url from within the template, but this doesn't seem to work outside of {% block content %}, and if I run it from within {% block content %} the variable doesn't carry over to _layout.twig where I need it in the meta tag.
My _layout.twig looks like this:
{% if openGraphImage is defined %}
<meta property="og:image" content="{{openGraphImage}}" />
{% endif %}

But how can I define an image Url that's coming from within an entry query and have it pass back to the meta tag?


texts:
I took the manual install route, unzipped the latest Craft version, and edited the .env file with my database settings, but when I direct my browser to /craft/web/index.php I get a plain page with

  Craft requires PHP 7.0 or later.

I have Bluehost Shared Site and have tried setting my PHP version to 7, but that justs adds a PHP 7 handler to my .htaccess file.  When I check the PHP version through the console it still says 5.6.

I have tried the composer route, and added --ignore-platform-reqs, but when I get to the ./craft setup step I get the exact same message.

I'm just not sure what to do from here.

Thanks


texts: Plugin function throwing error for missing argument

texts:
I'm trying to extend a plugin to allow for a limit to be added to the database call but it's throwing an error:

  Missing argument 1 for Craft\Curate_UsersContentService::getRank(),
  called

The services file has a function in it called getRank() and I've added a $count variable to it getRank($count). My twig template then calls it with the following code:

{% set count = 10 %}
{% set rank = craft.curate.getRank(count) %}

But the above error is thrown. What an I missing?

Any clues appreciated.


texts: Accessing named parameter in custom route from within a controller

texts:
I have a custom module in which I am setting a front end route that routes through to a controller. Like so:

 Event::on(
    UrlManager::class,
    UrlManager::EVENT_REGISTER_SITE_URL_RULES,
    function (RegisterUrlRulesEvent $event) {
        $event->rules['my-account/orders/<order>/pause'] = 'custom-module-name/order/pause-order';
    }
);

This works fine but how can I access that <order> named parameter within my controller? Is the only way to use craft::$app->request->getSegment(3);?


texts: Front End entry form, mapping a hidden field to a plugin?

texts:
I'm not entirely sure if this is possible, or the right way to go about this, however here goes.

I have a front end entry form that members use to create entries. These entries contain location data. I'm looking at using a maps plugin but nothing out there supports front end directly. I'm currently testing Squarebit Maps. (Smartmap is next!)

Now, from checking out the db, Squarebit Maps stores it's field data in the craft_content table in a format like so:

{"mapLat":"50.89150121867578","mapLng":"-1.4487441291137202","mapZoom":"15","pinLat":"50.89150121867578","pinLng":"-1.4487441291137202","__model__":"Craft\\SquareBitMaps_MapModel"}

I was wondering, if I included a map for users to choose a location within the front end form using something like Geocomplete could I pass through the lat & long in a hidden field to the squarebit field?

Hope that makes sense?


texts: Not able to see the page Create your Account

texts: Accessing the ../admin page, it shows me the login page directly instead of create your account page. I don't have any account for Craft so I'll definitely need to create an account of mine in Craft but not able to find the Create Your Account page.


texts: Inserting data into a table fieldtype via plugin?

texts:
I'm trying to import data from another database into a 'table' fieldtype via a plugin, and have a couple questions.

When setting the content on the EntryModel, are there any methods to assist in setting the rows and/or columns, or do I need to just format the data as a string in the expected format?

    $entry->getContent()->setAttributes(array(
        'tableFieldHandle' => '[{"col1":"data","col2":"data"}]'
    ));

Secondly, what's the recommended method to prepare strings for a table field (i.e. so as to escape or encode double and single quotes)?


texts: Ajax request returns code instead of result of the query (solved)

texts:
I'm trying to answer my own question in this post Basically, I have a bunch of checkboxes in multiple categories and when clicked, I want to use Ajax to filter the results and show them on the same screen.  I'm building up to that incrementally, and starting out by just trying to get the Ajax to work right with a single category filter.
My Ajax looks like this:
$('#filters input').change(function() {
  var value = $(this).val();

  $.ajax("ajax.twig?search=" + value, {
    type: 'get',
    dataType: 'html',
    success : function(html) {
      $("#ajaxresults").html(html)
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }
  });
});

ajax.twig look like this:
{% set searchTerm = craft.request.getParam('search') %}

{%  set galleries = craft.entries.section("gallery").colors(searchTerm) %}
{% if galleries|length %}

    {% for gallery in galleries.all() %}

{{ gallery.title }}

    {% endfor %}

{% endif %}

If I visit ajax.twig?color=red manually in the browser, it works as expected and I see the rendered result.  However, the page with the filters using ajax just returns the code inside ajax.twig rather than the result of the query.  I've also tried using .load() and .get() and had the same result.
Does anyone know what I'm doing wrong? I've been stuck for days. Thanks in advance.


texts: Is it possible to listen for Yii events?

texts:
I want to listen for Yii events like onBeginRequest and onEndRequest. I've tried the following but nothing happens :(

\Yii::app()->onBeginRequest = create_function('$event', 'die ("YO") ;');

and

craft()->attachEventHandler('onBeginRequest', array($this, 'dieyo'));

and

craft()->getEventHandlers('onBeginRequest')->add(array($this, 'dieyo'));

-

public function dieyo($event)
{
    craftdd($event);
}

Thanks in advance


texts: Limit control panel assets modal to a subfolder in plugin

texts:
I'm working on a control panel plugin where I want to limit users to a subfolder within a main assets folder. I have the subfolder ID, but am unable to amend the following to make use of it:

{{ forms.elementSelect({
    id: 'register',
    name: 'fields[register]',
    elementType: craft.elements.getElementType("Asset"),
    elements: register.register | default,
    criteria: {"kind":[],"localeEnabled":null,"locale":"en_gb"},
    jsClass: 'Craft.AssetSelectInput',
    addButtonLabel: 'Upload register',
    limit: 1,
    sources: ['folder:9'],
    disabled: register.locked | default
}) }}

So, for example, the folder ID above is a subfolder ID, but the asset ends up being saved within the main folder. If I revert back to the main folder ID, then everything works as expected.

To be fair, using this subfolder ID means existing assets aren't visible, which is the main reason I'm doing this anyway. But it would still be nice if this did what I wanted to.

Some more info:

If the folder ID is a valid asset folder, it works as expected.
If the folder ID is a dynamically generated subfolder of a valid asset folder, the modal doesn't show any existing files but does allow uploads (saving them directly into the parent, which actually works nicely for me).
If the folder ID isn't a valid folder or subfolder, the modal is empty.

Any ideas? This is kind of working from me, but more by accident.


texts:
In Craft CMS 2, I've created a task for updating Craft Commerce products from an Excel file. Everything's working correctly except the UI progression bar. The progression bar in control panel stays at 0 %, even if in database, I see steps increasing. Then when task is finished, it goes directly to the end (100 %) and disappear. I noticed that it will happen if I call for

craft()->commerce_products->saveProduct($product);

If I comment this line, progression works correctly. Any idea on what's going wrong?


texts: Sorting entries A-Z, ignoring 'The' and grouping by first letter

texts:
Probably going to be an easy win for someone here, but being able to do this is currently eluding me. So:

I'm trying to output a list of Artist names grouped by first letter but need to ignore 'The ' when it appears at the start of an Artist name.

To do this, I've added a 'Sort Title' field to the Artist entry (as I figured there might be other occasions where this could be useful) - and using Brad's answer here this works fine when outputting a standard alphabetical list.

However, there's also a page that needs to display the Artists grouped by first letter. Code for that currently is:

{% for letter, artists in craft.entries.section('lineup').order('title') | group('title|upper|slice(0, 1)') %}

How best could I adapt that to use my sortTitle field (when it isn't empty) to group the Artist entries? I get 'Expected name or number' if I try to use Brad's code in place of 'title'.


texts: Add custom attribute to standard element from plugin

texts:
Developing plugin for Craft 3, I want to add extra property to Assets (data being pulled from other table)

I am able to pull in the data by extending element query:

Event::on(
            ElementQuery::class,
            ElementQuery::EVENT_AFTER_PREPARE,
            function(CancelableEvent $e) {
                if ($e->sender->elementType == 'craft\\elements\\Asset')
                {
                    $e->sender->query->addSelect('linkstats.downloads');

                    $subQuery = (new Query())
                        ->select('assetId, SUM(downloads) AS downloads')
                        ->from('{{%my_plugin_table}}')
                        ->groupBy('assetId');

                    $e->sender->query->leftJoin(
                        ['linkstats' => $subQuery], 'assets.id = linkstats.assetId'
                    );
                }
            }
        );

However when trying to display the asset I get error:

  Setting unknown property: craft\elements\Asset::downloads

Question, how do I register this new property/attribute for Assets? I cannot find any event to do that, is it possible at all?


texts: Redactor 2 - Can a text alignment button be added?

texts: Left, Center, Right -- Can the text alignment button be added to Redactor 2, and if so, how?


texts: renderTemplate() renders the twig file without any CSS

texts:
I've set up the routing for a specific URL in my plugin to trigger the actionIndex controller method. I after logging a message to the Craft logs, I want to return the rendered twig file as the view, which is supposed to look just like an empty Control Panel page. Pretty simple in theory.

Everything in the twig file seems to render just fine (text & images) except for the CSS.

Controller: Controller.php

class Controller extends \craft\web\Controller
{
    public function actionIndex(){

        Craft::info("hello!", __METHOD__);

        return Craft::$app->getView()->renderTemplate('plugin/done');
    }
}

Template: done.twig

{% extends "_layouts/cp" %}
{% set title = "Manual Sync"|t('plugin') %}

{% block content %}

Manual Sync Done.

{% endblock %}

I've attached a screenshot of the elements that are rendered on the page.

Hopefully that is enough for someone to help bounce some ideas around with me. Any advice and suggestions would be greatly appreciated!


texts: Webhook plugin & hooking into Contact Form

texts:
As my first delve into webhooks I've just installed the Pixel&Tonic Webhooks plugin. I'm trying to send data from a front end contact form to Zapier. The front end form uses the Pixel&Tonic Contact Form plugin and the webhook setting is set to the beforeSend event.

I've got the connections working although the webhook doesn't seem to fire automatically. It only sends data to Zapier when I refresh the admin control panel (a 'Sending webhook ...' task displays briefly at the bottom of the control panel's left sidebar).

The email is sending just fine and is immediately received, it's just the webhook that seems to be getting 'stuck'. Is there anything I'm doing wrong?


texts:
I am getting the following error when trying to update Craft from 3.3.18.4 to 3.3.19 and any version after. It seems like Homestead or Vagrant is having some sort of issue with IpValidator or the Class 'Yii'. Anyone else seen this issue before?

Fatal error: Uncaught Error: Class 'Yii' not found in /home/vagrant/****/****/vendor/yiisoft/yii2/validators/IpValidator.php on line 218

Error: Class 'Yii' not found in /home/vagrant/****/****/vendor/yiisoft/yii2/validators/IpValidator.php on line 218


texts: How do I italicize words in an entry title?

texts:
I'm working on a site with a "Research" channel that is going to have scientific names in the titles of the entries.

What's the best way to allow these names to be marked up with <em> tags so I can display them in italics?

Right now I'm using the default "Title" field Craft supplies when you set up a section, but I haven't needed to insert formatting here before.


texts: How to get related entries from a Matrix block itself related to another section

texts:
3 sections:

Works
Discography
Interpretes

In "Discography"

Matrix block calling entries from "Interpretes"

In "Works"

Relational field pulling entries from "Discography"

In that Work template I need to display the related entry title from Discography (first part of the code below: working) and the related Interpretes selected in Discography (second part of the code: not working)

Is that possible?

{# This first part displays correctly: #}

{% set relatedRecords = craft.entries.section('contenuDiscographie').relatedTo(entry) %}
{% for record in relatedRecords %}

{{ record.title }}

{# And trying to display the related entries from "Interpretes". That's where I'm stuck: #}

    {% for block in entry.compDiscographie %}

        {% set relatedPerformers = craft.entries.section('interpretes').relatedTo(block) %}
        {% for performer in relatedPerformers %}
            {{ performer.title }}
        {% endfor %}

    {% endfor %}

{% endfor %}

Tried to be as clear as possible...
Thanks


texts: var_export does not handle circular references” when devMode = true and logDumpMethod = print_r

texts:
Here is a similar question that was asked but doesn't resolve my issue

Question has changed, see UPDATE below

I'm new here so I couldn't just tag a comment onto this post asking this question:

I ran into a similar issue, the suggested fix does not work even with the config setting 'logDumpMethod' => 'print_r', as well as directly editing the CLogFilter.php file

I'm relatively knew to PHP, general web design, or any sort of CMS, and Have only been using Craft for about a month now so bare with me.

The last change I was completing was editing the guestEntries plugin to store session data using craft()->httpSession->add($key, $value) in the guestEntries plugin's controller. The problem persists with or without this addition. Granted that addition is probably not something I needed to try, however now I'm locked out of devmode because I get the same error as mentioned in the title.

Hopefully it's not something painfully obvious that I'm missing here.

Again, question is related to the error I receive as mentioned in the title and NOT how I should store session data or best practices (I will learn that in due time elsewhere.)

The controller along with the single line of editing I made:

private function _returnSuccess($entry, $faked = false)
{
    $successEvent = new GuestEntriesEvent($this, array('entry' => $entry, 'faked' => $faked));
    craft()->guestEntries->onSuccess($successEvent);

    if (craft()->request->isAjaxRequest())
    {
        $return['success']   = true;
        $return['title']     = $entry->title;
        $return['cpEditUrl'] = $entry->getCpEditUrl();
        $return['author']    = $entry->getAuthor()->getAttributes();
        $return['postDate']  = ($entry->postDate ? $entry->postDate->localeDate() : null);

        $this->returnJson($return);
    }
    else
    {
        craft()->userSession->setNotice(Craft::t('Entry saved.'));

        // TODO: Remove for 2.0
        if (isset($_POST['redirect']) && mb_strpos($_POST['redirect'], '{entryId}') !== false)
        {
            Craft::log('The {entryId} token within the ‘redirect’ param on entries/saveEntry requests has been deprecated. Use {id} instead.', LogLevel::Warning);
            $_POST['redirect'] = str_replace('{entryId}', '{id}', $_POST['redirect']);
        }
        craft()->httpSession->add('entry', $entry)//<--the only line I added
        $this->redirectToPostedUrl($entry);
    }
}

UPDATE: Gave it another go of directly editing the CLogFilter.php by replacing public $dumper='print_r'; AND changed the config file 'logDumpMethod' => 'print_r' and that worked... Why? Should I not be able to just change it in the config file?


texts:
I'm trying to manually install a plugin Pic Puller for Craft 3 Beta.

My shared hosting won't allow enabling of allow_url_fopen so it can't be done via the plugin store within the dashboard.

Any docs I checked are telling me to add the plugin files to /craft/plugins/ but I'm not seeing this directory in Craft 3.

I tried adding it to the /modules/ directory but this didn't work for me.

Thanks!


texts: Multi-environment configs and running sites on different ports

texts:
In my studio, we have successfully used multi-environment config files to allow several machines on our local network to use local MAMP installs as well as designate dev and production environments at our web host.

Locally we run sites on separate ports, so for instance to look at my site I point my browser to http://10.0.1.2:8081/. To look at what’s going on on each other’s machines in the studio, we just change the ip address.

But now we are looking to run both a stable “trunk” version and a “branch” version for developing new features of our site on each local machine. And I can’t see how to make that work in the general.php and db.php files.

The following is what I’ve had in general.php for running a single instance of the site on my server:

'10.0.1.2' => array(
    'userSessionDuration' => false,

    'environmentVariables' => array(
        'siteUrl'        => 'http://10.0.1.2:8081/',
        'fileSystemPath' => ‘/path/to/trunk/files/‘,
    ),
),

I feel that what I’d like to do is something like the following to differentiate between the two sites running on 10.0.1.2:

'10.0.1.2:8081’ => array(
    'userSessionDuration' => false,

    'environmentVariables' => array(
        'siteUrl'        => 'http://10.0.1.2:8081/',
        'fileSystemPath' => ‘/path/to/trunk/files/‘,
    ),
),

'10.0.1.2:8082’ => array(
    'userSessionDuration' => false,

    'environmentVariables' => array(
        'siteUrl'        => 'http://10.0.1.2:8082/',
        'fileSystemPath' => ‘/path/to/branch/files/‘,
    ),
),

Similarly, in the db.php file, currently I’ve got:

'10.0.1.2' => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => 'root',
    'database' => 'trunk.database’
),

Which I thought I’d change to:

'10.0.1.2:8081’ => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => 'root',
    'database' => 'trunk.database’
),

'10.0.1.2:8082’ => array(
    'server' => 'localhost',
    'user' => 'root',
    'password' => 'root',
    'database' => ‘branch.database’
),

But alas these kick off this error:

An exception has been thrown during the rendering of a template ("Craft canâ€™t connect to the database with the credentials in craft/config/db.php.") in "_layout" at line 15.

Am I trying to do something impossible, or can anyone point me in the right direction?

Thank you much,
Willhaus


texts: Is it possible to add a category to an object through twig?

texts:
I'm currently working on a registration page for users on a site.

There are two attributes that users may have on sign up that I need to reflect in the sign up process. (I will probably use checkboxes to indicate whether the user will have the categories assigned to them)

Currently, my idea to solve this is to have categories for users.

So, I have to ask first, is it even possible to set a category from a template? If so, how?


texts: Changing Content-Type on Sprout Forms custom endpoint

texts:
I'm using Sprout Forms 3.3.7 and have created a custom endpoint integration to post the form data to Pardot. The integration fires successfully, but Pardot was rejecting the request.

I used Guzzle Middleware to inspect the request (right around here https://github.com/barrelstrength/craft-sprout-forms/blob/v3/src/integrationtypes/CustomEndpoint.php#L83) and it tells me that the Content-Type is application/json but Pardot only accepts application/x-www-form-urlencoded.

Is it possible to change the Content-Type when using a custom integration? Either in the CP or in the form.twig code?


texts:
I'm working on a plugin to calculate price based on width and height but struggling to get the product type of each product into the 'onPopulateLineItem' event.

So far, I've looked into the purchasables and lineItems arrays to get the information, and although I can see the typeId under the $event array, I just can't get this value.

Can anyone point me in the right direction for this please?

** UPDATE **

I've managed to get something with the below, but this feels really hacky. Is there a better way I should be doing this?

$lineItem = $event->params['lineItem'];
echo $lineItem['snapshot']['product']['typeId'];


texts: Search going to /index.php?q= instead of results

texts:
I've pushed my site to Digital Ocean from Localhost, the site is all up and running - URL's are all working. But when I try and search the site it seems to be heading to

  http://123.456.789/index.php?q=test

Instead of

  http://123.456.789/search/results?q=ariz

I have manually entered the second page in and I get to the search results page, so it does exist but Craft's routes seem to be breaking? Any help would be brilliant!

        <form action="{{ url('search/results') }}">
          <input class="text-field w-input" type="search" name="q" placeholder="Search for any University...">
          <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1" />
        </form>


texts: Localhost can't connect to plugin store or updates (WAMP Server)

texts:
I've now tried installing Craft on multiple PCs to run a local dev environment, but keep getting the same problem. It installs fine, the System Report shows all green,  but when I first load the Dashboard I get the message "An unknown error has occurred" and it fails to fetch Craft News items or updates, and then on the Plugin Store it states "The Plugin Store is not available, please try again later."

I've tried playing around with my Apache setup, but honestly I'm not particularly knowledgeable in that area.

All PCs have been running Windows 10, the latest version of WAMP server, PHP 7.2, and "latest" version of Craft (though it's now two installs behind, which is why I know the updates aren't working despite stating that I'm "up to date").

Live version of the site is working perfectly after upload via FTP, and I've tried reinstalling several times.


texts:
Have a site registering users.
The user record in the CP says they registered at 11:39 June 12.

The database 'dateCreated' says 10:39.

The site settings timezone are UTC+1 BST.

PHP config date.timezone is Europe/London (actual location)
and Default timezone is UTC.

If I turn off UTC +1 in Craft timezone settings to UTC then front end user record matches database.

What I can't figure out for sure is what time did they really register? :)


texts: Craft 3: Recognize cookies created in Craft 2

texts:
In Craft 2, we could set a cookie like this...

craft()->userSession->saveCookie()

... and that would make it a state cookie. This thread describes it pretty well. Essentially, you would end up with a cookie whose name began with a hashed string.

  b72b7553c36d6600e9aeb6c40513deb8MyCookie

However, it seems like that behavior has been largely removed in Craft 3. When I try to save a cookie now, I do it more like this...

$cookie = new Cookie();
$cookie->name = $cookieName;
$cookie->value = $cookieValue;
$cookie->expire = time() + $lifespan;
Craft::$app->getResponse()->getCookies()->add($cookie);

... which doesn't create a state cookie. The cookie name is very simple.

  MyCookie

Generally speaking, that doesn't bother me. But I worry about compatibility issues with the Craft 2 version of my plugin. It's somewhat important that cookies from the old system are recognized when Craft is upgraded.

What is the solution for this? How do I ensure that my old cookies are recognized properly, and/or continue saving this data using the original hashed format?


texts: Want to add a custom field in craft commerce plugin

texts: Is it possible to add a custom field in craft commerce plugin and is it a good idea to add it?


texts:
As there is no native config to control the naming of assets I am trying to write a small plugin to do this.
Here is what I have;

    craft()->on('assets.saveAsset', function (Event $event) {
        if ($event->params['isNewAsset']) {

            $asset = $event->params['asset'];

            // Set the filename to a variable, appending the file extension
            // $extension = $asset->getExtension();
            // $filename = strtolower($asset->filename.md5(time()).'.'.$asset->getExtension());
            $filename = strtolower($asset->filename.'.'.$asset->getExtension());

            // Rename the file on the server
            craft()->assets->renameFile($asset, $filename);

            // Set filename attribute and re-save asset
            $asset->setAttribute('filename', $filename);
            craft()->assets->storeFile($asset);
        }
    });

However, this currently results in a duplication of the extension like so;
model-rendering-image.jpg.jpg
special-services.jpg.jpg

If I remove this part of the code
'.'.$asset->getExtension()) then the asset isn't renamed at all.

Can't seem to get past this hurdle.

Anyone able to shed some light?

Also is there a reason that assets are not renamed to lowercase by default or why this isn't rolled in as a config option?


texts: How do I create an advanced route with an ID that hits a controller method

texts:
I am trying to create a page I can hit to update a record in the db, something I am used to doing in Laravel, but now have to do in Craft.

The controller method would look something like this:

public function updateUserRecordsTest($userId) {

    $user = craft()->users->getUserById($userId);
    // $data['status'] = 'asleep';
    // $user->update($data);

}

So I am trying to make a route in craft/config/routes.php like this

 route => user/update/{id} , controller => UsersController@updateUserRecordsTest;

Any suggestions on how to set this route up in Craft would be greatly appreciated.

*Update

So I will try to clear up what I am trying to do.

I need to update the users db when they pass classes.  This will most likely be a boolean, but may end up being an enum.  So what I would usually set up is a page with a controller method like below

 // sudo code

 public function passedThisClass($id) {
    $user = User::find($id);
    $data['passed'] = 1
    User::update($data);
 });

the route would look like

 // sudo code
 route::get('updatethisclass/{id} => UsersController@updateThisClass);

When I hit that page it updates the value from 0 to 1 flagging that they passed the class.


texts:
Can I manually set a user's password?

I know I can change it but it is asking for the current password which is null at the moment.


texts: Is there any way which does not remove Specific Html tags from the redactor editor using striptags only?

texts: Is there any way to do it with striptags only or we have to use another filter?


texts:
I'm currently working on a multi-market Craft3 project with Commerce2. Each product can and will have a different fixed price on each page.

Product A
project.tld/de-de - € 120
project.tld/en-gb - £ 100

I am aware that Commerce2 has no multi-site support, but I still need a solution for my problem. I tried to modify the LineItem at the event Order :: EVENT_AFTER_ADD_LINE_ITEM. But I failed miserably.

Is there perhaps a workaround that could solve the problem?

Event::on(Order::class, Order::EVENT_AFTER_ADD_LINE_ITEM, function (Event $e) {
    /** @var Order $order */
    $order = $e->sender;

    foreach ($order->lineItems as $lineItem) {
        $price = '234.0000';
        $lineItem->price = $price;
        $lineItem->salePrice = $price;
        if (is_array($lineItem->snapshot)) {
            $snapshot = $lineItem->snapshot;
        } else {
            $snapshot = json_decode($lineItem->snapshot, true);
        }
        $snapshot['price'] = $price;
        $snapshot['product']['defaultPrice'] = $price;
        $lineItem->snapshot = json_encode($snapshot);
    }
    $order->setLineItems($resultLineItems);
    Craft::$app->elements->saveElement($order);
});


texts: Form Builder plugin returns 'undefined' when I submit

texts:
Today I wanted to add a contact form to my webpage, and I chose the Form Builder plugin for its ease of use. So far all went well, and I managed to display the form in the page (not that difficult), but when testing the form I got an undefined error.

As of now I have no idea what is undefined. I checked the code, the fields I use (they are all Form Builder fields, the email and the plain text), and I checked the settings of Form Builder.

Can you guys help me out?

The link to my website: www.evinwijninga.com

The code in the template

{% set form = craft.formBuilder.getFormByHandle('contactForm') %}
{% set tabs = form.fieldLayout.getFieldLayout().getTabs() %}
{% set pluginScripts = craft.formBuilder.pluginScripts(form) %}

How to contact me

    <form method="post" accept-charset="utf-8" name="{{ form.handle }}" class="formbuilder-form grid-60 prefix-20 suffix-20 {{ form.handle }}" id="{{ form.handle }}" data-parsley-errors-container=".formbuilder-notification"{% if form.hasFileUploads %} enctype="multipart/form-data" {% endif %}>
        <input type="hidden" name="action" value="formBuilder/entries/saveFormEntry">
        <input type="hidden" name="formredirect" data-redirect="{{form.successPageRedirect}}" value="{{form.redirectUrl}}">
        <input type="hidden" name="formHandle" value="{{form.handle}}">

        {% for tab in tabs %}
        {% set fields = tab.getFields() %}

        <fieldset class="{{loop.index}}">
            <legend>{{ tab.name }}</legend>
            {% for field in fields %}
            {% set input = craft.formBuilder.getInputHtml(field) %}

{{ input | raw }}

            {% endfor %}
        </fieldset>
        {% endfor %}

        {# Error/Success Messages #}
        {% if craft.session.hasFlash('error') or craft.session.hasFlash('success') %}
        {% if craft.session.hasFlash('error') %}

{{ craft.session.getFlash('error') | raw }}

{% endif %}
        {% if craft.session.hasFlash('success') %}

{{ craft.session.getFlash('success') | raw }}

{% endif %}
        {% else %}

        {% endif %}

        <button type="submit" class="grid-100">Submit Message</button>

    </form>

The fields:

and the settings in Form Builder

This is the latest error entry. The timestamp however is different than the time when I tested the form (which was later):


texts: How do I delete an asset with module or plugin

texts:
I'm trying to clean-up the assets in a specific folder that aren't being used at all, i.e. aren't related to anything.

I got the list O.K. just using this

$assets = Asset::find()->volume('artists')->kind('image')->limit(50000)->ids();

$assetsToDelete = [];

foreach($assets as $asset) {
    $results = (new Query())
        ->select(['id'])
        ->from(['{{%relations}}'])
        ->where(['targetId' => $asset])
        ->orWhere(['sourceId' => $asset])
        ->all();

    if (!count($results)) {
        $assetsToDelete[]  = $asset;
    }
}

return  $this->asJson($assetsToDelete);

Right now I'm just returning all the ids in an array but I'm hoping to find a command to delete the element AND delete the stored asset on the server

Any ideas?


texts:
this is my first question on StackExchange regarding CraftCMS.

Currently im working on a plugin that should insert a relation row (in db) regarding an entry and asset (image).

Is there a simple and easy way to insert a row in the DB with asset id, source id and field id?

Thanks in advance


texts: The Variable {{ siteUrl }} Produces Two /es/es/ On Multisite

texts:
I'm getting example.com/es/es for my Spanish site instead of the expected example.com/es when using the {{ siteUrl }} variable.

The primary site is producing the expected example.com/

Any idea of how I did that incorrectly?


texts: CP entries structure tree view folded (not expanded) by default?

texts:
Is there a simple way to display the CP entries structure tree folded (not expanded) by default ?
Because we have a very complex entries tree whith lots of entries and levels and my users needs to fold everything each time they access it.


texts: Exclude "featured" entries from a "recent" entries {% for %} loop

texts:
Here's my current setup:

Blog (Channel) - All of my blog posts will go here

Blog Landing (Single) - This section only has one field - a Featured Articles Entries field that lets me select 3 entries from the "Blog" channel.

Basically what I want to do on the Blog Landing section is have a dedicated area for the 3 Featured articles (ones that I will choose from that Featured Articles entries field), but then display the next 5 most recent articles that have not been selected as a Featured article in a different area.

I've successfully outputted my Featured Articles with this code:

{% set featured = entry.featuredArticles %}
  {% for entry in featured %}
    {{ entry.title }}
  {% endfor %}

And I can get my 5 most recent with this code:

{% set allEntries = craft.entries.section('blog') %}
  {% for entry in allEntries.limit(5) %}
   {{ entry.title }}
  {% endfor %}

I can't figure out how to exclude the entries from the Featured Articles area from the output of the Recent Articles area.

So say I have 10 entries in my Blog channel, (Post 1 is most recent, Post 2 is second most recent, and so on), and I've selected Posts 2, 4, and 5 as my "Featured" articles, how do I get it so that the 5 "Recent" articles display Posts 1, 3, 6, 7, and 8 instead of Posts 1, 2, 3, 4, and 5?


texts:
I have something I can not get my head around.

This works as expected:

.relatedTo(['and',{targetElement:22},{targetElement:33}])

But when I am building an array to use as relation criteria like so:

{% set related = [{targetElement:22},{targetElement:33}] %}

.relatedTo(['and',related])

Nothing returns.

It’s pretty late here in Berlin and I might be missing something simple but can not see what exactly. Anyone?


texts: Adding entry type using setContentFromPost

texts:
I'm creating a new user using $user->setContentFromPost(). It all works fine except I can't attach an entry to an Entries field.

$user = new UserModel();
$user->username         = $email;
$user->email            = $email;
$user->unverifiedEmail  = $email;

$user->setContentFromPost(array(
  'companyName' => $admin->companyName,
  'companyId' => $admin->companyId,
  'partnerManager[]' => $admin->partnerManager[0]->id
));

This will create user but the partnerManager Entries field will be empty. I've tried a few different syntax variations, but none of them seem to work:

'fields[partnerManager][]' => $admin->partnerManager[0]->id
'partnerManager' => $admin->partnerManager[0]->id
'partnerManager[0]' => $admin->partnerManager[0]->id

How to fill this field?


texts: Changing URL format in craft commerce products error 502

texts:
I have more than 150k products on craft commerce, and i need to do some changes in the URL format, but when i click save, the server returns a 502 error.
I think that is because craft is trying yo re-generate every url in the 150k products.  do you have any idea  how to resolve this issue?


texts:
I have a macro for form fields, including select:
{% macro select(name, options) %}
  <select name="{{ name }}">
    {% for key, value in options %}
      <option value="{{ key }}">{{ value }}</option>
    {% endfor %}
  </select>
{% endmacro %}

Which I call with:
{{ macro.select('name', {'key': 'value'}) }}
This works well when I define the key and value, however, I want to populate it from my categories.
{% set categoriesQuery = craft.categories().group('categories').all() %}
How can I make {'key': 'value'} loop over results from categoriesQuery? Hope that makes sense!


texts: Does deleting an original asset but keeping the transform folder asset make Craft replace the original file with the biggest transform?

texts: I have a client who has uploaded many giant images to the CMS (8mb+). I'd like to free up that space now that those image have been transformed to more web-friendly sizes. Is it safe for me to delete the original files stored on the server or does Craft require those to create new transforms?


texts:
Suppose I have a section for Products, that uses the template at products/_entry and is set up to have the URL format of 'products/{slug}'.

Our existing page structure shows a Product page when you go to the URL (such as example.com/products/cool_product, but we also have a sub-page for "Product Details" which we would get to (using the previous example) by going to example.com/products/cool_product/details.

Is something like this possible with Craft routes? I've tried adding a route in craft/config/routes.php that looks like:

return array(
    'products/<slug>/details' => 'products/_details'
);

however that doesn't do what I'd expect, which is load the product entry using that slug and display the template (which would in turn display the relevant data from that product entry)

Do I need to have something in my _layout.html that catches such a request somehow? I'm a bit confused I guess. I suppose I can handle the request a bit more manually in the template by parsing the request and loading the product that way. I guess I'm hoping there is something a little more elegant (read: I'm lazy )


texts: DevMode not showing detailed Internal 500 Errors

texts:
I've noticed lately, maybe after the last Craft update or two, that internal 500 errors no longer show information or error traces. I simply get a message like:

Internal Server Error
Undefined offset: 0

And that's all it will show. I've checked that devmode is set to true, and in dashboard it shows that devmode is on. Is there a particular reason this would be happening? Maybe because the error is coming from a plugin and not twig? Or a general setting I'm not aware of for more detailed errors? It used to show all the information I needed.


texts: How to import existing users into database

texts:
Ok this is now a general question as I managed to import the user table to the database.

Unfortunately it appears that whilst the users all show in the database they do not show in the CMS. Digging a bit deeper it seems they are related to the elements table as each appear to have an entry with a type User.

So my question now is how can you import your existing user list into a new craft set up without breaking it or anything else. With over 10000 users this is not one to be done manually.

Any help appreciated.


texts: Custom translation file (Not using Locales/Multisite)

texts:
Is it possible to make Craft 3 load a custom translation/language file? Even if not using multisite or locales?

My use case for this is just to change the way certain things are said. E.g. 'Invalid username or password.' => 'Invalid username or password.', when a user logs in. I wanted to be a bit more descriptive on this.

I can see the translation files in vendor/craftcms/cms/src/translations/[language code here] so I assume theres a way of adding bespoke ones to this, but outside of the vendor folder.

I just can't find it in the docs.


texts:
Database Exception: SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'n2-cr_matrixcontent_column1_locale_fk'; check that column/key exists

This is the error I am receiving when attempting to update the database for the new version of craft. I've checked for that specific table and confirmed that it doesn't exist. How do I prevent it from trying to drop it or otherwise fix this problem?


texts:
Just wondering: Is there a equivalent for this piece of code written in EE:

{if logged_in}
    <div id=“admin”>
        Page render time: {elapsed_time} sec |
        Queries: {total_queries} |
        Gzip: {gzip_mode}  |
        EE version: {app_version} build {app_build}
    </div>
{/if}

Source: http://www.blue-dreamer.co.uk/blog/entry/expressionengine-measuring-performance-during-development


texts: Where and how should you listen for entry delete in plugin?

texts: When an entry is created with my plugin's field type, data is saved to a separate table with entries id for reference. I need to delete that data if the entry that is associated with the data is deleted.  How and where should I listen for entry delete event to execute a method to delete this separate data?


texts: how to create Super Table field programmatically

texts:
i am trying to create a super table field programmatically.
this is the code i tried.

i see super table field in field list but i can see fields inside of super table.

how can i do this?

    //create super table field itself
    $superTable = new SuperTableField([
        'name' => 'supertablefield',
        'handle' => 'supertablefield',
        'groupId' => 1
    ]);
    Craft::$app->getFields()->saveField($superTable);
    //field inside super table
    $field = new \craft\fields\PlainText([
        "name" => 'textfield',
        "handle" => 'textfield',
        "translationMethod" => "site",
        "multiline" => 0,
    ]);
   //create and set block type
    $blockModel = new SuperTableBlockTypeModel();
    $blockModel->fieldId = $superTable->id;
    $blockModel->uid = StringHelper::UUID();
    $blockModel->setFields([$field]);

    $superTable->setBlockTypes([$blockModel]);
    SuperTable::$plugin->service->saveBlockType($blockModel);


texts: Want to add page number to title and meta description because I have a lot of duplicates. Could you tell me how I can do it?


texts: How to handle payments on a multicurrency website using Mollie gateway?

texts:
We built a multicurrency website on Craft Commerce that uses both Euros and Dollars. The base currency is EUR. We use Mollie as payment gateway. However, Mollie only supports Euros on their platform and does not convert other currencies to euros. The conversion has to take place on the website before the user arrives on their platform.

The problem is: when a user checks out on our website with dollars, say 100USD, the amount will show up on Mollie as 100EUR. Obviously this is a big issue as the amounts will be off by several percents.

How do we properly fix this?


texts:
I'm getting this error on the back-end and have no idea how to solve it. I re-uploaded the APP directory already once to no avail. Any input on how to resolve this would be greatly appreciated.

[error] [exception.Craft\HttpException.400] exception 'Craft\HttpException' with message 'POST param “code” doesn’t exist.' in /path to craft/craft/app/services/HttpRequestService.php:509
Stack trace:
/path to craft/craft/app/controllers/UsersController.php(333): Craft\HttpRequestService->getRequiredPost('code')
/path to craft/craft/app/framework/web/actions/CInlineAction.php(49): Craft\UsersController->actionSetPassword()


texts: Add an add entry button to my Plugin in Craft CP

texts:
Hey I'm writing my first Craft plugin and would like to add a button to have a dialog box in . I want to create a link to a page entry with this and save it to the database.

This is the code I want to extend in my template:

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

    <div class="" style="width: 50%">
        <form method="post" action="" accept-charset="UTF-8">
            <input type="hidden" name="action" value="glossary/entry/saveEntry">
            <input type="hidden" name="redirect" value="glossary">
            {{ forms.textField({
               label: 'Glossary Entry'|t,
               instructions: 'Enter a new Word'|t,
               id: 'entry',
               name: 'entry',
               value: ''}) }}
            <input class="btn submit" type="submit" value="{{ 'Submit'|t }}">
        </form>
    </div>


texts: Creating a Custom Field Type with nested Fields

texts:
I'm just wondering is it possible to have nested Fields inside of a Custom Field type.

So if I create a custom Field type. I wish for it to contain all of the following. So it will contain multiple fields inside of it.

Asset
Matrix
Entry

Is this something that can be achieved.

Appreciate any pointers.


texts: Check number against 2 seperate fields and return the entry that matches

texts:
I have imported entries, each with 2 fields that comprise a range of numbers... numberStart and numberEnd. e.g. 3000 - 3006, in some instances both are the same number e.g. 8001 - 8001 The user will be inputting a single number and I need to return the single entry where the inputted number lands between (or is equal to) the start and (or) end number.

This is what I have so far...

{% set userInputtedNumber = 3000 %}

{% set entries = craft.entries({
    section: 'section',
    numberStart: '>=' ~ userInputtedNumber,
    numberEnd: '<=' ~ userInputtedNumber,
}) %}

This just returns nothing as the operators clash.

Any ideas will be welcomed!


texts:
I'm using Weighted Search on a site and want to prevent the results from listing entries from certain sections.

Looking at the README.md suggests that this functionality has not been built into the plugin. However, does anyone have any experience of getting the plugin to only search in certain sections? Either through the {% set results %} OR tweaking the plugin?

I've tried added .section('mysection') to the {% set results %} but this seems to break the search.

// Working

{% set query = craft.request.getParam('q') %}
{% set results = craft.weightedSearch.substringSearch(query) %}

// Not working

{% set query = craft.request.getParam('q') %}
{% set results = craft.weightedSearch.substringSearch(query).section('mysection') %}

Hoping someone else has managed this and I don't have to go back to the standard Craft search.

Thanks


texts:
I’m trying to set data within a global set. I’ve tried the following without success:

$globalSetHandle = 'settings';
$globalSet = craft()->globals->getSetByHandle($globalSetHandle);

$globalSet->fieldHandle = 'value';

craft()->globals->saveContent(GlobalSetModel $globalSet);


texts: Sprout Email trigger when entry goes live

texts:
In Sprout Email is it possible to set a notification trigger to be when an entry goes live?

I'd like to create entries ahead of time and post date them so that they go live on the specified date.  I'd like the Sprout Email notification to get triggered when the entry is live (rather than when it is saved).


texts: Create new entry from related Entry field

texts:
It would be really nice to create a new entry in a section (say "Dates"-channel) direct from a related entries field in another section (say "Events"-channel). Is this possible already, or are there any plugins for this?

I have asked this before on Google+, but not sure if it's been answered.


texts: Asset Volume using Environment Variable on File System Path as literal string on upload

texts:
I have a volume called "Website" with a File System Path that uses an environment variable, $ASSET_ADHOC_PATH. The variable has been setup in my .env file as follows:

ASSET_ADHOC_PATH="/home/theadhoc/craftcms/web/assets/theadhocracy"

The Volume has the following in the File System Path input:

$ASSET_ADHOC_PATH/website

That should resolve to my actual folder location, but when I upload a file it just creates a folder at:

/home/theadhoc/craftcms/web/$ASSET_ADHOC_PATH/website

If I get rid of the environment variable and use the literal value then it works fine (which is what I'm doing for now) but I'd like to get to the bottom of why this isn't working as I would expect.

EDIT: Just in case this helps, I've discovered I have the same issue when using (different) environment variables in the Base URL field too. Am I missing a step in setting up env vars? Do I need to add them to general.php or something as well? They seem to resolve without issue in the dropdown list, which accurately displays the variable contents.


texts: My website isn't working: "Craft does not support backtracking to this version. Please upload Craft 2750 or later."

texts: I have been unable to access both my website and my login page. What's going on?


texts:
I cant update my sprout plugins due to a dependency / version issue with sprout base. Ive tried updating via composer - but I think I need to edit my composer file to work around the sprout base dependency issue - not certain of what that edit should be - any help appreciated.

Your requirements could not be resolved to an installable set of packages.

Problem 1
- barrelstrength/sprout-email 4.0.0-beta.15 requires barrelstrength/sprout-base ^4.0.8 -> satisfiable by barrelstrength/sprout-base[4.0.8].
- barrelstrength/sprout-email 4.0.0-beta.15 requires barrelstrength/sprout-base ^4.0.8 -> satisfiable by barrelstrength/sprout-base[4.0.8].
- barrelstrength/sprout-email 4.0.0-beta.15 requires barrelstrength/sprout-base ^4.0.8 -> satisfiable by barrelstrength/sprout-base[4.0.8].
- Can only install one of: barrelstrength/sprout-base[5.0.0, 4.0.8].
- Can only install one of: barrelstrength/sprout-base[4.0.8, 5.0.0].
- Can only install one of: barrelstrength/sprout-base[5.0.0, 4.0.8].
- barrelstrength/sprout-forms 3.0.0-beta.57 requires barrelstrength/sprout-base ^5.0.0 -> satisfiable by barrelstrength/sprout-base[5.0.0].
- Installation request for barrelstrength/sprout-forms 3.0.0-beta.57 -> satisfiable by barrelstrength/sprout-forms[3.0.0-beta.57].
- Installation request for barrelstrength/sprout-email 4.0.0-beta.15 -> satisfiable by barrelstrength/sprout-email[4.0.0-beta.15].


texts: Product category not being added to the order model. Craft Commerce

texts:
I've created a form in which to specify a category for a product on the product entry page. I can't seem to add the category that the customer selects to the order model. I've checked the orders in the control panel and they do not seem to be storing the category. Does anybody know how to add a selected category to the order model?

<form id="values" method="POST">
     <input type="hidden" name="action" value="commerce/cart/updateCart">
     <input type="hidden" name="redirect" value="cart">
     ...
     <select id="chocOptions" name="chocolateOptions" class="options">
          <option title="selectOption">Select Option</option>
          {% for category in craft.categories.group('chocolate') %}
               <option value="{{ category.title }}">{{ category.title }}</option>
          {% endfor %}
     </select>
     ...
</form>


texts:
Can anyone shed any light on this duplicated db query issue?
I've noticed when going through my site with the debug toolbar on, sometimes when I click a page or entry there is often double the amount of DB queries being run than normal? And when I look at the details it's often just every query duplicated?
If I refresh the page the proper amount of queries are run and TTFB is exactly half. It's worth noting regardless of whether 'disable cache' is set in Chrome Dev tools this happens. If I navigate to another area of the site and come back, it's hit and miss whether the duplicated queries are run. On manually refreshing the same page the correct number of queries always run...
What do you think would be causing this? I've eager loaded everything thing that I can on each template and performance is generally very good but random duplicate query issue is baffling me.
Edit: Seems to be only happening on my main entry template.
I've removed all the code from this template to only leave in basic scripts and it still spits out 100 db queries and says 50% of them are duplicate. But in the template there are no queries to even be made??


texts: Using the CP login session expiration for the frontend

texts:
I love the session handling on the backend CP. The prompts that come up on session expiration after setting 'userSessionDuration' => 'PT5M', in config/general.php are exactly what I want to use on the frontend website, (shown below).

I would like to use this logic on the frontend to force session-ends after x minutes. Doing some digging I can see the logic lies in UserController under actionGetAuthTimeout(), and this is polled while I'm on the CP every minute.
My question is whether I would have to manually run the controller constantly in the background and make the modal pop up? is there a more elegant method I've missed?

Thanks!


texts: Only fetch structure entries that are first level or sub level that don't have a parent

texts:
I have a Structure with my entries in. How can I hide the parent entries that contain children? I still want to show the parents children.

For example I want all the below entries bar "About" and "Services"

- Home
- About
    - Sub
    - Sub
    - Sub
- Stuff
- Services
    - Sub
    - Sub
    - Sub
- Things

So, this is my code right now

{# Set parameters for prev/next elements list #}
{% set params = craft.entries.section('pages') %}

{# Get the prev/next elements #}
{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

Do I need to modify the params to remove the entries that are parents?


texts: Flush Compiled Templates Migration File breaks Craft Migration Setup from 3.0 to 3.3

texts:
I was attempting to upgrade my Craft CMS from 3.0 to 3.3.19 on my production site. I had tested this out on several dev environments and worked with no issue. However, when doing it live I ran into a yii/exception

  Exception: rmdir(/app/b4mhz722nsjh4/storage/runtime/compiled_templates/f1): Input/output error (/app/b4mhz722nsjh4/vendor/yiisoft/yii2/helpers/BaseFileHelper.php:399)

I checked the storage/runtime folder and I noticed there was no f1 directory so I'm guessing it stopped the upgrade with this exception when it tried to remove a directory that didn't exist. The runtime folder is git ignored and I believe they're temporary files anyway. I couldn't find any info as to why it would be trying to delete a directory that doesn't exist.

My question is was this just a freak bug? Any help in the right direction would be appreciated.

One thing to note is I had tried the setup initially (after updating my composer JSON and lock file with the new updated packages) and tried the setup from my siteurl but ran into a CORS error because our control panel base URL is actually different. And ran into this migration error when trying again from the correct domain. I'm wondering if that may have caused issues.

Would like to try the upgrade again but wanted a little more clarity if possible on why I ran into that migration issue.


texts:
The login page logo does not resize on Craft V3 Beta, but the site icon does, using the identical image. The images are resized to 500 x 500 when uploaded to the cp settings page, but the logo width is cropped to 300 X 412 approximately

I think this is a bug - is anyone else seeing this?


texts: How can I get a restricted Asset Allowed File Type upload to accept RTF files

texts: I have an Asset field for front end users to upload asset files. I prefer to use the 'Restrict allowed file types?' option. However I do not see a choice for Rich Text Format (RTF). I have 'Word' checked, amongst others, but RTF is still rejected. Is there a way to amend this so users can submit RTF files? I am using the Sprout Forms plugin if it matters.


texts:
I have a number of entries that all belong under a Channel that I created. Each entry has a category field where the user can select one or many categories to associate the entry with.

I am displaying these entries on my page, but would like to display each entry under the appropriate category.

For example, my entries are currently displayed like this:

Entry 1 (Category A)
Entry 2 (Category C)
Entry 3 (Category A)
Entry 4 (Category B)
Entry 5 (Category A)

I want it to display like this:

Entry 1 (Category A)
Entry 3 (Category A)
Entry 5 (Category A)
Entry 4 (Category B)
Entry 2 (Category C)

What's the best way to do this?


texts:
I am working on a site for a client who posts many jobs for chefs.

A lot of the jobs are essentially similar, so writing the job postings is something I am trying to simplify.

I can write a series of statements that will serve up similar job descriptions, with pre-written statements that then use |replace to integrate other field data.

So an example statement:

We cook %jobFoodType% to %jobRatingStars%.

Would render as:

'We cook Pub food to a 3 star rating.'

I can write many of these type of statements which can either be selected from a drop down, but I'd like to go a step further and have the drop down when entering a new entry, to be randomly selected from the list of options.

So what I'm asking for, is there a way Craft can randomly pre-populate a field, with a set of predefined statements.

I've had a look at Randomm plugin, which while useful, doesn't let me pre-populate from a predefined set of statements like sentences.

The alternative is to use Randomm to create a random number I use to pick a statement that is in the template, but for obvious reasons, I'd prefer the statements to be driven from Craft.

Any help / thoughts much appreciated. Thank you.


texts: Empty .getParam() does not return an array with dump()

texts:
craft.request.getQuery() returns:

array (size=5)
  'tags' => string 'anxiety' (length=7)
  'maxPrice' => string '' (length=0)
  'sessions' =>
    array (size=4)
      0 => string 'email' (length=5)
      1 => string 'chat' (length=4)
      2 => string 'skype' (length=5)
      3 => string 'phone' (length=5)
  'hours' =>
    array (size=3)
      0 => string 'office' (length=6)
      1 => string 'evenings' (length=8)
      2 => string 'weekends' (length=8)

Whereas craft.request.getParam() throws an error:

  PHP warning

  Missing argument 1 for Craft\HttpRequestVariable::getParam(), called in /home/vagrant/Sites/counselling-anywhere/craft/app/vendor/twig/twig/lib/Twig/Template.php on line 609 and defined

This should have changed in Build #2465 right? I'm assuming it'll still work the same, but it's confusing that they don't return the same results.

Is this by design?


texts:
I'm trying to get some auto translating done in a craft module. In order to do this I need to get the entry of another language in a save event. Is it possible to get this by language?

Event::on(
        Entry::class,
        Entry::EVENT_AFTER_SAVE,
        function(ModelEvent $event) {
            $entry = $event->sender;
            $isNew = $event->isNew;

            if ($isNew) {
                $enEntry = $entry->getEntryByLanguage('en');
            }
        }
    );


texts: 503 Response on fresh install, FastCGI possible culprit

texts:
I've spent all of today trying to configure a server block that will let me install Craft 2.62797 on a Digital Ocean droplet running Ubuntu 14.04 with NGINX and PHP 7.

After uploading the craft directory and a public directory with the index.php file, a visit to my site gets the

**Service Unavailable** Our site is temporarily unavailable. Please try again later.

error.

At first I was using the server block recommended by Brad Bell in this post.

Unfortunately that setup uses 127.0.0.1:9000 for a socket, and none of the other sites on our droplet uses a TCP socket -- they all use this chunk for fastcgi

location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
   }

So I tried dropping that in, no dice. Here's some of the debug info from the site's error log. I think this is where it all goes wrong:

2016/07/19 16:50:08 [debug] 4362#4362: *18 connect to unix:/var/run/php/php7.0-fpm.sock, fd:23 #20
2016/07/19 16:50:08 [debug] 4362#4362: *18 connected
2016/07/19 16:50:08 [debug] 4362#4362: *18 http run request: "/index.php?"
2016/07/19 16:50:08 [debug] 4362#4362: *18 http upstream check client, write event:1, "/index.php"
2016/07/19 16:50:08 [debug] 4362#4362: *18 http upstream recv(): -1 (11: Resource temporarily unavailable)
2016/07/19 16:50:08 [debug] 4362#4362: *18 http upstream request: "/index.php?"
2016/07/19 16:50:08 [debug] 4362#4362: *18 http upstream dummy handler
2016/07/19 16:50:08 [debug] 4362#4362: *18 post event 00007FB15402C770
2016/07/19 16:50:08 [debug] 4362#4362: *18 post event 00007FB15403E780
2016/07/19 16:50:08 [debug] 4362#4362: *18 delete posted event 00007FB15402C770
2016/07/19 16:50:08 [debug] 4362#4362: *18 http upstream request: "/index.php?"
2016/07/19 16:50:08 [debug] 4362#4362: *18 http fastcgi parser: 0
2016/07/19 16:50:08 [debug] 4362#4362: *18 http fastcgi header: "Status: 503 Service Unavailable"

(I edited it for brevity, don't think I clipped out anything relevant).

For what it's worth, I tried editing PHP's www.conf settings, to allow for listening on 127.0.0.1 and port 9000, as per this post. I knew this would break all the other sites, but I wanted to see if I could get it working -- still got a bad gateway error. (Possible that I hadn't restarted PHP after that change, though.)

The bizarre thing about all this is that I have a working Craft CMS install on this same droplet. I tried duplicating its server block, which was auto-generated by Laravel Forge, but that netted me the same error message and didn't log anything to the error log.

Anyway, that's about all I know -- I'm sure I'm leaving something out, but I'm a bit frayed by the debugging process. Would be grateful for any advice.


texts: Deleting primary commerce address throws error

texts:
When i try to delete a user address in Craft Commerce, I get an error thrown, saying the address id does not exist.

However the address id being passed to the action is output from a loop of the current addresses, so it does exist?

This only happens if it is the primary shipping or billing address. If there is a single address, where its neither the primary shipping or billing address the error does not occur.

For example:

{% for address in customer.addresses %}
{% include 'shop/_includes/addresses/address' with {'address': address} %}
<form method="POST">
 <input type="hidden" name="action" value="commerce/customer-addresses/delete">
 {{ csrfInput() }}
 <input type="hidden" name="id" value="{{ address.id }}"/>
 <input type="submit" class="default-button" value="Delete"/>
</form>
{% endfor %}

The error is attached in the following screenshot :

This is using the default form/examples from the craft commerce example template - wondering what might be causing this error and how i can fix it?

If refresh the page the address is deleted as expected, but i can't get around the error being thrown.


texts: returning HTML in $event->sender->addErrors doesn't work

texts:
I have a plugin which is checking if there is a duplicate entry before save. I'm trying to give the user back an anchor to the entry which exists so my client can switch without searching for it in a giant structure.
I have this code
$event->sender->addErrors([
    'expiryDate' => 'cpEditUrl.'>'.$entry[0]->title.''
]);

But somehow I can't render the HTML correctly in the Control Panel, it's getting displayed as plain tekst. Is there any way to achieve this?


texts: Allowing CRAFT_TEMPLATE_PATH in index.php from .env variable

texts:
It appears on Craft 3.1.8 that I can't set the CRAFT_TEMPLATE_PATH from .env without throwing a PHP notice error. This appears to be because the .env is loaded after the defines and I want to access the .ENV for my CRAFTENV_template path.

How can I set CRAFT_TEMPLATE_PATH from my .env without producing an error/warning?


texts: “Access Plugin” doesn't appear in Permissions list

texts:
Non-admin users are not able to access my plugin in the CP. With admin rights, everything is fine—the templates are accessible, but all the other users are getting 403.

I've tried to build the plugin based on Craft 3 best practices and used:

EVENT_REGISTER_CP_NAV_ITEMS - to register nav items

EVENT_REGISTER_CP_URL_RULES - to register url rules like this:

$event->rules['plugin-name'] =  ['template' => 'plugin-handle/index'];

What am I missing?

Should I add / register something else in the plugin's init()?

The permission checkbox for the plugin doesn't even show up in User(Group) Permissions.

I'm not using controllers because routing to templates are working fine and seems to be enough. Is that a problem?


texts:
I have a section called "events" in which I have a table field that contains dates and times of these events.

So I want to order my events by date and within each day by time.

I thought of mergin an array that contains only the basic stuff and the Id to output the rest of the entry. (yes! I will cache the template).

This is how far I got, but I am struggling on how to first order by date, and then within a day, by time.

{% set entries = craft.entries.section('events').limit(null) %}

{% set dates = [] %}

{% for entry in entries %}
    {% set table = entry.cf_dates_table %}

    {% for row in table if row.startDate %}
        {% set dates = dates|merge(
            [{
                'startDate': row.startDate,
                'startTime': row.startTime|date('G:i'),
                'endTime': row.endTime|date('G:i'),
                'id': entry.id,
                'uniqueId': entry.id ~ '-' ~ loop.index,
            }]
        )%}
    {% endfor %}
{% endfor %}

    {% for date in dates|sort() %}
        {{ date.startDate|date('l, d. F') }} {{ date.startTime }} – {{ date.endTime }}, {{ date.id }}

    {% endfor %}

I could imagine grouping the array by the day and then sort them within each day. But I can't get it to work.

Could somebody point me into the right direction?
Is this a viable approach?

Cheers
Stefan


texts: Identifying users and site permissions when logged in

texts:
If I'm logged in as a user in user Group A, how can I tell which site I am currently viewing?

I want to be able to create a multilingual site switcher. But my setup is complex.

I have Company A, User A is in  Group A

Company A Russian, User A is in Group A

Company A Hindi, User A is in Group A

I want to be able to let the user choose the Russian version of the current content. Same for Company B User B in Group B, etc. etc.


texts: Is this an ok approach to building a secondary navigation?

texts:
I have a site which has multiple menus e.g. primary and utility. I've built the menus via sections and the entry type for those sections has a title and a entry field.

This site requires me to show a secondary nav which shows the top level page and it's children as well as highlighting the current page.

I've written this below which works but seem overly complicated for what I'm trying to achieve, being new to Craft I was hoping someone could check this is ok.

The site structure is similar to this:
- home
- page 1
-- child page 1
-- child page 2
- page 2

Now say I was on page 1, I need to display the following:
Page 1 - Child Page 1 - Child Page 2
The same applies if I was on Child Page 1.

What I have currently:

{% set showNav = false %}
{% set entryInNavigation = craft.entries.section(['primaryNavigation', 'utilityNavigation']).relatedTo(entry).one() %}
{% if entryInNavigation %}
    {% set hasDescendants = entryInNavigation.getDescendants().with('relatedEntry').all() %}
    {% if hasDescendants|length %}
        {% set showNav = true %}
    {% else %}
        {% set getParentsChildren = entryInNavigation.parent().children.with('relatedEntry').all() %}
        {% if getParentsChildren|length %}
            {% set showNav = true %}
        {% endif %}
    {% endif %}
{% else %}
    {% set showNav = false %}
{% endif %}

{% if showNav %}

    {% if hasDescendants|length %}
        {% for entryInNav in hasDescendants %}

{{ entryInNav.title }}

        {% endfor %}
    {% else %}
        {% if getParentsChildren|length %}
            {% for entryInNav in getParentsChildren %}

{{ entryInNav.title }}

            {% endfor %}
        {% endif %}
    {% endif %}

{% endif %}


texts:
In Control Panel we can see the progress of a certain job. I would like to hook on events like "DONE" or "FAILED" and do certain things in Control Panel, e.g. reloading the page, or redirecting somewhere

Update: in Craft.js line 11429, I can find

// Fire a setJobInfo event
this.trigger('setJobInfo');

Maybe I can do something with it.


texts:
Im trying to figure out how to move asset(s) to a different volume. Also if I move it will that affect the entries that are using the asset?

Here's what im using to target the asset:
$resourceImage = Asset::find()->volume('resourceImages')->filename($filename);

I need to move it to my productImages volume.

Thanks!


texts:
I'm trying to work out how I can order news posts by postDate, unless a lightswitch is toggled for a post, at which point it will use the dateUpdated to order that item.

This is so a client can still change posts without them appearing at the top of the list (for corrections, etc), but also make substantial updates to certain posts and have them appear as the latest newest item.


texts: Has anyone experienced any cURL error 28: timeout errors using php 7.4 and craft 3.5?

texts:
So the site was working on a new server. But over night I am now seeing the site hang and not load. When it does give an error it gives a cURL error 28 with connection timed out on various resources it may be trying to load like google or other apis.
Does anyone know if this is a craft issue or a server problem. As I said it was working until this morning!


texts: Dragging images inside of rich text editor

texts:
On Redactor's website, they provide a demo with an image that you can click on and drag around the editor to relocate it among the text.

Video example from Redactor's website

Trying this same functionality in the rich text editor in the Craft control panel doesn't work though. I even copied the demo HTML from Redactor's website and pasted it into Craft, without any luck.

Video example from Craft control panel

Has anybody been able to get this working or have any idea why this functionality would be missing in Craft?


texts: Creating JS slideshow with Twig "for" loop

texts:
I have an entry with a matrix field called quantification containing plain text and asset field.

Im looping through the matrix field and for each asset quantification I have a new gallery. Each div id needs to be unique, for example
,
, etc. Within the for loop I think I can use
 for that, right?

But here comes the tricky part, at least for me. I also have some JS code (look here: http://help.dimsemenov.com/kb/royalslider-jquery-plugin-faq/how-to-add-multiple-sliders-to-one-page-and-style-them-differently) which initiates each gallery. How do I dynamically add slider1, slider2, etc since this part of the code lives outside of the for loop?

Any suggestions with respect to the stylesheet, as I need to add them too there. At this point I'm going for hardcoded.


texts: Nearest entry using related entry Smart Map field

texts:
I’m trying to build a query to get the geographically closest entries, based on an Smart Map field value within a related entry.

The following template tags were my first guess, but returned an empty result set.

{% set nearest = allUnitsCriteria.relatedPropertyField.smartMapField(params).order('distance') %}

What’s the best way to do this?


texts: Craft Commerce: where to modify data sent to gateway (need to send customer data)?

texts:
I'm using Braintree with Craft Commerce using this Omnipay Braintree Gateway for Craft Commerce
https://github.com/samuelbirch/craftcommerce-braintree

It's working well, but I noticed that some customer data is not passed through to Braintree at the time of a successful purchase. Specifically, the customer information that is mapped from the customer parameters in the transactions sale call.

Working directly with Braintree API it would be done as part of the sale method that includes amount and creditCard etc on the transaction.

Braintree_Transaction::sale([...], array('customer' => array()));

I'm a bit stuck trying to find where to actually make a modification to pass this data through in the context of Omnipay and Craft Commerce. Does anyone have an idea of where to start? I realize this is a vague question... please comment if there is something specific that I can clarify to make this question more answerable.

Update:

It looks like maybe what I should be using is a Craft Commerce hook. Probably commerce_modifyGatewayRequestData. So I'm starting there, but if anyone has tips it would be appreciated!


texts: A user deleted my craft Admin account, what to do?

texts:
A created user was able to delete the Admin account, now I can't log in Craft anymore with an admin account. How is it possible that a normal user can delete an Admin?
I'm in contact with this user to try and re-activate the Admin account because I think the Soft delete is at work here, so fingers crossed!


texts: Edit custom field value inside "commerce_orders.onBeforeSaveOrder" event

texts:
I would like to edit custom Lightswitch field value to true inside of event on order save

          $order = $event->params["order"];
          $order->setContentFromPost(array(
              'ediCheck' => true,
          ));

          $order->getContent()->setAttributes(array(
              'ediCheck' => true,
          ));

Tried following but the value still stays the same.

Also If there is an documentation file on following that I maybe missed would also be helpful.


texts: Add localised tracking codes for production environments

texts:
I have a localised site. I want to add in kiss metric and google analytic tracking codes for each locale, however, I don't want the tracking codes to output in staging and dev environments.

I considered using globals, but then I'd need a way to print the global in the template if the environment is production.
I have also considered using environment variables for in general.php file for the production environment and print the environment variable in the template.

Does anyone have advice on best practice for this.


texts: Can you call a controller method from within a plugin/module in Craft 3?

texts:
I initially asked a question here about how to use Solspace Freeform to build a custom front-end login form. I gave up too easily and accepted the "it's possible but probably not a good idea" answer. Full disclosure: I'm still trying to see if I can use Freeform as a replacement for all of the stock Craft front-end forms (login, user profile, entry, etc). There is so much available out of the box with Freeform in terms of form validation rules and styling, I really want to leverage that for all my forms.

I have a Freeform login form with the appropriate fields
In my custom module, I'm hooking into Freeform's EVENT_FORM_VALIDATE
At this point the Craft::$app->request object has everything that the craft\controllers\UsersController's actionLogin() method would need to attempt to log the user in
Is there some way to "hand off" the current request to the UsersController?
If the login is successful, will the UsersController go about its business and redirect the user properly?
If the login fails, I can add errors the Freeform's response as needed
Is this a terrible idea? Is there a better way to accomplish this?


texts: Where/how to add a page title to a section (listing)

texts:
I have a number of pages/sections (listings) in either channels or structures. Each page/section (listing) will have a heading that displays an editable title of each page/section.

Should I be able to set this up so the client can edit the title of each section from within that section page in admin? I'm not seeing where to do that. Or do I have to put that field in another place, not within my section? Like in a global settings section that provides editing of each of my sections/pages?

For example, if the page heading says 'Our Projects', but my client wants to be able to change it to 'About Our Amazing Projects' or whatever, where is the best place to put that? I see a 'Name' field for each section, but I'm not sure if that is the appropriate place for it.


texts: Is it possible to add a custom error message when a migration is aborted?

texts:
I've got a plugin migration that returns false from its safeUp() method when certain conditions aren't met.

Upon returning false from the migration, the update stalls, rolls back changes and gives an error screen with a generic error message – i.e. "There was a problem updating your database".

For many users (i.e. those who aren't tech savvy enough to check logs etc.) this message isn't very helpful at all. Is it possible to add a custom message when a migration is aborted?

I've tried throwing an exception inside safeUp(), which gets logged but does not display on the error screen.

If I use a die() statement for the error message, Craft does display it on the error screen, but that makes the whole update process halt, which seems like an unsafe thing to do.

I've also attempted to use craft()->userSession->setError(), but that doesn't appear to be working, either.


texts:
I keep seeing this deprecation message every time I upgrade Craft and cannot figure out what's going on for the life of me. There is nothing in the stack trace (that I can see) that points to a specific template file.

Below is the full stack trace:

> Deprecation error: The Tag ‘name’ property has been deprecated. Use ‘title’ instead.

>Called from /Users/Rhys/www/madebydusk.com/live/craft/app/models/TagModel.php (109)

>16 Craft\TagModel::getName() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/base/CComponent.php (111)

>15 Craft\TagModel::__get("name") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/models/BaseModel.php (87)

>14 Craft\TagModel::__get("name") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/models/BaseElementModel.php (141)

>13 Craft\TagModel::__get("name") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/services/SearchService.php (78)

>12 Craft\SearchService::indexElementAttributes(Craft\TagModel) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/tools/SearchIndexTool.php (99)

>11 Craft\SearchIndexTool::performAction(array("id" => "340", "type" => "Tag")) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/controllers/ToolsController.php (50)

>10 Craft\ToolsController::actionPerformAction() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/actions/CInlineAction.php (49)

>9  CInlineAction::runWithParams(array()) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CController.php (308)

>8  Craft\ToolsController::runAction(CInlineAction) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CController.php (286)

>7  Craft\ToolsController::runActionWithFilters(CInlineAction, array()) Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CController.php (265)

>6  Craft\ToolsController::run("performAction") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/web/CWebApplication.php (282)

>5  Craft\WebApp::runController("tools/performAction") Called from /Users/Rhys/www/madebydusk.com/live/craft/app/etc/web/WebApp.php (817)

>4  Craft\WebApp::_processActionRequest() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/etc/web/WebApp.php (287)

>3  Craft\WebApp::processRequest() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/framework/base/CApplication.php (185)

>2  Craft\WebApp::run() Called from /Users/Rhys/www/madebydusk.com/live/craft/app/index.php (62)

>1  require_once("/Users/Rhys/www/madebydusk.com/live/craft/app/index.php") Called from /Users/Rhys/www/madebydusk.com/live/public/index.php (19)


texts: Building a website containing restaurant menus from multiple vendors -- need some advice on Section hierarchy of data

texts:
Figure I'd query with the geniuses over on StackExchange as I think I've hit a roadblock in my project. I'm building a website containing menus from multiple restaurants with the vision that it could eventually grow to become a local online food ordering marketplace.

Taking into consideration the e-commerce plugins currently in development, I'm going to make an assumption that a single product would constitute as a single entry with these add-ons, so this makes the hierarchy of data a bit of a challenge.

Some requirements:

Menu items need to be associated with a restaurant.
Menu items need to be categorized, but categories are unique per
restaurant

I've played with various configurations thus far and haven't really found a method that I'd deem "ideal."

I've considered using Structure exclusively where parent items would be the restaurants and children would be the menu categories with the items nested beneath. What are your thoughts on this? Could use a few different entry types for indexes and one for menu items.

Right now, I'm using a combination of related entries, an Inverse related entries plugin for informational purposes where restaurants are also channels, but just doesn't seem like a sensible approach so far, so probably scrapping this method.

Thoughts, advice, any feedback really appreciated. Thank you so much!


texts: Is it possible to view entries in admin panel list view with specific field?

texts:
I want to add a checkbox field to all my entries.

But the key factor being that if 3 entries from 100 have this checkbox enabled, the 3 entries will show in the list of 100+ entries with a specific colour/sign/ anything really that makes it stand out and shows that this entry has this field checked.

Im hoping I made sense!

Thanks


texts:
I'm currently finishing a client-website which has to be 100% valid HTML5. For one of the sections, I am using a matrix containing rich-text fields. This content is simply shown on the front page.
The name of the client is "E&K".

Requirements:

The output contains HTML tags.
The output has to be 100% valid HTML.

Problem:
The & character won't be escaped to &amp; wherever it is outputted. This breaks the valid requirement. It seems the problem is the input, not the output. However the rich text editor keeps replacing manually placed &amp; with &

How can I get this to work correctly?


texts:
I have PluginA that needs to listen for something that PluginB does. PluginB needs to include a Model in the event data so that PluginA (and any other subscriber) can pick that up and do whatever it needs to do.

Is that possible right now?


texts: Get current date / time in specific timezone?

texts:
How can I get the current date / time for specific timezones?

My local time is easy:

{{ now|date("H:i") }}

So how can I get this for New York? or Singapore?


texts: When uploading assets what determines the maximum file size?

texts: When I upload an asset I get an alert window stating my file size is to large. I have increased the file size in the general.php config file larger than the file size, however I keep getting a error. We are using AmazonS3. Is Craft limiting the file size, PHP or AmazonS3?


texts: Undefined index error in trying to duplicate file

texts:
I've inherited a Craft-based website, and I'm much more familiar with WordPress, so please pardon the extremely basic question: the homepage for this site uses {% extends "_layout" %} and then references some field data associated with an entry (within "Singles") for "Homepage". I wanted to create a duplicate page to experiment with the template syntax, so I literally copied the contents of index.html into another file of the same name in a folder labeled "preview". Now, if I visit the site via www.site.org/preview I get the following error:

Internal Server Error
Undefined index: entry

I have tried numerous ways of identifying the source of the entries, e.g. set entries but I can't seem to get the field data to output. Of course, if I remove any reference to entry data, the rest of the template renders fine. Why on earth would simply duplicating the homepage file result in the above undefined error? I've tried re-indexing the site assets, clearing caches, etc. Thanks for any assistance here- I'm at my wits' end.