How to get ID from different controllers Yii2? - php

In the ActiveForm I have model button with Pjax render field after form from the modal button will created. Added a picture for an example. How can I get newly created id (not select added to the database, need to get the id that comes from this form).
I think I need to set get to button, than with ajax catch this and transfer to my Pjax rendered cell
I tried variations, but unsuccessfully, I cann't fully understand how to implement it. Can anyone help with the solution ?
//TwoController
public function actionCreate()
{
$model = new Formtwo();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
echo 1;
//maybe here I must to do query ?
} else {
echo 0;
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Index GridView

I hope I understood correct; you wish that when a user creates an instance of Form2, it is transferred then to create an instance of Form1, and the id of newly created record for Form2, is put in the Form1 _form.
If I did not understand correctly, please explain better :)
In TwoController create action, after creation, you would call the create action of OneContrller:
if ($model->save()) {
return \Yii::$app->runAction('/controller/action-name', ['form2_id'=>$model->id]);
}
On OneController actionCreate add parameter with default value:
public function actionCreate($form2_id=null) {
and make sure it is passed to the view (don't forget to make sure you pass it on create.php as well to the _form.

//TwoController
public function actionCreate()
{
$model = new Formtwo();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
echo $model->id;
//maybe here I must to do query ?
} else {
echo 0;
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
You don't need query. Just use $model->id. It has value after save().
Update
It doesn't matter in which controller you are. You get the id of the model saved after save(). Then you can use id attribute. So, you can open modal form with ajax load. On form2 you register script to ajax post form. Something like this:
$("#form :submit").click(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: $("#form").attr("action"),
data: $("#form").serialize(),
success: function (response) {
$("#modalid").modal("hide")
$.pjax.reload({
container: "#grid"
});
$('#Form2_id').val(response); //here you get the id
},
})
return false;
});

Related

Yii2: How to send new variable from view to controller?

I have a table called persons with id and name fields.
I have a create.php view that loads the model called Persons and now I want to add a checkbox called hasCar to show if a person has a car (so it is a boolean condition).
Then I have the send button that send the $model array of the form to the controller so I need to add the hasCar variable to $model array.
But the checkbox is not a column of the persons table so I got some errors because it is not part of the model.
I added the checkbox in this way but it is not working, of course.
<?= $form->field($model, 'hasCar')->checkbox(); ?>
Is it possible to send the hasCar variable inside the $model array? I mean, how can I send the hasCar variable to the controller when the send button is pressed?
Create a new model extending Person that contains hasCar member, and load the model from PersonForm class, such as:
class PersonForm extends Person
{
public $hasCar;
public function rules()
{
return array_merge(parent::rules(), [
[['hasCar'], 'safe'],
]);
}
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'hasCar' => 'Has car',
]);
}
}
You can't pass the variable to the $model object orbit is affiliated with a db table, you are right about this. You need to pass the variable to the controller via a request method (GET, POST).
Try :
Yii::$app->request->post()
for POST, and :
Yii::$app->request->get()
for GET.
Also on the form add the checkbox as an HTML class component.
EXAMPLE:
CONTROLLER:
...
$hasCar = Yii::$app->request->post('hasCar');
....
VIEW:
...
// We use ActiveFormJS here
$this->registerJs(
$('#my-form').on('beforeSubmit', function (e) {
if (typeof $('#hasCar-checkbox').prop('value') !== 'undefined') {
return false; // false to cancel submit
}
return true; // true to continue submit
});
$this::POS_READY,
'form-before-submit-handler'
);
...
<?= HTML::checkbox('hasCar', false, ['id' => 'hasCar-checkbox', 'class' => 'form-control']) ?>
...
More on ActiveFormJS:
enter link description here
I hope this answer covered you.
Damian

Silverstripe - populate fields depending on selected DataObject

I want to display a members details on screen when I select their name from a Dropdown
More information: I have a form that submits a few fields. Amongst them I have a "Select User" Dropdown to link this person to the data being submitted
Problem is- client wants the user's details to show when they select a user(make sure its the right person etc)
How can i accomplish this? There are like 3 seperate input fields that will need to contain data. I know how to do it using raw PHP/javascript, but do not know how to implement this in a Silverstripe way
You don't have to use Ajax for this, when you setup the form on your controller you can use loadDataFrom (http://api.silverstripe.org/3.3/class-Form.html#_loadDataFrom) to load the member directly into the form.
An example implementation could be (I haven't tested this, but it should work):
class Page_Controller extends ContentController
{
public function index()
{
$member = Member::currentUser();
$this->customise(array(
"Form" => $this->Form()->loadDataFrom($member)
));
}
public function Form() {
return Form::create(
$this,
"Form",
$fields, // Add your own fields here
$actions // Add your own actions here
);
}
}
Got a solution based off of this: https://www.silverstripe.org/community/forums/form-questions/show/24628
The way I did it was like this:
SS template
$("table.myTable").on('change','select#Some_Form',function(){
$.ajax({
type: "POST",
data: {param:param},
url: window.location.href+"your_action_here",
success: function(result) {
var resArr = JSON.parse(result);
$('input#Some_Field').val(resArr['key']);
}
});
});
Controller
static $allowed_actions = array('your_action_here');
//parameter is a SS_HTTPRequest
public function your_action_here($request){
//assuming my parameter is an ID
$ID = $request['param'];
$dataObject = DataObject::get_by_id('Object',$ID);
$JSONArray = array('key'=>$dataObject->Field);
echo json_encode($JSONArray);
}
When the select changes, gets the DataObject and populates correctly :)

Post Data not working correctly Laravel

I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.
Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});
If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});

How to enable hiddenField in Yii Framework?

I am using a Yii hiddenField in a CActiveForm widget. I have saved this hidden field value in database. There is no issue with storing in DB with Controller action at all. after saving this the hidden field should display the value. And how can I populate the form with the database stored value. Or how to refer some other field in the form to contain value from DB after save is processed.
<?php echo $form->hiddenField($model,'ad_form_id',array('value'=>$base)); ?>
My controller action
public function actionBCFormFields()
{
$model=new BCFormField();
if(isset($_POST['BCFormField']))
{
$model->ad_form_id = $_POST['BCFormField']['ad_form_id'];
$model->attributes=$_POST['BCFormField'];
if ($model->save()){
echo'saved';
}
$this->redirect(array('create',
'crm_base_form_field_id'=>$model->crm_base_form_field_id));
}
Based on the very litle code you have given us i would suggest something like this in your controller, but if you edit your question and elaborate , i will edit my question:
public $ad_form_id
public function actionCreate()
{
$model = new User;
$this->ad_form_id = $this->base;
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
$this->base = $this->ad_form_id;
if ($model->validate() && $model->save()) {
$this->redirect(array('view'));
}
}
$this->render('create',array('model' => $model,));
}

Yii - updating a model and using the model to echo data in the view

I have the following code for updating a Yii model:
public function actionSettings($id) {
if (!isset($_POST['save_hostname']) && isset($_POST['Camera']) && isset($_POST['Camera']['hostname'])) {
$_POST['Camera']['hostname'] = '';
}
$model = $this->loadModel($id);
$model->setScenario('frontend');
$this->performAjaxValidation($model);
if (isset($_POST['Camera'])) {
$model->attributes = $_POST['Camera'];
unset($model->api_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Camera settings has been saved!");
} else {
Yii::app()->user->setFlash('error', "Unable to save camera settings!");
}
}
$this->render('settings', array(
'model' => $model,
));
}
This works fine, except in my model I have code like this:
<h1>Settings For: <?php echo CHtml::encode($model->name); ?></h1>
The problem is that, even when the user input fails validation, the h1 tag is having bad input echoed out into it. If the input fails the validation, the h1 attribute should stay the same.
I can 'reset' the $model variable to what is in the database before the view is returned, but this then means I don't get any error feedback / validation failed messages.
Is my only option to have 2 $models ($model and $data perhaps), one used for handling the form and the other for sending data to the page? Or does someone have a more elegant solution?
performAjaxValidation assigns all save attributes to the model so this behavior is normal.
I would reload model if save fails.
$model->refresh();

Categories