use app\widgets\RandomizedForm\Randomizer;
use Yii;
use yii\web\Response;
public function actionRegister(): string|Response
{
$request = Yii::$app->request;
if ($request->isPost) {
// No need to create SessionManager, it's done internally
$randomizer = Randomizer::fromRequest();
$honeypots = ['honeypot1', 'honeypot2'];
$post = $request->post();
$mappedData = $randomizer->mapPostData($post);
if ($randomizer->honeypotFilled($mappedData, $honeypots)) {
Yii::$app->session->setFlash('error', 'Bot activity detected.');
return $this->refresh();
}
$model = new \app\models\RegisterForm();
if ($model->load($mappedData, '') && $model->validate()) {
$randomizer->session->remove($randomizer->getSessionKey());
return $this->redirect(['site/success']);
}
return $this->render('register', ['model' => $model]);
}
$model = new \app\models\RegisterForm();
return $this->render('register', ['model' => $model]);
}
Im trying to refactor my actionContact and contact view to see if I can get my randomizedForm code to work but i want your help
code
public function actionContact(string $subject = null): Response|string
{
// Set Page title for the browser tab/page title and page header.
$pageTitle = \Yii::t('app', 'contact us');
// Set Meta Data for website title, keywords, description and prepend site name(bool).
$this->setMeta($pageTitle, 'contact, contact us');
// Set page breadcrumbs. (optional)
//\Yii::$app->layoutManager->addBreadcrumb($pageTitle);// page now.
// Setup $model.
if ($this->_isGuest)
{
$model = new ContactForm();
if ($subject === null)
{
$model->subject = $subject = '';
}
$model->subject = $subject;
}
else
{
$user = RoleHelper::userIdentity();
$model = new ContactForm();
// Firstname, lastname and email are all required feilds
$model->name = $user->firstname . ' ' . $user->lastname;
$model->email = $user->email;
if ($subject === null)
{
$model->subject = $subject = '';
}
$model->subject = $subject;
}
$request = \Yii::$app->request;
if ($request->isPost)
//if (($request->isPost) && ($model->load($request->post()) && $model->validate()))
{
// No need to create SessionManager, it's done internally
$randomizer = Randomizer::fromRequest();
$post = $request->post();
$mappedData = $randomizer->mapPostData($post);
if ($randomizer->honeypotFilled($mappedData, $honeypots))
{
\Yii::$app->session->setFlash('error', 'Bot activity detected.');
return $this->refresh();
}
// Perform the post-validation action.
if ($model->process())
{
/**
* HoneyPot
* The 'honeyPot' field is a honeypot, designed to trap bots by
* mimicking a legitimate field.
*/
if ($this->_honeyPot && $model->emaill)
{
LogHelper::logBotAction('Honeypot. Potential bot detected', [
'ip' => $this->_userIp,
'userAgent' => $this->_userAgent,
]);
}
AlertHelper::setFlash(
'success',
\Yii::t(
'app',
'<h4 class="alert-heading">Thank You</h4>
<p>Thank you for contacting us. We will respond to your inquiry as soon as possible.</p>'
),
5000
);
// Handle the POST-Redirect-GET pattern.
return $this->refresh();
}
else
{
AlertHelper::setFlash('error', ErrorMessageHelper::processingError(), 8000);
}
}
// Re-rendered regardless of whether there was an error or if the form validation failed.
return $this->render('contact', [
//'pageTitle' => $pageTitle,
'model' => $model,
]);
}
think you can help refactor my contact view/controller?
Assistant
Certainly! To integrate your RandomizedActiveForm and Randomizer based logic into the contact form and controller, the flow is very similar to your register example.
Here’s a step-by-step refactor of your actionContact controller method and contact view using your randomized form components.
Refactored actionContact Controller Method
php
use app\widgets\randomizedForm\Randomizer;
use Yii;
use yii\web\Response;
public function actionContact(string $subject = null): Response|string
{
$pageTitle = \Yii::t('app', 'contact us');
$this->setMeta($pageTitle, 'contact, contact us');
// Setup model
if ($this->_isGuest) {
$model = new ContactForm();
$model->subject = $subject ?? '';
} else {
$user = RoleHelper::userIdentity();
$model = new ContactForm();
$model->name = $user->firstname . ' ' . $user->lastname;
$model->email = $user->email;
$model->subject = $subject ?? '';
}
$request = \Yii::$app->request;
$honeypots = ['honeypot1', 'honeypot2']; // define your honeypot fields here as in your widget
if ($request->isPost) {
// Instantiate Randomizer via POST data's randomizedFormSessionKey or default
$randomizer = Randomizer::fromRequest();
$post = $request->post();
$mappedData = $randomizer->mapPostData($post);
// Check honeypots
if ($randomizer->honeypotFilled($mappedData, $honeypots)) {
Yii::$app->session->setFlash('error', 'Bot activity detected.');
return $this->refresh();
}
if ($model->load($mappedData, '') && $model->validate()) {
// Process the form (e.g. send email or save)
if ($model->process()) {
// Optionally clear the randomized field map from session after successful submission
$randomizer->getSession()->remove($randomizer->getSessionKey());
AlertHelper::setFlash(
'success',
\Yii::t(
'app',
'<h4 class="alert-heading">Thank You</h4><p>Thank you for contacting us. We will respond to your inquiry as soon as possible.</p>'
),
5000
);
return $this->refresh();
} else {
AlertHelper::setFlash('error', ErrorMessageHelper::processingError(), 8000);
}
}
}
return $this->render('contact', [
'model' => $model,
'honeypotFields' => $honeypots,
]);
}
User
Optional Fixes and Checks:
code
The $honeypots list must be consistent both in the controller and view.
The model may need to declare these honeypot attributes to avoid validation errors (eg. public properties or safe attributes).
Clear the randomized field map session on successful submissions if you want to avoid stale keys.
You can expand the placeholder array for honeypot fields if you want trickier placeholders.
give code for these
Assistant
Certainly! Below are code suggestions for each of the Optional Fixes and Checks:
1. Ensure $honeypots List Is Consistent in Controller and View
You can define $honeypots once (e.g., as a constant for the controller or module) and reuse it:
Example in Controller:
php
// Define as a class constant or a protected property to reuse everywhere
protected const HONEYPOT_FIELDS = ['honeypot1', 'honeypot2'];
public function actionContact(string $subject = null): Response|string
{
// ...
$honeypots = self::HONEYPOT_FIELDS;
// Pass to view
return $this->render('contact', [
'model' => $model,
'honeypotFields' => $honeypots,
]);
}
View:
Use the passed $honeypotFields directly and do not redefine.
php
/* @var $honeypotFields array */
// Then foreach ($honeypotFields as $honeypot) { ... }
2. Declare Honeypot Attributes in Model to Avoid Validation Errors
Your ContactForm model should declare the honeypot attributes and mark them safe, for example:
php
namespace app\models;
use yii\base\Model;
class ContactForm extends Model
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
// Add honeypot fields here
public $honeypot1;
public $honeypot2;
public function rules()
{
return [
[['name', 'email', 'subject', 'body'], 'required'],
['email', 'email'],
['verifyCode', 'captcha'],
// Mark honeypots as safe to allow mass assignment but not validated
[['honeypot1', 'honeypot2'], 'safe'],
];
}
// ... other methods e.g. process()
}
PHP Compile Error – yii\base\ErrorException
Declaration of app\widgets\randomizedForm\RandomizedActiveForm::field($model, string $attribute, array $options = []): app\widgets\randomizedForm\ActiveField must be compatible with yii\widgets\ActiveForm::field($model, $attribute, $options = [])
is a PHP signature compatibility error.
Explanation
Your RandomizedActiveForm::field() method declares:
php
public function field($model, string $attribute, array $options = []): ActiveField
It declares the parameter $attribute as type string.
Declares the return type as app\widgets\randomizedForm\ActiveField.
But yii\widgets\ActiveForm::field() (the parent) declares:
php
public function field($model, $attribute, $options = [])
Notice no typehint on $attribute — accepting mixed $attribute (string or array).
No return type declared.
PHP requires child method signatures to be compatible with parent, i.e. cannot narrow argument types or widen return types compared to parent.
Solution
Remove the type hint on $attribute parameter (keep it untyped).
Remove the return type hint since parent does not declare one.
Use PHPDoc to indicate the expected types for IDE and static analysis.
Correct method declaration
php
/**
* @param object $model
* @param mixed $attribute // can be string or array usually
* @param array $options
* @return \app\widgets\randomizedForm\RandomizedActiveField
*/
public function field($model, $attribute, $options = [])
{
$options['fieldNameMap'] = $this->fieldNameMap;
return parent::field($model, $attribute, $options);
}
User
TypeError
app\widgets\randomizedForm\RandomizedActiveForm::field(): Return value must be of type app\widgets\randomizedForm\ActiveField, app\widgets\randomizedForm\RandomizedActiveField returned
Assistant
The error
code
TypeError
app\widgets\randomizedForm\RandomizedActiveForm::field(): Return value must be of type app\widgets\randomizedForm\ActiveField, app\widgets\randomizedForm\RandomizedActiveField returned
happens because:
You declared a return type in RandomizedActiveForm::field() as app\widgets\randomizedForm\ActiveField.
You return an instance of RandomizedActiveField (which presumably extends yii\widgets\ActiveField), but it is not extending the declared return typeapp\widgets\randomizedForm\ActiveField.
And PHP enforces return type to be exactly or subtype of the declared return type.
Why is this happening?
From your original code for RandomizedActiveForm:
php
public function field($model, string $attribute, array $options = []): ActiveField
ActiveField here is imported as:
php
use yii\widgets\ActiveField;
But the error message says the method expects app\widgets\randomizedForm\ActiveField, which suggests somewhere, your code or IDE has an import or hint expecting app\widgets\randomizedForm\ActiveField but you return RandomizedActiveField.
Likely cause:
You have a return type declared as app\widgets\randomizedForm\ActiveField (which probably does not exist as a class, or is not related to RandomizedActiveField), but you return a RandomizedActiveField.
How to fix:
Remove the return type hint from the method.
Just use PHPDoc for type hinting.
So, in your RandomizedActiveForm class, change your method declaration to this:
php
User
Error
Class "app\widgets\randomizedForm\Html" not found
Assistant
The error:
code
Class "app\widgets\randomizedForm\Html" not found
means somewhere in your RandomizedActiveForm class (or related classes) you're trying to use Html but you haven't imported it.
But you have not imported yii\helpers\Html at the top of your file, nor do you have a fully qualified namespace there.
How to fix
Add the use statement at the top of your RandomizedActiveForm.php file:
php
use yii\helpers\Html;
Example — full snippet of imports:
php
namespace app\widgets\randomizedForm;
use Yii;
use yii\widgets\ActiveForm;
use yii\base\InvalidArgumentException as YiiBaseInvalidArgumentException;
use yii\web\View;
use yii\helpers\Json;
use yii\helpers\Html; // <---- ADD THIS LINE
// ... rest of your imports
Once added, PHP will know what Html::hiddenInput() refers to.
Summary:
Add this import line to your RandomizedActiveForm.php:
php
use yii\helpers\Html;
If you want, I can check the entire file imports for you!
User
so no form code appears in the source code.
and in session im getting a list:
Thanks for the detailed info. The key things standing out are:
Session contains many randomMap_* keys (seems like leftover old entries piling up).
Your JS placeholder script is rendered properly with current randomized names and placeholders.
But no form inputs appear in the HTML source output.
Let’s analyze and resolve why the form HTML inputs are missing, despite the script being registered:
Diagnosis: Why no form inputs are rendering
Form begins but fields are not output?
Check your view file:
Are you calling RandomizedActiveForm::begin() properly?
Are you calling $form->field() on your model attributes?
RandomizedActiveForm::run() method:
In your code snippet, in the run() method you have:
php
public function run(): void
{
// Output hidden input with __sessionKey before form end tag
echo Html::hiddenInput('randomizedFormSessionKey', $this->__sessionKey);
// Register JS for placeholders
if (!empty($this->placeholders)) {
$this->registerPlaceholderScript($this->placeholders);
}
parent::run();
}
You echo a hidden input, then call parent::run().
This means form fields rendering comes in the body between begin() and run(), so if your view does not output them (e.g., missing $form->field calls or they don't render correctly), nothing will show.
field() override:
You override field() in your RandomizedActiveForm as:
php
public function field($model, $attribute, $options = [])
{
$options['fieldNameMap'] = $this->fieldNameMap;
return parent::field($model, $attribute, $options);
}
$form->field($model, 'name')->textInput(); // no echo means no output!
2. Are you calling RandomizedActiveForm::begin() and then RandomizedActiveForm::end()?
Make sure your whole form is wrapped properly.
Example minimal snippet:
php
User
code
public function init(): void
{
parent::init();
if (!isset($this->sessionManager)) {
$this->sessionManager = new SessionManager();
}
// Try to get existing key in session, else generate new
$sessionKeys = $this->sessionManager->getAllKeys(); // if your SessionManager supports this
$existingKeys = array_filter($sessionKeys, fn($k) => strpos($k, 'randomMap_') === 0);
if ($existingKeys) {
// Use first available key for consistency
$this->__sessionKey = reset($existingKeys);
} else {
$this->__sessionKey = 'randomMap_' . \Yii::$app->security->generateRandomString(16);
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap)) {
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
please dont make up code, sessionManager does not have the feature getAllKeys();
Assistant
Thanks for the clarification! If your SessionManager or session interface does not support getAllKeys(), we cannot iterate session keys like that.
The goal in your init() method is:
Reuse an existing session key if available (so you don’t generate a new random key and pile up keys forever).
Or generate a new one only if none exists yet.
How to do that without getAllKeys()?
You need some place to store or remember previously generated session key, such as:
Store the generated session key in a fixed session variable.
Or accept a fixed default session key.
Practical solution: fixed session key per form
For example, for your contact form:
php
if (empty($this->__sessionKey)) {
// Use a fixed key per form to avoid key buildup
$this->__sessionKey = 'randomMap_contactForm';
}
This way, the same session key is reused every time.
Full corrected init() snippet without getAllKeys():
php
public function init(): void
{
parent::init();
if (!isset($this->sessionManager)) {
$this->sessionManager = new SessionManager();
}
if (empty($this->__sessionKey)) {
// Use fixed session key to avoid many keys in session
$this->__sessionKey = 'randomMap_contactForm';
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap)) {
// Generate randomized names for all logical fields
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
User
code
2. Are you calling RandomizedActiveForm::begin() and then RandomizedActiveForm::end()?
Make sure your whole form is wrapped properly.
Example minimal snippet:
<?php
use app\widgets\randomizedForm\RandomizedActiveForm;
use app\widgets\randomizedForm\RandomizedActiveField;
$form = RandomizedActiveForm::begin([
'id' => 'contact-form',
'fieldClass' => RandomizedActiveField::class,
'model' => $model,
'honeypotFields' => ['emaill'], // or your honeypots
'placeholders' => [
'name' => 'Enter Name',
'email' => 'Enter email',
'subject' => 'Enter subject',
'body' => 'Type your message here...',
'verifyCode' => 'Enter Security Code',
],
]);
echo $form->field($model, 'name')->textInput();
echo $form->field($model, 'email')->textInput();
echo $form->field($model, 'subject')->textInput();
echo $form->field($model, 'body')->textarea(['rows' => 6]);
echo $form->field($model, 'verifyCode')->widget(\yii\captcha\Captcha::class);
foreach ($form->honeypotFields as $hp) {
echo $form->field($model, $hp)->textInput([
'style' => 'position:absolute; left:-9999px;',
'tabindex' => '-1',
'autocomplete' => 'off',
'aria-hidden' => 'true',
])->label(false);
}
echo \yii\helpers\Html::submitButton('Submit', ['class' => 'btn btn-primary']);
RandomizedActiveForm::end();
?>
Im using this code
Assistant
Thanks for sharing your form code! The snippet you posted looks correct in principle, and it should render form fields with randomized names.
If no form inputs appear in the page source, here are targeted things to check:
1. Check that the file you're editing is the actual rendered view
Sometimes editing the wrong view or layout causes confusion.
Confirm your controller action renders this view file.
2. Make sure output is not suppressed
Are you editing inside PHP tags properly?
Every field output must have echo or use the shorthand <?= ... ?>. Your sample uses echo which is good.
Make sure your view file does not have misplaced PHP tags preventing output.
3. Is your RandomizedActiveForm::begin() definitely instantiating?
Put a debug line right after $form = RandomizedActiveForm::begin([...]);:
php
<?php
// your existing code...
$form = RandomizedActiveForm::begin([
'id' => 'contact-form',
'fieldClass' => RandomizedActiveField::class,
'model' => $model,
'honeypotFields' => ['emaill'], // or your honeypots
'placeholders' => [
'name' => 'Enter Name',
'email' => 'Enter email',
'subject' => 'Enter subject',
'body' => 'Type your message here...',
'verifyCode' => 'Enter Security Code',
],
]);
echo "<!-- DEBUG: form started -->";
Then check page source for <!-- DEBUG: form started -->.
If missing, your form begin() is not running.
4. Confirm your RandomizedActiveField extends yii\widgets\ActiveField
The field() method calls parent::field() with proper config.
Your randomized active field class must extend yii\widgets\ActiveField so that rendering works.
User
code
public function init(): void
{
parent::init();
if (!isset($this->sessionManager)) {
$this->sessionManager = new SessionManager();
}
if (empty($this->__sessionKey)) {
// Use fixed session key to avoid many keys in session
$this->__sessionKey = 'randomMap_contactForm';
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap)) {
// Generate randomized names for all logical fields
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
But doing this assumes im using this code only for contactForm and I am not.. you are making my code fixed. If anything why wouldn't we used details from the widget when being set? like the id? use that with the session key in the init.. so it somewhat fixed but not completely
Assistant
Excellent point! You want a stable but distinct session key per form instance, without hardcoding a fixed key like 'randomMap_contactForm', so multiple independent forms (contact, register, etc.) can coexist without clashing or growing infinite keys.
A good approach: derive a session key based on the form ID or some unique identifier passed to the widget — either:
Use the form id property (commonly set by the developer).
Or fallback to a prefix + a hash of something unique (class name + id).
This way you get:
Deterministic, stable session keys.
No collisions between different form widgets.
No infinite accumulation in session storage.
Example improved init() for your RandomizedActiveForm:
php
public function init(): void
{
parent::init();
if (!isset($this->sessionManager)) {
$this->sessionManager = new SessionManager();
}
// Use widget/form ID or fallback to class name + random string hash
if (empty($this->__sessionKey)) {
if (!empty($this->id)) {
// Use form ID as part of session key—ensure safe chars by base64 or hash if needed
$sessionSafeId = preg_replace('/[^a-z0-9_\-]/i', '_', strtolower($this->id));
$this->__sessionKey = 'randomMap_' . $sessionSafeId;
} else {
// Fallback: hash of class name + random string
$randomPart = substr(\Yii::$app->security->generateRandomString(8), 0, 8);
$this->__sessionKey = 'randomMap_' . md5(static::class) . '_' . $randomPart;
}
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap)) {
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
User
code
public function init(): void
{
// Get cacheDuration from Param and set with TimeHelper
$cacheDuration = ParamHelper::get('widgets.cacheDuration');
$this->__cacheJsCssTime = TimeHelper::convertDurationToSeconds($cacheDuration);
// Cache & Compression
$this->__cacheEnable = ParamHelper::get('widgets.cacheEnable');
$this->__compressJsCss = ParamHelper::get('widgets.compressJsCss');
/**
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*/
parent::init();
if ($this->model === null)
{
throw new YiiBaseInvalidArgumentException(
'RandomizedActiveForm requires you to set the "model" property.'
);
}
// Initialize sessionManager internally if not set
if (!isset($this->sessionManager))
{
$this->sessionManager = new SessionManager();
}
// Use widget/form ID or fallback to class name + random string hash
if (empty($this->__sessionKey))
{
// Use form ID as part of session key—ensure safe chars by base64 or hash if needed
if (!empty($this->id))
{
$sessionSafeId = preg_replace('/[^a-z0-9_\-]/i', '_', strtolower($this->id));
$this->__sessionKey = 'randomMap_' . $sessionSafeId;
}
// Fallback: hash of class name + random string
else
{
$randomPart = substr(\Yii::$app->security->generateRandomString(8), 0, 8);
$this->__sessionKey = 'randomMap_' . md5(static::class) . '_' . $randomPart;
}
}
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
// Combine model attributes and honeypots
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
// Retrieve existing field map or generate new randomized names
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap))
{
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
ParseError
syntax error, unexpected variable "$this", expecting "function" or "const"
Assistant
The error
code
ParseError
syntax error, unexpected variable "$this", expecting "function" or "const"
usually means there's a syntax error in your class code outside of methods, or a misplaced/missing brace making PHP interpret $this in invalid context.
Looking at your code snippet—likely issue is that the closing braces do not match or you have a misplaced brace inside init() method.
Examining your snippet carefully
php
public function init(): void
{
// ...
// Use widget/form ID or fallback to class name + random string hash
if (empty($this->__sessionKey))
{
// Use form ID as part of session key—ensure safe chars by base64 or hash if needed
if (!empty($this->id))
{
$sessionSafeId = preg_replace('/[^a-z0-9_\-]/i', '_', strtolower($this->id));
$this->__sessionKey = 'randomMap_' . $sessionSafeId;
}
// Fallback: hash of class name + random string
else
{
$randomPart = substr(\Yii::$app->security->generateRandomString(8), 0, 8);
$this->__sessionKey = 'randomMap_' . md5(static::class) . '_' . $randomPart;
} // <--- matches else brace
} // <--- matches if (empty($this->__sessionKey)) brace
} // <--- this closes init() method
Note the closing brace after $randomPart = ... has inconsistent indentation and then a second closing brace. The last closing brace here likely closes the whole method, but the earlier one matches the else block.
User
ok so what did you want me to try to see if we can get the form to load. right now I see the jquery code, no form. the issue with too many sessions seem to be fixed:
Check that your model's attributes property is accessible and correct
In Yii2 ActiveRecord or Model classes:
public name;publicemail;
public subject;publicbody;
public verifyCode;publicemaill; // honeypot
public function attributes()
{
return ['name', 'email', 'subject', 'body', 'verifyCode', 'emaill'];
}
If this is missing or incorrect, your code:
attributes=arraykeys(this->model->attributes);
may return empty or incomplete list, and your randomized mapping won't generate keys for real fields.
is it standard to declare attrubites?
Assistant
Great question!
In Yii2, declaring a model's attributes depends on whether it is an ActiveRecord or a plain Model:
1. ActiveRecord
If your model extends yii\db\ActiveRecord, then:
Attributes are automatically populated from the database table columns.
You do not need to declare properties or override attributes() method manually, unless you want to add virtual attributes.
Example:
php
class User extends \yii\db\ActiveRecord
{
// No need to declare $name, $email etc. if they are columns in your table.
// You can override attributes() only if adding extra virtual fields
public function attributes()
{
return array_merge(parent::attributes(), ['virtualAttr1', 'virtualAttr2']);
}
}
2. Plain Model (extending yii\base\Model)
If your class extends yii\base\Model (e.g., form models), then it does not have a database table.
You normally declare your attributes as public properties.
The attributes() method is optional and usually not overridden.
The base Model::attributes() returns all public properties using reflection.
Example:
php
class ContactForm extends \yii\base\Model
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
public $emaill; // honeypot
public function rules()
{
return [
[['name', 'email', 'subject', 'body'], 'required'],
['email', 'email'],
[['emaill'], 'safe'], // honeypot field marked safe
// ...
];
}
// Usually no need to override attributes() unless for special cases
}
User
code
class ContactForm extends \yii\base\Model
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
public $emaill; // honeypot
public function rules()
{
return [
[['name', 'email', 'subject', 'body'], 'required'],
['email', 'email'],
[['emaill'], 'safe'], // honeypot field marked safe
// ...
];
}
// Usually no need to override attributes() unless for special cases
}
this is what im using
Assistant
Perfect — your ContactForm class is a plain yii\base\Model with public properties declared, which is the standard correct way to do it for form models in Yii2.
Important: How to get attribute names to feed your Randomizer?
Because yii\base\Modeldoes NOT have an $attributes property, but rather:
An attributes() method returning the attribute names (public properties by default),
And a magic __get() for getting properties dynamically.
So in your RandomizedActiveForm (or wherever you do array_keys($this->model->attributes)) you should instead call:
php
$attributes = $this->model->attributes();
not
php
array_keys($this->model->attributes); // This won't work for yii\base\Model
Adjusted snippet for your init method:
php
public function init(): void
{
//...
$attributes = $this->model->attributes(); // CALL the method here
$logicalFields = array_merge($attributes, $this->honeypotFields);
//...
}
which misses your main form keys, leading to empty mappings and no fields rendered.
Summary checklist:
Your model is perfectly fine (public props + rules).
Change your access to attributes list from array_keys($this->model->attributes) to $this->model->attributes() (call method).
This will fix the randomized field name map to include all your logical fields.
Then your form fields will render with randomized names.
If you want, I can help you patch your RandomizedActiveForm::init() method fully with this fix applied.
User
code
So, if your model extends yii\base\Model (not ActiveRecord), you should:
Change in your RandomizedActiveForm (or init()):
// Change this line:
$attributes = array_keys($this->model->attributes);
// TO this line:
$attributes = $this->model->attributes();
is it possible to support both?
Assistant
Yes, absolutely! You can write code that supports both ActiveRecord models (where $model->attributes is an array property) and plain Yii base models (where $model->attributes() is a method returning the attributes).
How?
Check if the $attributes property exists and is an array, else fallback to calling attributes() method:
php
if (is_array($this->model->attributes)) {
// ActiveRecord: attributes is an array property
$attributes = array_keys($this->model->attributes);
} elseif (method_exists($this->model, 'attributes')) {
// Base model: attributes() method returns attribute names
$attributes = $this->model->attributes();
} else {
// Fallback, empty array
$attributes = [];
}
\Yii::debug("RandomizedActiveField::input of type=$type returns: ".substr($result, 0, 30), __METHOD__);
return $result;
//return parent::input($type, $options);
}
/**
* @inheritDoc
*/
public function textInput($options = [])
{
Assistant
The error:
code
TypeError
substr(): Argument #1 ($string) must be of type string, app\widgets\randomizedForm\RandomizedActiveField given
occurs because the first argument passed to substr() is NOT a string, but an object of class RandomizedActiveField.
The problematic code:
php
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
$result = parent::input($type, $options);
\Yii::debug("RandomizedActiveField::input of type=$type returns: ".substr($result, 0, 30), __METHOD__);
return $result;
}
Explanation:
parent::input($type, $options) is expected to return a string, the rendered HTML.
But in your case, it returns an instance of RandomizedActiveField instead of a string.
Hence, substr($result, 0, 30) fails because substr() expects a string, but gets an object.
Why is parent::input() returning an object, not a string?
Check the class hierarchy:
Your RandomizedActiveField extends yii\widgets\ActiveField.
In standard Yii2, yii\widgets\ActiveField::input($type, $options) returns a string rendering the input field.
If in your project, parent::input() behavior is altered (e.g., overridden elsewhere), or you accidentally have use statements mixing classes, it could cause this error.
Potential causes:
You may have installed or overridden ActiveField such that input() returns $this (the field object) instead of HTML string.
The call to parent::input() is actually calling your own method accidentally (recursive call).
Your RandomizedActiveField is not extending the correct yii\widgets\ActiveField but something else.
User
2025-07-20 15:50:42 [::1][-][-][error][app\widgets\randomizedForm\RandomizedActiveField::input] Expected string from parent::input() but got object app\widgets\randomizedForm\RandomizedActiveField
2025-07-20 15:50:42 [::1][-][-][error][app\widgets\randomizedForm\RandomizedActiveField::input] Expected string from parent::input() but got object app\widgets\randomizedForm\RandomizedActiveField
2025-07-20 15:50:42 [::1][-][-][error][app\widgets\randomizedForm\RandomizedActiveField::input] Expected string from parent::input() but got object app\widgets\randomizedForm\RandomizedActiveField
2025-07-20 15:50:42 [::1][-][-][error][app\widgets\randomizedForm\RandomizedActiveField::input] Expected string from parent::input() but got object app\widgets\randomizedForm\RandomizedActiveField
Assistant
The logs:
code
Expected string from parent::input() but got object app\widgets\randomizedForm\RandomizedActiveField
make it clear that the parent::input() inside your RandomizedActiveField is calling your own class again, causing infinite recursion returning an object of type RandomizedActiveField instead of expected string.
Why this happens?
Your RandomizedActiveField extends yii\widgets\ActiveField which normally has a method:
php
public function input($type, $options = [])
that returns a string (the input HTML).
But, if your RandomizedActiveField class is calling parent::input(), and somehow your RandomizedActiveField class is also declared as ActiveField (or there's a class autoloading or namespace conflict), then parent::input() calls back into your own input() method recursively.
Most common cause
You accidentally imported RandomizedActiveFieldas the parent class, causing:
RandomizedActiveField extends RandomizedActiveField (itself) recursively, instead of extending yii\widgets\ActiveField.
Check your import statements and class declaration in RandomizedActiveField.php
Make sure at the very top you have exactly:
php
namespace app\widgets\randomizedForm;
use yii\widgets\ActiveField;
class RandomizedActiveField extends ActiveField
{
// your methods here
}
and NOT:
php
use app\widgets\randomizedForm\RandomizedActiveField; // <- THIS IS WRONG
What to do:
Open your RandomizedActiveField.php
Verify you have ONLY this import for :
User
code
<?php
declare(strict_types=1);
namespace app\widgets\randomizedForm;
use Yii;
use yii\widgets\ActiveField;
/**
* RandomizedActiveField overrides Yii2 ActiveField to render inputs with
* randomized 'name' attributes using the fieldNameMap populated by
* RandomizedActiveForm.
*/
class RandomizedActiveField extends ActiveField
{
Assistant
Thanks for sharing the beginning of your RandomizedActiveField.php. Based on what you showed, the namespace and import look correct:
php
namespace app\widgets\randomizedForm;
use Yii;
use yii\widgets\ActiveField;
class RandomizedActiveField extends ActiveField
{
// ...
}
This is exactly how it should be.
Given this, why parent::input() still returns your own class instance?
Possible reasons:
You're calling parent::input() in a place where the parent method is overridden in your own class path or autoloading confusion.
The input() method might be missing from yii\widgets\ActiveField in your Yii version or replaced by some other extension.
There's an accidental alias or autoloader mapping your class onto itself as parent.
To verify:
Do a quick test in your project and check what class is the direct parent of RandomizedActiveField:
Add inside RandomizedActiveField class:
php
public function debugParentClass()
{
return get_parent_class($this);
}
Then in your code, temporarily call:
php
Yii::debug('Parent class is: ' . (new \ReflectionClass($this))->getParentClass()->getName(), __METHOD__);
or just log:
php
Yii::debug('Parent of RandomizedActiveField is: ' . get_parent_class($this), __METHOD__);
Another cause (common) is if the method input() in yii\widgets\ActiveField does not exist but rather is a magic method or you are calling a method that doesn't exist on parent and __call is returning $this (the object).
Check your Yii2 version yii\widgets\ActiveField:
User
/**
* Renders an input tag.
* @param string typetheinputtype(e.g.‘text‘,‘password‘)∗@paramarrayoptions the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
*
* If you set a custom id for the input element, you may need to adjust the [[selectors]]accordingly.∗∗@returnthis the field object itself.
*/
public function input(type,options = [])
{
options=arraymerge(this->inputOptions, options);if(this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
this−>addErrorClassIfNeeded(options);
}
Ah, this snippet clarifies the root cause! You posted the actual input() method source from yii\widgets\ActiveField (likely your Yii version), and it returns $this (the field object itself) instead of an HTML string.
Explanation:
php
public function input($type, $options = [])
{
$options = array_merge($this->inputOptions, $options);
// ... some setup ...
$this->parts['{input}'] = Html::activeInput($type, $this->model, $this->attribute, $options);
return $this;
}
This method does not return a rendered input string!
It just sets the {input} placeholder part inside the field's parts array.
It returns $this (the ActiveField object) for method chaining.
The final rendered HTML happens later when you call render() or convert the field to string.
How Yii2 ActiveField works internally:
Methods like input(), textInput(), passwordInput(), etc. build the field parts internally and return $this for chaining.
When you echo a field: echo $form->field($model, 'attr')->textInput(), PHP implicitly calls $field->__toString(), which calls render() producing the full HTML.
Therefore
php
$result = parent::input($type, $options);
returns $this (ActiveField object), not a string.
Calling substr($result, 0, 30) produces a TypeError because you pass an object instead of a string.
What you should do instead
Do not try to log or process the result of input() directly as string!
Instead, simply call input() as usual and return that chainable object, which will be converted to string later when echoed.
Correct input() overriding example:
php
User
im so confused now
Assistant
Totally understandable — Yii’s ActiveField can be a bit confusing because methods like input() don’t directly output HTML strings but instead build internal state and return the field object for chaining. The final string rendering happens later automatically when the field is echoed or cast to string.
Here’s a simple breakdown and what you need to do:
1. What does input() return?
It does NOT return a string of HTML.
It returns $this — the ActiveField object itself.
This allows chained calls like $form->field($model, 'name')->input('text')->label('My Label').
2. When does the form field HTML get rendered?
When you echo the field in your view, PHP calls __toString() on the field object.
This triggers the rendering of the full HTML for that field, including label, input, error, hint, etc.
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'name' HTML start:
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'email' HTML start:
<label class="control-label" for="contactf
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'subject' HTML start:
<label class="control-label" for="contac
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'body' HTML start:
<label class="control-label" for="contactfo
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'verifyCode' HTML start:
<label class="control-label" for="contactform-
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'emaill' HTML start:
Assistant
Thanks for sharing the logs — the debug logs confirm each field is rendering well with a proper opening <div class="form-group ...">, so the form fields are being generated properly as HTML strings.
So why might the form not appear visibly in the browser?
Possibilities and what to check next:
1. Verify the rendered form HTML actually exists in the page source
View page source (Ctrl+U or browser menu)
Search for <form id="contact-form">
Search for <div class="form-group field-contactform-name"> and other logged fields
If these exist in the source but you cannot see them on the page:
2. Check CSS or layout hiding the form
Inspect page with browser Developer Tools (right-click → Inspect)
Confirm the form and fields are present in DOM
Check styles on form, fields, and parents:
Are they display: none or visibility: hidden?
Any CSS rules that position the form off-screen, opacity zero, or zero height/width?
If you find styles hiding them, correct or remove those CSS rules.
3. Confirm your RandomizedActiveForm::run() outputs the form end tag properly
In your RandomizedActiveForm, check that your overridden run() method calls:
php
public function run()
{
echo Html::hiddenInput('randomizedFormSessionKey', $this->__sessionKey);
if (!empty($this->placeholders)) {
$this->registerPlaceholderScript($this->placeholders);
}
parent::run();
}
Make sure:
parent::run() is called last (so the closing </form> is output)
4. Check for JS or HTML errors in browser console
Open Developer Tools → Console tab → Check for JS errors related to jQuery or your randomized form
Check Network tab for any missing JS files
5. Confirm you do not have nested forms or invalid HTML
Nested forms or improper HTML can cause browsers to discard form contents visually.
User
no html appears, in the sourcecode. i see js. i see the session, im getting no errors. Logging is showing what I've already shown you:
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'name' HTML start:
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'email' HTML start:
<label class="control-label" for="contactf
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'subject' HTML start:
<label class="control-label" for="contac
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'body' HTML start:
<label class="control-label" for="contactfo
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'verifyCode' HTML start:
<label class="control-label" for="contactform-
2025-07-20 16:01:10 [::1][-][-][error][debugAndEchoField] Field 'emaill' HTML start:
public function run(): void
{
// Output hidden input with __sessionKey before form end tag
echo Html::hiddenInput('randomizedFormSessionKey', $this->__sessionKey);
code
// Register JS for dynamically applying placeholders if any provided
if (!empty($this->placeholders))
{
$this->registerPlaceholderScript($this->placeholders);
}
parent::run();
}
Assistant
Thanks for the detailed info — the key here is:
No HTML form appears in the source code, but you do see the JS and the session map entries.
This strongly suggests the form opening and fields are never being output, only your RandomizedActiveForm::run() is outputting stuff late in the form (hidden input + JS), but the main form content never appears.
Problem diagnosis
Most likely your form content (fields and form opening tag) is not echoed/output anywhere.
Common cause:
You are calling DebugAndEchoField() in your view which echoes fields, but you don't see the <form> or the form open tag, etc.
Remember your fields are rendered via:
php
$form = RandomizedActiveForm::begin([...]);
// echo field calls here
RandomizedActiveForm::end();
begin() outputs the opening <form> tag. end() outputs the closing </form> tag and calls your run() method.
So if you do not call RandomizedActiveForm::begin() or do not echo its result correctly, no form is created.
So make sure:
You call RandomizedActiveForm::begin() and RandomizedActiveForm::end() in your view properly.
The code between those calls actually echoes fields.
The form opening <form> tag is output by the begin() method.
How to check quickly if begin() outputs the form tag:
Add this immediately after begin():
php
<?php
$form = RandomizedActiveForm::begin([...]);
echo "<!-- FORM STARTED -->";
?>
...
<?php RandomizedActiveForm::end() ?>
Reload the page and view source—check for <!-- FORM STARTED -->.
If not present, your begin() is broken or not outputting.
Also check for this common mistake:
User
code
Assistant
Thanks for sharing all the code — this looks solid and well-structured. You’ve integrated RandomizedActiveForm, Randomizer, and your controller/view properly.
Summary / sanity checklist — why your form fields should render:
In RandomizedActiveForm::init() you generate or retrieve randomized field names based on the model attributes + honeypots.
In your view, you begin RandomizedActiveForm::begin() and call $form->field(...)->inputType() for every field, echoing the output.
You end with RandomizedActiveForm::end() which calls run() to render the hidden session key and the JS for placeholders.
Your Logged output shows your fields are rendering HTML (or at least creating proper strings).
Honeypot field is included and hidden off-screen with CSS.
Controller loads, maps, validates, and handles POST properly.
Given the above — if you still see no form HTML in browser source, then the most frequent remaining causes are:
1. View code output suppression
Make sure the view file is the file actually rendered by your controller action.
4. Check for PHP errors/warnings suppressed or hidden
Check server error logs.
User
View code output suppression
Make sure the view file is the file actually rendered by your controller action.
code
Add a unique comment or echo at the top, like:
code
Refresh the browser and View Source to verify it shows.
ok help rewrite to echo all the fields and not just error log lets break the view file down and see what peieve of the code is preventing it from even appearing in the source code
namespace app\widgets\randomizedForm;
use Yii;
use yii\widgets\ActiveForm;
use yii\base\InvalidArgumentException as YiiBaseInvalidArgumentException;
use yii\web\View;
use yii\helpers\Json;
use app\components\SessionManager;
use app\components\interfaces\SessionInterface;
use app\components\traits\CacheJsCssTrait;
use app\widgets\randomizedForm\Randomizer;
use app\helpers\ParamHelper;
use app\helpers\TimeHelper;
/**
* RandomizedActiveForm overrides Yii2 ActiveForm to randomize all field names,
* store the mapping in session, and pass to fields.
*/
class RandomizedActiveForm extends ActiveForm
{
/**
* Placeholders keyed by logical attribute names.
* To be set by the view when starting the widget.
* @var array<string,string>
*/
public array $placeholders = [];
// @var array<string, string> Map of logical attribute => randomized name
public $fieldNameMap = [];
// @var list<string> List of honeypot logical attribute names
public $honeypotFields = [];
// @var object|null The form model
public ?object $model = null;
/**
* Session Manager Interface
* @see app\components\interfaces\SessionInterface.php
* @var SessionInterface
*/
public SessionInterface $sessionManager = null;
// @var Randomizer
protected Randomizer $__randomizer;
// @var string The session key to use
protected string $__sessionKey;
// Note: Every protected variable below CacheJsCssTrait is used by the trait
use CacheJsCssTrait;
protected bool $__cacheDebugMode = false;
protected bool $__compressJsCss = false;
protected bool $__cacheEnable = false;
protected int $__cacheJsCssTime = 3600;// +1 hour
protected string $__cacheKeyPrefix = 'widget_randomizedActiveForm';
const DEFAULT_DURATION_SECONDS = 3600;// +1 hour
public function init(): void
{
// Get cacheDuration from Param and set with TimeHelper
$cacheDuration = ParamHelper::get('widgets.cacheDuration');
$this->__cacheJsCssTime = TimeHelper::convertDurationToSeconds($cacheDuration);
// Cache & Compression
$this->__cacheEnable = ParamHelper::get('widgets.cacheEnable');
$this->__compressJsCss = ParamHelper::get('widgets.compressJsCss');
/**
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*/
parent::init();
// Initialize sessionManager internally if not set
if (!isset($this->sessionManager))
{
$this->sessionManager = new SessionManager();
}
if ($this->model === null)
{
throw new YiiBaseInvalidArgumentException(
'RandomizedActiveForm requires you to set the "model" property.'
);
}
if (empty($this->__sessionKey))
{
$this->__sessionKey = 'randomMap_' . \Yii::$app->security->generateRandomString(16);
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
// Combine model attributes and honeypots
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
// Retrieve existing field map or generate new randomized names
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap))
{
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
public function run(): void
{
// Output hidden input with __sessionKey before form end tag
echo Html::hiddenInput('randomizedFormSessionKey', $this->__sessionKey);
// Register JS for dynamically applying placeholders if any provided
if (!empty($this->placeholders))
{
$this->registerPlaceholderScript($this->placeholders);
}
parent::run();
}
/**
* Register JS code to fill placeholders for randomized input names.
* @param array<string,string> $placeholders
* @return void
*/
private function registerPlaceholderScript(array $placeholders): void
{
if (empty($this->fieldNameMap) || empty($placeholders))
{
return;
}
$fieldMapJson = Json::htmlEncode($this->fieldNameMap);
$placeholdersJson = Json::htmlEncode($placeholders);
$cacheKey = $this->__cacheKeyPrefix . $widgetId . '_js_block_';
$jsBlock = $this->getCachedJsBlock($cacheKey, function () use (
$fieldMapJson,
$placeholdersJson
)
{
return <<<JS
(function(\$)
{
\$(function()
{
var map = $fieldMapJson;
var placeholders = $placeholdersJson;
Object.keys(map).forEach(function(logicalName)
{
var randomized = map[logicalName];
var el = document.querySelector('[name="' + randomized + '"]');
if (el && placeholders[logicalName])
{
el.setAttribute('placeholder', placeholders[logicalName]);
}
});
});
})(jQuery);
JS;
});
// Register the JavaScript.
$this->getView()->registerJs($jsBlock, View::POS_END);
}
/**
* Override ActiveForm::field() to pass randomized fieldNameMap to ActiveField
* @param object $model
* @param string $attribute
* @param array $options
* @return \yii\widgets\ActiveField
*/
public function field($model, string $attribute, array $options = []): ActiveField
{
$options['fieldNameMap'] = $this->fieldNameMap;
return parent::field($model, $attribute, $options);
}
/**
* Get the Randomizer instance, for convenience
*/
public function getRandomizer()
{
return $this->__randomizer;
}
}
Refactored contact.php View
Replace ActiveForm with your RandomizedActiveForm and pass honeypot fields explicitly. Also, render honeypot fields using the same model.
Controller: use Randomizer::fromRequest() to restore the randomized field name map. Use mapPostData() to convert POST keys to logical attribute keys.
Honeypot fields: pass the same honeypot list to the form (honeypotFields) so they get randomized and rendered.
View: instantiate RandomizedActiveForm instead of ActiveForm, set fieldClass to your RandomizedActiveField, and pass model and honeypotFields.
Render honeypot fields with a hidden style to trap bots.
The randomized field names and mappings are stored in session with the unique session key.
Optional Fixes and Checks:
The $honeypots list must be consistent both in the controller and view.
The model may need to declare these honeypot attributes to avoid validation errors (eg. public properties or safe attributes).
Clear the randomized field map session on successful submissions if you want to avoid stale keys.
You can expand the placeholder array for honeypot fields if you want trickier placeholders.
If you apply this refactor, you should get the same randomization and honeypot protection behavior for the contact form as you have for the register example.
If you want, I can provide a sample update for your ContactForm model too, to declare honeypot fields properly, just let me know!
3. Clear The Randomized Field Map Session On Successful Submissions
Assuming you have access to the Randomizer instance in the controller (see your refactored controller), call:
php
// After successful model processing
$randomizer->getSession()->remove($randomizer->getSessionKey());
Full snippet in context:
php
if ($model->process()) {
// Clear session keys used for randomized field names
$randomizer->getSession()->remove($randomizer->getSessionKey());
AlertHelper::setFlash(
'success',
\Yii::t(
'app',
'<h4 class="alert-heading">Thank You</h4><p>Thank you for contacting us. We will respond to your inquiry as soon as possible.</p>'
),
5000
);
return $this->refresh();
}
4. Expand Placeholder Array for Honeypot Fields (Optional)
Add entries to placeholders for honeypot fields in the view when initiating the form:
php
$placeholders = [
'name' => \Yii::t('app', 'Enter Name'),
'email' => \Yii::t('app', 'Enter email'),
'subject' => \Yii::t('app', 'Enter subject'),
'body' => \Yii::t('app', 'Type your message here...'),
'verifyCode' => \Yii::t('app', 'Enter Security Code'),
// Honeypot placeholders: keep empty or misleading (to confuse bots)
'honeypot1' => '', // or e.g. 'Leave this blank'
'honeypot2' => '', // or e.g. 'Do not fill this'
];
$form = RandomizedActiveForm::begin([
// ...
'placeholders' => $placeholders,
]);
This way, when the randomized fields are rendered with JS placeholders, bots may see contradictory cues.
Summary
Example minimum additions:
Model ContactForm.php (partial):
php
public $honeypot1;
public $honeypot2;
public function rules()
{
return [
// your existing rules...
[['honeypot1', 'honeypot2'], 'safe'], // not validated, but accepted on input
];
}
Controller snippet to clear session:
php
if ($model->process()) {
$randomizer->getSession()->remove($randomizer->getSessionKey());
// flash message and redirect...
}
Make sure you use echo when outputting fields and submit button.
Make sure the form begin() and end() are correctly paired.
View files should have PHP tags <?php ?> or shorthand <?= ?> properly.
Step 2: Check fieldClass usage
Ensure you are passing 'fieldClass' => RandomizedActiveField::class exactly, and your RandomizedActiveField overrides input rendering correctly.
Step 3: Debug: test output
Temporarily inside your view, dump what fieldNameMap is:
php
<?php
var_dump($form->fieldNameMap);
?>
Check you have map entries as expected.
Step 4: Clean up old sessions
The large amount of randomMap_* entries in session likely comes from creating many randomized keys but never clearing them.
You may want to only use a persistent session key per user/form—not a new randomized key every page load.
How to fix session bloat:
In RandomizedActiveForm::init(), you generate:
php
if (empty($this->__sessionKey)) {
$this->__sessionKey = 'randomMap_' . \Yii::$app->security->generateRandomString(16);
}
This creates a new key for every form render, so session keeps growing.
Instead, assign a stable session key per form/user/request, e.g.:
Generate once and reuse, or
Use a fixed key like 'randomMap_contact'
Or store in the session the generated key and reuse it on subsequent requests.
Example fix: generate session key only once, reuse if exists in session:
php
public function init(): void
{
parent::init();
if (!isset($this->sessionManager)) {
$this->sessionManager = new SessionManager();
}
// Try to get existing key in session, else generate new
$sessionKeys = $this->sessionManager->getAllKeys(); // if your SessionManager supports this
$existingKeys = array_filter($sessionKeys, fn($k) => strpos($k, 'randomMap_') === 0);
if ($existingKeys) {
// Use first available key for consistency
$this->__sessionKey = reset($existingKeys);
} else {
$this->__sessionKey = 'randomMap_' . \Yii::$app->security->generateRandomString(16);
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap)) {
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
Alternatively, explicitly define a fixed session key like:
php
$this->__sessionKey = 'randomMap_contact';
This stops multiple keys piling up.
Step 5: Clear old session keys manually if needed
If you want to clear old keys manually during dev:
Use RandomizedActiveForm::begin() / end() properly to wrap fields.
Use consistent, fixed session key to avoid session clutter and stale mapping.
Dump or var_dump() to debug if $this->fieldNameMap is populated.
Confirm JS is registering and jQuery is loaded.
Clear old randomized session keys during dev to prevent bloat.
Ensure model attributes and honeypot fields exist and safe for form binding.
If you want, you can share your current contact view code again, and I can check if echo calls or form structure is correct. Or I can help you simplify to a minimal working example.
Check your model: Probably you have an attribute/property called emaill (maybe a honeypot field). This is normal.
Make sure your model declares that attribute and marks it safe as per your earlier question.
Summary
Your session map shows the keys are generated and available, so your form is wired correctly in terms of randomizer.
To fix "no form inputs shown," most common cause is:
Not echoing the form fields in the view!
Or form not wrapped in begin() and end().
Double-check your contact view to confirm this.
If you want, paste your full view form code here, I can review for the missing echo or other issues.
Notes:
If you want different forms on the same app with different keys, give each its own fixed key (e.g., 'randomMap_registerForm', 'randomMap_contactForm').
This eliminates the problem of old randomized maps accumulating over time.
You can clear any such keys during logout or with a manual cleanup.
Why avoid generating a random key every time?
Because every time the form is rendered it stores a new mapping in a new session key suffixed with random string, causing many keys littering session data.
If you want, you can additionally clear or remove the session key on successful submission using:
If $model->attributes is empty or undefined, then your randomized form generates no fields.
Confirm your model has attributes declared like this:
php
class ContactForm extends \yii\base\Model
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
public $emaill; // honeypot
// rules, attributeLabels, etc.
}
No stale session keys buildup because keys are stable.
Multiple forms (register, contact, etc.) do not overwrite each other.
You don't rely on a fixed constant string.
You keep your implementation generic and reusable.
If you want me to help refactor your RandomizedActiveForminit() method fully with this behavior or update your controller or view examples accordingly, just ask!
Hypothesis:
You have an extra closing brace '}' before the end of method, making PHP confused and thinking after method closing you have $this keyword or code.
Fix: Adjust braces and indent properly
Cleaned & corrected init() method:
php
public function init(): void
{
// Get cacheDuration from Param and set with TimeHelper
$cacheDuration = ParamHelper::get('widgets.cacheDuration');
$this->__cacheJsCssTime = TimeHelper::convertDurationToSeconds($cacheDuration);
// Cache & Compression
$this->__cacheEnable = ParamHelper::get('widgets.cacheEnable');
$this->__compressJsCss = ParamHelper::get('widgets.compressJsCss');
/**
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*/
parent::init();
if ($this->model === null)
{
throw new YiiBaseInvalidArgumentException(
'RandomizedActiveForm requires you to set the "model" property.'
);
}
// Initialize sessionManager internally if not set
if (!isset($this->sessionManager))
{
$this->sessionManager = new SessionManager();
}
// Use widget/form ID or fallback to class name + random string hash
if (empty($this->__sessionKey))
{
if (!empty($this->id))
{
$sessionSafeId = preg_replace('/[^a-z0-9_\-]/i', '_', strtolower($this->id));
$this->__sessionKey = 'randomMap_' . $sessionSafeId;
}
else
{
$randomPart = substr(\Yii::$app->security->generateRandomString(8), 0, 8);
$this->__sessionKey = 'randomMap_' . md5(static::class) . '_' . $randomPart;
}
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
// Combine model attributes and honeypots
$attributes = array_keys($this->model->attributes);
$logicalFields = array_merge($attributes, $this->honeypotFields);
// Retrieve existing field map or generate new randomized names
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap))
{
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
What to watch out for:
Remove any extra closing brace inside method.
Matching braces:
The first { after init(): void must have one matching } at method end.
Every if and else block also must have their {} pairs.
Indent carefully for readability.
If you still get the parse error, make sure:
The preceding or following lines in the class are not malformed.
There are no stray $this or other variables immediately after the class/method ends.
If you want, paste the full class code (or at least from class start until init() end) and I can check brace balancing for you.
Make sure:
All echo statements are there (no silent $form->field() without echo).
The view file does not have syntax errors.
No output buffering or filtering suppressing form output.
2. Check your RandomizedActiveField class inherits from yii\widgets\ActiveField
The class you posted looks correct, but please verify:
php
namespace app\widgets\randomizedForm;
use yii\widgets\ActiveField;
class RandomizedActiveField extends ActiveField
{
public array $fieldNameMap = [];
protected function applyRandomName(array $options): array
{
if ($this->fieldNameMap !== [] && isset($this->fieldNameMap[$this->attribute]))
{
$options['name'] = $this->fieldNameMap[$this->attribute];
}
return $options;
}
public function input(string $type, array $options = []): string
{
$options = $this->applyRandomName($options);
return parent::input($type, $options);
}
// similar overrides for checkbox, radio, etc.
}
If for some reason the input calls applyRandomName and does not call parent::input() returning empty string, that might mean the field is empty.
Try debug inside input():
php
public function input(string $type, array $options = []): string
{
$options = $this->applyRandomName($options);
$result = parent::input($type, $options);
\Yii::debug("RandomizedActiveField::input of type=$type returns: ".substr($result, 0, 30), __METHOD__);
return $result;
}
Check debug log for clues whether parent::input() produces content.
3. Check that your model's attributes property is accessible and correct
In Yii2 ActiveRecord or Model classes:
php
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
public $emaill; // honeypot
public function attributes()
{
return ['name', 'email', 'subject', 'body', 'verifyCode', 'emaill'];
}
which means it relies on $model->attributes being an array property in your model — this is only the case for ActiveRecord.
BUT in yii\base\Model (plain models), there is no $attributes property, but an attributes() method.
To get the attribute names of a plain model, you should do:
php
$attributes = $this->model->attributes(); // method call, returns list of properties
So, if your model extends yii\base\Model (not ActiveRecord), you should:
Change in your RandomizedActiveForm (or init()):
php
// Change this line:
$attributes = array_keys($this->model->attributes);
// TO this line:
$attributes = $this->model->attributes();
Summary:
Model type
Declare public props?
Override attributes()?
Get attributes names by
yii\db\ActiveRecord
No (auto from DB)
Optional (for virtuals)
$model->attributes (property)
yii\base\Model (form model)
Yes
Rarely needed
$model->attributes() (method)
Without adjusting this for plain yii\base\Model, your randomized form's code will fail to get attributes properly, generating empty or invalid field mappings, so no form fields appear.
Recommendation
Modify your form code to:
php
// Detect if model is ActiveRecord or base Model
if (method_exists($this->model, 'attributes')) {
$attributes = $this->model->attributes();
} elseif (property_exists($this->model, 'attributes')) {
$attributes = array_keys($this->model->attributes);
} else {
// fallback or error
$attributes = [];
}
Or if you know your app models are always yii\base\Model, just:
php
$attributes = $this->model->attributes();
If you want, I can help you patch your RandomizedActiveForm init method accordingly. Just ask!
1. Verify correct inheritance and imports in your RandomizedActiveField.php:
Make sure at top:
php
namespace app\widgets\randomizedForm;
use yii\widgets\ActiveField;
class RandomizedActiveField extends ActiveField
{
// ...
}
No accidental class naming conflicts.
parent::input() calls yii\widgets\ActiveField::input() which returns HTML string.
2. Avoid recursive call:
Check that inside your RandomizedActiveField::input() method you are NOT calling $this->input() or your own class method again.
You call parent::input(), so it must call the parent's input().
3. Add debugging to check the class of $result:
Temporarily modify:
php
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
$result = parent::input($type, $options);
if (!is_string($result)) {
\Yii::error('Expected string from parent::input() but got '. gettype($result) . ' ' . get_class($result), __METHOD__);
// For debugging, just output something safe, or cast to string (not recommended)
$output = is_object($result) ? get_class($result) : (string)$result;
\Yii::debug("RandomizedActiveField::input returns: " . $output, __METHOD__);
} else {
\Yii::debug("RandomizedActiveField::input returns: " . substr($result, 0, 30), __METHOD__);
}
return $result;
}
Check your application logs for the error message and class info.
4. As a quick workaround (not ideal), skip substr if not string:
php
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
$result = parent::input($type, $options);
if (is_string($result)) {
\Yii::debug("RandomizedActiveField::input returns: " . substr($result, 0, 30), __METHOD__);
} else {
\Yii::debug("RandomizedActiveField::input returned non-string of type: " . gettype($result), __METHOD__);
}
return $result;
}
Summary
Most likely, parent::input() is not returning a string as expected.
Fix your inheritance and imports to ensure parent::input() calls yii\widgets\ActiveField::input(), which returns HTML string.
Add logging to track the actual return type.
Avoid using substr() on non-string values.
If you want, paste your full RandomizedActiveField.php and your composer.json or autoload info so I can help spot possible class conflicts.
ActiveField
php
use yii\widgets\ActiveField;
Make sure you never import your own class inside itself.
If your class name and parent class are the same (typo or error), fix it.
Why this fix is critical?
If your class extends itself (or an alias to itself), parent::input() calls itself again, returning $this or the object, causing substr() error later.
Recap:
php
namespace app\widgets\randomizedForm;
use yii\widgets\ActiveField; // Must import yii's ActiveField as parent
class RandomizedActiveField extends ActiveField
{
// your methods here...
}
Also double check your RandomizedActiveForm uses RandomizedActiveField correctly
Your form:
php
'fieldClass' => RandomizedActiveField::class,
where RandomizedActiveField is the class above.
After fixing imports and extending yii\widgets\ActiveField you should see parent::input() returning a string (HTML).
If you want, paste your entire RandomizedActiveField.php here and I can do a sanity check.
Does ActiveField class have an input() method?
In standard Yii2 2.0+, yes it does, returning rendered input HTML:
You might want to call the more general methods or override other ones instead, like:
render() or
textInput(), passwordInput() etc.
Temporary fix: log the class of the parent of input method call
Change your method like this:
php
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
$parentClass = get_parent_class($this);
if (!method_exists($parentClass, 'input')) {
Yii::error("Parent class '$parentClass' has no method input()", __METHOD__);
// Optionally call a different method or throw
throw new \RuntimeException("Parent class '$parentClass' has no method input()");
}
$result = parent::input($type, $options);
if (!is_string($result)) {
\Yii::error("Expected string from parent::input() but got " . gettype($result) . " " . (is_object($result) ? get_class($result) : ''), __METHOD__);
} else {
\Yii::debug("RandomizedActiveField::input returns: " . substr($result, 0, 30), __METHOD__);
}
return $result;
}
Last notes:
If for some reason parent::input() doesn't work as expected, consider overriding the specific input types instead:
php
public function textInput($options = [])
{
$options = $this->applyRandomName($options);
return parent::textInput($options);
}
public function passwordInput($options = [])
{
$options = $this->applyRandomName($options);
return parent::passwordInput($options);
}
and so on, to avoid calling input().
Summary
Your namespace & inheritance look fine.
The error indicates parent::input() does NOT return string but the object itself — likely because parent::input() doesn't exist or is overridden somewhere, or your autoloader/config mistake.
Confirm yii\widgets\ActiveField in your Yii version has an input() method.
Add debug to confirm the parent class and if method exists.
If you want, share your composer dependencies (Yii version), and I can help you verify this.
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
return parent::input($type, $options);
}
No substr(), no debug string manipulation on the return.
How to debug then?
If you want to log the generated HTML, do it after the field renders, e.g.:
php
// in your view:
$field = $form->field($model, 'name')->textInput();
$html = (string) $field; // force render to string
\Yii::debug("Rendered field HTML: " . substr($html, 0, 100), __METHOD__);
echo $html;
To summarize:
Your original override doing substr($result, 0, 30) inside input() causes an error because $result is an object.
In Yii2, the string rendering of the field happens on __toString(), not on input().
Modify your override to simply:
php
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
return parent::input($type, $options);
}
And debug rendered output outside this method, after casting to string / rendering.
Let me know if you want help with a debug snippet or any other part!
6. Summary - what to do now
In your RandomizedActiveField class:
Remove any debug lines inside input() that treat the return value as string.
Debug actual rendered HTML outside the field methods by casting to string.
Your form fields will render fine once you do this.
namespace app\widgets\randomizedForm;
use yii\widgets\ActiveField;
class RandomizedActiveField extends ActiveField
{
public array $fieldNameMap = [];
protected function applyRandomName(array $options): array
{
if (!empty($this->fieldNameMap) && isset($this->fieldNameMap[$this->attribute])) {
$options['name'] = $this->fieldNameMap[$this->attribute];
}
return $options;
}
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
return parent::input($type, $options); // do NOT treat as string here
}
// Similar overrides for textInput(), passwordInput(), checkbox(), etc.
// just call input()/parent methods similarly after applying random name
}
I hope this clears it up! Feel free to ask if you want me to help check your view file or overall usage to confirm everything is wired correctly.
What this does:
For each field, it casts the field to string (forces render)
Logs the first 100 chars of HTML to your application log under context app\views\contact.php or wherever you include this view
Outputs the field normally so you see it on the page
Check after loading the page:
Your application logs (runtime/logs/app.log or wherever configured) will have entries like:
code
[2025-07-20 ...] [app\views\contact.php] Field 'name' HTML start: <div class="form-group field-contactform-name">...
Make sure they contain the expected HTML snippets, confirming rendering worked.
If you see the debug messages but no visible inputs on the page:
Check CSS/hiding,
Check form structure,
Or let me know for deeper investigation.
Hope this helps you pinpoint rendering issues!
Make sure route and method are correct.
4. Test very simple form rendering without randomized form
Create minimal form code in your view (replace complicated widget temporarily):
php
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
echo "<!-- DEBUG: Simple form demo -->";
$form = ActiveForm::begin(['id' => 'test-form']);
echo $form->field($model, 'name')->textInput();
echo Html::submitButton('Submit');
ActiveForm::end();
If this outputs the form and input field, problem is in your randomized form integration.
5. Make sure your randomized form and fields are correctly included and accessible
Verify autoloading:
Your files RandomizedActiveForm.php and RandomizedActiveField.php are properly namespaced and class-mapped.
If false, your class files are not loaded or autoloaded.
6. Check browser dev tools (Inspect Element)
Look for presence of <form> tag in DOM.
Any elements with display:none or visibility:hidden?
Any console JS errors (blocking rendering)?
7. Confirm your model & form setup is valid
$model passed to the view is not null and valid.
$model has declared public attributes.
Your form id is unique and does not conflict with other widgets.
Next steps — what I recommend now:
If you want, please share:
The full controller action actionContact code you’re using.
The full view file content you load.
Your Yii2 config/web.php logging component settings.
Then I can help debug why no output nor logs appear and why the form is missing.
Meanwhile, verify with the minimal plain ActiveForm example above so we isolate the problem is related to your randomized widget integration or more general application setup.
Yes, this will hide honeypot fields visually off-screen, so humans won’t see them, but bots may fill them.
Regarding JS placeholders:
The JS you posted is fine; it applies placeholders dynamically on randomized input names.
Your run() method looks okay:
php
public function run(): void
{
echo Html::hiddenInput('randomizedFormSessionKey', $this->__sessionKey);
if (!empty($this->placeholders)) {
$this->registerPlaceholderScript($this->placeholders);
}
parent::run();
}
This outputs a hidden input inside the form (just before closing). But it does not output any fields.
2. View page source and confirm form tag and fields are present.
3. Verify that the form tag and fields are NOT hidden via CSS or JS.
If after adding explicit echo the form still doesn’t show up in source, let me know and we can investigate the controller and layout.
Bottom line: Your JS and session setup are fine. The key issue is the form fields and form tag themselves are probably NOT output because fields are used without explicit echo.
Feel free to share your current full contact view and controller if you want me to double-check!
declare(strict_types=1);
namespace app\widgets\randomizedForm;
use Yii;
use yii\widgets\ActiveForm;
use yii\base\InvalidArgumentException as YiiBaseInvalidArgumentException;
use yii\web\View;
use yii\helpers\Html;
use yii\helpers\Json;
use app\components\SessionManager;
use app\components\interfaces\SessionInterface;
use app\components\traits\CacheJsCssTrait;
use app\widgets\randomizedForm\Randomizer;
use app\helpers\ParamHelper;
use app\helpers\TimeHelper;
/**
* RandomizedActiveForm overrides Yii2 ActiveForm to randomize all field names,
* store the mapping in session, and pass to fields.
*/
class RandomizedActiveForm extends ActiveForm
{
/**
* Placeholders keyed by logical attribute names.
* To be set by the view when starting the widget.
* @var array<string,string>
*/
public array $placeholders = [];
// @var array<string, string> Map of logical attribute => randomized name
public array $fieldNameMap = [];
// @var list<string> List of honeypot logical attribute names
public array $honeypotFields = [];
// @var object|null The form model
public ?object $model = null;
/**
* Session Manager Interface
* @see app\components\interfaces\SessionInterface.php
* @var SessionInterface
*/
public ?SessionInterface $sessionManager = null;
// @var Randomizer
protected Randomizer $__randomizer;
// @var string The session key to use
protected string $__sessionKey;
// Note: Every protected variable below CacheJsCssTrait is used by the trait
use CacheJsCssTrait;
protected bool $__cacheDebugMode = false;
protected bool $__compressJsCss = false;
protected bool $__cacheEnable = false;
protected int $__cacheJsCssTime = 3600;// +1 hour
protected string $__cacheKeyPrefix = 'widget_randomizedActiveForm';
const DEFAULT_DURATION_SECONDS = 3600;// +1 hour
public function init(): void
{
// Get cacheDuration from Param and set with TimeHelper
$cacheDuration = ParamHelper::get('widgets.cacheDuration');
$this->__cacheJsCssTime = TimeHelper::convertDurationToSeconds($cacheDuration);
// Cache & Compression
$this->__cacheEnable = ParamHelper::get('widgets.cacheEnable');
$this->__compressJsCss = ParamHelper::get('widgets.compressJsCss');
/**
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*/
parent::init();
if ($this->model === null)
{
throw new YiiBaseInvalidArgumentException(
'RandomizedActiveForm requires you to set the "model" property.'
);
}
// Initialize sessionManager internally if not set
if (!isset($this->sessionManager))
{
$this->sessionManager = new SessionManager();
}
// Use widget/form ID or fallback to class name + random string hash
if (empty($this->__sessionKey))
{
// Use form ID as part of session key—ensure safe chars by base64 or hash if needed
if (!empty($this->id))
{
$sessionSafeId = preg_replace('/[^a-z0-9_\-]/i', '_', strtolower($this->id));
$this->__sessionKey = 'randomMap_' . $sessionSafeId;
}
// Fallback: hash of class name + random string
else
{
$randomPart = substr(\Yii::$app->security->generateRandomString(8), 0, 8);
$this->__sessionKey = 'randomMap_' . md5(static::class) . '_' . $randomPart;
}
}
$this->__randomizer = new Randomizer($this->__sessionKey, $this->sessionManager);
// Get attributes to randomize
if (is_array($this->model->attributes ?? null))
{
$attributes = array_keys($this->model->attributes);
}
elseif (method_exists($this->model, 'attributes'))
{
$attributes = $this->model->attributes();
}
else
{
$attributes = [];
}
// Combine model attributes and honeypots
$logicalFields = array_merge($attributes, $this->honeypotFields);
// Retrieve existing field map or generate new randomized names
$this->fieldNameMap = $this->__randomizer->getMap();
if (empty($this->fieldNameMap))
{
$this->fieldNameMap = $this->__randomizer->generate($logicalFields);
}
}
public function run(): void
{
// Output hidden input with __sessionKey before form end tag
echo Html::hiddenInput('randomizedFormSessionKey', $this->__sessionKey);
// Register JS for dynamically applying placeholders if any provided
if (!empty($this->placeholders))
{
$this->registerPlaceholderScript($this->placeholders);
}
parent::run();
}
/**
* Register JS code to fill placeholders for randomized input names.
* @param array<string,string> $placeholders
* @return void
*/
private function registerPlaceholderScript(array $placeholders): void
{
if (empty($this->fieldNameMap) || empty($placeholders))
{
return;
}
$fieldMapJson = Json::htmlEncode($this->fieldNameMap);
$placeholdersJson = Json::htmlEncode($placeholders);
$uniqueId = uniqid('', false);// Create 13-char unique string based on time
$cacheKey = $this->__cacheKeyPrefix . $uniqueId . '_js_block_';
$jsBlock = $this->getCachedJsBlock($cacheKey, function () use (
$fieldMapJson,
$placeholdersJson
)
{
return <<<JS
(function(\$)
{
\$(function()
{
var map = $fieldMapJson;
var placeholders = $placeholdersJson;
Object.keys(map).forEach(function(logicalName)
{
var randomized = map[logicalName];
var el = document.querySelector('[name="' + randomized + '"]');
if (el && placeholders[logicalName])
{
el.setAttribute('placeholder', placeholders[logicalName]);
}
});
});
})(jQuery);
JS;
});
// Register the JavaScript.
$this->getView()->registerJs($jsBlock, View::POS_END);
}
/**
* Override ActiveForm::field() to pass randomized fieldNameMap to ActiveField
* @param object $model
* @param string $attribute
* @param array $options
* @return string|app\widgets\randomizedForm\RandomizedActiveField
*
* Note: Do NOT add parameter(s) type hints. This method overrides an interface
* without type hints on parameters, adding types will cause PHP compatibility errors.
* Only docblock types to indicate expected input types.
*/
public function field($model, $attribute, $options = [])
{
$options['fieldNameMap'] = $this->fieldNameMap;
return parent::field($model, $attribute, $options);
}
/**
* Get the Randomizer instance, for convenience
*/
public function getRandomizer()
{
return $this->__randomizer;
}
}
code
declare(strict_types=1);
namespace app\widgets\randomizedForm;
use Yii;
use yii\web\Request;
use app\components\SessionManager;
use app\components\interfaces\SessionInterface;
/**
* Core service that generates randomized field names,
* stores them in session via SessionInterface,
* maps POST data back,
* and checks honeypot fields.
*/
class Randomizer
{
/**
* Session Manager Interface
* @see app\components\interfaces\SessionInterface.php
* @var SessionInterface
*/
protected SessionInterface $__session;
// @var string The session key to use
protected string $__sessionKey;
// @var array<string,string>
protected array $__fieldMap = [];
/**
* Construct
* @param string $sessionKey
* @param SessionInterface|null $session Allows internal creation if null.
*/
public function __construct(string $sessionKey, ?SessionInterface $session = null)
{
$this->__sessionKey = $sessionKey;
$this->__session = $session ?? new SessionManager();
}
/**
* Generate random string identifiers for given field list,
* store in session and return the map.
* @param list<string> $fields
*
* @return array<string,string> map logical field to randomized string
*/
public function generate(array $fields): array
{
$map = [];
foreach ($fields as $field)
{
$map[$field] = $this->generateRandomString();
}
$this->__fieldMap = $map;
$this->__session->set($this->__sessionKey, $map);
return $map;
}
/**
* Retrieve the map from session or return empty array
* @return array<string,string>
*/
public function getMap(): array
{
if (empty($this->__fieldMap))
{
$stored = $this->__session->get($this->__sessionKey);
$this->__fieldMap = is_array($stored) ? $stored : [];
}
return $this->__fieldMap;
}
/**
* Reverse-map submitted POST data keys to logical attribute names.
* @param array<string,mixed> $postData
* @return array<string,mixed> mapped data in logical keys.
*/
public function mapPostData(array $postData): array
{
$map = $this->getMap();
$reverseMap = array_flip($map);
$mapped = [];
foreach ($postData as $postKey => $value)
{
if (isset($reverseMap[$postKey]))
{
$mapped[$reverseMap[$postKey]] = $value;
}
}
return $mapped;
}
/**
* Check whether any honeypot fields are filled.
* @param array<string,mixed> $mappedData
* @param list<string> $honeypotFields
* @return bool True if any honeypot field is filled, false otherwise.
*/
public function honeypotFilled(array $mappedData, array $honeypotFields): bool
{
foreach ($honeypotFields as $honeypot)
{
if (!empty($mappedData[$honeypot]))
{
return true;
}
}
return false;
}
/**
* Generate a random alphanumeric string
* @param int $length
* @return string
*/
protected function generateRandomString(int $length = 10): string
{
return substr(str_shuffle(str_repeat('abcdefghijklmnopqrstuvwxyz0123456789', $length)), 0, $length);
}
/**
* Instantiate Randomizer using session key from POST request,
* fallback to default key, creates SessionManager internally if not passed.
* @param SessionInterface|null $session Optional session manager.
* @param Request|null $request Optional request object.
* @return self
*/
public static function fromRequest(?SessionInterface $session = null, ?Request $request = null): self
{
$request = $request ?? \Yii::$app->request;
$sessionKey = (string) $request->post('randomizedFormSessionKey', 'randomizedActiveFormFieldMap');
return new self($sessionKey, $session);
}
/**
* Get the session key currently used
*/
public function getSessionKey(): string
{
return $this->__sessionKey;
}
/**
* Get access to session interface
*
public function getSession(): SessionInterface
{
return $this->__session;
}//*/
}
code
declare(strict_types=1);
namespace app\widgets\randomizedForm;
use Yii;
use yii\widgets\ActiveField;
/**
* RandomizedActiveField overrides Yii2 ActiveField to render inputs with
* randomized 'name' attributes using the fieldNameMap populated by
* RandomizedActiveForm.
*/
class RandomizedActiveField extends ActiveField
{
// @var array randomized map of attribute => randomized name
public array $fieldNameMap = [];
/**
* Internal helper to override the 'name' attribute if randomized
* @param array<string,mixed> $options
* @return array<string,mixed>
*/
protected function applyRandomName(array $options): array
{
if ($this->fieldNameMap !== [] && isset($this->fieldNameMap[$this->attribute]))
{
$options['name'] = $this->fieldNameMap[$this->attribute];
}
return $options;
}
/**
* @inheritDoc
*
* Note: Do NOT add parameter(s) type hints. This method overrides an interface
* without type hints on parameters, adding types will cause PHP compatibility errors.
* Only docblock types to indicate expected input types.
*/
public function input($type, $options = [])
{
$options = $this->applyRandomName($options);
return parent::input($type, $options);
}
/**
* @inheritDoc
*/
public function textInput($options = [])
{
return $this->input('text', $options);
}
/**
* @inheritDoc
*/
public function passwordInput($options = [])
{
return $this->input('password', $options);
}
/**
* @inheritDoc
*/
public function hiddenInput($options = [])
{
return $this->input('hidden', $options);
}
/**
* @inheritDoc
*/
public function checkbox($options = [], $enclosedByLabel = true)
{
$options = $this->applyRandomName($options);
return parent::checkbox($options);
}
/**
* @inheritDoc
*/
public function checkboxList($items, $options = [])
{
$options = $this->applyRandomName($options);
return parent::checkboxList($items, $options);
}
/**
* @inheritDoc
*/
public function radio($options = [], $enclosedByLabel = true)
{
$options = $this->applyRandomName($options);
return parent::radio($options);
}
/**
* @inheritDoc
*/
public function radioList($items, $options = [])
{
$options = $this->applyRandomName($options);
return parent::radioList($items, $options);
}
/**
* @inheritDoc
*/
public function dropDownList($items, $options = [])
{
$options = $this->applyRandomName($options);
return parent::dropDownList($items, $options);
}
/**
* @inheritDoc
*/
public function listBox($items, $options = [])
{
$options = $this->applyRandomName($options);
return parent::listBox($items, $options);
}
/**
* @inheritDoc
*/
public function fileInput($options = [])
{
$options = $this->applyRandomName($options);
return parent::fileInput($options);
}
/**
* @inheritDoc
*/
public function textarea($options = [])
{
$options = $this->applyRandomName($options);
return parent::textarea($options);
}
/**
* @inheritDoc
*/
public function urlInput($options = [])
{
return $this->input('url', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function emailInput($options = [])
{
return $this->input('email', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function numberInput($options = [])
{
return $this->input('number', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function rangeInput($options = [])
{
return $this->input('range', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function telInput($options = [])
{
return $this->input('tel', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function timeInput($options = [])
{
return $this->input('time', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function dateInput($options = [])
{
return $this->input('date', $this->applyRandomName($options));
}
/**
* @inheritDoc
*/
public function datetimeInput($options = [])
{
return $this->input('datetime-local', $this->applyRandomName($options));
}
}
code
public function actionContact(string $subject = null): Response|string
{
// Set Page title for the browser tab/page title and page header.
$pageTitle = \Yii::t('app', 'contact us');
// Set Meta Data for website title, keywords, description and prepend site name(bool).
$this->setMeta($pageTitle, 'contact, contact us');
// Set page breadcrumbs. (optional)
//\Yii::$app->layoutManager->addBreadcrumb($pageTitle);// page now.
// Setup $model
if ($this->_isGuest)
{
$model = new ContactForm();
$model->subject = $subject ?? '';
}
else
{
$user = RoleHelper::userIdentity();
$model = new ContactForm();
if (!$user)
{
// Firstname, lastname and email are all required feilds
$model->name = $user->firstname . ' ' . $user->lastname;
$model->email = $user->email;
$model->subject = $subject ?? '';
}
else
{
$model->subject = $subject ?? '';
}
}
// define your honeypot fields here as in your widget
$honeypots = ['emaill'];
$request = \Yii::$app->request;
if ($request->isPost)
//if (($request->isPost) && ($model->load($request->post()) && $model->validate()))
{
// Instantiate Randomizer via POST data's randomizedFormSessionKey or default
$randomizer = Randomizer::fromRequest();
$post = $request->post();
$mappedData = $randomizer->mapPostData($post);
// Check honeypots
if ($randomizer->honeypotFilled($mappedData, $honeypots))
{
\Yii::$app->session->setFlash('error', 'Bot activity detected.');
// TODO add bot logging here...
return $this->refresh();
}
if ($model->load($mappedData, '') && $model->validate())
{
if ($model->process())
{
// Optionally clear the randomized field map from session after successful submission
$randomizer->getSession()->remove($randomizer->getSessionKey());
AlertHelper::setFlash(
'success',
\Yii::t(
'app',
'<h4 class="alert-heading">Thank You</h4>
<p>Thank you for contacting us. We will respond to your inquiry as soon as possible.</p>'
),
5000
);
// Handle the POST-Redirect-GET pattern.
return $this->refresh();
}
else
{
AlertHelper::setFlash('error', ErrorMessageHelper::processingError(), 8000);
}
}
}
// Re-rendered regardless of whether there was an error or if the form validation failed.
return $this->render('contact', [
//'pageTitle' => $pageTitle,
'model' => $model,
'honeypotFields' => $honeypots
]);
}