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 :)
Related
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;
});
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
});
I need a help..
I have a unique form with multiples fieldsets, and i need separate some fieldsets in tabs..
So, i tried in the view (form is my variable with the whole form):
$form = $this->form;
$customFieldset = $form->get('customFieldset');
$form->remove('customFieldset');
It works, my fieldset form is in $customFieldset.. but, i can't render this!
When a try:
echo $this->form($customFieldset);
//OR
echo $this->formInput($customFieldset);
//OR
$this->formCollection($customFieldset);
None of that works..
I'm doing right? How i can do it?
Thank very much.
To achieve the result you want (using the form across several tabs, it is better to construct the form differently, based on the tab's number. For example, your form constructor method would look like below:
<?php
namespace Application\Form;
use Zend\Form\Form;
// A form model
class YourForm extends Form
{
// Constructor.
public function __construct($tabNum)
{
// Define form name
parent::__construct('contact-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
// Create the form fields here ...
if($tabNum==1) {
// Add fields for the first tab
} else if($tabNum==2) {
// Add fields for the second tab
}
}
}
In the example above, you pass the $tabNum parameter to form model's constructor, and the constructor method creates a different set of fields based on its value.
In your controller's action, you use the form model as below:
<?php
namespace Application\Controller;
use Application\Form\ContactForm;
// ...
class IndexController extends AbstractActionController {
// This action displays the form
public function someAction() {
// Get tab number from POST
$tabNum = $this->params()->fromPost('tab_num', 1);
// Create the form
$form = new YourForm($tabNum);
// Check if user has submitted the form
if($this->getRequest()->isPost()) {
// Fill in the form with POST data
$data = $this->params()->fromPost();
$form->setData($data);
// Validate form
if($form->isValid()) {
// Get filtered and validated data
$data = $form->getData();
// ... Do something with the validated data ...
// If all tabs were shown, redirect the user to Thank You page
if($tabNum==2) {
// Redirect to "Thank You" page
return $this->redirect()->toRoute('application/default',
array('controller'=>'index', 'action'=>'thankYou'));
}
}
}
// Pass form variable to view
return new ViewModel(array(
'form' => $form,
'tabNum' => $tabNum
));
}
}
In your view template, you use the following code:
<form action="">
<hidden name="tab_num" value="<?php echo $this->tabNum++; ?>" />
<!-- add other form fields here -->
</form>
I am sure I am going about this the wrong way, but I need to unset an array key from one of my choices in a sfWidgetFormChoice. The only way to get that variable to the Form is from the action. Here's what I have:
Action:
$id = $request->getParameter('id');
$deleteForm = new UserDeleteForm();
$choices = array();
$choices = $deleteForm->getWidgetSchema('user')->getAttribute('choices');
unset($choices[$id]); //I obviously don't want the user to be able to transfer to the user being deleted
$this->deleteForm = $deleteForm;
Form:
$users = Doctrine_Core::getTable('sfGuardUser')->getAllCorpUsers()->execute();
$names = array();
foreach($users as $userValue){
$names[$userValue->getId()] = $userValue->getProfile()->getFullName();
};
// unset($names[$id]); //this works, but I can't figure out how to get $id here.
$this->widgetSchema['user'] = new sfWidgetFormChoice(array(
'choices' => $names
));
$this->validatorSchema['user'] = new sfValidatorChoice(array(
'required' => true,
'choices' => $names
));
Understanding forms and actions:
Usually we will setup a form with fields, print it in a html page and fill the form with data. Pressing the submit form button will send all the data to a method defined in your form action html attribute.
The method will receive and get a $request , with a lot of parameters and also the form with the data. Those values will be processed in the action.
Lets look how it exactly works in symfony:
Define and Setup a symfony form, like the one you have shown above.
Print the form and in the action parameter point to the submit method
which will receive the request:
<form action="currentModuleName/update"
Symfony will automatically send the request to the action.class.php
of your module, and will look for and send the data to the function
executeUpdate
public function executeUpdate(sfWebRequest $request){ //...
$this->form = new TestForm($doctrine_record_found);
$this->processForm($request, $this->form); }
After some checks, symfony will process the form and set a result
template.
processForm(sfWebRequest $request, sfForm $form)
{ ... } $this->setTemplate('edit');
In the processForm of your module action.class.php, you should process all the received values (request) also with the form:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$formValues = $this->form->getValues();
$Id = $formValues['yourWidgetName'];
}
}
You may check the following link for an example like yours, about how to process a sfWidgetFormChoice.
And now answering to the real question, in order to select the deleted users, add the following code in your action:
//process the form, bind and validate it, then get the values.
$formValues = form->getValues();
$choicesId = $formValues['choices'];
Pass variable from action to the form:
Excuse me if I have not understand your question at all but in case you need to pass some parameters from your action to the form, send the initialization variables in an array to the form constructor:
Pass a variable to a Symfony Form
In your case, get the list of users, delete the user you dont want and send the non deleted users to the form constructor.
You will need to redeclare/overwrite your form again in the configure() function so that you could change the initialization of the form. Copy and paste the same code into the configure() function and comment the line: //parent::setup();
class TbTestForm extends BaseTbTestForm
{
public function configure()
{
//.. copy here the code from BaseTbTestForm
//parent::setup();
$vusers = $this->getOption('array_nondeleted_users');
//now set the widget values with the updated user array.
}
}
i'am a cakephp newbie :D
how can i modify data in a controller before cakephp put the data into mysql?
function add() {
if (!empty($this->data)) {
$this->Template->create();
/* This works! */
$this->data['Template']['slug'] = Inflector::slug(utf8_encode(strtolower($this->data['Template']['name'])),'-');
/* does not work ! */
$this->data['Template']['created'] = time();
$this->data['Template']['category_id'] = $this->data['Template']['category'];
if ($this->Template->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}else{
/* dropdown */
$this->set('categories',$this->Template->Category->find('list'));
}
}
Fields in my database:
templates
id
slug
category_id (belong to categories)
name
created
Can anyone help my?
greetings!
The correct way is putting it in your Model, not in your controller (because you are treating data, so it must be in the model).
For this, you can use model's "beforeSave" method:
Cake1.2: http://book.cakephp.org/view/683/beforeSave
Cake1.3: http://book.cakephp.org/view/1052/beforeSave
Cake 2: http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave