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,
]);
}
Related
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 need to define more conditions in the JOIN statement.
How can I make this in Yii2 with a hasMany relation?:
... LEFT JOIN orders ON (customer.id = order.customer_id AND orders.position = 1) ...
I have a DataProvider for GridView. It look like this:
...
public function search($params)
{
$query = Customer::find()
->joinWith('orders');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}
...
Model:
...
public function getFirstOrder()
{
$query = $this->hasMany(Orders::className(), ['customer_id' => 'id']);
return $query;
}
...
Is it even possible?
public function search($params){
$activeDataProvider = new ActiveDataProvider([
"query" => Customer::find()
->joinWith('orders')
]);
// Valdate the search $params.
// Build your query depending on search params. I am assuming we get key => value pair in params
foreach($params as $key => $value){
$activeDataProvider->query->andWhere("`$key` = '$value'");
}
return $activeDataProvider;
}
I hope that helps you :)
You can also preview the generated sql using:
$command = $activeDataProvider->query->createCommand();
print_r ($command->sql);
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 want to make a Kendo TreeView that shows all nodes on first load. I'm using the Kendo 'Binding to remote data' sample but it doesn't work correctly. It shows just the first level and the id passed to the controller action is always null.
Please help me.
View code :
#(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Title")
.ExpandAll(true)
.LoadOnDemand(false)
.DataSource(dataSource => dataSource
.Read(read => read.Action("Employees", "Follow").Data("addData"))))
function addData(data) {
return { id: data.id };
}
Controller code : (controller Follow)
public System.Web.Mvc.JsonResult Employees(int? id)
{
System.Collections.Generic.List<FollowType> List =
new System.Collections.Generic.List<FollowType>();
if (id.HasValue == true) {
List = FollowTypeList.FindAll(current => current.ParentId == id);
} else {
List = FollowTypeList.FindAll(current => current.ParentId == null);
}
System.Collections.Generic.List<Kendo.Mvc.UI.TreeViewItemModel> NodeList =
new System.Collections.Generic.List<Kendo.Mvc.UI.TreeViewItemModel>();
foreach (CommonData.Domain.FollowType item in List)
{
NodeList.Add(new Kendo.Mvc.UI.TreeViewItemModel() {
Id = item.Id.ToString(),
Text = item.Title,
HasChildren = FollowTypeList.Exists(c => c.Id == item.ParentId)
});
}
return Json(NodeList, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
I guess that in your javascript code, the id field of data should be Id (be careful to the capitalization) :
return { id : data.Id };
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