I need to set conditions to fields of left joined table.
So I need to know:
Is this table has been left joined?
If so, what alias of leftjoined table to use to add new condition.
Here current code example:
class PStudentFormFilter extends BasePStudentFormFilter
{
public function configure()
{
$this->setWidget('name', new sfWidgetFormInput());
$this->setWidget('phone', new sfWidgetFormInput());
$this->setValidator('name', new sfValidatorPass(array('required' => false)));
$this->setValidator('phone', new sfValidatorPass(array('required' => false)));
}
private function leftJoinPersonalInfoQuery(Doctrine_Query $query)
{
if (isset($this->__leftJoinPersonalInfoQuery)) return;
$this->__leftJoinPersonalInfoQuery = true;
$query->leftJoin($query->getRootAlias().'.PersonalInfo pi');
}
public function addNameColumnQuery(Doctrine_Query $query, $field, $value)
{
$value = trim($value['text']);
if (!$value)
{
return;
}
$value = str_replace(' ', '%', $value);
$this->leftJoinPersonalInfoQuery($query);
$query->andWhere("CONCAT(pi.surname, ' ', pi.first_name, ' ', pi.patronymic) LIKE ?", "%$value%");
}
public function addPhoneColumnQuery(Doctrine_Query $query, $field, $value)
{
$value = trim($value['text']);
if (!$value)
{
return;
}
$value = str_replace(' ', '%', $value);
$this->leftJoinPersonalInfoQuery($query);
$query->andWhere("pi.mobile_phone LIKE ?", "%$value%");
}
}
You could try to analyse the return value of $query->getDqlPart('from') to get this to work.
Related
I have this error after this code to :
This result is a forward only result set, calling rewind() after moving forward is not supported.
Page.phtml :
foreach ($company as $key => $value)
{
foreach ($userfeature as $key => $data)
{
echo "<tr>";
if($value->site_id == $data->site_id)
{
echo "<td>".$value->party_code." ".$value->party_name. "</td>";
}
}
}
Controller.php
public function indexsiteuserAction()
{
$this->layout('layout/admin');
$compteAdmin[] = $this->admincompte();
$user_id = (int) $this->params()->fromRoute('id', 0);
if (!$user_id)
{
return $this->redirect()->toRoute('administrateur', array('action' => 'adduser'));
}
try
{
$user = $this->getUserTable()->getUser($user_id);
$userfeature = $this->getAdminUserFeatureTable()->afficheruserFeature($user_id);
}
catch (\Exception $ex)
{
return $this->redirect()->toRoute('administrateur', array('action' => 'indexuser'));
}
return new ViewModel(
array(
'user_id' => $user_id,
'user'=> $user,
'userfeature' => $userfeature,
'compteAdmin' => $compteAdmin,
'company' => $this->getCompanyTable()->fetchAll(),
));
}
Userfeaturetable.php
public function getUserFeature($user_id)
{
$user_id = (int) $user_id;
$rowset = $this->tableGateway->select(array('user_id' => $user_id));
$row = $rowset->current();
if (!$row)
{
throw new \Exception("Could not find row $user_id");
}
return $row;
}
companyTable.php
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet ;
}
Why do not I have the right to embed my two ' foreach ()' ?
Your need to buffer the result.
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
$resultSet->buffer();
return $resultSet ;
}
How can I setup default for Text element in ZF2 Forms?
I tried the following:
In the view file. This does not get to data, and is not saved:
if($form->get('agencyName')->getValue() === '')
$form->get('agencyName')->setValue('Virtual Field Practicum');
This affects neither view, nor DB:
$this->add(array(
'name' => 'agencyName',
'options' => array(
'label' => 'Agency Name',
),
'attributes' => array(
'disabled' => 'disabled',
'value' => 'Virtual Field Practicum',
)
));
I also tried to modify entity in two ways, but it did not affect anything:
public function __construct()
{
//set default agency name
$this->agencyName = 'Virtual Field Practicum';
}
OR:
public function setAgencyName($agencyName)
{
if ($agencyName === '')
$this->agencyName = 'Virtual Field Practicum';
else
$this->agencyName = $agencyName;
return $this;
}
Edit 1
Adding my generic actions to the post:
1) This one is responsible to load the forms, and process non-ajax calls:
public function editTabAction()
{
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
// Get your ObjectManager from the ServiceManager
$objectManager = $this->getEntityManager();
// get from from FormElementManager plugin
//forms are defined in Module.php
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$form->setObject($this->getEntityInstanceFromBuildName($buildName));
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$request = $this->getRequest();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->savetodb($form->getData(), $buildName);
// Redirect to list of forms
return false;
} else {
foreach ($form->getMessages() as $messageId => $message) {
echo '<pre>';
echo "Validation failure '$messageId':";
print_r($message);
echo '</pre>';
}
}
}
$view = new ViewModel(array(
'studEvalId' => $studEvalId,
'buildName' => $buildName,
'form' => $form,
));
$view->setTemplate('online-field-evaluation/tabs/edit' . $buildName . '.phtml');
return $view;
}
2) This one is responsible for ajax calls:
public function validatepostajaxAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$buildName = $this->params()->fromRoute('buildName', 'unknown');
if ($buildName == 'unknown') {
$buildName = $this->params()->fromPost('buildName', 'unknown');
if ($buildName == 'unknown') {
trigger_error('Could not retrieve build name for ' . $buildName . ' entity for this form!');
}
}
//extract parameter from dispatch command
$studEvalId = (int)$this->params()->fromRoute('studEvalId', 0);
if ($studEvalId == 0) {
//extract parameter from the form submission
$studEvalId = (int)$this->params()->fromPost('studEvalId', 0);
if ($studEvalId == 0) {
return $this->notFoundAction();
}
}
$data = $this->getEntity($buildName, $studEvalId);
$objectManager = $this->getEntityManager();
$formName = $buildName . "Form";
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get($formName);
$form->setHydrator(new DoctrineHydrator($objectManager ));
$entityName = 'OnlineFieldEvaluation\Entity\\' . $buildName;
$form->setObject(new $entityName());
$form->bind($data);
//set class and Id for buttons like SaveChanges to reference it
$form->setAttribute('class', "studentFormsClass_$studEvalId");
$form->setAttribute('id', "studentFormsId_$studEvalId" . "_$buildName");
//set buildName to the form
$form->get('buildName')->setAttribute('value', $buildName);
$messages = array();
if ($request->isPost()) {
$formValidatorName = "OnlineFieldEvaluation\Form\\" . $buildName . "FormValidator";
$formValidator = new $formValidatorName();
$form->setInputFilter($formValidator->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
$errors = $form->getMessages();
foreach ($errors as $key => $row) {
if (!empty($row) && $key != 'submit') {
foreach ($row as $keyer => $rower) {
//save error(s) per-element that
//needed by Javascript
$messages[$key][] = $rower;
}
}
}
}
if (!empty($messages)) {
$response->setContent(
\Zend\Json\Json::encode(
array('status' => 'error',
'messages' => (array) $messages,
'buildName' => $buildName,
'studEvalId' => $studEvalId
)));
} else {
//save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span>
$this->savetodb($form->getData(), $buildName);
$response->setContent(
\Zend\Json\Json::encode(
array(
'status' => 'success',
'messages' => 'Successfuly saved.',
'buildName' => $buildName,
'studEvalId' => $studEvalId
)
));
}
}
return $response;
}
To setup a default value for an element, simply do the following:
Open controller's action, that renders desired view
Instantiate a form, get the element by its name and do call setValue() on that
That looks like as following:
public function addAction()
{
$form = new YourAgencyForm();
$form->get('agencyName')->setValue('Virtual Field Practicum');
....
It's really that simple
How am I able to access Zend\db\Adapter from within my controller plugin Controller\Plugin\MyPlugins?
I would like to execute
$this->getServiceLocator()
->getServiceLocator()
->get('Zend\Db\Adapter\Adapter')
->query("Select * from ABC ")
From within the plugin you can access the controller (providing it extends Zend\Mvc\Controller\Plugin\AbstractPlugin), and therefore the service manager, using:
$this->getController()->getServiceLocator();
However accessing the service manager to fetch the plugin dependency (the adapter) from within the plugin is very bad practice.
A much better solution would be to 'inject' the adapter using a service factory.
use MyModule\Mvc\Controller\Plugin\MyPlugin;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
class MyPluginFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $pluginManager)
{
$serviceManager = $pluginManager->getServiceLocator();
return new MyPlugin(
$serviceManager->get('My/Db/Adapter') // inject db adapter
);
}
}
Modify the plugin's __construct to allow the adapter in
class MyPlugin extends AbstractPlugin
{
protected $dbAdapter;
public function __construct(Adapter $dbAdapter)
{
$this->dbAdapter = $dbAdapter;
}
//...
}
Lastly register it as a controller plugin in Module.php (or in module.config.php)
// Module.php
public function getControllerPluginConfig()
{
return array(
'factories' => array(
'MyPlugin' => 'MyModule\Mvc\Controller\Plugin\MyPluginFactory'
),
);
}
Here is my code snippets
inside the controller path "modules/Admin/Controller/AreaController.php"
public function arealistAction() {
$Search = new Plugin\SearchBox(); //calling the searchbox class
$Search->setButtons('Operator', 'query', 'Select id,name as text from Operator where Status=1 ');
//passing parameter for searchbox
$box = $Search->renderSearchBox();
}
The below code for SearchBox at "modules/Admin/Controller/Plugin/SearchBox.php"
namespace Admin\Controller\Plugin;
class SearchBox extends \Zend\Mvc\Controller\Plugin\AbstractPlugin {
protected $RawSearch = array();
//Get the user data
public function setButtons($label, $opt, $dbcols, $values = "") {
$this->$RawSearch = array(
'label' => $label,
'opt' => $opt,
'values' => $values,
'dbcols' => $dbcols,
);
}
//Process the search value
public function ProcessSearchValue($val) {
switch ($val['opt']) {
case 'date':
case 'text':
$vHtml = '<input type="text" name="' . $val['dbcols'] . '" id="' . $val['dbcols'] . '">';
break;
case 'query':
$dbadpater = $this->getController()->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$Statement = $dbadpater->query($val['values']);
$results = $Statement->execute();
$vHtml = '<select name="' . $val['dbcols'] . '" id="' . $val['dbcols'] . '">';
if (!empty($results)) {
foreach ($results as $rkey => $rval) {
$vHtml .='<option value="' . $rval['id'] . '">' . $rval['text'] . '</option>';
}
}
$vHtml .='</select>';
break;
}
return $vHtml;
}
public function ProcessOptValue($val) {
$oHtml = '<select name="' . $val['dbcols'] . '" id="' . $val['dbcols'] . '">';
$oHtml .='<option value="eq">Equal</option>';
switch ($val['opt']) {
case 'date':
break;
case 'text':
$oHtml .='<option value="cnt">Contain</option>';
$oHtml .='<option value="ncnt">Not Contain</option>';
break;
case 'query':
$oHtml .='<option value="lth">Less Than</option>';
$oHtml .='<option value="gth">Greater Than</option>';
$oHtml .='<option value="leq">Less than Equal</option>';
$oHtml .='<option value="geq">Greater than Equal</option>';
break;
}
$oHtml .= '</select>';
return $oHtml;
}
public function renderSearchBox() {
if (!empty($this->RawSearch)) {
$Sbox = '<table cellspacing="0px" cellpadding="0px">';
foreach ($this->RawSearch as $key => $val) {
$Sbox.= '<tr>'
. '<td><label>'.$val['label'].'</label></td>'
. '<td>'.$this->ProcessOptValue($val).'</td>'
. '<td>'.$this->ProcessSearchValue($val).'</td>'
. '</tr>';
}
$Sbox.='</table>';
}
return $Sbox;
}
}
Now when i execute the statement "$box = $Search->renderSearchBox();" it give me the error.
I am not able to execute the query inside the plugins.
I want my form fields to contain the previous data contained in database when the form page opens. I went through lots of queries here and came to know using populate() or bind() method is the way to do it. But when I try to use it, I get an undefined method error.
Is there any other way to do it?
I am unable to use bind() as well. I am getting a fresh form with default values after I submit.
Sorry if this is a stupid question. Its been only 4-5 days since I started learning Zend framework. Also, most of the methods I get online are for older frameworks. I am using Zend Framework2.
This is Controller Code
<?php
class ChatController extends AbstractActionController
{
protected $chatTable;
public function indexAction()
{
$form = new ChatForm();
$model= new Chat();
$form->bind($model);
$form->get('submit')->setValue('Save');
$request = $this->getRequest();
if ($request->isPost()) {
$gen_set = new Chat();
$form->setInputFilter($gen_set->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$gen_set->exchangeArray($form->getData());
$this->getChatTable()->saveChat($gen_set);
// Redirect to list of albums
return $this->redirect()->toRoute('chat');
}
}
return array('form' => $form);
}
public function getChatTable()
{
if (!$this->chatTable) {
$sm = $this->getServiceLocator();
$this->chatTable = $sm->get('Chat\Model\ChatTable');
}
return $this->chatTable;
}
}
My Entity Class, Here api_key and anon_prefix are rows of the column 'settings' and there is one more column with value.
<?php
class Chat implements InputFilterAwareInterface
{
protected $inputFilter;
public function exchangeArray($data)
{
$this->api_key=(isset($data['api_key'])) ? $data['api_key'] : null;
$this->anon_prefix = (isset($data['anon_prefix'])) ? $data['anon_prefix'] : null;
}
// Add content to these methods:
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'iflychat_external_api_key',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
));
$inputFilter->add(array(
'name' => 'iflychat_show_admin_list',
'required' => true,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => array(1,2),
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
This is used to enter values into db
<?php
class ChatTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function saveChat(Chat $gen_set)
{
$data = array(
'value' => $gen_set->api_key,
);
$id='iflychat_external_api_key';
$this->tableGateway->update($data,array('settings' => $id));
$data = array(
'value' => $gen_set->anon_prefix,
);
$id='anon_prefix';
$this->tableGateway->update($data,array('settings' => $id));
}
}
I am getting this error, 'Cannot use object of type Chat\Model\Chat as array'
Your action doesn't make much sense as it is, you instantiate a Chat instance as $model and later another instance as $gen_set. What you should be doing is binding the first one, and using the form class getData method to later return the instance you bound to it, along with the values you gave it in the setData method. There's no need for any transformations from object to array and back again.
Here's how it should look ...
public function indexAction()
{
$form = new ChatForm();
// bind the model
$model= new Chat();
$form->bind($model);
$form->get('submit')->setValue('Save');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($gen_set->getInputFilter());
// set data from POST as properties of the bound model ...
$form->setData($request->getPost());
if ($form->isValid()) {
// get the bound model instance with the POSTed values
// ($gen_set is now the original $model object instance bound above)
$gen_set = $form->getData();
// and save it
$this->getChatTable()->saveChat($gen_set);
// Redirect to list of albums
return $this->redirect()->toRoute('chat');
}
}
return array('form' => $form);
}
Controller Code -
<?php
class ChatController extends AbstractActionController {
protected $chatTable;
public function indexAction() {
$model = $this->getChatTable()->fetchLastChat();
if($model === null || $model->count() == 0)
$model = new Chat();
//Now if no record exists in the database then $model will be empty
//Else $model will contain data of last record.
$form = new ChatForm();
$form->bind($model);
$form->get('submit')->setValue('Save');
$request = $this->getRequest();
if ($request->isPost()) {
$gen_set = new Chat();
$form->setInputFilter($gen_set->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$gen_set->exchangeArray($form->getData());
$this->getChatTable()->saveChat($gen_set);
}
}
return array('form' => $form);
}
public function getChatTable() {
if (!$this->chatTable) {
$sm = $this->getServiceLocator();
$this->chatTable = $sm->get('Chat\Model\ChatTable');
}
return $this->chatTable;
}
}
ChatTable Class Code -
<?php
//Other use statements
use Zend\Db\Sql\Select;
class ChatTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function fetchLastChat() {
$select = new Select('TABLE_NAME'); //Change the tablename accordingly
$select->order('PRIMARY_KEY DESC'); //Set the Primary Key of the table
$select->limit(1);
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet->current();
}
//Rest of the Code ....
Please take the idea from the above code.
I use symfony 1.4.11 .I have next component class:
class companiesComponents extends sfComponents {
public function executeCompanylist(sfWebRequest $request) {
// And the URL
if (!isset($this->url)) {
throw new Exception('Please specify the URL');
}
// Save the page
if ($request->getParameter('page')) {
$this->setPage($request->getParameter('page'));
}
// Create pager
$this->pager = new sfDoctrinePager('Companies', sfConfig::get('app_ads_per_page', 5));
$this->pager->setQuery($this->query);
$this->pager->setPage($this->getPage());
$this->pager->init();
}
protected function getPager($query) {
$pager = new Doctrine_Pager($query, $this->getPage(), 3);
return $pager;
}
protected function setPage($page) {
$this->getUser()->setAttribute('users.page', $page, 'admin_module');
}
protected function getPage() {
return $this->getUser()->getAttribute('users.page', 1, 'admin_module');
}
I have action:
public function executeAll(sfWebRequest $request)
{
$this->query = Doctrine_Core::getTable('Companies')->getAllCompany();
$this->url = '#companylist';
}
And I have allSucess.php
<?php include_component('companies', 'companylist', array(
'query' => $query,
'url' => $url,
'noneFound' => __('You haven\'t created any ads yet.')
)) ?>
In my Companies Table class
public function getAllCompany()
{
$q = $this->createQuery('a')
->andWhere('a.active = ?',1)
->leftJoin('a.Owner o')
->leftJoin('o.Profile p')
->andWhere('p.payed_until > NOW()')
->addORDERBY ('created_at DESC');
}
And it is do not work. I get all my record "companies" from database,but they are not selected according to the my query...
When I make
public function getAllCompany()
{
}
or when I comment
// $this->pager->setQuery($this->query);
I still get all my records :(
In logs I see :
Template: companies … allSuccess.php
Parameters:
$query (NULL)
$url (string)
When I make
public function getAllCompany()
{
$q = $this->createQuery('a')
->andWhere('a.active = ?',1)
->leftJoin('a.Owner o')
->leftJoin('o.Profile p')
->andWhere('p.payed_until > NOW()')
->addORDERBY ('created_at DESC');
return $q->execute();
}
I have error:
Fatal error: Call to undefined method Doctrine_Collection::offset()
I do not understand how it get all records, and where I made mistake :(
Thank you!
remove the ->execute(); text from the return statement in the getAllCompany() function ... the DoctrinePager executes the statement - you don't need to ...
public function getAllCompany()
{
$q = $this->createQuery('a')
->andWhere('a.active = ?',1)
->leftJoin('a.Owner o')
->leftJoin('o.Profile p')
->andWhere('p.payed_until > NOW()')
->addOrderBy('created_at DESC');
return $q;
}