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 List of honeypot logical attribute names
public array $honeypotFields = [];
// @var object|null The form model
public ?object $model = null;
public function init(): void
{
// Get cacheDuration from Param and set with TimeHelper
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);
code
// 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;
}
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 bool True if any honeypot field is filled, false otherwise.
*/
public function honeypotFilled(array mappedData,arrayhoneypotFields): bool
{
foreach (honeypotFhoneypot)
{
if (!empty(honeypot]))
{
return true;
}
}
@return self
*/
public static function fromRequest(?SessionInterface session=null,?Requestrequest = null): self
{
request ?? \Yii::sessionKey = (string) $request->post('randomizedFormSessionKey', 'randomizedActiveFormFieldMap');
/**
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;
}//*/
}
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));
}
}
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::apageTitle);// page now.
code
// 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
]);
}
code
Refresh the browser and View Source to verify it shows.
2. Output buffering / echo missing somewhere
Your form fields are cast and echoed correctly, but still no markup?
code
Make sure the PHP template engine (e.g. if you use renderAjax() or layouts) outputs content.
Make sure no ob_start() or flush issues supress output.
3. Layout or main template issues
If your layout is missing or swallows output, nothing appears.
Check you have in your layout file:
Check for PHP errors/warnings suppressed or hidden
Check server error logs.
Temporarily enable error display with:
At top of entry script.
Sometimes fatal errors prevent output but no visible message.
5. Verify $model attributes and validation
You have model public properties — good.
Try:
var_dump($model->attributes());
in controller or view to verify attributes list is not empty.
6. Browser Inspect / View Source comparison
code
View source in browser (Ctrl+U) — do you see <form id="contact-form"?
Use devtools to check for form in DOM even if empty or hidden.
7. Confirm CSS / JS do not hide form or remove it
code
Check CSS rules affecting form or .form-group
Check console for JS errors causing form scripts to fail.
Next Debug Step
Try minimal test — replace your view content temporarily with this:
code
The full view file path and confirm if that matches the edited file
I can help pinpoint where the output is swallowed/missing.
code
View code output suppression
Make sure the view file is the file actually rendered by your controller action.
Add a unique comment or echo at the top, like:
'; ?>
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
Let's simplify your view to the minimal version, to isolate and verify that output is rendered and visible on the page source:
We removed the helper function and Yii::error logging to keep the output simpler.
We added HTML comments <!-- DEBUG Contact form view loaded --> and <!-- Contact form rendered --> around the form, so in browser View Source you can confirm if the view file is rendered at all.
If these comments do NOT appear in browser source:
You are rendering a different view file or output is blocked.
Missing <?= $content ?> in layout.
If the comments appear but the form fields still do not:
Suspect CSS hiding or faulty widget integration.
Also view the browser Developer Tools Elements tab to see if form elements exist but hidden.
You can then gradually restore logging, separate honeypots, and other features one by one to isolate.
If even this minimal view produces no visible HTML output, check:
Your controller action calls correct view file with render() or renderPartial() properly.
Layout files include <?= $content ?> and beginBody()/endBody().
No PHP fatal errors before or during rendering (check server error logs).
No output buffering or flush issues suppressing output.
$model passed to view is not null and has attributes.
If you'd like, you can share your controller render call and layout snippet and I can help audit those next.