Hi,
I was wondering what the correct, or more appropriate way of adding widgets to a web application is through Phalcon. For example, I have a simple widget next to the logo that allows an admin to change what company they are in through a select box. My current code is as follows:
Adding it to the library seems silly. Is it possible to create a widgets directory in the app folder, stick all of the widget classes there, and have a folder called widgets in the views directory?
use Mac\CompanyChanger\CompanyChanger;
/**
* Elements component
*/
$di->set('companyChanger', function(){
return new CompanyChanger();
});
<?php
namespace Mac\CompanyChanger;
use Phalcon\Mvc\User\Component,
Phalcon\Forms\Form,
Phalcon\Forms\Element\Select,
Phalcon\Forms\Element\Hidden,
Phalcon\Forms\Element\Submit,
Phalcon\Validation\Validator\Identical;
/**
* Mac\Elements\CompanyChanger
*
* Helps build the company menu changer next to the logo
*/
class CompanyChanger extends Component
{
protected $_compCount;
protected $_companies;
protected $_keyfob;
protected $_userCompany;
public function __construct()
{
//Cached APC key for companies
$this->_keyFob = 'companies' . $this->user->id;
//Companies count
$this->_compCount = $this->modelsCache->get($this->_keyFob)->count();
//Companies array
$this->_companies = $this->modelsCache->get($this->_keyFob);
foreach($this->_companies as $company) {
$storeTemp[$company->companies->getCompanyId()] = $company->companies->getCompanyName();
}
$this->_companies = $storeTemp;
$this->_keyFob = 'userData' . $this->user->id;
//Grab user company
$this->_userCompany = $this->modelsCache->get($this->_keyFob)->company->getCompanyName();
}
public function render()
{
$this->view->form = $this->getForm();
$this->view->partial('layouts/CompanyChanger', array('compCount' => $this->_compCount, 'companies' => $this->_companies, 'userCompany' => $this->_userCompany));
}
protected function getForm()
{
$form = new Form();
//company
$company = new Select('company', $this->_companies);
$form->add($company);
//CSRF
$csrf = new Hidden('csrf');
$csrf->addValidator(
new Identical(array(
'value' => $this->security->getSessionToken(),
'message' => 'CSRF validation failed'
))
);
$form->add($csrf);
$form->add(new Submit('Change', array(
'class' => 'btn btn-success'
)));
return $form;
}
}
{% if compCount > 1 %}
<form id="application_name" method="post">
<div id="application-name-select">
<span id="applcation-text">Working with</span>
<div id="company-name2">
<span id="company-name-link">{{ userCompany }}</span>
</div>
<div id="company-select">
{{ form.render('company') }}
</div>
</div>
{{ form.render('csrf', ['value': security.getToken()]) }}
<div id="company-submit">
{{ form.render('Change') }}
</div>
</form>
{% else %}
<p id="application_name">Working with {{ userCompany }}</p>
{% endif %}