I've created a basic CMS system using PHP and MySQL. I've run into a roadblock where I want the ability to create a custom field on a record.
Creating the field was easy, the issue I'm having is adding the custom field to the array which is sent in the mysql query.
Here's what I tried so far.
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
try {
$record->create('test_record', array(
foreach ($cust_field->results() as $val) {
$val->{'Field'} => Input::get($val->{'Field'}),
}
));
} catch(Exception $e) {
die($e->getMessage());
}
}
}
I know now that using a foreach loop inside an array doesn't work. But I can't seem to find anything that will work.
this should work:
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
try {
$fields = array();
foreach ($cust_field->results() as $val) {
$fields[$val->{'Field'}] = Input::get($val->{'Field'});
}
$record->create('test_record', $fields);
} catch(Exception $e) {
die($e->getMessage());
}
}
}
Related
I had 2 tables. driver and part_time_available in the same form, when I select driver type = parttime, it'll show part_time_available field(day, start_time, end_time).
How to make condition if user choose fulltime. it didn't store part_time_available field to database.
here's my savehandler code so far :
public function saveHandler(Request $request, $obj)
{
try {
DB::beginTransaction();
$obj->fill($request->all());
if (!$obj->save()) {
throw new ValidationException($obj->errors());
}
foreach($request->parttimeAvailabilities as $pta) {
\Log::info($pta);
if (empty($pta['id'])) {
$parttimeAvailability = new PartTimeAvailability();
}
else {
$parttimeAvailability = PartTimeAvailability::find($pta['id']);
}
$parttimeAvailability->driver()->associate($obj);
$pta['driver_id'] = isset($pta['driver_id']);
$parttimeAvailability->day = $pta['day'];
$parttimeAvailability->start_time = isset($pta['start_time']) ? $pta['start_time'] : '00:00:00';
$parttimeAvailability->end_time = isset($pta['end_time']) ? $pta['end_time'] : '00:00:00';
$parttimeAvailability->available = isset($pta['available']);
$parttimeAvailability->save();
};
$obj->save();
if (!$parttimeAvailability->save()) {
throw new ValidationException($parttimeAvailability->errors());
}
DB::commit();
return $this->sendSuccessResponse($request);
} catch (ValidationException $e) {
DB::rollback();
\Log::error($e->errors);
return $this->sendErrorResponse($request, $e->errors);
} catch (Exception $e) {
DB::rollback();
\Log::error($e->getMessage());
return $this->sendErrorResponse($request,'Unable to process. Please contact system Administrator');
}
}
I mean before running foreach, it needs to check it's parttime or not.
any idea ?
You can give a condition before the whole foreach loop. such as:
if($request->get('driver_type') != 'full_time'){
foreach loop
}
Reference: https://www.zen-cart.com/showthread.php?64003-zen_mail-How-does-it-work
I have modified a php file in the below lines:
function sub_button() {
$process_button_string = zen_draw_getuserinfo_field('usercasenumber_', $_POST['u_case'])
}
return $process_button_string;
try {
zen_mail("xxxxxx", "xxxxxx#gmail.com","xxxxxxxx", $process_button_string, W_NAME, EMAIL_FROM);
} catch (Exception $e) {
}
}
but still not receiving any email on completing doing submit on that page. everything else goes well. I am not very good with php and just added below part:
try {
zen_mail("xxxxxx", "xxxxxx#gmail.com","xxxxxxxx", $process_button_string, W_NAME, EMAIL_FROM);
} catch (Exception $e) {
}
Am I doing something wrong? Please help
I resolved it! :)
function sub_button() {
$process_button_string = zen_draw_getuserinfo_field('usercasenumber_', $_POST['u_case']);
}
$msg = $_POST['u_case'];
try {
zen_mail("xxxxxx", "xxxxxx#gmail.com","xxxxxxxx",
$msg, W_NAME, EMAIL_FROM);
} catch (Exception $e) {
}
return $process_button_string;
}
I have a form which represnts single answer object (this is standard propel generated form I have not changed much there only some validation rules) and another form that represents a collection of answers code as below:
class BbQuestionAnswersForm extends sfForm {
public function __construct($defaults = array(), $options = array(), $CSRFSecret = null) {
parent::__construct($defaults, $options, $CSRFSecret);
}
public function configure() {
if (!$questions = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need array of BbExamQuestion objects.');
}
if (!$taker = $this->getOption('taker')) {
throw new InvalidArgumentException('The form need BbExamtaker object.');
}
if (!$user = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need sfGuardUser object.');
}
foreach($questions as $question) {
$answer = new BbExamAnswer();
$answer->setBbExamQuestion($question);
$answer->setBbExamTaker($taker);
$answer->setCreatedBy($user);
$answer->setUpdatedBy($user);
$form = new BbExamAnswerForm($answer, array('question' => $question));
$this->embedForm($question->getId(), $form);
}
$this->widgetSchema->setNameFormat('solve[%s]');
}
}
Everything(validation, display) goes fine with this form until I try to save it. Part of action which trying to save the form:
...
$this->form = new BbQuestionAnswersForm(null, array('questions' => $this->questions, 'taker' => $this->taker, 'user' => $this->getUser()->getGuardUser()));
if($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if($this->form->isValid()) {
if($this->form->save()) {
$this->getUser()->setFlash('success', 'Save goes fine.');
$this->redirect($this->generateUrl('#bb'));
} else {
$this->getUser()->setFlash('error', 'Upps an error occurred.');
}
}
}
When I send valid form I receive "Call to undefined method BbQuestionAnswersForm::save()" error.
I tried to write this method like this:
public function save() {
$conn = Propel::getConnection(ZlecPeer::DATABASE_NAME);
$conn->beginTransaction();
try{
foreach($this->getEmbeddedForms() as $form) {
$form->save();
}
$conn->commit();
} catch(Exception $e) {
$conn->rollback();
echo 'upps something goes wrong';
die($e->getMessage());
return false;
}
return true;
}
but it doesnt work, I receive exception without any message.
What am I doing wrong, how to make save method work?
I believe your BbQuestionAnswersForm is extending the wrong object. It should extend BaseFormDoctrine or possibly BaseBbQuestionAnswersForm if you are using the framework correctly.
Edit: Just noticed you are using propel but it should be the same thing. Try:
class BbQuestionAnswersForm extends BaseBbQuestionAnswersForm
and less likely:
class BbQuestionAnswersForm extends BaseFormPropel
Save method should looks like this:
public function save($con = null) {
if (null === $con) {
$con = Propel::getConnection(BbExamAnswerPeer::DATABASE_NAME);
}
$con->beginTransaction();
try{
foreach($this->embeddedForms as $name => $form) {
if(!isset($this->values[$name]) || !is_array($this->values[$name])) {
continue;
}
if($form instanceof sfFormObject) {
$form->updateObject($this->values[$name]);
$form->getObject()->save($con);
$form->saveEmbeddedForms($con);
} else {
throw new Exception('Embedded form should be an instance of sfFormObject');
}
}
$con->commit();
} catch(Exception $e) {
$con->rollBack();
throw $e;
return false;
}
return true;
}
I have a function in my class which is not completed. I'm searching a way to do it all night long. Well I want to fetch all the result of a SELECT request to MYSQL using PDO in a OOP class/function.
Here my function
function select($query)
{
try
{
$sql = $this->connect->query($query);
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
return ????
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
I know that I can do it with a while loop, I tested a few options but most of the time I only got 1 result. Anyone a point for me, where I could start my search for a solution to this issue?
It's pretty easy, actually. You use PDO::FETCH_CLASS and specify which class you want to instantiate for each row.
Here is an example that fetches all available rows as an array of objects of class YourClassName.
function select($query) {
try {
$sql = $this->connect->query($query);
return $sql->fetchAll(PDO::FETCH_CLASS, YourClassName);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
Only use $sql->fetch(PDO::FETCH_ASSOC) within the while loop, not before, as you have it.
So, like:
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// something
}
I have a collection of items to save to database, but I want the record to be inserted only if not exists.
I think the most effective way would be to filter the collection before saving. Can Doctrine do it automatically?
Or shall I get all id's of all items in the collection, then query the database for items which do not exists on the list of these id's, then in foreach remove all collection items which we do not need, and finally save collection?
Any better approach suggested?
This is the save function from the Doctrine_Collection class
public function save(Doctrine_Connection $conn = null, $processDiff = true)
{
if ($conn == null) {
$conn = $this->_table->getConnection();
}
try {
$conn->beginInternalTransaction();
$conn->transaction->addCollection($this);
if ($processDiff) {
$this->processDiff();
}
foreach ($this->getData() as $key => $record) {
$record->save($conn);
}
$conn->commit();
} catch (Exception $e) {
$conn->rollback();
throw $e;
}
return $this;
}
I'm not sure where you are getting your collection from, or if you are manually building it, but you might want to try extending the Doctrine_Collection class and overloading the save function like this
<?php
class My_Collection extends Doctrine Collection
{
public function save(Doctrine_Connection $conn = null, $processDiff = true, $createOnly = true)
{
if ($conn == null) {
$conn = $this->_table->getConnection();
}
try {
$conn->beginInternalTransaction();
$conn->transaction->addCollection($this);
if ($processDiff) {
$this->processDiff();
}
foreach ($this->getData() as $key => $record) {
if($createOnly)
{
if ($record->exists())
{
$record->save($conn);
}
}else{
$record->save($conn);
}
}
$conn->commit();
} catch (Exception $e) {
$conn->rollback();
throw $e;
}
return $this;
}
}
I don't know anything about Doctrine, but the MySQL REPLACE query does just what you want - updates existing rows & creates new rows if no primary key matches were found.