Multiply categories and bind them to Database Symfony2 - php

i need help with my forms that i create, i created 5 forms in a twig file and created a controller , how can i bind my value from the forms to database, when i bind now it displays me only one Value form the 5 times , but i need 5 times to be different value :(, please help , I stuck on this thing all day already..
my twig file:
<div class="new-test">
<h2>New test </h2>
<form action="{{ path('test.create') }}" method="post">
Test name: <input type="text" name="name"/><br>
Category 1<input type="text" name="category-new" >
<div id="customWidget">
<div id="colorSelector1"><div style="background-color: #00ff00"></div>
</div>
<div id="colorpickerHolder1"></div>
</div>
Category 2<input type="text" name="category-new" ><br>
Category 3<input type="text" name="category-new" ><br>
Category 4<input type="text" name="category-new" ><br>
Category 5<input type="text" name="category-new" ><br>
<input type="submit" value="Add">
</form>
my controller:
/**
* #Route("/add/test", requirements={"name" = "\s+"}, name="test.create")
* #Method("Post")
* #return array
*/
public function createAction()
{
$success = 0;
$name = $this->getRequest()->get('name');
if( !empty($name) )
{
$test = new Test();
$test->setName($this->getRequest()->get('name'));
$em = $this->getDoctrine()->getManager();
$em->persist($test);
$em->flush();
$success = 'Test '.$test->getName().' was created';
}
else
{
$success = 'Test name can not be empty';
}
$category = $this->getRequest()->get('category-new');
for ($i=0; $i<=5; $i++){
if( !empty($category) )
{
$categoryName = new Category();
$categoryName->setName($this->getRequest()->get('category-new'));
$em = $this->getDoctrine()->getManager();
$em->persist($categoryName);
$em->flush();
$success = ' Category '.$categoryName->getName().$i.' was created';
}
else
{
$success = 'Test name can not be empty';
}
}
return $this->redirect($this->generateUrl('test.new'));
}

Not sure if i understand correctly. You want to have inputs with name 'category-new' that have different value. If so, you have problem in form view:
Category *<input type="text" name="category-new" ><br>
name should have bracket at the end name="category-new[]" or name="category-new[1]" for category 1, name="category-new[2]" for category 2, and so on.

Template:
Category 1<input type="text" name="category-new[]" >
<div id="customWidget">
<div id="colorSelector1"><div style="background-color: #00ff00"></div>
</div>
<div id="colorpickerHolder1"></div>
</div>
Category 2<input type="text" name="category-new[]" ><br>
Category 3<input type="text" name="category-new[]" ><br>
Category 4<input type="text" name="category-new[]" ><br>
Category 5<input type="text" name="category-new[]" ><br>
It`s meen, that your controller take array with name category-new
/**
* #Route("/add/test")
*
* #return array
*/
public function createAction()
{
$success = 0;
$name = $this->getRequest()->get('name');
if (!empty($name)) {
$test = new Test();
$test->setName($name);
$em = $this->getDoctrine()->getManager();
$em->persist($test);
$em->flush();
$success = 'Test ' . $test->getName() . ' was created';
} else {
$success = 'Test name can not be empty';
}
$categoryList = array_map('trim', $this->getRequest()->get('category-new'));
foreach ($categoryList as $category) {
if (!empty($category)) {
$categoryName = new Category();
$categoryName->setName($category);
$em = $this->getDoctrine()->getManager();
$em->persist($categoryName);
$em->flush();
$success = ' Category ' . $category . ' was created';
} else {
$success = 'Test category-new may not be empty';
}
}
return $this->redirect($this->generateUrl('test_create'));
}
Some words
Route("/add/test", requirements={"name" = "\s+"}, name="test.create")
requirements not need for you
name of this action will be project_bundlename_controller_action for you {project}_{bundlename}_test_create whereis i dont know you project name and bundle name - its not a diffucult i think for you. And some code :)

Related

codeigniter: closure table - add descendant

I'm trying to add a new descendant, but having difficulties achieving it, it displays some error, Would be grateful if you could take time to review what I've done thus far.
Here's
Controller
public function index() {
$this->load->view('closure_view');
}
public function add() {
$add_new = array(
'ancestor' => $this->input->post('ancestor'),
'descendant' => $this->input->post('descendant'),
'lvl' => $this->input->post('lvl'),
'id' => $this->input->post('id')
);
$cust_id = $this->closure->add($add_new);
redirect('http://localhost/kgmerchant/index.php/welcome');
}
Model
public $table;
public $closure_table = 'closures';
public function __construct($table_name = NULL, $closure_table = NULL){
parent::__construct();
$this->table = $table_name;
if ($closure_table !== NULL) {
$this->closure_table = $closure_table;
}
}
public function add($node_id, $target_id = 0) {
$sql = 'SELECT ancestor, '.$node_id.', lvl+1
FROM '.$this->closure_table.'
WHERE descendant = '.$target_id.'
UNION
SELECT '.$node_id.','.$node_id.',0';
$query = 'INSERT INTO '.$this->closure_table.' (ancestor, descendant, lvl) ('.$sql.')';
$result = $this->db->query($query);
return $result;
}
View
<form name="home" method="post" action="<?php echo base_url().'index.php/home/add' ?>" >
<input placeholder="ancestor" type="text" name="ancestor" required/>
<input placeholder="descendant" type="text" name="descendant" required/>
<input placeholder="lvl" type="text" name="lvl" required />
<input placeholder="id" type="hidden" name="id" value="" />
<input type="submit" value="Okay" />
</form>
Thanks.
Error
Message: Array to string conversion
Your model can't be called "Closure" because that's a reserved name in PHP. Change the name to something else and it should work.

Account Edit in CodeIgniter

I tried to edit users account but when I loaded the view it does not display the users default account information.Below is my model view and controller. Any help would be greatly appreciated.
I have a database which includes includes all the users information. so I want to retrieve it and perform an update function.
CONTROLLER
/**
* This function is used load user edit information
* #param number $userId : Optional : This is user id
*/
function editOld($userId = NULL)
{
if($userId == null)
{
redirect('pages/settings');
}
$data['userInfo'] = $this->settings_model->getUserInfo($userId);
$data['title'] = 'Settings';
$this->load->view('templates/header');
$this->load->view('pages/settings', $data);
$this->load->view('templates/footer');
}
/**
* This function is used to edit the user information
*/
function editUser()
{
$this->load->library('form_validation');
$userId = $this->session->userdata('user_id');
$this->form_validation->set_rules('name','Full Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|xss_clean|max_length[128]');
$this->form_validation->set_rules('username','Username','trim|required|xss_clean|min_length[3]');
$this->form_validation->set_rules('birthday','Birthday','required|xss_clean');
$this->form_validation->set_rules('gender','Gender','required|xss_clean');
$this->form_validation->set_rules('mobile','Mobile Number','required|min_length[9]|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->editOld($userId);
}
else
{
$name = $this->input->post('name');
$username = $this->input->post('username');
$email = $this->input->post('email');
$bio = $this->input->post('bio');
$mobile = $this->input->post('mobile');
$birthday = $this->input->post('birthday');
$gender = $this->input->post('gender');
$userInfo = array();
if(empty($password))
{
$userInfo = array('email'=>$email, 'username'=>$username, 'name'=>$name,
'mobile'=>$mobile, 'bio'=>$bio, 'birthday'=>$birthday, 'gender'=>$gender, 'updatedBy'=>$userId, 'updatedDtm'=>date('Y-m-d H:i:s'));
}
else
{
$userInfo = array('email'=>$email, 'username'=>$username, 'name'=>$name,
'mobile'=>$mobile, 'bio'=>$bio, 'birthday'=>$birthday, 'gender'=>$gender, 'updatedBy'=>$userId, 'updatedDtm'=>date('Y-m-d H:i:s'));
}
$result = $this->settings_model->editUser($userInfo, $userId);
if($result == true)
{
$this->session->set_flashdata('success', 'Profile updated successfully');
}
else
{
$this->session->set_flashdata('error', 'Profile update failed');
}
redirect('pages/settings');
}
}
MODEL
function getUserInfo($userId)
{
$this->db->select('id, name, email, username, mobile, birthday, gender, bio');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('id', $userId);
$query = $this->db->get();
return $query->result();
}
/**
* This function is used to update the user information
* #param array $userInfo : This is users updated information
* #param number $userId : This is user id
*/
function editUser($userInfo, $userId)
{
$this->db->where('id', $userId);
$this->db->update('users', $userInfo);
return TRUE;
}
VIEW
<?php
$userId = '';
$name = '';
$email = '';
$mobile = '';
$username = '';
$birthday = '';
$bio = '';
if(!empty($userInfo))
{
foreach ($userInfo as $uf)
{
$userId = $uf->id;
$name = $uf->name;
$email = $uf->email;
$mobile = $uf->mobile;
$username = $uf->username;
$birthday = $uf->birthday;
$bio = $uf->bio;
}
}
?>
<form class="col s12" role="form" action="<?php echo base_url() ?>settings/editUser" method="post" id="editUseri" role="form">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate" name="name" value="<?php echo $name; ?>">
<input type="hidden" value="<?php echo $userId; ?>" name="userId" id="userId" />
<label for="name">Full Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="username" type="text" class="validate" data-length="15" name="username" value="<?php echo $username; ?>">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="text" class="validate" name="email" value="<?php echo $email; ?>">
<label for="email">Email</label>
</div>
</div>
<div class="box-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
<input type="reset" class="btn btn-default" value="Reset" />
</div>
</form>
You can just pass your details into session and use sessions to display it. remember to update the session .
value="<?php echo $this->session->userdata('username'); ?>"
mark as correct if it works for you.
Try to add :
$this->db->last_query()
to check what is the query going. I think it would needs to set the
$query->result();
$this->db->set() the data part for handling update query
try this only for debug your error
you not checked user session set or not
change from
if($this->form_validation->run() == FALSE)
{
$this->editOld($userId);
}else{
....
....
}
to
if($this->form_validation->run() == FALSE)
{
//your validation error
echo "validation error";
}else if($userId){
//if session set for user
$this->editOld($userId);
}else{
....
....
}

Not inserting null values

I am trying to insert multiple values in the todo input of the form. but if i do not input a value to any input the null value is inserted in the database. This is my controller action:
public function actionAdd()
{
if (Yii::$app->request->isAjax) {
$request = Yii::$app->request;
$add = new Project();
$add->project_name = $request->post('project');
$add->deadline = $request->post('deadline');
$add->profile_id = $request->post('profile_id');
$add->project_status = "Running";
$add->save();
$getlast = Yii::$app->db->getLastInsertId();
$todo = $request->post('todo');
if (isset($todo)) {
foreach ($todo as $to) {
$add = new Todo();
$add->todo_name=$to;
$add->status="Running";
$add->project_id=$getlast;
$add->save();
}
}
echo json_encode(TRUE); die;
}
echo json_encode(FALSE);die;
}
the form is:
<form class="formclass" method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/todo/add/" role="form" id="register-form" novalidate="novalidate">
<label> Project Name: </label> <input type="name" name="project" class="form-control" placeholder="Project Name" required><br><br>
<input type="hidden" name="profile_id" value="<?php echo $profile_id;?>">
<label> Todo: </label><br>
<textarea type="text" name="todo[]" placeholder="Todo Description..."></textarea>
<div id="dynamicInput">
<span class="glyphicon glyphicon-plus" onClick="addInput('dynamicInput');"></span>
</div><br>
<label> Project Deadline:</label><br>
<input type="date" name="deadline"><br><br>
<button type="submit" class="btn btn-default">Add Project</button><BR><BR>
</form>
And the jquery is:
var counter = 1;
var limit = 10;
function addInput(divName)
{
if (counter != limit)
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br><textarea type='text' name='todo[]' placeholder='Todo Description...'></textarea>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Could be you problem is related to the validation rules ..
for check this and only for debugging try use $add->savel(false)
$add = new Todo();
$add->todo_name=$to;
$add->status="Running";
$add->project_id=$getlast;
$add->save(false);
if in this case the rows are inserted the check for validations rule (eventually comment temporary) .. for find the wrong rules or condition

php Notice: Trying to get property of non-object in

I have to recognize that I'm new in php oop, but I want to learn. I searched for the same title here but I didn't see any topic close to mine to get an idea.
I have an function in a events calendar class, that display a form to add an event. Where I have the form I get an error on each line, about the event variable:
Notice: Undefined variable: event in C:\wamp\www
This is the function:
public function displayForm() {
/*
* Check if an ID was passed
*/
if(isset($_POST['event_id'])) {
$id = (int)$_POST['event_id'];
}
else {
$id = NULL;
}
/*
* Instantiate the headline/submit button text
*/
$submit = "Create a New Event";
/*
* If an ID is passed, loads the associated event
*/
$event = NULL;
if(!empty($id)) {
$event = $this->_loadEventById($id);
/*
* If no object is returned, return NULL
*/
if(!is_object($event)) {
return NULL;
}
$submit = "Edit This Event";
}
/*
* Build the markup
*/
return <<<FORM_MARKUP
<form action="assets/inc/process.inc.php" method="post">
<fieldset>
<legend>$submit</legend>
<label for="event_title">Event Title</label>
<input type="text" name="event_title" id="event_title" value="$event->title" />
<label for="event_start">Event Start</label>
<input type="text" name="event_start" id="event_start" value="$event->start" />
<label for="event_end">Event End</label>
<input type="text" name="event_end" id="event_end" value="$event->end" />
<label for="event_description">Event Description</label>
<textarea name="event_description" id="event_description" >$event->description</textarea>
<input type="hidden" name="event_id" value="$event->id" />
<input type="hidden" name="token" value="$_SESSION[token]" />
<input type="hidden" name="action" value="event_edit" />
<input type="hidden" name="event_submit" value="$submit" />
or cancel
</fieldset>
</form>
FORM_MARKUP;
}
If anyone has an idea feel free to tell me. Thank you.
You should make sure all the variables you use in your form markup are defined in all circumstances... So, $event should never be NULL... you should define default values in case no POST it's received or the id it's not found.
Also, $_SESSION should have the parameter with quotation marks and also should be checked before printing!
Here it's the code I propose you to use:
public function displayForm() {
// Initialize vars
$id = NULL;
$token = '';
/*
* Check if an ID was passed
*/
if(isset($_POST['event_id'])) {
$id = (int)$_POST['event_id'];
}
if (isset($_SESSION['token'])) {
$token = $_SESSION['token'];
}
/*
* Instantiate the headline/submit button text
*/
$submit = "Create a New Event";
/*
* If an ID is passed, loads the associated event
*/
if(!empty($id)) {
//$event = $this->_loadEventById($id);
$event = new stdClass();
$event->title = 'title';
$event->start = '1';
$event->end = '1';
$event->id = '1';
$event->description = 'description';
$submit = "Edit This Event";
}
if (empty($id) || !is_object($event)) {
$event = new stdClass();
$event->title = 'default title';
$event->start = 'default start';
$event->end = 'default end';
$event->id = 'default id';
$event->description = 'default description';
}
/*
* Build the markup
*/
return <<<FORM_MARKUP
<form action="assets/inc/process.inc.php" method="post">
<fieldset>
<legend>$submit</legend>
<label for="event_title">Event Title</label>
<input type="text" name="event_title" id="event_title" value="$event->title" />
<label for="event_start">Event Start</label>
<input type="text" name="event_start" id="event_start" value="$event->start" />
<label for="event_end">Event End</label>
<input type="text" name="event_end" id="event_end" value="$event->end" />
<label for="event_description">Event Description</label>
<textarea name="event_description" id="event_description" >$event->description</textarea>
<input type="hidden" name="event_id" value="$event->id" />
<input type="hidden" name="token" value="$token" />
<input type="hidden" name="action" value="event_edit" />
<input type="hidden" name="event_submit" value="$submit" />
or cancel
</fieldset>
</form>
FORM_MARKUP;
}
You set $event = NULL; and you probably pass an empty $id

Verify custom table in magento for custom module

I have made the redirect from the question i have posted here
Now i have another form in the redirected page where i need to enter name and mobile number and if it matches in my db table helloworld it will go to one page or else to another
<p>You have successfully registered</p>
<div>
<label>Login</label>
</div>
<div>
<form action="" method="post">
<label> Username </label>
<strong>:</strong>
<input class="input-text required-entry" type="text" name="fname" maxlength="20">
<label>Mobile No</label>
<strong>:</strong>
<input class="required-entry" type="number" maxlength="10" name="mobileno">
<input type="submit" name="login" value="Login">
<input type="button" name="cancel" value="Cancel">
</form>
</div>
Can any one help me how no i can verify it with existing data in db and make this work ? Shall I start it with using index controller or is there any magento way?
Update:
this is my Indexcontroler.php after below answer update
<?php
class MyCustom_Helloworld_IndexController extends Mage_Core_Controller_Front_Action
{
/*
* this method privides default action.
*/
public function indexAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
echo $firstname = $param['fname'];
$lastname = $param['lname'];
$address = $param['address'];
$state = $param['state'];
$city = $param['city'];
$mobile = $param['mobileno'];
$model = Mage::getModel('helloworld/helloworld');
// $model->setTitle($title);
$model->setFirstname($firstname);
$model->setLastname($lastname);
$model->setAddress($address);
$model->setState($state);
$model->setCity($city);
$model->setMobileno($mobile);
$model->save();
$this->_redirect('helloworld/index/login');
// $this->_redirectReferer();
}else {
/*
* Initialization of Mage_Core_Model_Layout model
*/
$this->loadLayout();
/*
* Building page according to layout confuration
*/
$this->renderLayout();
}
}
public function loginAction()
{
$this->loadLayout();
$this->renderLayout();
}
public function loginnAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
$username = $param['fname'];
$mobile = $param['mobileno'];
$check = Mage::getModel('helloworld/helloworld')
->AddFieldToFilter('mobileno', array('eq' => $mobile))
->AddFieldToFilter('fname', array('eq' => $username));
if(count($check)==1) {
$this->_redirectReferer();
}else {
$this->_redirect('helloworld/index/login');
}
}
}
}
you can add check like that
public function loginAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
$username = $param['fname'];
$mobile = $param['mobile'];
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
$table = $connectionresource->getTableName('helloworld/helloworld');
$allrecord = $readconnection->select()->from(array('helloworld'=>$table))->where('helloworld.mobileno=?', $mobileno)
->where('helloworld.fname=?', $username);
$alldata =$readconnection->fetchAll($allrecord);
if(count($alldata)==1) {
$this->_redirect('home');
}else {
$this->_redirect('customer/account');
}
}

Categories