I'm trying to set up a multi-select filter on a foreign key in the symfony admin. I think I've set up everything correctly but for some reason it's not working:
public function configure()
{
parent::configure();
$s = Doctrine_Query::create()->
from('Status s')->
execute();
$status_choices = array();
foreach ($s as $key => $value) {
$status_choices[$value->getId()] = $value->getName();
}
$this->widgetSchema['status_id'] = new sfWidgetFormChoice(array('choices' => $status_choices, 'multiple' => true, 'expanded' => true));
$this->validatorSchema['status_id'] = new sfValidatorChoice(array('required' => false, 'choices' => $status_choices, 'multiple' => true));
}
public function getFields()
{
$fields = parent::getFields();
$fields['status_id'] = 'StatusId';
return $fields;
}
public function addStatusIdQuery(Doctrine_Query $query, $field, $values)
{
$fieldName = $this->getFieldName($field);
if (!empty($values))
{
$query->addWhereIn(sprintf('%s.%s', $query->getRootAlias(), $fieldName), $values);
}
}
Any help would be greatly appreciated...
In your validatorSchema, to validate data posted, you have to use array_keys($status_choices)
because values sent after posting the form are keys and not labels.
And the addWhereIn is not a Doctrine_Query method, use andWhereIn or whereIn
Hope that will help you
Related
I have two submit buttons (submit1 and submit2). When I click "submit2", the controller should write a value (1) in a specific column (abgerechnet) in my db.
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if(isset($_POST['submit2']) )
{
$request = Yii::$app->request;
$test= $request->post('test', '1');
}
return $this->redirect(['view', 'id' => $model->ID]);
}
return $this->render('update', [
'model' => $model,
]);
}
But when I click the button "submit2" the column "test" remains empty.
With the lines $request = Yii::$app->request;
$test= $request->post('test', '1');
it should write the value in the column "test".
If you want update the colum abgerechnet in your model based on $_POST['submit2'] then you should set the the value before invoking model->save()
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) ) {
if(isset($_POST['submit2']) )
{
$model->abgerechnet = 1;
}
$model->save();
return $this->redirect(['view', 'id' => $model->ID]);
}
return $this->render('update', [
'model' => $model,
]);
}
I am trying to update records in my database. I am following a book but something isnt working.
This is the edit action. On post form action leads to process action.
public function editAction()
{
$userTable = $this->getServiceLocator()->get('UserTable');
$user = $userTable->getUser($this->params()->fromRoute('id'));
$form = $this->getServiceLocator()->get('UserEditForm');
$form->bind($user);
$viewModel = new ViewModel(array(
'form' => $form,
'user_id' => $this->params()->fromRoute('id')
));
return $viewModel;
}
Process action
public function processAction()
{
// Get User ID from POST
$post = $this->request->getPost();
$userTable = $this->getServiceLocator()->get('UserTable');
// Load User entity
$user = $userTable->getUser($post->id);
// Bind User entity to Form
$form = $this->getServiceLocator()->get('UserEditForm');
$form->bind($user);
$form->setData($post);
// Save user
$this->getServiceLocator()->get('UserTable')->saveUser($user);
}
And this is the class UserTable with function save user:
public function saveUser(User $user)
{
$data = array(
'email' => $user->email,
'name' => $user->name,
'password' => $user->password,
);
$id = (int)$user->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getUser($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('User ID does not exist');
}
}
}
There is no error showing. It passes $this->tableGateway->update and just nothing !
EDIT: I can delete users, add users.
u miss this
if ($form->isValid()) {
$this->getServiceLocator()->get('UserTable')->saveUser($form->getData());
}
After validation you can now retrieve validate form data with $form->getData().
Also note that because of binding entity to form via $form->bind($user) $form->getData() is an instance of User
Hope it helps ;)
I dont know why but i must check if form is valid.
if($form->isValid()){
// do the save
}
i want to change PHPSESSID name and value. I can could name but i couldn't change value.
i have following stracture. How i change sessionid value.
My module.config.php is
return array(
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'portal1'
),
),
'storage' => 'Zend\Session\Storage\SessionArrayStorage',
'validators' => array(
array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
),
);
My Module.php
public function onBootstrap($e) {
$this->bootstrapSession($e);
}
public function bootstrapSession($e) {
$session = $e->getApplication()
->getServiceManager()
->get('Zend\Session\SessionManager');
$session->start();
$container = new Container('initialized');
if (!isset($container->init)) {
$session->regenerateId(true);
$container->init = 1;
}
}
public function getServiceConfig() {
return array(
'factories' => array(
'Zend\Session\SessionManager' => function ($sm) {
$config = $sm->get('config');
if (isset($config['session'])) {
$session = $config['session'];
$sessionConfig = null;
if (isset($session['config'])) {
$class = isset($session['config']['class']) ? $session['config']['class']
: 'Zend\Session\Config\SessionConfig';
$options =
isset($session['config']['options']) ? $session['config']['options'] : array();
$sessionConfig = new $class();
$sessionConfig->setOptions($options);
}
$sessionStorage = null;
if (isset($session['storage'])) {
$class = $session['storage'];
$sessionStorage = new $class();
}
$sessionSaveHandler = null;
if (isset($session['save_handler'])) {
$sessionSaveHandler = $sm->get($session['save_handler']);
}
$sessionManager = new SessionManager($sessionConfig, $sessionStorage, $sessionSaveHandler);
if (isset($session['validator'])) {
$chain = $sessionManager->getValidatorChain();
foreach ($session['validator'] as $validator) {
$validator = new $validator();
$chain->attach('session.validate', array($validator, 'isValid'));
}
}
} else {
$sessionManager = new SessionManager();
}
Container::setDefaultManager($sessionManager);
return $sessionManager;
},
),
);
}
MyController.php is; i want to change PHPSESSID key and value here.
public function loginAction() {
$container = new Container(); /*
i want to change PHPSESSID key and value
eg: portal1: fafsafg43kgfdsgfds //my sessionid value
*/
}
Well, I want to clarify something before answer the question -
What dose it means "i want to change PHPSESSID key and value"
As far I understand you want to change the "PHPSESSID" text. that means you want to call it in different name like "MySessionId" isn't it?
Actually I'm not authorized to write comment where I can ask!
Anyway, if you want to call it with different name than its not the issue of ZF its your server's PHP session settings. So, consult the session part of the server. You may get help from http://php.net/manual/en/session.configuration.php#ini.session.name OR http://php.net/manual/en/function.session-name.php
And ZF also let you change that name by Zend\Session\Config\SessionConfig class or Zend\Session\SessionManager class you have to set the preferred name by calling setName method.
Now if you want to change the value of session id (its automatically generated and save it into PHPSESSID) you may do it in ZF. Here is the code of ZF2 to set the value explicitly
$container->getManager()->setId($id); # For current session manager of your container
$container->getDefaultManager()->setId($id); # For default session manager of your entire app
In above code $id is the value you want to set.
I've this configure() function in my form:
public function configure() {
$this->current_user = sfContext::getInstance()->getUser()->getGuardUser();
unset($this['updated_at'], $this['created_at']);
$this->widgetSchema['idempresa'] = new sfWidgetFormInputHidden();
$id_empresa = $this->current_user->getSfGuardUserProfile()->getIdempresa();
$this->setDefault('idempresa', $id_empresa);
$this->widgetSchema['no_emisor'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingEmisor', 'add_empty' => 'Seleccione un Emisor', 'expanded' => false, 'multiple' => false));
$this->validatorSchema['idempresa'] = new sfValidatorPass();
$this->validatorSchema['no_emisor'] = new sfValidatorPass();
}
And I'm need to define a relation data in save() function so I do this:
public function save($con = null) {
$new_machine = parent::save($con);
$relation = new SdrivingMaquinaEmisor();
$relation->setIdmaquina($new_machine);
$relation->setIdemisor();
$relation->save();
return $new_machine;
}
In order the set the Idemisor, how do I access to the selected value when users submit the form? Is this the best way to achieve this?
EDIT
After take the suggestion about how to access no_emisor value now my code looks like:
public function save($con = null) {
$new_machine = parent::save($con);
$relation = new SdrivingMaquinaEmisor();
$relation->setIdmaquina($new_machine);
$relation->setIdemisor($this->values['no_emisor']);
$relation->save();
return $new_machine;
}
But I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'idmaquina' cannot be null
For some reason $new_machine doesn't return the id of the latest saved element. Maybe I'm doing in the wrong way so what I'm doing wrong?
I think you might want to do this in the form's doUpdateObject instead, since that receives the cleaned values.
http://www.symfony-project.org/api/1_4/sfFormObject#method_doupdateobject
Edit:
Alternatively, $this->values['no_emisor'] should work once the form has been bound.
Hi I have a business logic layer that returns selectlistitems to a controller, so that will then pass to the view to populate select lists.
I have this method that works:
public IEnumerable<SelectListItem> GetDevices
{
get
{
using (IDeviceData repository = _dataFactory.Create())
{
return repository.DeviceTypes.ToList()
.Where(dt => dt.ParentId == 10 )
.Select(dt =>
new SelectListItem
{
Text = (dt.Name).Trim(),
Value = dt.Id.ToString()
});
}
}
}
And this that doesn't:
public IEnumerable<SelectListItem> GetGroups(int deviceTypeId)
{
using (IDeviceData repository = _dataFactory.Create())
{
return repository.DeviceTypeConfigurationParameterGroupMaps.ToList()
.Where(cm => cm.DeviceTypeId == deviceTypeId)
.Join(repository.ConfigurationParameterGroups, cm => cm.ConfigurationParameterGroupId, cg => cg.Id, (cm, cg) => new { cm, cg })
.Select(cg =>
new SelectListItem
{
Text = (cg.cg.Name).Trim(),
Value = cg.cg.Id.ToString()
});
}
}
The obvious difference is the join between two tables, the error I receieve is:
Results View = The type '<>f__AnonymousType0<p,d>' exists in both 'System.Web.dll' and 'EntityFramework.dll'
This is receieved when trying to expand the results whiel debugging. Any advice would eb welcome as I'm not overly familiar with LINQ
Figured it out:
public IEnumerable<SelectListItem> GetGroupsForDevice(int deviceTypeId)
{
using (IDeviceData repository = _dataFactory.Create())
{
return repository.DeviceTypeConfigurationParameterGroupMaps
.Where(cm => cm.DeviceTypeId == deviceTypeId)
.Join(repository.ConfigurationParameterGroups, cm => cm.ConfigurationParameterGroupId, cg => cg.Id, (cm, cg) => cg )
.ToList()
.Select(cg =>
new SelectListItem
{
Text = (cg.Name).Trim(),
Value = cg.Id.ToString()
}).ToList() ;
}
}
I needed to add ToList() after the join, and then again after converting to SelectlistItem. I also didnt need th create the new anonymous type - Thanks to joanna above for that.
This is the answer but not a good explanation, if anyone wants to pad it out a little please feel free!