sf 1.4 Access & customize embededObject() in root form - forms

I got a problem to save custom values for embededforms in root form.
I can actually edit a "manifestation" and i can add as much as i want "commande_wifi".
Everything is good saved.
I need to customize the process for every "commande_wifi" ( there is a 'puht' value depending on other values of the object() ). I have already lost a few hours only to do that.
save() is only called on the root form
That’s right! Only the root form has save() called. So if there’s other logic you want to run, you will want to override the saveEmbeddedForm method and call that code before. Oversimplification ahead: when you save a form with embedded forms, it calls $this->getObject()->save(), then it calls saveEmbeddedForms, which, for each embedded form, calls $form->saveEmbeddedForms() and then calls $form->getObject()->save(). This is critical to know, as it will save you a lot of headaches later on.
http://jmather.com/2011/01/29/6-things-to-know-about-embedded-forms-in-symfony/
I've tried to overwrite the saveembededForms() but fail at this point.
class manifestationForm extends BasemanifestationForm
{
public function configure()
{
$this->embedRelation('commande_wifi');
}
public function addNewFields($number){
$new_commandes = new BaseForm();
for($i=0; $i <= $number; $i+=1){
$commande = new Commande_wifi();
$commande->setManifestation($this->getObject());
$commande_form = new commande_wifiForm($commande);
$new_commandes->embedForm($i,$commande_form);
}
$this->embedForm('new', $new_commandes);
}
public function bind(array $taintedValues = null, array $taintedFiles = null){
$new_commandes = new BaseForm();
foreach($taintedValues['new'] as $key => $new_commande){
$commande = new Commande_wifi();
$commande->setManifestation($this->getObject());
$commande_form = new commande_wifiForm($commande);
$new_commandes->embedForm($key,$commande_form);
}
$this->embedForm('new',$new_commandes);
parent::bind($taintedValues, $taintedFiles);
}
public function saveEmbeddedForm($con = null, $forms = null)
{
if ($con === NULL)
{
$con = $this->getConnection();
}
if ($forms === NULL)
{
$forms = $this->getEmbeddedForms();
}
foreach ($forms as $form)
{
if ($form instanceof sfFormObject)
{
$form->saveEmbeddedForms($con);
$form->getObject()->setPuht(99);
$form->getObject()->save($con);
}
else
{
$this->saveEmbeddedForms($con, $form->getEmbeddedForms());
}
//$form->getObject()->setPuht(99)->save();
}
}
}
It's won ASAP i can access the embedForm Object().
Any suggestion?

Related

Is it possible to declare a form object inside a block of if condition in zend framework?

I am very new to zend framework. I want to declare a form object inside an if condition. but I don't know is it possible or not ?. I write the below code:
public function editAction()
{
$modelUsers = new Model_Users();
$userId = $this->_getParam('userId');
if ($userId) {
$populateData = array();
$user = $modelUsers->fetch($userId);
// print_r($user); exit();
if ($user instanceof Model_User) {
$populateData = $user->toArray();
$form = $this->_geteditForm($user->email);
}
$form->populate($populateData);
}
$request = $this->getRequest();
if ($request->isPost()) {
Please let me know I am going to the write path or not.
Thanks in advance
It's OK, but (assuming that it's some kind of a crud) it's better to redirect back to list or throw exception if the ID is missing. Than you don't need to close the whole form in condition. i.e:
if (!$userId = $this->_getParam('userId')) {
throw new Exception('Missing userId');
//or
$this->_helper->redirector('index');
}

Symfony: exclude empty values from form save

I have a many to many relation between Product and Properties. I'm using embedRelation() in my Product form to edit a Product and it's Properties. Properties includes images which causes my issue. Every time I save the form the updated_at column is updated for file properties even when no file is uploaded.
Therefore, I want to exclude empty properties when saving my form.
I'm using Symfony 1.4 and Doctrine 1.2.
I'm thinking something like this in my ProductForm.class.php, but I need some input on how to make this work.
Thanks
class ProductForm extends BaseProductForm
{
public function configure()
{
unset($this['created_at'], $this['updated_at'], $this['id'], $this['slug']);
$this->embedRelation('ProductProperties');
}
public function saveEmbeddedForms($con = null, $forms = null)
{
if (null === $forms)
{
$properties = $this->getValue('ProductProperties');
$forms = $this->embeddedForms;
foreach($properties as $p)
{
// If property value is empty, unset from $forms['ProductProperties']
}
}
}
}
I ended up avoiding Symfony's forms and saving models instead of saving forms. It can be easier when playing with embedded forms. http://arialdomartini.wordpress.com/2011/04/01/how-to-kill-symfony%E2%80%99s-forms-and-live-well/
Solved it by checking if posted value is a file, and if both filename and value_delete is null I unset from the array. It might not be best practice, but it works for now.
Solution based on http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms
class ProductPropertyValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
// N0thing to configure
}
protected function doClean($values)
{
$errorSchema = new sfValidatorErrorSchema($this);
foreach($values as $key => $value)
{
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if(array_key_exists('value_delete', $values))
{
if(!$value && !$values['value_delete'])
{
unset($values[$key]);
}
}
// Some error for this embedded-form
if (count($errorSchemaLocal))
{
$errorSchema->addError($errorSchemaLocal, (string) $key);
}
}
// Throws the error for the main form
if (count($errorSchema))
{
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}

Indexing Adds/Changes not working using Lucene in Zend Framework

I am pretty new to programming and definitely to Zend/Lucene indexing. From what I can tell, though, my code is correct. I feel like I may be overlooking a step or something trying to upload changes and adds to the database so that they appear in the search on my website. I'm not getting any kind of an error message though. Below is the code from the controller. I guess let me know if you need anything else to help this make sense. Thanks in advance for any direction you can give.
class SearchController extends Zend_Controller_Action
{
public function init()
{
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$this->view->identity = $auth->getIdentity();
}
}
public function indexAction()
{
// action body
}
public function buildAction()
{
// create the index
$index = Zend_Search_Lucene::open(APPLICATION_PATH . '/indexes');
$page = $this->_request->getParam('page');
// build product pages
if ($page == 'search') {
$mdl = new Model_Search();
$search = $mdl->fetchAll();
if ($search->count() > 0) {
foreach ($search as $s) {
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::unIndexed('id', $s->id));
$doc->addField(Zend_Search_Lucene_Field::text('name', $s->name));
$doc->addField(Zend_Search_Lucene_Field::text('uri', $s->uri));
$doc->addField(Zend_Search_Lucene_Field::text('description', $s->description));
$index->addDocument($doc);
}
}
$index->optimize();
$this->view->indexSize = $index->numDocs();
}
}
public function resultsAction()
{
if($this->_request->isPost()) {
$keywords = $this->_request->getParam('query');
$query = Zend_Search_Lucene_Search_QueryParser::parse($keywords);
$index = Zend_Search_Lucene::open(APPLICATION_PATH . '/indexes');
$hits = $index->find($query);
$this->view->results = $hits;
$this->view->keywords = $keywords;
} else {
$this->view->results = null;
}
}
}
Lucene indexes won't stay in sync with your database automatically, you either need to rebuild the entire index or remove and re-add the relevant documents when they change (you cannot edit an existing document).
public function updateAction()
{
// something made the db change
$hits = $index->find("name: " . $name);
foreach($hits as $hit) {
$index->delete($hit->id)
}
$doc = new Zend_Search_Lucene_Document();
// build your doc
$index->add($doc);
}
Note that lucene documents had their own internal id property, and be careful not to mistake it for an id keyword that you provide.

How to use the Zend_Log instance that was created using the Zend_Application_Resource_Log in a model class

Our Zend_Log is initialized by only adding the following lines to application.ini
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.mode = "a"
So Zend_Application_Resource_Log will create the instance for us.
We are already able to access this instance in controllers via the following:
public function getLog()
{
$bootstrap = $this->getInvokeArg('bootstrap');
//if (is_null($bootstrap)) return false;
if (!$bootstrap->hasPluginResource('Log')) {
return false;
}
$log = $bootstrap->getResource('Log');
return $log;
}
So far, so good.
Now we want to use the same log instance in model classes, where we can not access the bootstrap.
Our first idea was to register the very same Log instance in Zend_Registry to be able to use Zend_Registry::get('Zend_Log') everywhere we want:
in our Bootstrap class:
protected function _initLog() {
if (!$this->hasPluginResource('Log')) {
throw new Zend_Exception('Log not enabled');
}
$log = $this->getResource('Log');
assert( $log != null);
Zend_Registry::set('Zend_Log', $log);
}
Unfortunately this assertion fails ==> $log IS NULL --- but why??
It is clear that we could just initialize the Zend_Log manually during bootstrapping without using the automatism of Zend_Application_Resource_Log, so this kind of answers will not be accepted.
This is the final solution. We basically shall not call the function _initLog()
Big thanks to ArneRie!
// Do not call this function _initLog() !
protected function _initRegisterLogger() {
$this->bootstrap('Log');
if (!$this->hasPluginResource('Log')) {
throw new Zend_Exception('Log not enabled in config.ini');
}
$logger = $this->getResource('Log');
assert($logger != null);
Zend_Registry::set('Zend_Log', $logger);
}
Possible it is not bootstraped at this time, try:
try {
$this->bootstrap('log'); // bootstrap log
$logger = $this->getResource('log');
} catch (Zend_Application_Bootstrap_Exception $e) {
$logger = new Zend_Log();
$writer = new Zend_Log_Writer_Null();
$logger->addWriter($writer);
}
$registry = Zend_Registry::set('logger', $logger);

Drupal 6: Modifying uid of a submitted node

I have a situation where I want a set of users (employees) to be able to create a node, but to replace the uid (user ID) with that of the users profile currently displayed.
In other words, I have a block that that calls a form for a content type. If an employee (uid = 20) goes to a clients page (uid =105), and fills out the form, I want the uid associated with the form to be the client's(105), not the employee's.
I'm using arg(1) to grab the Client's uid - here is what I have..
<?php
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$form['#submit'][] = 'addSR_submit_function';
}
}
function addSR_submit_function($form, $form_state) {
$account = user_load(arg(1));
$form_state['values']['uid'] = $account->uid;
$form_state['values']['name'] = $account->name;
}
?>
The form is loading in the block, but when submitted, is still showing the employee uid. I don't want to use hook_form_alter because I don't want to modify the actual form, because clients can fill out the form directly, in this case, I don't want to modify the form at all.
I'm also ashamed that I'm putting this in a block, but I couldn't think of a way to put this in a module, so any suggestions on that would also be appreciated...
To create your form in a block, you could use the formblock module. Especially if you are not used to use the Drupal API. Then all that's left if to add your own submit handler to the form. This is a piece of code that is run, when the form is submitted. You only want to do this on clients pages so you would do that using the hook_form_alter function.
/**
* Hooks are placed in your module and are named modulename_hookname().
* So if a made a module that I called pony (the folder would then be called
* pony and it would need a pony.info and pony.module file I would create this function
*/
function pony_form_service_request_node_form_alter(&$form, $form_state) {
// Only affect the form, if it is submitted on the client/id url
if (arg(0) == 'client' && is_numeric(arg(1))) {
$form['#submit'][] = 'pony_my_own_submit_function';
}
}
function pony_my_own_submit_function($form, &$form_state) {
$account = user_load(arg(1));
$form_state['values']['uid'] = $account->uid;
$form_state['values']['name'] = $account->name;
}
The idea behind this code, is to only alter the form when the condition is met - that it is submitted on a client page. I guessed that the arg(0) would be client so if it's something else you would need to change that of cause. We only need to add a submit function, since what we want is to change the values if the form has passed validation.
Then if that is the case our 2nd function is run, which does that actual alteration of the values.
PHP blocks are bad. You can put them in a module.
function hook_block($op, $delta = 0) {
// Fill in $op = 'list';
if ($op == 'view' && $delta = 'whatever') {
$account = user_load(arg(1));
$node = array('uid' => $account->uid, 'name' => $account->name, 'type' => 'service_request', 'language' => '', '_service_request_client' => $account->uid);
$output = drupal_get_form('service_request_node_form', $node);
// Return properly formatted array.
}
}
Additionally, you want a form_alter just to enforce the values. It's ugly but it works.
function hook_form_service_request_node_form_alter(&$form, $form_state) {
if (isset($form_state['node']['_service_request_client'])) {
$form['buttons']['submit']['#submit'] = array('yourmodule_node_form_submit', 'node_form_submit');
}
}
function yourmodule_node_form_submit($form, &$form_state) {
$account = user_load($form_state['node']['_service_request_cilent'])l
$form_state['values']['uid'] = $account->uid;
$form_state['values']['name'] = $account->name;
}